modified Use Claude Code with a screen reader View current →
Show diff (134 lines)
--- a/accessibility.md +++ b/accessibility.md @@ -1,10 +1,6 @@ Claude Code has a screen reader mode that replaces its visual terminal interface with plain, linear text. Instead of boxes, progress animations, and in-place redraws, Claude Code prints labeled lines that a screen reader such as VoiceOver or NVDA reads in order. You can hold a full conversation, approve tool permissions, and review output end to end. Screen reader mode is opt-in. If you use a screen magnifier, reduced motion, or a colorblind-friendly theme instead of a screen reader, set `CLAUDE_CODE_ACCESSIBILITY`, `prefersReducedMotion`, or `theme` from the Accessibility settings table. Screen reader mode adapts the terminal interface only, so you don’t need it in the VS Code extension’s chat panel. On Claude Code v2.1.236 or later, the extension [announces conversation activity to your screen reader](</docs/en/vs-code#use-a-screen-reader>) there without any setting. -## - -​ - -Turn on screen reader mode +## Turn on screen reader mode Pick the method that matches how often you use a screen reader: @@ -14,30 +10,18 @@ If you combine methods, Claude Code applies the [`--ax-screen-reader`](</docs/en/cli-reference#cli-flags>) flag over the [`CLAUDE_AX_SCREEN_READER`](</docs/en/env-vars#variables>) environment variable, and the variable over the [`axScreenReader`](</docs/en/settings-reference#axscreenreader>) setting. If you use Claude Code over SSH, set the environment variable or setting on the remote machine where Claude Code runs. The first line Claude Code prints confirms the mode: `[Screen Reader Mode: on via flag]`, `[Screen Reader Mode: on via env]`, or `[Screen Reader Mode: on via settings]`. -### - -​ - -Project settings can’t turn on screen reader mode +### Project settings can’t turn on screen reader mode The startup line `Screen reader mode is off: project settings can't turn it on` means the project asked for screen reader mode and nothing else turns it on. Claude Code ignores both the `axScreenReader` key and a `CLAUDE_AX_SCREEN_READER` value under `env` in the project’s `.claude/settings.json` and `.claude/settings.local.json`, whatever their value. * **To turn the mode on** : start Claude Code with `--ax-screen-reader`, set `CLAUDE_AX_SCREEN_READER` to `1` in your shell, or add `"axScreenReader": true` to your user [settings file](</docs/en/settings>) and restart Claude Code. You don’t need to change the project’s files. Once you turn the mode on, the confirmation line appears at startup instead. * **If you don’t use a screen reader** : you don’t need to do anything. To stop the line from appearing, add `"axScreenReader": false` to your user settings file, or remove the `axScreenReader` key and the `CLAUDE_AX_SCREEN_READER` variable from the project’s settings files. -## - -​ - -Turn off screen reader mode +## Turn off screen reader mode Reverse whichever method turned the mode on: start without the flag, unset the environment variable, or set `axScreenReader` to `false` in your user settings file. If you set `CLAUDE_AX_SCREEN_READER` to `0`, Claude Code keeps the mode off even when the setting is `true`. -## - -​ - -Accessibility settings +## Accessibility settings The table lists each accessibility option, whether you set it as a flag, an environment variable, or a setting, and what it changes. @@ -53,11 +37,7 @@ [`theme`](</docs/en/settings-reference#theme>)| Setting| The interface colors, including the colorblind-friendly `dark-daltonized` and `light-daltonized` themes. You can also pick one with [`/theme`](</docs/en/commands#all-commands>). [`preferredNotifChannel`](</docs/en/settings-reference#preferrednotifchannel>)| Setting| With the value `"terminal_bell"`, a terminal bell outside screen reader mode when Claude is waiting on you. -## - -​ - -What your screen reader hears +## What your screen reader hears In screen reader mode, Claude Code writes flat text: @@ -89,19 +69,11 @@ When you cycle [permission modes](</docs/en/permission-modes>) with `Shift+Tab`, Claude Code announces the permission mode you land on, such as `[plan mode on]` or `[accept edits on]`. Claude Code prints the announcement once and doesn’t repeat it on later redraws. -### - -​ - -Read earlier output without losing your place +### Read earlier output without losing your place If your screen reader jumps back to the prompt while you’re reading earlier output, it’s following the terminal cursor. Claude Code moves the terminal cursor back to the prompt each time it writes new text. To keep your place while you read, stop your screen reader from following the terminal cursor. In NVDA, press `NVDA+6` to stop the review cursor from following the terminal cursor. Press `NVDA+6` again to turn following back on. -### - -​ - -Jump between turns +### Jump between turns Claude Code emits OSC 133 shell-integration markers at turn boundaries, so your terminal’s jump-to-previous-prompt key moves between turns without reading through the whole transcript: @@ -112,11 +84,7 @@ macOS Terminal doesn’t act on the markers, and Claude Code doesn’t emit them in WezTerm. In those terminals, search the scrollback for the `you:` label instead. -## - -​ - -Answer menus and prompts +## Answer menus and prompts In screen reader mode, menus you’d normally navigate with the arrow keys, including permission prompts, become numbered lists. Claude Code announces each option as a numbered line, then a `Select with numbers` prompt that names the valid range. Type the number of the option you want and press Enter. @@ -125,11 +93,7 @@ The [`/effort`](</docs/en/model-config#adjust-effort-level>) selector, which is a slider outside screen reader mode, becomes the same kind of numbered list. Yes-or-no prompts ask for a typed answer instead of a two-option menu. Answer `y` or `n` and press Enter. `yes` and `no` also work. -## - -​ - -Hear when Claude Code needs you +## Hear when Claude Code needs you In screen reader mode, Claude Code rings the terminal bell when it needs your attention, so you don’t have to keep checking the transcript. The bell rings when: @@ -139,11 +103,7 @@ The bell is your terminal’s standard alert. To silence it, change the bell setting in your terminal application. Outside screen reader mode, set [`preferredNotifChannel`](</docs/en/settings-reference#preferrednotifchannel>) to `"terminal_bell"` to get a [similar bell](</docs/en/terminal-config#get-a-terminal-bell-or-notification>) when Claude is waiting on you. -## - -​ - -Known limitations +## Known limitations Some behaviors aren’t adapted for screen reader mode: @@ -153,10 +113,6 @@ * Claude Code announces costs in the summary it prints at exit, not per turn. * Screen reader mode doesn’t change [non-interactive mode](</docs/en/headless>) with the `-p` flag. Non-interactive mode already writes plain text and remains an alternative for scripting. -## - -​ - -Report an issue +## Report an issue If something doesn’t work with your screen reader, magnifier, or terminal, open an issue on the [Claude Code issue tracker](<https://github.com/anthropics/claude-code/issues>) and mention your assistive technology in the title. Include your operating system, terminal application, and assistive technology name and version in the report.
modified Manage mods for your organization View current →
Show diff (193 lines)
--- a/admin.md +++ b/admin.md @@ -9,11 +9,7 @@ * **You haven’t deployed managed settings before** : start with [Deploy managed settings](</docs/en/managed-settings>) * **You want to control which plugins users can install** : see [Manage plugins for your organization](</docs/en/plugins/org>) -## - -​ - -Stop user-installed mods from loading +## Stop user-installed mods from loading To keep every mod your users bring from running its hooks, set the `allowManagedModsOnly` option on the built-in guard, a policy mod that Claude Code loads ahead of every mod a user installs. The option goes in managed settings under `pluginConfigs`, keyed by `cc-plugin-sec-default@builtin`: @@ -40,11 +36,7 @@ To confirm the option on a user’s machine, start Claude Code there with `--plugin-dir` and the path of a directory that holds a mod, such as `claude --plugin-dir ./first-mod`. The mod’s hooks don’t run, and the transcript and the debug log have the [guard’s message](</docs/en/plugins/mods/troubleshoot#messages-from-the-built-in-guard>), which names the mod and `allowManagedModsOnly`. If the message isn’t there, see [Check that a policy is in force](</docs/en/managed-settings#check-that-a-policy-is-in-force>) and the rules that decide whether an option takes effect. If you set `CLAUDE_CODE_ENABLE_FUNCTION_HOOKS` to `0` during early access, replace it with this option. Claude Code v2.1.287 and later ignores the variable at any value, so a `0` there leaves mods on. -## - -​ - -Know what happens by default +## Know what happens by default With no mod settings of your own, this is what your users get: @@ -60,11 +52,7 @@ The guard’s source is public in the [`mods/sec-default` directory of the Claude Code repository](<https://github.com/anthropics/claude-code/tree/main/mods/sec-default>). -### - -​ - -Know which controls still apply +### Know which controls still apply Mods don’t replace the controls you already have: @@ -83,11 +71,7 @@ None of these controls sandboxes a mod. A mod you allow runs as the user, with the user’s access to files, processes, and the network. -### - -​ - -Know which hooks of a user’s mod don’t run +### Know which hooks of a user’s mod don’t run Where the built-in guard loads, a hook that a user’s mod registers on one of these events never runs, and `/plugin` tells that user so in a note. In the [`session.append`](</docs/en/plugins/mods/reference#session>) rows, `door` is the kind of stored row the hook is filtered to. @@ -118,11 +102,7 @@ If you deliver a list without the guard through [server-managed settings](</docs/en/server-managed-settings#fetch-and-caching-behavior>), the guard stays loaded until the server confirms the settings for the session. To confirm either change on a machine that runs v2.1.299 or later, open `/plugin` in a session there and check that the note is gone. A `session.append` hook with no `door` filter still runs and gets no note, but the stored rows in the table don’t reach it. -## - -​ - -Decide whether to leave mods on +## Decide whether to leave mods on A mod can do more than the other parts of a plugin because it runs inside Claude Code. It sees every prompt and tool call, can change them, and can allow or deny a tool call before a permission prompt appears. What a user can load as a mod depends on the plugin controls you already have: @@ -134,11 +114,7 @@ [Manage plugins for your organization](</docs/en/plugins/org>) lists the ways a plugin loads and the setting that controls each. To check the mods in a marketplace before your users install them, see Review what a mod can do. To keep users’ mods out until you’ve done that, see Stop user-installed mods from loading. -### - -​ - -Review what a mod can do +### Review what a mod can do You can see what a mod is able to do without running it. In your shell, run `claude plugin validate` on the plugin’s directory: @@ -165,11 +141,7 @@ In the `hooks:` line, [`tool.call`](</docs/en/plugins/mods/reference#tools>) and [`prompt.submit`](</docs/en/plugins/mods/reference#prompts-and-what-claude-reads>) mean the mod sees every tool call and every prompt, and can change them. [`session.append`](</docs/en/plugins/mods/reference#session>) means the mod can rewrite each row of the conversation before it’s stored, apart from the rows the guard passes over. [`ui.render{component=AskUserQuestion}`](</docs/en/plugins/mods/interface#change-what-claude-code-already-draws>) means the mod can redraw the dialog Claude uses to ask the user a question. `tool.check` means the mod can approve or deny a tool call before a permission prompt appears. Know what happens by default lists which of your rules and hooks take precedence over its answer. -## - -​ - -Choose how much to allow +## Choose how much to allow Mod policies range from no installed mods at all to any mod a user chooses, with your own mod checking the others, and each one is a few managed settings. Find the policy you want in the first column and set what the second column names. [Deploy managed settings](</docs/en/managed-settings>) covers where managed settings live. @@ -190,11 +162,7 @@ Mods built into Claude Code, such as `AGENTS.md` support, aren’t affected by these settings. Each has [its own switch](</docs/en/plugins/mods/overview#mods-built-into-claude-code>). A user whose mod was refused or didn’t load finds the reason in their debug log. [Refusal messages](</docs/en/plugins/mods/troubleshoot#refusal-messages>) lists the lines for `allowManagedHooksOnly` and `disableAllHooks`, and [Messages from the built-in guard](</docs/en/plugins/mods/troubleshoot#messages-from-the-built-in-guard>) has the line for `allowManagedModsOnly`. -### - -​ - -Allow only your organization’s mods +### Allow only your organization’s mods To run your organization’s mods and block the ones users bring, deploy the settings from the **Only your organization’s mods** row of the policy table, plus `disableSideloadFlags`. With this complete `managed-settings.json`, Claude Code refuses users’ own mods, so none of their hooks run, and your policy mod runs ahead of other mods: @@ -230,11 +198,7 @@ To also limit which marketplaces users can add, combine this file with your [marketplace restrictions](</docs/en/plugins/org#restrict-what-users-can-install>). -### - -​ - -Apply your plugin controls to mods +### Apply your plugin controls to mods A mod is a plugin, so the ways you [manage plugins for your organization](</docs/en/plugins/org>) also apply to a plugin that holds a mod: @@ -245,11 +209,7 @@ * **Set up CI and containers** : [Seed containers and CI](</docs/en/plugins/org#seed-containers-and-ci>) * **Offer mods your users may install** : [Host a marketplace](</docs/en/plugins/host-marketplace>). A mod that Claude Code copies from a GitHub, git, URL, or npm source counts as a user’s, not as your organization’s. -### - -​ - -Set options on the built-in guard +### Set options on the built-in guard The built-in guard takes options. Set them in managed settings under `pluginConfigs`, keyed by `cc-plugin-sec-default@builtin`, as the example in Stop user-installed mods from loading does. The table gives what your users get with each option unset and with it set to `true`: @@ -267,19 +227,11 @@ The [messages from the built-in guard](</docs/en/plugins/mods/troubleshoot#messages-from-the-built-in-guard>) are what your users see when either option applies. -## - -​ - -Run your organization’s own mods +## Run your organization’s own mods You can deploy mods of your own to every user, choose where they run relative to users’ mods, and use one to enforce a policy. -### - -​ - -Install your organization’s mods and set the order +### Install your organization’s mods and set the order Your organization’s mods load where users’ mods don’t and can run ahead of them, so Claude Code has to be able to tell that a mod came from you. It treats a mod as your organization’s only when all of these are true: @@ -349,11 +301,7 @@ * **Repositories can’t set either list** : Claude Code ignores both in a repository’s settings file, so set them in managed settings. * **A user can set them to order their own mods** : in `~/.claude/settings.json`, only on a machine with no managed settings or `managed-mcp.json` file, and only when the session’s credential isn’t a Team or Enterprise `/login`. Anywhere else, Claude Code ignores both keys in user settings. A list there neither adds nor removes the built-in guard. -### - -​ - -Enforce a policy with a mod of your own +### Enforce a policy with a mod of your own To keep every user’s mod out, you don’t need a mod of your own. Set `allowManagedModsOnly`. Write a policy mod when you want to allow some users’ mods and refuse others, or to record what mods do. Each time another mod is about to load, your mod receives the list that `claude plugin validate` prints, in an event named [`plugin.register`](</docs/en/plugins/mods/reference#other-mods>). A mod in `prependPlugins` can read that list and refuse the mod. It can also [handle any mods API call by name](</docs/en/plugins/mods/api#reach-files-processes-and-the-network>) to record or refuse that call for every other mod. The name is the method without the `$.`, so a hook on `fs.write` sees every `$.fs.write` call. This policy mod refuses any user’s mod whose own code calls `$.process.run` or `$.process.spawn`. It also keeps an audit log, writing each tool call and each file a mod writes to the debug log. Because it runs first, the log records what was requested, before any user’s mod changes it. Save it as `acme-guard/hooks/register.js`: @@ -401,11 +349,7 @@ When a user installs a mod that calls `$.process.run`, the mod doesn’t load, and their debug log has a line that ends with `refused by acme-guard:` and your reason. The refusal also reaches the transcript in a [session that hot-reloads a plugin directory](</docs/en/plugins/mods/troubleshoot#find-out-why-a-mod-does-nothing>). To block a call without refusing the whole mod, return `{ deny: 'your reason' }` from a hook on that call’s name. To send the audit lines somewhere other than the debug log, call `$.http.fetch` from the same hooks. A session can run without your mod. If the worker thread that runs installed mods [crashes three times](</docs/en/plugins/mods/troubleshoot#mods-that-run-in-the-hooks-worker-are-off-for-this-session>), Claude Code unloads every mod that isn’t built in, including yours, until the user runs `/reload-plugins` or starts a new session. And a user who starts Claude Code with `--safe-mode` runs without installed mods, yours included. [Create a mod](</docs/en/plugins/mods/create>) covers the files a mod needs. [Test a policy mod](</docs/en/plugins/mods/test#test-a-mod-that-judges-other-mods>) has a test file for this policy mod. -#### - -​ - -Refuse mods when your check fails +#### Refuse mods when your check fails If your `plugin.register` hook throws or exceeds its time limit, Claude Code skips the hook, so the check fails open and the mod it was checking loads. To fail closed and refuse users’ mods, move the check into a named function and add a `.catch` handler that returns the refusal. This version of the file shows the `plugin.register` hook only, so keep the two audit hooks from the first version in `register`: @@ -434,11 +378,7 @@ With the handler in place, a mod that was being checked when the check threw or timed out doesn’t load, and the refusal line carries the second reason, as in `refused by acme-guard: Acme policy check failed, so this mod was not loaded`. The handler passes every mod outside the `user` tier to `next(e)`, so a failed check doesn’t stop the mods your organization lists. [Handle a hook that fails](</docs/en/plugins/mods/events#handle-a-hook-that-fails>) covers `.catch` for other events. -## - -​ - -Next steps +## Next steps * [Plugin security](</docs/en/plugins/security>): what any plugin can do on a user’s machine, and how to review one before it’s installed * [Mods overview](</docs/en/plugins/mods/overview>): what a mod is and how it compares to hooks, skills, and MCP servers
modified Set up Claude Code for your organization View current →
Show diff (119 lines)
--- a/admin-setup.md +++ b/admin-setup.md @@ -10,11 +10,7 @@ Set up usage visibility| How you track spend and adoption| [Analytics](</docs/en/analytics>), [Monitoring](</docs/en/monitoring-usage>), [Costs](</docs/en/costs>) Review data handling| Data retention and compliance posture| [Data usage](</docs/en/data-usage>), [Security](</docs/en/security>) -## - -​ - -Choose your API provider +## Choose your API provider Claude Code connects to Claude through one of several API providers. Your choice affects billing, authentication, which compliance posture you inherit, and which Claude Code features your developers can use. @@ -28,11 +24,7 @@ Some Claude Code features require a claude.ai account. [Cloud sessions](</docs/en/claude-code-on-the-web>), [cloud scheduled tasks](</docs/en/routines>), [Code Review](</docs/en/code-review>), [Remote Control](</docs/en/remote-control>), and the [Chrome extension](</docs/en/chrome>) aren’t available through Console API keys or cloud-provider credentials alone. If you deploy through Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry, plan whether developers also need Claude for Teams or Enterprise seats. Each feature page lists its plan requirements. For the full provider comparison covering authentication, regions, and feature parity, see the [enterprise deployment overview](</docs/en/third-party-integrations>). Each provider’s auth setup is in [Authentication](</docs/en/authentication>). Proxy and firewall requirements in [Network configuration](</docs/en/network-config>) apply regardless of provider. If you want a single endpoint in front of multiple providers or centralized request logging, see [LLM gateway](</docs/en/llm-gateway>). -## - -​ - -Decide how settings reach devices +## Decide how settings reach devices Managed settings define organization policy. Claude Code checks the four sources in the table below in priority order. [How Claude Code combines managed sources](</docs/en/managed-settings#precedence-within-the-managed-tier>) says which of them apply, what a policy helper changes, and how to compose every source. The table is the decision map. @@ -48,11 +40,7 @@ Claude Code fetches server-managed settings at startup and refreshes them hourly during the session, with no endpoint infrastructure to deploy. Delivery through the claude.ai admin console requires a Claude for Teams or Enterprise plan. Deployments on Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry can get the same remote delivery by running a [Claude apps gateway](</docs/en/claude-apps-gateway>), or use one of the file-based or OS-level mechanisms instead. If your organization mixes providers, configure [server-managed settings](</docs/en/server-managed-settings>) for claude.ai users plus a [file-based or plist/registry fallback](</docs/en/managed-settings#delivery-mechanisms>) so other users still receive managed policy. The plist and HKLM registry locations work with any provider and resist tampering because they require admin privileges to write. The Windows user registry at HKCU is writable without elevation, so treat it as a convenience default rather than an enforcement channel. By default, WSL reads only the Linux file path at `/etc/claude-code`. To extend your Windows registry and `C:\Program Files\ClaudeCode` policy to WSL on the same machine, set [`wslInheritsWindowsSettings: true`](</docs/en/settings-reference#wslinheritswindowssettings>) in either of those admin-only Windows sources. Whichever mechanism you choose, managed values take precedence over user and project settings, apart from a few security-sensitive [exceptions](</docs/en/settings#exceptions-to-managed-settings-precedence>). Array settings such as `permissions.allow` and `permissions.deny` merge entries from all sources, so developers can extend managed lists but not remove from them. For `fallbackModel`, `availableModels`, and [`modelPicker`](</docs/en/settings-reference#modelpicker>), the managed value replaces lower layers rather than merging. -### - -​ - -WSL sessions in Claude Code Desktop +### WSL sessions in Claude Code Desktop On Windows, [Claude Code Desktop can run Code sessions inside a WSL 2 distribution](</docs/en/desktop-wsl>). The session’s Claude Code process runs inside the distribution, so it resolves managed settings through the WSL discovery path above: Windows-only sources don’t reach it unless `wslInheritsWindowsSettings: true` is deployed. Claude Desktop turns off WSL sessions by default on devices it detects as organization-managed, for example when `C:\Program Files\ClaudeCode\managed-settings.json` exists. To turn them on, deploy a Windows registry policy, which requires Claude Desktop v1.19367.0 or later: @@ -66,11 +54,7 @@ If a WSL session starts on a device with Claude Desktop’s [`allowedWorkspaceFolders`](<https://claude.com/docs/third-party/claude-desktop/configuration#allowedworkspacefolders>) list, a `~` entry means the home directory inside the distribution. Processes inside the WSL 2 utility VM aren’t visible to Windows-side endpoint detection sensors. To observe in-distro process and file activity, check your endpoint detection vendor’s WSL guidance for a Linux sensor you can run inside the distribution and the exclusions it needs. Claude Code’s [OpenTelemetry tool-execution telemetry](</docs/en/monitoring-usage>) is emitted identically for WSL and native sessions. -## - -​ - -Decide what to enforce +## Decide what to enforce Managed settings can lock down tools, sandbox execution, restrict MCP servers and plugin sources, and control which hooks run. Each row is a control surface with the setting keys that drive it. @@ -110,11 +94,7 @@ Permission rules and sandboxing cover different layers. Denying WebFetch blocks Claude’s fetch tool, but if Bash is allowed, `curl` and `wget` can still reach any URL. Sandboxing closes that gap with a network domain allowlist enforced at the OS level. For the threat model these controls defend against, see [Security](</docs/en/security>). -### - -​ - -Connected GitHub accounts +### Connected GitHub accounts On Team and Enterprise plans, the GitHub section of [**Organization settings > Git providers**](<https://claude.ai/admin-settings/source-control>) lists the GitHub organizations and personal accounts linked to your Claude organization through the [Claude GitHub App](<https://github.com/apps/claude>). Claude Code, [Claude Tag](<https://claude.com/docs/claude-tag/admins/configure-github>), and Claude Security share the list. Opening the page requires an [Owner role](</docs/en/server-managed-settings#access-control>) in your Claude organization. The Admin role can’t open it. Someone can link an account from the Git providers page or by connecting GitHub to Claude: @@ -123,11 +103,7 @@ A row marked **Not linked** comes from your own GitHub sign-in. It’s an account you can see on GitHub where the Claude GitHub App is installed. To unlink an account from your Claude organization, open its row’s menu and select **Unlink from this workspace**. Unlinking leaves the Claude GitHub App installed on GitHub, and the account is linked again the next time one of its owners connects GitHub to Claude. To keep it from being linked again, uninstall the Claude GitHub App from that account on GitHub. On Enterprise plans, the [Compliance API](<https://platform.claude.com/docs/en/api/compliance/activities/list>) activity types for linking and unlinking are `github_app_installation_linked` and `github_app_installation_unlinked`. -## - -​ - -Set up usage visibility +## Set up usage visibility Choose monitoring based on what you need to report on. The dashboards, APIs, and spend controls differ between Claude for Teams or Enterprise plans and Claude Console organizations, so check the Availability column before you plan your reporting around a capability. @@ -140,11 +116,7 @@ On Teams and Enterprise, per-user usage and spend numbers come from the [spend report](<https://support.claude.com/en/articles/12883420-view-usage-analytics-for-team-and-enterprise-plans>) in your organization’s analytics settings, not the analytics dashboard. Cloud providers expose spend through AWS Cost Explorer, GCP Billing, or Azure Cost Management. For planning enterprise budgets across Claude chat, Claude Code, and Cowork, see the [Claude Enterprise consumption guide](<https://support.claude.com/en/articles/14782391-claude-enterprise-consumption-guide>). -## - -​ - -Review data handling +## Review data handling On Team, Enterprise, Claude API, and cloud provider plans, Anthropic doesn’t train models on your code or prompts. Your API provider determines retention and compliance posture. @@ -157,11 +129,7 @@ If you need request-level audit logging or to route traffic by data sensitivity, we recommend you place a gateway between developers and your provider: a self-hosted [Claude apps gateway](</docs/en/claude-apps-gateway>) records a per-request audit log with IdP identity, or you can use another [LLM gateway](</docs/en/llm-gateway>). Sessions that go through a gateway aren’t eligible for the HIPAA configuration. [Check how developers sign in and connect](</docs/en/hipaa-setup#check-how-developers-sign-in-and-connect>) lists which sign-in and connection methods are. For regulatory requirements and certifications, see [Legal and compliance](</docs/en/legal-and-compliance>). -## - -​ - -Verify and onboard +## Verify and onboard After configuring managed settings, have a developer run `/status` inside Claude Code. On the **Status** tab, the `Setting sources` line shows `Enterprise managed settings` followed by the source that won in parentheses; [Verify enforcement](</docs/en/managed-settings#verify-enforcement>) lists the labels. Share these resources to help developers get started: @@ -177,11 +145,7 @@ If a developer sees “You haven’t been added to your organization yet,” their seat doesn’t include Claude Code access and needs to be updated in the admin console. -## - -​ - -Next steps +## Next steps With provider and delivery mechanism chosen, move on to detailed configuration:
modified Escalate hard decisions with the advisor tool View current →
Show diff (193 lines)
--- a/advisor.md +++ b/advisor.md @@ -2,19 +2,11 @@ The advisor tool lets Claude consult a second, typically stronger model at key moments during a task, such as before committing to an approach, when stuck on a recurring error, or before declaring a task complete. The advisor receives the full conversation, including every tool call and result, and returns guidance that Claude applies before continuing. The advisor runs server-side on Anthropic’s infrastructure as a [server tool](<https://platform.claude.com/docs/en/agents-and-tools/tool-use/advisor-tool>), available to both subscription and API-billed accounts. You choose which model acts as the advisor, and Claude decides when to call it. This page covers how to enable the advisor, which model pairings are accepted, what Claude shows during a consultation, and how advisor usage is billed. -## - -​ - -When to use the advisor +## When to use the advisor The advisor fits long, multi-step tasks where most turns are routine but plan quality determines the outcome. Examples include large refactors, debugging sessions where an error keeps recurring, and tasks you want independently checked before Claude declares them done. It adds less value on short tasks where there is little to plan, or on work where every turn needs the strongest model. For those, [switch the main model](</docs/en/model-config#setting-your-model>) instead, or see how the advisor compares with opusplan and subagents for other ways to get a second opinion. -## - -​ - -Enable the advisor +## Enable the advisor You can set the advisor model in three ways: @@ -24,11 +16,7 @@ Each of these enables the advisor for sessions whose main model supports it. After the session starts, Claude Code shows an `Advisor Tool (experimental) is on and may use more tokens · /advisor` notification. To stop using the advisor, see Turn the advisor off. On some plans, Fable as the advisor also needs your one-time [consent to bill Fable usage to usage credits](</docs/en/model-config#fable-and-usage-credits>). For what happens before you have given that consent, see Fable advisor and usage credits. -### - -​ - -Use the `/advisor` command +### Use the `/advisor` command Run `/advisor` without arguments to open a picker listing the available advisor models, or pass the model directly: @@ -42,11 +30,7 @@ Claude Code doesn’t invoke a saved advisor that your organization’s [`availableModels`](</docs/en/model-config#restrict-model-selection>) allowlist excludes. To use the advisor, pick an allowed model with `/advisor`. Claude Code still saves an advisor that your current main model doesn’t support. That advisor activates after you switch to a compatible main model with [`/model`](</docs/en/model-config#setting-your-model>). If the API already refused the saved advisor in the current conversation, it stays off until `/clear` or `/compact`, even after you switch models. On some plans, Fable as the advisor also needs your one-time [consent to bill Fable usage to usage credits](</docs/en/model-config#fable-and-usage-credits>). For what `/advisor fable` does before you have given that consent, see Fable advisor and usage credits. -### - -​ - -Set `advisorModel` in settings +### Set `advisorModel` in settings To configure the advisor as a default without opening a session, set it in your settings file: @@ -54,11 +38,7 @@ "advisorModel": "opus" } -### - -​ - -Use the `--advisor` flag +### Use the `--advisor` flag To set the advisor for a single session without changing your saved setting, launch with the flag: @@ -73,11 +53,7 @@ If you start a [background session](</docs/en/agent-view>) with `--advisor` and one of these applies, Claude Code starts the session without the advisor instead of exiting. If the model you pass can act as an advisor but ranks below your main model, the session starts whether or not it’s a background session. Your main model then runs without the advisor. -## - -​ - -Choose an advisor model +## Choose an advisor model Claude Code ranks models by capability for the advisor role, and an advisor must rank at or above your session’s main model. Rows run from the lowest-ranked main model to the highest: @@ -100,19 +76,11 @@ * If the API refuses the pairing of an advisor that Claude Code attached, Claude Code resends that request without the advisor. The conversation continues without one, so you see no error and get no advisor calls. If you then pick a different advisor with `/advisor`, it takes effect after `/clear` or `/compact` and in new sessions. * If the main model or the advisor is a model Claude Code does not recognize, the advisor is not attached. -### - -​ - -Fable advisor and usage credits +### Fable advisor and usage credits On some plans, Fable usage bills to usage credits, and Fable as the advisor bills the same way. If your account requires the [one-time consent to bill Fable usage to usage credits](</docs/en/model-config#fable-and-usage-credits>), Claude Code asks for it when you select a Fable model with `/model` and doesn’t apply Fable as the advisor until you have accepted that consent. Before you have accepted it, Claude Code doesn’t save Fable as the advisor when you type `/advisor fable` or pick Fable in the `/advisor` picker. It points you to `/model fable` instead. With `claude --advisor fable`, Claude Code exits at launch with a message that points to `/model fable`. In a background session, it starts the session without the advisor instead of exiting. With Fable already saved as your `advisorModel`, Claude Code sends requests without the advisor. In an interactive session whose main model supports the advisor, it also shows a notification that points to `/model fable`. To accept the consent, run `/model fable` and choose to continue on Fable. Claude Code records the consent and [saves Fable as your selected model](</docs/en/model-config#default-model-setting>). Then select Fable as the advisor. -### - -​ - -Common model pairings +### Common model pairings Any accepted pairing works. These combinations balance cost against capability in different ways: @@ -125,19 +93,11 @@ Fable main + Fable advisor| Highest-capability pairing when Fable is available. Claude Code doesn’t apply an Opus or Sonnet advisor to a Fable main model Sonnet main + Sonnet advisor| A lower-cost second opinion for catching routine oversights -## - -​ - -When Claude consults the advisor +## When Claude consults the advisor Claude decides when to call the advisor. It tends to consult before committing to an approach, when an error keeps recurring, and before declaring a task done, but the timing is model-driven rather than rule-based. You can ask for a consultation in your prompt the same way you would request any tool, for example `consult the advisor before you continue`. There is no setting to cap or force advisor calls; if you want Claude to consult more or less often during a task, say so in your instructions. -## - -​ - -What you see during a session +## What you see during a session When Claude calls the advisor, the transcript shows an `Advising` line with the advisor model name while the call is in progress. When the result returns, the line reports whether the advisor gave guidance: @@ -147,11 +107,7 @@ Claude generally follows the advisor’s guidance, but adapts when its own evidence contradicts a specific claim: if a recommended step fails when tried, or the file contents contradict the advice, Claude surfaces the conflict rather than following the guidance unconditionally. The advisor always receives the full conversation, and Claude controls the timing. For more control or a different configuration, see how the advisor compares with subagents and opusplan. -## - -​ - -Cost +## Cost When Claude calls the advisor, the advisor model reads the conversation, so each call consumes tokens at the advisor model’s rates in addition to your main model’s usage. How those advisor tokens are billed depends on how you pay: @@ -160,30 +116,18 @@ For how a Fable advisor works with usage credits, see Fable advisor and usage credits. Claude calls the advisor at decision points rather than on every turn, so pairing a faster main model with a stronger advisor typically costs less than running the stronger model throughout. Advisor usage counts toward the session totals shown by [`/usage`](</docs/en/costs#track-your-costs>). For how advisor tokens are reported in API responses, see [Usage and billing](<https://platform.claude.com/docs/en/agents-and-tools/tool-use/advisor-tool#usage-and-billing>) in the Claude API documentation. -## - -​ - -Impact on prompt caching +## Impact on prompt caching Enabling or disabling the advisor mid-session does not invalidate your main model’s [prompt cache](</docs/en/prompt-caching>). Unlike [switching models](</docs/en/prompt-caching#switching-models>), toggling `/advisor` keeps the cached prefix intact, and the advisor’s returned guidance is cached as part of the transcript on later turns. The advisor model’s own read of the conversation is not cached. Each advisor call processes the full transcript anew, with no reuse between calls. -## - -​ - -Requirements +## Requirements * **Provider** : the Anthropic API or [Claude Platform on AWS](</docs/en/claude-platform-on-aws>), not Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry. On Claude Platform on AWS, the advisor requires Claude Code v2.1.300 or later. * **LLM gateway** : through an [LLM gateway](</docs/en/llm-gateway>) configured with `ANTHROPIC_BASE_URL`, availability depends on whether the gateway forwards the request intact to the Anthropic API. If the gateway or its upstream doesn’t recognize the advisor tool, see [Automatic retry and error forwarding](</docs/en/llm-gateway-protocol#automatic-retry-and-error-forwarding>) for how Claude Code responds. * **Supported main model** : Fable, Opus 4.6 or later, Sonnet 4.6 or later, Haiku 4.5, or Haiku 5.5. See Choose an advisor model for which advisors each accepts. * **Feature-flag fetching** : unless you’re on Claude Platform on AWS, the advisor needs a feature flag fetched from Anthropic. A session with a variable that turns fetching off, such as `DISABLE_TELEMETRY`, doesn’t have that flag. To check your session, see [which sessions skip the fetch or start without the flag](</docs/en/env-vars#features-that-need-feature-flag-fetching>). -## - -​ - -Turn the advisor off +## Turn the advisor off To stop using the advisor, run `/advisor off` or choose **No advisor** in the `/advisor` picker: @@ -191,11 +135,7 @@ To disable the advisor tool entirely, set `CLAUDE_CODE_DISABLE_ADVISOR_TOOL=1`. The `/advisor` command becomes unavailable and any configured `advisorModel` is ignored. The `--advisor` flag is accepted but has no effect. See [Environment variables](</docs/en/env-vars>). -## - -​ - -Compare with related features +## Compare with related features The advisor is one of several ways to combine model strengths. Pick based on when you want a second model involved. @@ -206,11 +146,7 @@ [Subagents](</docs/en/sub-agents#choose-a-model>) with `model` set| For the entire delegated subtask| Claude delegates, or you invoke the subagent [`/model`](</docs/en/model-config#setting-your-model>)| From the next request onward| You switch models -## - -​ - -See also +## See also * [Model configuration](</docs/en/model-config>): switch models, set effort levels, and use `opusplan` * [Manage costs effectively](</docs/en/costs>): track token usage across models
modified How the agent loop works View current →
Show diff (281 lines)
--- a/agent-loop.md +++ b/agent-loop.md @@ -1,10 +1,6 @@ The Agent SDK lets you embed Claude Code’s autonomous agent loop in your own applications. The SDK is a standalone package that gives you programmatic control over tools, permissions, cost limits, and output. Both the TypeScript and Python SDKs bundle a native Claude Code binary, so most installs need no separate Claude Code install. See the [quickstart’s install note](</docs/en/agent-sdk/quickstart>) for the installs that do. When you start an agent, the SDK runs the same [execution loop that powers Claude Code](</docs/en/how-claude-code-works#the-agentic-loop>): Claude evaluates your prompt, calls tools to take action, receives the results, and repeats until the task is complete. This page explains what happens inside that loop so you can build, debug, and optimize your agents effectively. -## - -​ - -The loop at a glance +## The loop at a glance Every agent session follows the same cycle: @@ -16,11 +12,7 @@ A quick question such as “what files are here?” might take two or three turns: one or two calling `Glob`, then one responding with the results. A complex task such as “refactor the auth module and update the tests” can chain dozens of tool calls across many turns as Claude adjusts after each result. -## - -​ - -Turns and messages +## Turns and messages A turn is one pass through the loop: Claude produces output, and if it includes tool calls, the SDK executes them and the results feed back to Claude automatically. This happens without yielding control back to your code. Turns continue until Claude produces output with no tool calls, at which point the loop ends and the final result is delivered. Consider what a full session might look like for the prompt “Fix the failing tests in auth.ts”. First, the SDK sends your prompt to Claude and yields a `SystemMessage` with the session metadata. Then the loop begins: @@ -31,11 +23,7 @@ That was four turns: three with tool calls, one final text-only response. You can cap the loop with `max_turns` / `maxTurns`. Count each turn with tool calls, plus one for the final text-only response. Without that extra turn, the run ends with a `ResultMessage` of subtype `error_max_turns` and no final response. For example, `max_turns=2` in the loop above would have stopped before the edit step. You can also use `max_budget_usd` / `maxBudgetUsd` to cap turns based on a spend threshold. Without limits, the loop runs until Claude finishes on its own, which is fine for well-scoped tasks but can run long on open-ended prompts (“improve this codebase”). Setting a budget is a good default for production agents. See Turns and budget below for the option reference. -## - -​ - -Message types +## Message types As the loop runs, the SDK yields a stream of messages. Each message carries a type that tells you what stage of the loop it came from. The five core types are: @@ -52,11 +40,7 @@ These five types cover the full agent loop lifecycle. Both SDKs also yield observability events such as rate-limit status and task notifications that are not required to drive the loop. See the [Python message types reference](</docs/en/agent-sdk/python#message-types>) and [TypeScript message types reference](</docs/en/agent-sdk/typescript#message-types>) for the complete lists. -### - -​ - -Handle messages +### Handle messages Which messages you handle depends on what you’re building: @@ -130,19 +114,11 @@ console.log(`Session ended with an error: ${error}`); } -## - -​ - -Tool execution +## Tool execution Tools give your agent the ability to take action. Without tools, Claude can only respond with text. With tools, Claude can read files, run commands, search code, and interact with external services. -### - -​ - -Built-in tools +### Built-in tools The SDK includes the same tools that power Claude Code: @@ -161,11 +137,7 @@ * **Define custom tools** with [custom tool handlers](</docs/en/agent-sdk/custom-tools>) * **Load project skills** via [setting sources](</docs/en/agent-sdk/claude-code-features>) for reusable workflows -### - -​ - -Tool permissions +### Tool permissions Claude determines which tools to call based on the task, but you control whether those calls are allowed to execute. Use these options to auto-approve tools, block tools, and set the permission mode: @@ -175,27 +147,15 @@ You can also scope individual tools with rules like `"Bash(npm *)"` to allow only specific commands. See [Permissions](</docs/en/agent-sdk/permissions>) for the full rule syntax. When a tool is denied, Claude receives a rejection message as the tool result and typically attempts a different approach or reports that it couldn’t proceed. -### - -​ - -Parallel tool execution +### Parallel tool execution When Claude requests multiple tool calls in a single turn, both SDKs can run them concurrently or sequentially depending on the tool. Read-only tools (like `Read`, `Glob`, `Grep`, and MCP tools marked as read-only) can run concurrently. Tools that modify state (like `Edit`, `Write`, and `Bash`) run sequentially to avoid conflicts. Custom tools default to sequential execution. To enable parallel execution for a custom tool, set `readOnlyHint` in its annotations. Both the [TypeScript](</docs/en/agent-sdk/typescript#tool>) and [Python](</docs/en/agent-sdk/python#tool>) SDKs use this field name from the MCP SDK. -## - -​ - -Control how the loop runs +## Control how the loop runs You can limit how many turns the loop takes, how much it costs, how deeply Claude reasons, and whether tools require approval before running. All of these are fields on [`ClaudeAgentOptions`](</docs/en/agent-sdk/python#claudeagentoptions>) (Python) / [`Options`](</docs/en/agent-sdk/typescript#options>) (TypeScript). -### - -​ - -Turns and budget +### Turns and budget Option| What it controls| Default ---|---|--- @@ -204,19 +164,11 @@ When either limit is hit, the SDK returns a `ResultMessage` with a corresponding error subtype (`error_max_turns` or `error_max_budget_usd`). See Handle the result for how to check these subtypes and [`ClaudeAgentOptions`](</docs/en/agent-sdk/python#claudeagentoptions>) / [`Options`](</docs/en/agent-sdk/typescript#options>) for syntax. The budget cap covers [subagents](</docs/en/agent-sdk/subagents>): their spend counts toward the total. Once spend reaches the cap, spawning another subagent fails with `Budget limit reached`, and Claude Code stops any background subagents still running. The cap-enforcement behaviors require Claude Code v2.1.217 or later. With [streaming input](</docs/en/agent-sdk/streaming-vs-single-mode>), a message that is still queued when a turn ends at the max-turns limit stays queued. Claude Code doesn’t add it to that turn’s last model call. It starts a new turn for the message, and the max-turns count starts over for that turn. The budget total keeps accumulating across messages, and once spend reaches `maxBudgetUsd`, later messages in the same conversation end with the `error_max_budget_usd` result. A [`/clear`](</docs/en/agent-sdk/cost-tracking>) starts the budget over. -#### - -​ - -Budget headroom +#### Budget headroom Claude Code compares spend with the `max_budget_usd` / `maxBudgetUsd` cap after model responses arrive, because each response’s cost comes from the token usage the API returns with it. The response that reaches the cap still completes and counts toward [`total_cost_usd`](</docs/en/agent-sdk/cost-tracking#get-the-total-cost-of-a-query>). Spend can therefore pass the cap by up to the cost of that one response, plus anything that subagents still running at that moment spend before they stop. Leave headroom for this when you set the cap. -### - -​ - -Effort level +### Effort level The `effort` option controls how much reasoning Claude applies. Lower effort levels use fewer tokens per turn and reduce cost. Not all models support the effort parameter. See [Effort](<https://platform.claude.com/docs/en/build-with-claude/effort>) for which models support it. @@ -234,11 +186,7 @@ Use lower effort for agents doing simple, well-scoped tasks, such as listing files or running a single grep, to reduce cost and latency. Set `effort` in the top-level `query()` options for the [session](</docs/en/sub-agents#choose-an-effort-level>), or per subagent with the `effort` field on [`AgentDefinition`](</docs/en/agent-sdk/subagents#agentdefinition-configuration>) to override the session level. -### - -​ - -Permission mode +### Permission mode The permission mode option (`permission_mode` in Python, `permissionMode` in TypeScript) controls whether the agent asks for approval before using tools: @@ -253,45 +201,29 @@ For interactive applications, use `"default"` with a tool approval callback to surface approval prompts. For agents that edit files on a dev machine, use `"acceptEdits"`. Reserve `"bypassPermissions"` for CI, containers, or other isolated environments. See [Permissions](</docs/en/agent-sdk/permissions>) for full details. -### - -​ - -Model +### Model Set the `model` option to choose which model runs the session. For more information, see [Choose a model](</docs/en/agent-sdk/configuration#choose-a-model>). -## - -​ - -The context window +## The context window The context window is the total amount of information available to Claude during a session. It does not reset between turns within a session. Everything accumulates: the system prompt, tool definitions, conversation history, tool inputs, and tool outputs. Content that stays the same across turns (system prompt, tool definitions, CLAUDE.md) is automatically [prompt cached](<https://platform.claude.com/docs/en/build-with-claude/prompt-caching>), which reduces cost and latency for repeated prefixes. For how a custom system prompt or `append` text affects cache reuse across sessions, see [Modifying system prompts](</docs/en/agent-sdk/modifying-system-prompts#improve-prompt-caching-across-users-and-machines>). -### - -​ - -What consumes context +### What consumes context Here’s how each component affects context in the SDK: Source| When it loads| Impact ---|---|--- **System prompt**| Every request| Small fixed cost, always present -**CLAUDE.md files**| Session start, via [`settingSources`](</docs/en/agent-sdk/claude-code-features>)| Full content in every request (but prompt-cached, so only the first request pays full cost) +**CLAUDE.md files**| Session start, via [`settingSources`](</docs/en/agent-sdk/claude-code-features>)| Full content in every request (but prompt-cached) **Tool definitions**| Every request for core built-in tools such as Bash, Read, and Edit; on demand for MCP tools and other built-in tools, which [tool search](</docs/en/agent-sdk/mcp#mcp-tool-search>) defers by default| Every schema loads upfront in the cases under [Configure tool search](</docs/en/agent-sdk/tool-search#configure-tool-search>) **Conversation history**| Accumulates over turns| Grows with each turn: prompts, responses, tool inputs, tool outputs **Skill descriptions**| Session start, via setting sources| Short summaries; full content loads only when invoked Large tool outputs consume significant context. Reading a big file or running a command with verbose output can use thousands of tokens in a single turn. Context accumulates across turns, so longer sessions with many tool calls build up significantly more context than short ones. -### - -​ - -Automatic compaction +### Automatic compaction When the context window approaches its limit, the SDK automatically compacts the conversation: it summarizes older history to free space, keeping your most recent exchanges and key decisions intact. The SDK emits a message with `type: "system"` and `subtype: "compact_boundary"` in the stream when this happens (in Python this is a `SystemMessage`; in TypeScript it is a separate `SDKCompactBoundaryMessage` type). Compaction replaces older messages with a summary, so specific instructions from early in the conversation may not be preserved. Persistent rules belong in CLAUDE.md (loaded via [`settingSources`](</docs/en/agent-sdk/claude-code-features>)) rather than in the initial prompt, because CLAUDE.md content is re-injected on every request. You can customize compaction behavior in several ways: @@ -313,11 +245,7 @@ - Test results and error messages - Decisions made and the reasoning behind them -### - -​ - -Keep context efficient +### Keep context efficient A few strategies for long-running agents: @@ -328,21 +256,13 @@ For a detailed breakdown of per-feature context costs, see [Understand context costs](</docs/en/features-overview#understand-context-costs>). -## - -​ - -Sessions and continuity +## Sessions and continuity Each interaction with the SDK creates or continues a session. Capture the session ID from `ResultMessage.session_id` (available in both SDKs) to resume later. The TypeScript SDK also exposes it as a direct field on the init `SystemMessage`; in Python it’s nested in `SystemMessage.data`. When you resume, the full context from previous turns is restored: files that were read, analysis that was performed, and actions that were taken. You can also fork a session to branch into a different approach without modifying the original. See [Session management](</docs/en/agent-sdk/sessions>) for the full guide on resume, continue, and fork patterns. To resume sessions across stateless containers or serverless hosts, pass a [`session_store` / `sessionStore` adapter](</docs/en/agent-sdk/session-storage>) so the SDK mirrors transcripts to your own backend and another host can resume them. The Claude Code subprocess still writes to local disk first. See [Dual-write architecture](</docs/en/agent-sdk/session-storage#dual-write-architecture>) for which copy outlives a fresh session versus a run resumed from the store, and how to keep the local copy ephemeral. In Python, `ClaudeSDKClient` handles session IDs automatically across multiple calls. See the [Python SDK reference](</docs/en/agent-sdk/python#choosing-between-query-and-claudesdkclient>) for details. -## - -​ - -Handle the result +## Handle the result When the loop ends, the `ResultMessage` tells you what happened and gives you the output. The `subtype` field (available in both SDKs) is the primary way to check termination state. @@ -368,11 +288,7 @@ The result also includes a `stop_reason` field (`string | null` in TypeScript, `str | None` in Python) indicating why the model stopped generating on its final turn. Common values are `end_turn` (model finished normally), `max_tokens` (hit the output token limit), and `refusal` (the model declined the request). On error results that the loop produced, `stop_reason` carries the value from the last assistant response before the loop ended; the result Claude Code synthesizes after a session crash carries `null`. To detect refusals, check `stop_reason === "refusal"` (TypeScript) or `stop_reason == "refusal"` (Python). See [`SDKResultMessage`](</docs/en/agent-sdk/typescript#sdkresultmessage>) (TypeScript) or [`ResultMessage`](</docs/en/agent-sdk/python#resultmessage>) (Python) for the full type. -## - -​ - -Hooks +## Hooks [Hooks](</docs/en/agent-sdk/hooks>) are callbacks that fire at specific points in the loop: before a tool runs, after it returns, when the agent finishes, and so on. Some commonly used hooks are: @@ -387,11 +303,7 @@ Hooks run in your application process, not inside the agent’s context window, so they don’t consume context. Hooks can also short-circuit the loop: a `PreToolUse` hook that rejects a tool call prevents it from executing, and Claude receives the rejection message instead. Both SDKs support all the events above. The TypeScript SDK includes additional events that Python does not yet support. See [Control execution with hooks](</docs/en/agent-sdk/hooks>) for the complete event list, per-SDK availability, and the full callback API. -## - -​ - -Put it all together +## Put it all together This example combines the key concepts from this page into a single agent that fixes failing tests. It configures the agent with allowed tools (auto-approved so the agent runs autonomously), project settings, and safety limits on turns and reasoning effort. As the loop runs, it captures the session ID for potential resumption, handles the final result, and prints the total cost. Because a single-shot `query()` call raises after yielding an error result, the loop is wrapped in a try block so the script exits cleanly when a limit is hit. @@ -489,11 +401,7 @@ When the agent finishes successfully, the example prints a `Done:` line with the agent’s summary of the fix, then a line like `Cost: $0.0312`. -## - -​ - -Next steps +## Next steps Now that you understand the loop, here’s where to go depending on what you’re building:
modified Orchestrate teams of Claude Code sessions View current →
Show diff (459 lines)
--- a/agent-teams.md +++ b/agent-teams.md @@ -2,11 +2,7 @@ Agent teams let you coordinate multiple Claude Code instances working together. One session acts as the team lead, coordinating work, assigning tasks, and synthesizing results. Teammates work independently, each in its own context window, and communicate directly with each other. You can also talk to any teammate directly without going through the lead. Before you set up a team, check whether a lighter option does the job. [Subagents](</docs/en/sub-agents>) work within a single session, and with [cross-session messaging](</docs/en/cross-session-messaging>) Claude can pass findings between the sessions you run yourself. -## - -​ - -When to use agent teams +## When to use agent teams Agent teams are most effective for tasks where parallel exploration adds real value. See use case examples for full scenarios. The strongest use cases are: @@ -17,11 +13,7 @@ Agent teams add coordination overhead and use significantly more tokens than a single session. They work best when teammates can operate independently. For sequential tasks, same-file edits, or work with many dependencies, a single session or [subagents](</docs/en/sub-agents>) are more effective. -### - -​ - -Compare with subagents +### Compare with subagents Both agent teams and [subagents](</docs/en/sub-agents>) let you parallelize work, but they operate differently. For separate sessions that pass messages to each other without a team, see [cross-session messaging](</docs/en/cross-session-messaging>). @@ -37,11 +29,7 @@ Use subagents when you need quick, focused workers that report back. Use agent teams when teammates need to share findings, challenge each other, and coordinate on their own. -## - -​ - -Enable agent teams +## Enable agent teams Agent teams are disabled by default. Enable them by setting the `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` environment variable to `1`, either in your shell environment or through [settings.json](</docs/en/settings>): @@ -55,11 +43,7 @@ Enabling agent teams also changes ordinary delegation. Claude may [name a subagent](</docs/en/sub-agents#subagent-names>) on its own, and while agent teams are enabled, a subagent that Claude names launches as a teammate, so teams can form even when you didn’t ask for one. For more, see How Claude starts agent teams; to turn the behavior off, see Claude spawns teammates instead of subagents. Spawning teammates also requires an interactive session. In [non-interactive mode](</docs/en/headless>) with the `-p` flag, including Agent SDK sessions, Claude doesn’t spawn teammates, and a subagent that Claude names runs as an ordinary [subagent](</docs/en/sub-agents>) even with agent teams enabled. -## - -​ - -Start your first agent team +## Start your first agent team After enabling agent teams, describe the task and the teammates you want in natural language. Claude spawns them and coordinates work based on your prompt. This example works well because the three roles are independent and can explore the problem without waiting on each other: @@ -75,19 +59,11 @@ An idle teammate’s row stays in the panel while any teammate or subagent is still working, so you can select it to review its transcript or send it more work. Once every agent in the panel is idle, idle rows hide after 30 seconds and reappear on the teammate’s next turn; the teammate stays running and addressable while hidden. When more than three teammates are idle at once, the rows beyond the first three collapse into a single row that counts the collapsed teammates, such as `2 idle agents` when five are idle. Select it and press Enter to expand the collapsed rows, or press Esc to collapse them again. Working teammates, failed teammates, and the teammate you’re viewing always keep their own rows. If you want each teammate in its own split pane, see Choose a display mode. -## - -​ - -Control your agent team +## Control your agent team Tell the lead what you want in natural language. It handles team coordination, task assignment, and delegation based on your instructions. -### - -​ - -Choose a display mode +### Choose a display mode Agent teams support two display modes: @@ -111,11 +87,7 @@ * **tmux** : install through your system’s package manager. See the [tmux wiki](<https://github.com/tmux/tmux/wiki/Installing>) for platform-specific instructions. * **iTerm2** : install the [`it2` CLI](<https://github.com/mkusaka/it2>), then enable the Python API in **iTerm2 → Settings → General → Magic → Enable Python API**. -### - -​ - -Specify teammates and models +### Specify teammates and models Claude decides the number of teammates to spawn based on your task, or you can specify exactly what you want: @@ -140,11 +112,7 @@ By default, a teammate on the lead’s model inherits the lead’s [effort level](</docs/en/model-config#adjust-effort-level>). In split-pane mode this applies from v2.1.186; earlier versions did not pass the lead’s session effort to split-pane teammates. For a teammate on another model, see [Effort level of subagents and teammates](</docs/en/model-config#effort-level-of-subagents-and-teammates>). -### - -​ - -Have teammates plan before implementing +### Have teammates plan before implementing For complex or risky tasks, you can have teammates plan before implementing. A teammate that Claude spawns while the lead is in [plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>) also works in plan mode until its plan is ready. Switch the lead into plan mode first, then ask for the teammate: @@ -152,11 +120,7 @@ When that teammate finishes planning, it sends a plan approval request to the lead. If you haven’t changed that teammate’s permission mode since it was spawned, Claude Code approves the plan as soon as the request arrives, without the lead reviewing it. Once approved, the teammate exits plan mode and begins implementation. Claude Code passes it the lead’s current permission mode, or Manual if that’s plan mode. If you put a running in-process teammate in plan mode by pressing [`Shift+Tab`](</docs/en/permission-modes#switch-permission-modes>) while viewing its session, the lead reviews that run’s plan instead of Claude Code approving it. You aren’t asked to approve it; the lead approves it or sends it back for revision. -### - -​ - -Talk to teammates directly +### Talk to teammates directly Each teammate is a full, independent Claude Code session. You can message any teammate directly to give additional instructions, ask follow-up questions, or redirect their approach. @@ -170,11 +134,7 @@ A teammate’s model and fast mode are fixed when it spawns. -### - -​ - -Assign and claim tasks +### Assign and claim tasks The shared task list coordinates work across the team. The lead creates tasks and teammates work through them. Tasks have three states: pending, in progress, and completed. A task can also depend on other tasks and shows as blocked in the task list until they’re completed. Teammates don’t self-claim a blocked task, but you or the lead can still assign it. Agents [without the Task tools](</docs/en/tools-reference#task-tool-availability>) coordinate through messages instead of the shared task list. The lead can assign tasks explicitly, or teammates can self-claim: @@ -183,11 +143,7 @@ Task claiming uses file locking to prevent race conditions when multiple teammates try to claim the same task simultaneously. -### - -​ - -Shut down teammates +### Shut down teammates To gracefully end a teammate’s session, refer to it by name. For example, with a teammate named researcher: @@ -195,11 +151,7 @@ The lead sends a shutdown request. The teammate can approve, exiting gracefully, or reject with an explanation. The team’s shared directories are cleaned up automatically when the session ends, so there’s no separate cleanup step. See Architecture for which directories are removed and which stay on disk. -### - -​ - -Enforce quality gates with hooks +### Enforce quality gates with hooks Use [hooks](</docs/en/hooks>) to enforce rules when teammates finish work or tasks are created or completed: @@ -207,27 +159,15 @@ * [`TaskCreated`](</docs/en/hooks#taskcreated>): runs when a task is being created. Exit with code 2 to prevent creation and send feedback. * [`TaskCompleted`](</docs/en/hooks#taskcompleted>): runs when a task is being marked complete. Exit with code 2 to prevent completion and send feedback. -## - -​ - -How agent teams work +## How agent teams work This section covers the architecture and mechanics behind agent teams. If you want to start using them, see Control your agent team above. -### - -​ - -How Claude starts agent teams +### How Claude starts agent teams To start a team, ask Claude for teammates. Claude launches a teammate when it calls the [Agent tool](</docs/en/tools-reference>) with a [`name`](</docs/en/sub-agents#subagent-names>) while agent teams are enabled, unless the call is a [fork](</docs/en/sub-agents#fork-the-current-conversation>) or passes `isolation` on the call itself. Claude Code doesn’t ask you to confirm the launch. Claude also names ordinary subagents on its own so it can message them later. Those calls follow the same rule, so teams can form even when you didn’t ask for one. If you want subagents instead, turn agent teams off. -### - -​ - -Architecture +### Architecture An agent team consists of: @@ -245,11 +185,7 @@ Claude Code generates both of these automatically at session startup and updates them as teammates join, go idle, or leave. The team config holds runtime state such as session IDs and tmux pane IDs, so don’t edit it by hand or pre-author it: your changes are overwritten on the next state update. To define reusable teammate roles, use subagent definitions instead. The team config contains a `members` array with each member’s name and agent ID. The lead’s entry always carries the agent type `team-lead`. A teammate’s entry carries whatever agent type the lead named when spawning it, whether a [built-in type](</docs/en/sub-agents#built-in-subagents>) or a subagent definition, and omits the field when the lead named none. Teammates can read this file to discover other team members. There is no project-level equivalent of the team config. A file like `.claude/teams/teams.json` in your project directory is not recognized as configuration; Claude treats it as an ordinary file. -### - -​ - -Use subagent definitions for teammates +### Use subagent definitions for teammates When spawning a teammate in either display mode, you can reference a [subagent](</docs/en/sub-agents>) type from the project, user, managed, or plugin [subagent scope](</docs/en/sub-agents#choose-the-subagent-scope>). This lets you define a role once, such as a security-reviewer or test-runner, and reuse it both as a delegated subagent and as an agent team teammate. To use a subagent definition, name it when you ask Claude to spawn the teammate: @@ -268,11 +204,7 @@ When Claude messages an in-process teammate that is no longer running, Claude Code brings it back in the same session, restores any conversation saved for it, and gives it the message as its next prompt. After you resume a session, teammates aren’t brought back this way, per the resume limitation. For a teammate it brings back, Claude Code re-applies a definition that came from a project’s `.claude/agents/` directory or an `--add-dir` directory only if you’ve [trusted the folder the agent file is in](</docs/en/permissions#what-runs-before-you-trust-a-folder>). Trusting a parent folder doesn’t count. Until then, the teammate comes back with none of the definition’s tools or instructions, keeping only the tools Claude Code adds to every in-process teammate. See [the teammate’s agent definition was not restored](</docs/en/errors#teammate-agent-definition-not-restored>) for the notice text. -### - -​ - -Permissions +### Permissions To cycle a running teammate’s permission mode, press [`Shift+Tab`](</docs/en/permission-modes#switch-permission-modes>), though an in-process teammate can run in the lead’s mode instead. For a split-pane teammate, press it in its pane. For an in-process teammate, press it while viewing its session, and the teammate checks its mode when it starts its next turn. @@ -285,22 +217,14 @@ Teammate permission prompts appear in the lead session, so approve them there yourself. You don’t need to approve a teammate’s plan. -#### - -​ - -Messages between agents +#### Messages between agents When one agent sends another a message over `SendMessage`, Claude Code tells the receiving agent the message came from another Claude session, not from you. A teammate can’t approve a permission prompt or supply consent on your behalf, and a teammate that was denied an action can’t relay it to another teammate to bypass the check. The same rules apply to a message that arrives from [one of your other Claude Code sessions](</docs/en/cross-session-messaging#how-a-session-treats-an-incoming-message>), outside the team entirely. In [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>), the classifier applies two checks to messages between agents: * It treats an approval claim relayed from another agent as untrusted input rather than confirmation from you. * It reviews each message before Claude Code delivers it, whether a plain message or a structured protocol message such as a shutdown request or plan approval response. A message it blocks never reaches the recipient. -### - -​ - -Context and communication +### Context and communication Each teammate has its own context window. When spawned, a teammate loads the same project context as a regular session: CLAUDE.md, MCP servers, and skills. If you start the lead with [`--setting-sources`](</docs/en/cli-reference#cli-flags>), teammates load from the same restricted list of sources. Before v2.1.281, split-pane teammates loaded every settings source. A teammate also receives the spawn prompt from the lead. The lead’s conversation history does not carry over. **How teammates share information:** @@ -311,27 +235,15 @@ The lead assigns every teammate a name when it spawns them, and any teammate can message any other by that name. To get predictable names you can reference in later prompts, tell the lead what to call each teammate in your spawn instruction. -### - -​ - -Token usage +### Token usage Agent teams use significantly more tokens than a single session. Each teammate has its own context window, and token usage scales with the number of active teammates. For research, review, and new feature work, the extra tokens are usually worthwhile. For routine tasks, a single session is more cost-effective. See [agent team token costs](</docs/en/costs#agent-team-token-costs>) for usage guidance. An in-process teammate’s requests fall outside the main conversation’s [cache TTL bucket](</docs/en/prompt-caching#which-ttl-each-request-gets>), so its cache holds for five minutes by default, including on a Claude subscription. To keep it for an hour, set [`subagentPromptCacheTtl`](</docs/en/settings-reference#subagentpromptcachettl>) to `1h`. The API bills 1-hour cache writes at a higher rate. -## - -​ - -Use case examples +## Use case examples These examples show how agent teams handle tasks where parallel exploration adds value. -### - -​ - -Run a parallel code review +### Run a parallel code review A single reviewer tends to gravitate toward one type of issue at a time. Splitting review criteria into independent domains means security, performance, and test coverage all get thorough attention simultaneously. The prompt assigns each teammate a distinct lens so they don’t overlap: @@ -343,11 +255,7 @@ Each reviewer works from the same PR but applies a different filter. The lead synthesizes findings across all three after they finish. -### - -​ - -Investigate with competing hypotheses +### Investigate with competing hypotheses When the root cause is unclear, a single agent tends to find one plausible explanation and stop looking. The prompt fights this by making teammates explicitly adversarial: each one’s job is not only to investigate its own theory but to challenge the others’. @@ -358,17 +266,9 @@ The debate structure is the key mechanism here. Sequential investigation suffers from anchoring: once one theory is explored, subsequent investigation is biased toward it. With multiple independent investigators actively trying to disprove each other, the theory that survives is much more likely to be the actual root cause. -## - -​ - -Best practices - -### - -​ - -Give teammates enough context +## Best practices + +### Give teammates enough context Teammates load project context automatically, including CLAUDE.md, MCP servers, and skills, but they don’t inherit the lead’s conversation history. See Context and communication for details. Include task-specific details in the spawn prompt: @@ -377,11 +277,7 @@ management, and input validation. The app uses JWT tokens stored in httpOnly cookies. Report any issues with severity ratings." -### - -​ - -Choose an appropriate team size +### Choose an appropriate team size There’s no hard limit on the number of teammates, but practical constraints apply: @@ -391,11 +287,7 @@ Start with 3-5 teammates for most workflows. This balances parallel work with manageable coordination. If you have 15 independent tasks, 3 teammates is a good starting point. Scale up only when the work benefits from having teammates work simultaneously. Three focused teammates often outperform five scattered ones. -### - -​ - -Size tasks appropriately +### Size tasks appropriately * **Too small** : coordination overhead exceeds the benefit * **Too large** : teammates work too long without check-ins, increasing risk of wasted effort @@ -403,51 +295,27 @@ The lead breaks work into tasks and assigns them to teammates automatically. If it isn’t creating enough tasks, ask it to split the work into smaller pieces. Having 5-6 tasks per teammate keeps everyone productive and lets the lead reassign work if someone gets stuck. -### - -​ - -Wait for teammates to finish +### Wait for teammates to finish Sometimes the lead starts implementing tasks itself instead of waiting for teammates. If you notice this: Wait for your teammates to complete their tasks before proceeding -### - -​ - -Start with research and review +### Start with research and review If you’re new to agent teams, start with tasks that have clear boundaries and don’t require writing code: reviewing a PR, researching a library, or investigating a bug. These tasks show the value of parallel exploration without the coordination challenges that come with parallel implementation. -### - -​ - -Avoid file conflicts +### Avoid file conflicts Two teammates editing the same file leads to overwrites. Break the work so each teammate owns a different set of files. -### - -​ - -Monitor and steer +### Monitor and steer Check in on teammates’ progress, redirect approaches that aren’t working, and synthesize findings as they come in. Letting a team run unattended for too long increases the risk of wasted effort. -## - -​ - -Troubleshooting - -### - -​ - -Teammates not appearing +## Troubleshooting + +### Teammates not appearing If teammates aren’t appearing after you ask Claude to spawn them: @@ -460,11 +328,7 @@ * For iTerm2, verify the `it2` CLI is installed and the Python API is enabled in iTerm2 preferences. -### - -​ - -Claude spawns teammates instead of subagents +### Claude spawns teammates instead of subagents While agent teams are enabled, a subagent that Claude names in the lead’s session launches as a teammate. Claude can name subagents on its own, so this can happen during delegation you never framed as team work. To make named subagents launch as subagents again, turn agent teams off by setting `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` to `0`: @@ -483,19 +347,11 @@ After the change, Claude may still name subagents, and the name keeps working as a [`SendMessage` address](</docs/en/sub-agents#resume-subagents>). Claude receives each subagent’s result when it completes. -### - -​ - -Too many permission prompts +### Too many permission prompts Teammate permission requests bubble up to the lead, which can create friction. Pre-approve common operations in your [permission settings](</docs/en/permissions>) before spawning teammates to reduce interruptions. -### - -​ - -Agents stopping early +### Agents stopping early Teammates may stop after encountering errors instead of recovering. Check their output by selecting the teammate in the agent panel and pressing Enter in in-process mode, or by clicking the pane in split mode, then either: @@ -504,22 +360,14 @@ A message from the lead or another teammate wakes an in-process teammate that is waiting to retry a failed API request, so it retries immediately instead of waiting for the full retry delay. The lead can stop early too, deciding the team is finished before all tasks are actually complete. If that happens, tell it to keep going. -### - -​ - -Orphaned tmux sessions +### Orphaned tmux sessions If a tmux session persists after the Claude Code session ends, it may not have been fully cleaned up. List sessions and end the one created by the team: tmux ls tmux kill-session -t <session-name> -## - -​ - -Limitations +## Limitations Agent teams are experimental. Current limitations to be aware of: @@ -533,11 +381,7 @@ * **No per-teammate permission modes at spawn** : teammates start with the permission mode described under Permissions. * **Split panes require tmux or iTerm2** : the default in-process mode works in any terminal. Split-pane mode isn’t supported in VS Code’s integrated terminal, Windows Terminal, or Ghostty. -## - -​ - -Next steps +## Next steps Explore related approaches for parallel work and delegation:
modified Manage multiple agents with agent view View current →
Show diff (732 lines)
--- a/agent-view.md +++ b/agent-view.md @@ -2,11 +2,7 @@ Agent view is in research preview. The interface and keyboard shortcuts may change as the feature evolves. -## - -​ - -Quick start +## Quick start This walkthrough covers the core agent view loop: dispatch a task, watch its row update as Claude works, peek to check on it and reply, and attach for the full conversation. The session you dispatch keeps running after you close agent view, so you can leave and come back to it. @@ -52,11 +48,7 @@ The waiting count briefly changes color when it goes up or down and when a background session finishes successfully. If you turn on [`prefersReducedMotion`](</docs/en/settings-reference#prefersreducedmotion>), you see neither the color change nor the `done` count. In [screen reader mode](</docs/en/accessibility>), the `←` hint and its counts are hidden. -### - -​ - -Open agent view by default +### Open agent view by default To have `claude` with no arguments open agent view instead of a new conversation, turn on a `/config` setting. @@ -80,11 +72,7 @@ To start a regular session while the setting is on, pass a prompt: `claude "fix the login test"`. To turn the setting off, run `/config defaultToAgentsView=false` in a regular session or in one you attach to from agent view. -## - -​ - -Monitor sessions with agent view +## Monitor sessions with agent view Run `claude agents` to open agent view. It takes over the full terminal and lists every session grouped by state, with pinned sessions and the ones that need you at the top. Each row shows the session’s name, current activity, and its age, counted from when the session was created; a finished session’s age freezes at how long the run took. The name is tinted with the color set by [`/color`](</docs/en/commands>) in that session, including when you background a session with `←` or `/background`. By default the list shows every background session you’ve started, across all your projects. A session working in one repository and another in a different worktree both appear here, regardless of which directory you opened agent view from. To narrow the list to one project, pass `--cwd`: @@ -110,11 +98,7 @@ ∙ sound effects 14 SFX exported to assets/audio 4h … 6 more -### - -​ - -Read session state +### Read session state Each row starts with an icon whose color and animation show the session’s state: @@ -137,27 +121,15 @@ The `#N` or `!N` label that can appear at the right edge of a row is a link to the session’s pull request or merge request, not part of the state icon. The terminal tab title shows the awaiting-input count while agent view is open: `2 awaiting input · claude agents` when sessions need input, or `claude agents` when none do. To read session state from a script or another program, use `claude agents --json` rather than the files under `~/.claude/jobs/`. While agent view is open, Claude Code also sends a notification through your configured [terminal notification channel](</docs/en/terminal-config#get-a-terminal-bell-or-notification>) when a local background session starts needing your input, finishes, or fails. Sessions that run on a schedule, such as [`/loop`](</docs/en/scheduled-tasks>) sessions, notify only when they need your input. Notifications use the same [`preferredNotifChannel` setting](</docs/en/settings-reference#preferrednotifchannel>) as the rest of Claude Code and fire the [`Notification` hook](</docs/en/hooks#notification>) with the `agent_needs_input` or `agent_completed` type. Background sessions don’t need any terminal open to keep working. A separate supervisor process runs them, so you can close agent view, close your shell, or start a new interactive session and your dispatched work keeps going. Session state persists on disk through auto-updates and supervisor restarts. Sessions are also preserved when your machine sleeps. Their processes resume on wake and the supervisor reconnects to them instead of treating the time gap as idle. Shutting down still stops running sessions; see Sessions show as failed or stopped after shutdown for how to recover them. A session that was mid-response when the machine slept can come back unresponsive. When you open a session that has stopped responding, the supervisor restarts its process and the session continues the interrupted response from where it left off. -### - -​ - -Row summaries +### Row summaries The one-line summary in each row is generated by a [Haiku-class model](</docs/en/model-config>) so the row can tell you what the session is doing, what it needs, or what it produced without opening the transcript. While a session is actively working, the row text updates at most once every 15 seconds from the session’s own recent output without sending a model request, and the model writes a fresh summary when each turn ends. A working row shows what the session says it’s doing, and a blocked row shows the question it’s asking. During a long turn, the model also rewrites the summary every few minutes so a busy row doesn’t keep showing an outdated one. The summary text fills the row’s remaining width; open the peek panel to read a sentence the terminal edge clips. When the list is grouped by directory, the summary opens with the session’s state as a colored word, such as `Needs input · double jump or wall climb?`. In the default state grouping, the group header already names the state, so the row shows only the summary. -#### - -​ - -Cost of row summaries +#### Cost of row summaries The end-of-turn summary and each mid-turn rewrite are one short request through your normal provider, billed and handled under the same [data usage terms](</docs/en/data-usage>) as the session itself. On a third-party provider or gateway, summaries use the model you set in [`ANTHROPIC_DEFAULT_HAIKU_MODEL`](</docs/en/model-config#environment-variables>). With it unset, they use your provider’s model for background tasks: see [Amazon Bedrock](</docs/en/amazon-bedrock#4-pin-model-versions>), [Google Cloud’s Agent Platform](</docs/en/google-vertex-ai#5-pin-model-versions>), [Microsoft Foundry](</docs/en/microsoft-foundry#4-pin-model-versions>), or your [gateway](</docs/en/llm-gateway-protocol#requests-and-defaults-by-connection-method>). -### - -​ - -Pull request status +### Pull request status When a session opens a pull request, Claude Code adds a label at the right edge of the row, linked to the pull request: @@ -182,11 +154,7 @@ For a task that ends in a pull request, check this label for the result: review and merge the pull request when its number turns green. -### - -​ - -Peek and reply +### Peek and reply Press `Space` on a selected row to open the peek panel. It opens with the sentence the row truncates at the terminal edge, and which sentence that is depends on the session’s state: @@ -213,19 +181,11 @@ When a [`PermissionRequest`](</docs/en/hooks#permissionrequest>) or [`PreToolUse`](</docs/en/hooks#pretooluse>) hook returns output Claude Code can’t validate for the call the session is asking about, the row shows the hook event and `hook output invalid:` with the validation error before the pending request’s text. For a hook that fails another way, the row says the hook failed. The session still waits on the same request. When a reply can’t be delivered, the error message says whether it was saved. A reply prefixed with `!` or `/` is never saved. Claude Code sends a saved reply as the session’s next prompt the next time you restart the session; send any other reply again. With [voice dictation](</docs/en/voice-dictation>) enabled in [hold mode](</docs/en/voice-dictation#hold-to-record>), hold your push-to-talk key while the reply input is focused to dictate a reply instead of typing it. The same works in the dispatch input at the bottom of agent view. Use `↑` and `↓` to peek at adjacent sessions without closing the panel, or `→` to attach. -### - -​ - -Attach to a session +### Attach to a session Press `Enter` or `→` on a selected row to attach. Agent view is replaced by the full interactive session. When you attach, Claude posts a short recap of what happened while you were away. While attached, the session behaves like any other Claude Code session: [commands](</docs/en/commands>), keyboard shortcuts, and features all work, with the exceptions below. While you’re attached, `/install-github-app` and the [`/mcp`](</docs/en/mcp>) settings list work normally, since a human at the terminal can complete their dialogs. When nobody is attached, these commands can’t open their dialogs, so the session appears under `Needs input` in agent view with a row such as `open this session to manage MCP servers`, and the transcript reply says the same. Attach and run the command again to continue; the needs-input row clears when you attach. `/mcp reconnect <server>`, `/mcp enable`, and `/mcp disable` work without attaching either way. Attached sessions always render in [fullscreen mode](</docs/en/fullscreen>), regardless of your `tui` setting, because a background session has no terminal scrollback to append to. Scroll with `PgUp`, `PgDn`, or the mouse wheel, and press `Ctrl+O` for transcript mode. Your terminal’s native scroll and tmux copy mode show only the current viewport, the same as when you run any fullscreen application. An attached session doesn’t [report its status to your terminal](</docs/en/terminal-config#see-session-status-in-your-terminal>). Press `←` on an empty prompt, or run `/exit`, to detach and return to agent view, whether you opened the session from agent view or with `claude attach <id>` from your shell. `←` also detaches while the [`/btw` overlay](</docs/en/interactive-mode#side-questions-with-%2Fbtw>) is open. Requires Claude Code v2.1.257 or later. A side question that’s still answering keeps running while you’re away. The next time you attach, the overlay reopens with it, or with its answer. On Windows, if you press `←` within about half a second of attaching, Claude Code shows `Ambiguous ←, press again to detach`, because in that window the terminal can redeliver a press from before you attached. Press `←` again to detach. `Ctrl+Z` also detaches but goes back to where you started instead: agent view if you attached from there, or your shell if you ran `claude attach`. Use `Ctrl+Z` when a dialog has focus and isn’t responding to `←`. `Ctrl+C` keeps its standard interrupt behavior while attached: it cancels a running response or `!` shell command rather than detaching. Pressing `Ctrl+C` twice on an empty prompt detaches. Detaching never stops a background session: `←`, `Ctrl+Z`, `/exit`, and double `Ctrl+C` or double `Ctrl+D` all leave it running. If you detach while a `/loop` is waiting for its next iteration, the loop keeps running and that iteration starts on schedule without you. To stop the loop before you detach, see [Stop a loop](</docs/en/scheduled-tasks#stop-a-loop>). To end a session from inside it, run `/stop`. -#### - -​ - -Switch sessions without leaving the terminal +#### Switch sessions without leaving the terminal In a session running in the foreground, one you started in the terminal rather than attached to from agent view, pressing `←` on an empty prompt backgrounds it and opens agent view with that row selected, so you can switch sessions without leaving the terminal. The same single press detaches an attached session. If you press `←` right after you delete the last of the prompt’s text or move through prompt history, Claude Code asks you to confirm: the first press shows `Press ← again to open agents`, or `Press ← again to go back to agents` in an attached session, and the second press switches. When `←` backgrounds a foreground session, agent view shows `Your conversation moved to the background` above the list, with that session’s row already selected. From there: @@ -252,11 +212,7 @@ In both cases the text you typed is kept in [prompt history](</docs/en/interactive-mode#command-history>). To send it again, open the backgrounded session and press `↑` at its prompt to bring the text back. -### - -​ - -Organize the list +### Organize the list Agent view groups sessions so the ones that need input are at the top, with `Ready for review` and `Needs input` above `Working` and `Completed`. These group names don’t map one-to-one to the states above: a session moves to `Ready for review` when it has an open pull request that needs review or has failing checks, and `Completed` collects finished, failed, and stopped sessions together. Press `Ctrl+S` to group by directory instead. Your choice persists across runs. Within a group: @@ -268,11 +224,7 @@ Pressing `Ctrl+X` on a group header deletes every session in that group after confirmation. Except in the kept cases covered in What deleting a session removes, deleting removes the session from the list. A worktree Claude created for it is removed, kept, or left in place depending on how you delete and what the worktree holds. The conversation transcript stays on your local machine, available through `claude --resume`. Completed sessions that don’t fit on screen fold into a `… N more` row. The `Completed` group fills the vertical space left after the live groups. On a short terminal, the header compacts to a single summary line so sessions that are working or need input stay visible. -#### - -​ - -Bring back a past session +#### Bring back a past session To bring a session back, type `/resume` in the dispatch input. A picker opens with past sessions of the repository you opened agent view from, newest first, including sessions you deleted from the list. Sessions that already have a row aren’t listed. Press `Enter` to resume the selected session as a background session, so it rejoins the list as a row. `/resume` fails with `isn't available in agent view` when: @@ -283,11 +235,7 @@ If you typed anything after `/resume`, retype without it. If you used one of those flags, run `claude agents` in your shell without it, then type `/resume` alone. -### - -​ - -Filter sessions +### Filter sessions Start the dispatch input with one of these filters to narrow the list as you type: @@ -302,11 +250,7 @@ To combine filters, start with `a:`, `s:`, `n:`, or `o:` and add more, separated by spaces. The list shows the sessions that match all of them. For example, `s:blocked a:reviewer` lists the `reviewer` sessions that are waiting on you. While a filter is active, groups you collapsed expand to show their matches and a match is selected, so pressing `Enter` opens it. Clear the input to remove the filter, and those groups collapse again. -### - -​ - -Keyboard shortcuts +### Keyboard shortcuts Press `?` in agent view to see shortcuts in context. The table below summarizes them. @@ -337,19 +281,11 @@ The shortcuts that have an action in the [`Agents` context](</docs/en/keybindings#agents-actions>) follow your [`keybindings.json`](</docs/en/keybindings>). So does `Ctrl+G`, through the `Chat` context’s `chat:externalEditor` binding. -## - -​ - -Dispatch new agents +## Dispatch new agents You can dispatch new background sessions from agent view, send or copy an existing interactive session to the background, or start one directly from the shell. -### - -​ - -Dispatch an agent 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: @@ -372,11 +308,7 @@ Skills, your own commands, and prompt-expanding built-ins such as `/init` are sent to a new background session as its first prompt. The hint `isn't available in agent view` means the built-in command you entered didn’t run. To run it, attach to a session and enter it there. Everything you typed stays in the input next to the hint so you can edit it. Packaging a recurring task as a [skill](</docs/en/skills>) lets you start the same workflow from agent view repeatedly without retyping the prompt. When the same `@name` matches both a subagent and a sibling repository, the subagent takes precedence. The bare first-word match also applies, so a prompt that happens to begin with one of your subagent names dispatches that subagent rather than treating the word as plain text. Use the `@` form when you want to be explicit, or start the prompt with a different word to avoid the match. -#### - -​ - -Dispatch to a specific directory +#### Dispatch to a specific directory A new session runs in the directory you opened agent view from. To target a different directory, use any of these: @@ -390,27 +322,15 @@ When agent view is grouped by directory, dispatching sends the prompt to the selected row’s directory, so you can select a group and dispatch into it without retyping the path. -### - -​ - -Send or copy a session to the background +### 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. -#### - -​ - -Send the session to the background +#### Send the session to the background Run `/background` or its alias `/bg` to move the current conversation into a background session. Pass a prompt such as `/bg run the test suite and fix any failures` to give one more instruction first. If Claude is responding when you run `/bg`, the response continues in the background session. If you exit a session while some kinds of background work are running, such as subagents or workflows, a `Background work is running` dialog warns that the work stops. Choose `Move to background and exit` to background the session the same way `/background` does and return to your shell. The option isn’t shown when agent view is turned off. If a background session on the list already has the conversation’s name, Claude Code numbers the new row’s name, such as `my-session (2)`, and leaves the existing row’s name alone. To rename the new row, select it in agent view and press `Ctrl+R`. -#### - -​ - -Copy the session with /fork +#### Copy the session with /fork Run `/fork` to copy the current conversation into a new background session while the original keeps running. The copy starts with everything in the conversation up to that point; see the bullets below for where the copy runs. It also carries over the model, permission mode, effort level, and any directories or “don’t ask again” permission grants you added during the session. The copy appears as its own row in agent view. After the fork, the two conversations are independent: nothing the copy does enters the original conversation on its own, though in sessions where [cross-session messaging](</docs/en/cross-session-messaging>) is enabled, either session’s Claude can explicitly message the other. When agent view is turned off, `/fork` starts a [forked subagent](</docs/en/sub-agents#fork-the-current-conversation>) instead of copying the session. @@ -431,11 +351,7 @@ Sessions started with launch flags the copy wouldn’t inherit, such as a replaced system prompt or a `--tools` allowlist, can’t be forked; Claude Code says so instead of making a partial copy. A session dispatched from agent view forks normally: the copy is launched with the same [agent definition](</docs/en/sub-agents>) and appended instructions as the session it came from. -#### - -​ - -What carries over when you background +#### What carries over when you background When you background the session, each kind of in-flight background work either carries over to the background session, continues only when Claude relaunches it there, or stops: @@ -459,11 +375,7 @@ If a [dynamic workflow](</docs/en/workflows>) hasn’t continued after you backgrounded its session, ask Claude to [relaunch the workflow](</docs/en/workflows#resume-after-you-leave-the-session>). The run continues only when Claude relaunches it in the background session, and Claude Code can ask you to approve that relaunch first. The session’s conversation shows a notice that the workflow `could not be resumed`. When Claude relaunches the workflow, any of its subagents that were still running when you backgrounded the session start over and spend their tokens again. If you press `←` or run `/background` while any are still running, the `Background this session?` dialog says how many. To let them finish first, choose `Stay`. -### - -​ - -Dispatch an agent 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: @@ -489,11 +401,7 @@ claude logs 7c5dcf5d show recent output claude stop 7c5dcf5d stop this session -#### - -​ - -Prompts that contain `--bg` +#### Prompts that contain `--bg` A prompt that mentions `--bg` or `--background` is delivered as typed, and so is a reply of `--bg` that you send to a background session. For example, this command starts one background session, and the second `--bg` is part of its prompt: @@ -501,11 +409,7 @@ Claude Code reads a whole argument as the flag only where a flag can stand: before any bare `--` separator and not where another flag expects its value. Put the flag first, as in `claude --bg "<prompt>"`. Where the position is ambiguous, such as after a run of combined short flags, Claude Code starts nothing. It exits with [`Couldn't tell whether --bg is a flag or text here`](</docs/en/errors#couldnt-tell-whether-bg-is-a-flag-or-text>) instead. -#### - -​ - -Run a shell command +#### Run a shell command To run a shell command as a background job instead of a Claude session, pass `--exec`. The following example runs `pytest -x` as a background job: @@ -513,11 +417,7 @@ From agent view, dispatch the same kind of job by typing `!` as the first character of the dispatch input: the `!` shows as a prefix, everything after it is the command, and `Enter` starts the job. The command runs as a PTY-backed job and appears as a row in agent view, with the most recent line of output as its status. A shell job runs the command in place of Claude, so no model is invoked and the output isn’t sent to any session. To see the output, attach to the row, press `Space` to peek without attaching, or run `claude logs <id>` from your shell. The captured output stays in memory and isn’t written to disk. The row and its output clean up automatically about five minutes after the command exits, so read it before then if you need the result. -### - -​ - -How file edits are isolated +### How file edits are isolated When you dispatch a background session from agent view or start one with `claude --bg`, the session starts in your working directory. Before editing files, Claude moves the session into an isolated [git worktree](</docs/en/worktrees>) under `.claude/worktrees/`, so parallel sessions can read the same checkout but each writes to its own. Once the session is in its worktree, Claude Code [enforces worktree isolation](</docs/en/worktrees#how-claude-code-enforces-isolation>) for the session and for any subagents it spawns. Claude skips the worktree when: @@ -544,11 +444,7 @@ A session editing a checkout it didn’t isolate itself still asks before committing or switching branches. This applies when isolation is set to `"none"`, when the worktree move failed, or when the session started inside a worktree that already existed. Whatever the task, Claude ends the job with a report saying what it did and where the work is: a path, a branch, a pull request, or the answer itself. -#### - -​ - -What deleting a session removes +#### What deleting a session removes Delete a session with `Ctrl+X` twice in agent view or with `claude rm`. Except in the kept cases below, the session leaves the list. Its transcript stays on your machine through `claude --resume`, and the removal survives supervisor restarts. What happens to a worktree Claude created for the session: @@ -576,11 +472,7 @@ Either path keeps a directory that another finished session’s records name. -### - -​ - -Set the model, effort, and fast mode +### Set the model, effort, and fast mode In agent view, type `/model`, `/effort`, or `/fast` in the dispatch input and press `Enter`, and the sessions you dispatch afterward start with what you set. Your choice stays with that agent view window and isn’t saved to a settings file. `/effort` and `/fast` require Claude Code v2.1.299 or later, as does `/model` typed with nothing after it. Give the value after the command, or type the command alone to choose one from a list: @@ -601,27 +493,15 @@ * Attach to a running session and run `/model` to switch. A pick from the picker, or a typed `/model <name>`, saves as your default for new sessions unless you press `s` in the picker for a session-only switch. A session-only switch persists if the session is respawned. * Dispatch a [subagent](</docs/en/sub-agents>) that sets `model` in its frontmatter, by starting the prompt with its name or mentioning `@name`. While a `/model` choice in the dispatch input applies, the subagent’s `model` isn’t used, so enter `/model default` there. If you launched with `claude agents --model`, the subagent’s isn’t used either, so run `claude agents` in your shell without `--model`. -### - -​ - -Permission mode, model, and effort +### Permission mode, model, and effort A background session takes its settings, provider, permission mode, model, and effort from where and how you dispatched it. The subsections below cover each source, and what persists when the supervisor restarts the session. -#### - -​ - -Settings and provider +#### Settings and provider A background session reads its [settings](</docs/en/settings>) from the directory it runs in, the same as if you had started `claude` there with the configuration flags it carried over. This includes [`env` values](</docs/en/settings-reference#env>) in project settings, so an `ANTHROPIC_MODEL` or provider variable set there applies to every background session in that directory. A background session also runs with the `PATH` of the shell you dispatched it from, so the commands it runs find the same tools your terminal does. It keeps that shell’s cloud provider selection too, such as `CLAUDE_CODE_USE_BEDROCK` or `CLAUDE_CODE_USE_VERTEX`, along with its `ANTHROPIC_DEFAULT_*_MODEL` aliases and any [`CLAUDE_CODE_EXTRA_BODY`](</docs/en/env-vars>) override you exported there. -#### - -​ - -LLM gateway +#### LLM gateway If you route Claude Code through an [LLM gateway](</docs/en/llm-gateway>), put the gateway variables in a settings file’s `env` block rather than exporting them in your shell, and background sessions read them with the rest of their settings. [Set in a settings file](</docs/en/llm-gateway-connect#set-in-a-settings-file>) shows the block and which settings file to use for the credential. If you export a gateway `ANTHROPIC_BASE_URL` only in your shell instead, it reaches a background session, together with the `ANTHROPIC_CUSTOM_HEADERS` and credential you exported with it, only when the supervisor was itself started from a shell that exported the same gateway, and only in these cases: @@ -632,11 +512,7 @@ Claude Code forwards a gateway in front of a cloud provider. If the shell you dispatch from selects the provider and exports its gateway endpoint with its auth-bypass flag, Claude Code forwards the endpoint-and-flag pair to the session under the conditions that apply to `ANTHROPIC_BASE_URL`, together with `ANTHROPIC_CUSTOM_HEADERS`. For example, export `CLAUDE_CODE_USE_VERTEX=1` with `ANTHROPIC_VERTEX_BASE_URL` and `CLAUDE_CODE_SKIP_VERTEX_AUTH=1`, and Claude Code forwards that endpoint and flag. Claude Code applies a forwarded gateway to that session’s running process only and never writes it to disk. -#### - -​ - -Permission mode +#### Permission mode * **Backgrounded with`/bg` or `←`**: Claude Code keeps the [permission mode](</docs/en/permissions>) the session was in, so one you switched to `acceptEdits` or `auto` stays there after detaching * **Dispatched from`claude agents` started in a shell, or with `claude --bg`**: the new session starts the way a new `claude` session in that directory would, unless you dispatched it from an agent view you opened with dispatch defaults. [Which permission mode a session starts in](</docs/en/permission-modes#which-mode-a-session-starts-in>) lists the order @@ -648,11 +524,7 @@ When Claude Code refuses a source’s mode as too permissive, the next source in the list decides. For example, if you dispatch from a plan-mode session into a directory whose checked-in settings ask for `acceptEdits`, the new session starts in plan mode. If you move that `defaultMode` to `~/.claude/settings.json`, it applies regardless of the permission mode of the session you came from. Permissiveness runs plan, then Manual and `dontAsk`, then `acceptEdits` and auto, which each count as more permissive than the other, then `bypassPermissions`. -#### - -​ - -Dispatch defaults +#### Dispatch defaults To set defaults for every session you dispatch from agent view, pass any of `--permission-mode`, `--model`, `--effort`, or `--agent` when opening it: @@ -660,19 +532,11 @@ `--effort` here accepts the same values as the [top-level `--effort` flag](</docs/en/cli-reference#cli-flags>), including `ultracode`. `--agent` sets the [subagent](</docs/en/sub-agents>) used when a dispatch prompt doesn’t name one, either with `@name` or as the first word. It defaults to the [`agent` setting](</docs/en/settings-reference#agent>) if one is set, otherwise the built-in catch-all `claude` agent. Naming a subagent in the dispatch input overrides both. `claude agents` also accepts `--dangerously-skip-permissions` as shorthand for `--permission-mode bypassPermissions`, and `--allow-dangerously-skip-permissions` to make `bypassPermissions` available in each dispatched session’s `Shift+Tab` cycle without starting in that mode. Both match the [top-level CLI flags](</docs/en/cli-reference>). Pass `--restricted` to start every session you dispatch from the view in [restricted mode](</docs/en/cli-reference#cli-flags>), as if each were launched with the top-level `--restricted` flag. Requires Claude Code v2.1.248 or later. The active defaults appear in the footer below the dispatch input. A background session started in `bypassPermissions` mode needs your [acceptance of the bypass disclaimer](</docs/en/permission-modes#skip-all-checks-with-bypasspermissions-mode>) on record, since that mode lets a session you aren’t watching act without approval. Passing `--dangerously-skip-permissions` or `--permission-mode bypassPermissions` to `claude agents` shows the same disclaimer when you haven’t accepted it before, and accepting applies `bypassPermissions` to the sessions you launch from the view. Passing `--allow-dangerously-skip-permissions` shows the same disclaimer too, and accepting makes `bypassPermissions` available in the `Shift+Tab` cycle of those sessions without starting them in it. -#### - -​ - -What persists across restarts +#### What persists across restarts The permission mode, model, and effort you chose for a background session, along with the configuration flags it carries, all persist when the supervisor later stops and restarts its process. A model or effort you changed mid-session with `/model` or `/effort` is kept too. If the session took its effort from your settings rather than from `--effort` or `/effort`, Claude Code reads your settings again each time it starts a process for the session. After you edit the saved effort in `settings.json`, the change reaches sessions you background with `←` or `/bg`, and their later restarts. The saved effort is the [`effortLevel`](</docs/en/settings-reference#effortlevel>) key or a [`modelSettings`](</docs/en/settings-reference#modelsettings>) entry. Claude Code also keeps a name you set with [`/rename`](</docs/en/commands>) or `Ctrl+R` across that restart, so you can still run [`claude --resume <name>`](</docs/en/sessions#name-your-sessions>) to reach the session. A prompt you stashed with [`Ctrl+S`](</docs/en/interactive-mode#general-controls>) while attached is kept with the session too. Reopen the session after its process was stopped or restarted, and press `Ctrl+S` to restore the stashed text. Pasted content in the stash doesn’t survive the restart. -### - -​ - -Settings, plugins, and MCP servers +### Settings, plugins, and MCP servers Agent view accepts the same configuration flags as `claude` for loading settings, plugins, MCP servers, and additional directories. Agent view applies `--settings`, `--setting-sources`, and `--plugin-dir` to itself and passes every configuration flag through to the sessions you dispatch from it, so a plugin or MCP server you load this way is available in those sessions. @@ -691,11 +555,7 @@ `--settings` accepts a file path or an inline JSON string. A file path must point to an existing file; Claude Code exits with a `Settings file not found` error if it doesn’t. -## - -​ - -Manage sessions from the shell +## Manage sessions from the shell Every background session has a short ID you can use from the shell. The ID is printed when you start a session with `claude --bg`, and each session’s ID is its directory name under `~/.claude/jobs/`. These commands are useful for scripting or when you don’t want to open agent view. @@ -718,11 +578,7 @@ `claude attach` and `claude logs` can take part of a session’s name in place of the ID, as in `claude logs "auth refactor"`. `claude attach` opens a session by name only while its process is running, so pass the ID instead to restart a stopped session. Passing a name requires Claude Code v2.1.290 or later. -### - -​ - -List sessions as JSON +### List sessions as JSON `claude agents --json` prints active sessions as a JSON array and exits: every live session, plus background sessions that are still working or blocked even when their process has exited. Add `--all` to also include completed background sessions, and `--cwd <path>` to limit the list to sessions started under that directory. Each entry describes one session: @@ -735,11 +591,7 @@ `waitingFor`| When `status` is `waiting`| What the session is blocked on: `permission prompt` for an approval, `input needed` for a question from Claude or an MCP server’s input request, `sandbox request`, `worker request`, or `dialog open` `sessionId`, `name`| When set| `sessionId` is the full session UUID, usable with [`claude --resume`](</docs/en/sessions>). An interactive session’s `name` is its [default display name](</docs/en/sessions#name-your-sessions>) until you name the session or accept a plan in it -### - -​ - -Read session state from a script +### Read session state from a script `claude agents --json` is the supported way to read session state from outside Claude Code, for example from a status bar, a scheduler, or another Claude session that supervises background work. Poll `claude agents --json --all`, which keeps listing sessions whose process has exited, and read each entry’s `state`, `status`, and `waitingFor`. @@ -752,19 +604,11 @@ A session that finished its turn and is waiting for your next instruction reads `done`, not `blocked`. `blocked` always means the session needs something from you before it can continue. The files under `~/.claude/jobs/<id>/` are not a stable interface. Values that a session or another program writes to `state`, `detail`, `tempo`, or `needs` are replaced on the next update. If you want a session to report progress in its own words, have it write a file of its own, for example under `$CLAUDE_JOB_DIR/tmp`, instead of editing `state.json`. -## - -​ - -How background sessions are hosted +## How background sessions are hosted Claude Code treats every session listed in agent view as a background session, whether or not you’re currently attached to it. By contrast, a session started by running `claude` directly is tied to that terminal and ends when it closes, unless you send it to the background. To check which kind of session you’re in, run [`/status`](</docs/en/commands>). The `Session kind` row reads `background job · attached` or `background job · unattended` in a background session, depending on whether a terminal is attached, and `interactive` in any other session. -### - -​ - -The supervisor process +### The supervisor process The supervisor is a background service that runs your background sessions so they keep working after you close agent view or your terminal. Claude Code starts it the first time you background a session or open agent view, and you don’t need to manage it yourself. Each session is its own Claude Code process under the supervisor, and what happens to that process depends on the session’s state: @@ -776,11 +620,7 @@ When a session’s process stops or restarts, the background shell commands and background subagents Claude started in it carry over to its next process. A dynamic workflow continues only when Claude relaunches it. Running monitors and shell commands a subagent started stop with the process. If you delete the session, everything it carried over stops. To stop all of it with the process instead, set [`CLAUDE_CODE_DISABLE_BG_EXIT_HANDOFF`](</docs/en/env-vars#variables>) to `1`. The supervisor and its sessions authenticate with the same stored credentials as your interactive sessions. For which settings and shell variables reach a session, including `PATH`, see Settings and provider. For gateway endpoints, see LLM gateway. -#### - -​ - -Keep sessions running after the supervisor stops +#### Keep sessions running after the supervisor stops If agent view prints this notice as it exits, no supervisor is running: @@ -788,11 +628,7 @@ Run `claude agents` in your shell within that minute to start a new supervisor and keep your sessions running. If the minute passes first, the sessions stop, but their saved conversations stay on disk. To restart a session from its saved conversation, attach or reply to it, as described under Sessions show as failed or stopped after shutdown. -### - -​ - -Where state is stored +### Where state is stored Session state is stored under your Claude Code config directory. If you set [`CLAUDE_CONFIG_DIR`](</docs/en/env-vars>), the supervisor uses that directory instead of `~/.claude` and runs as a separate instance with its own sessions. @@ -805,41 +641,21 @@ Each background session has the `CLAUDE_JOB_DIR` environment variable set to its `~/.claude/jobs/<id>` directory, so shell commands the session runs can write temporary files to `$CLAUDE_JOB_DIR/tmp` without colliding with parallel sessions. To inspect this state without reading the files directly, run `claude daemon status`. It reports whether the supervisor is reachable, its process ID and version, the socket directory, and how many background sessions are live. The command also warns when the running supervisor is on a different version than the `claude` you invoked, which happens after an update the supervisor hasn’t restarted into yet. The warning shows both versions and tells you to run `claude daemon stop --any` to pick up the new version. -### - -​ - -Turn off agent view +### Turn off agent view To turn off background agents and agent view entirely, set the `disableAgentView` [setting](</docs/en/settings>) to `true` or set the `CLAUDE_CODE_DISABLE_AGENT_VIEW` environment variable. Administrators can enforce this through [managed settings](</docs/en/managed-settings>). -## - -​ - -Troubleshooting - -### - -​ - -`claude agents` lists subagents instead of opening agent view +## Troubleshooting + +### `claude agents` lists subagents instead of opening agent view If `claude agents` prints a count followed by your configured subagents and then exits, agent view is unavailable in your environment. Run `claude update` to install the latest version. If agent view still doesn’t open after updating, check whether it has been turned off by a setting or environment variable. -### - -​ - -Agent view opens with no sessions +### Agent view opens with no sessions Before you dispatch your first session, agent view shows the empty section headers with a description under each, plus a one-line explanation above the input, in place of the session list. Type a prompt in the input at the bottom and press `Enter` to dispatch your first session. -### - -​ - -Backgrounding shows a `Background this session?` dialog +### Backgrounding shows a `Background this session?` dialog When you press `←` to background a session, a `Background this session?` dialog means the session has in-flight background work that would stop, be interrupted, or keep running unattended: @@ -849,27 +665,15 @@ Run `/tasks` to see everything that’s running, then confirm to background anyway or choose `Stay` to let the work finish first. See What carries over when you background for which kinds of work carry over and which Claude Code stops. -### - -​ - -The conversation says a background agent `was carried into this session and not resumed` +### The conversation says a background agent `was carried into this session and not resumed` This notice names a background [subagent](</docs/en/sub-agents>) that isn’t running in this session. Claude sees the notice and replies on its own, so you don’t need to prompt it. If you still need that subagent’s work after reading Claude’s reply, ask Claude for it. -### - -​ - -Prompt rejected as too short +### Prompt rejected as too short The dispatch input expects a task description, not a conversational opener. A prompt shorter than four characters is rejected with a `Too short` hint so a stray keystroke doesn’t start a session. Describe what you want the session to do, such as `investigate the flaky checkout test`. -### - -​ - -Sessions show as failed or stopped after shutdown +### Sessions show as failed or stopped after shutdown Shutting down or restarting your machine stops running background sessions. A session that was waiting on your input stays under `Needs input` when you come back. For any other running session, what agent view shows depends on how long ago it last made progress: @@ -878,11 +682,7 @@ When [transcript cleanup](</docs/en/settings-reference#cleanupperioddays>) has removed a stopped session’s saved conversation, Claude Code refuses to open the row: the message says there is nothing to resume. `claude rm <id>` deletes the row, except in the kept cases described above, and `claude respawn <id>` runs its original prompt again. See [This session’s saved conversation is no longer on disk](</docs/en/errors#this-sessions-saved-conversation-is-no-longer-on-disk>). Sleep alone doesn’t stop sessions. Sessions are preserved across sleep and the supervisor reconnects to them on wake. -### - -​ - -Opening a session says the conversation is already open +### Opening a session says the conversation is already open Two processes can’t write to the same transcript. When a stopped session’s saved conversation is already open in another live Claude Code process, Claude Code refuses to start the session’s own process. What you see depends on what holds the conversation: @@ -891,11 +691,7 @@ Claude Code saves a reply you typed with the refused attempt, except one prefixed with `!` or `/`, and sends it the next time the session starts. -### - -​ - -Opening a session says it has no saved transcript +### Opening a session says it has no saved transcript When you open a session that you backgrounded from another conversation and that stopped before it ran a turn of its own, Claude Code resumes that conversation. If Claude Code can’t find the conversation, it refuses to open the session: @@ -904,27 +700,15 @@ Press `Enter` on the same row again to restart the session with an empty conversation, or run `claude respawn <id>` from the shell. See the [error reference](</docs/en/errors#this-session-has-no-saved-transcript>) for details. -### - -​ - -The terminal host died or the session stopped responding +### The terminal host died or the session stopped responding The supervisor runs each background session’s terminal in its own host process. When that process dies or stops responding, Claude Code shows the reason and offers a restart; in both cases the conversation is saved and the restart resumes it. The [error reference](</docs/en/errors#terminal-host-process-died>) quotes the full messages. Claude Code never restarts a row running a shell command, from `Enter` or from `claude attach`, because that would run the command again; the row’s message and `claude attach` both say the command isn’t run again. -### - -​ - -A session fails before starting with a `possibly low memory` note +### A session fails before starting with a `possibly low memory` note When a background session’s process exits before it finishes starting and the host is low on memory, the row’s status names the exit and adds `possibly low memory — free some up and retry`. The note is a hypothesis, not a confirmed cause. Claude Code adds it only when the process exited silently, without writing an error and without being stopped by a signal, and the host reported low memory at that moment. When the process did write an error before exiting, the row shows that error instead. Free up memory on the machine, then attach or reply to the row and the supervisor starts a fresh process for the session. When memory stays low, the supervisor also stops idle sessions to free resources on its own, and stops idle pinned sessions too if stopping the others freed nothing. -### - -​ - -Agent view says the background service did not respond +### Agent view says the background service did not respond If attaching, peeking, or `claude logs` reports that the background service did not respond, the supervisor process has likely stalled. Stop it and let the next `claude agents` start a fresh one. To keep your background sessions running through the restart, pass `--keep-workers`: @@ -939,11 +723,7 @@ `was not sent SIGKILL`| macOS, Linux| Run the stop command again. If the process remains, check it with `ps -ww -o args= -p <pid>`: Claude Code started with `daemon` is a supervisor, so run `kill -9 <pid>`. Leave anything else; if `claude agents` then can’t start a supervisor, delete `~/.claude/daemon.lock`. `supervisor (pid=<pid>) is still running`| Windows| End the process with `taskkill /PID <pid>` -### - -​ - -Dispatch fails with `Could not resolve authentication method` +### Dispatch fails with `Could not resolve authentication method` If a background dispatch fails with `Could not resolve authentication method` while interactive sessions authenticate normally, the worker that received the dispatch didn’t pick up credentials. Background sessions get their credentials from the supervisor, so this error means no stored credential was available to the supervisor process itself. Confirm you have run `/login` or configured an API key, then stop the supervisor: @@ -951,11 +731,7 @@ Within about a minute, run `claude agents` or `claude --bg` in your shell to start a fresh supervisor that reads your stored credentials. If you authenticate with an environment variable such as `ANTHROPIC_API_KEY` rather than `/login`, run that next command from a shell where the variable is set. See the [error reference](</docs/en/errors#could-not-resolve-authentication-method>) for the full list of causes and fixes. -### - -​ - -A background session shows `No LLM gateway` +### A background session shows `No LLM gateway` If a background session shows [`No LLM gateway`](</docs/en/errors#no-llm-gateway-opened-from-another-folder>), it didn’t get your gateway `ANTHROPIC_BASE_URL`, so its requests fail. Claude Code withheld it because you dispatched, woke, or restarted the session from a directory other than the folder the message names. You see the message, for example, after you dispatch into a repository with `@<repo>` or wake a stopped session by running `claude attach` from another directory. To give the session your gateway, pick the fix that matches where your gateway is set: @@ -963,43 +739,23 @@ * The gateway reaches the session only when the supervisor was itself started from a shell that exported the same gateway. If the supervisor wasn’t, restart it from the terminal where you ran the respawn command, as Dispatch fails with `Could not resolve authentication method` describes, then run that command again. * **You used agent view in a project whose settings set the gateway** : put `ANTHROPIC_BASE_URL` and its credential in [a settings file’s `env` block](</docs/en/llm-gateway-connect#set-in-a-settings-file>). Use `~/.claude/settings.json`, or `.claude/settings.local.json` in the session’s own project, both of which a respawned session reads. Then run `claude respawn <id>` in your shell from any directory to restart this session on the gateway. -### - -​ - -Background sessions can’t read Desktop, Documents, or Downloads on macOS +### Background sessions can’t read Desktop, Documents, or Downloads on macOS On macOS, the background session host runs as its own process and requests access to protected folders separately from your terminal. If a background session reports `Operation not permitted` when reading `~/Desktop`, `~/Documents`, `~/Downloads`, or another protected location, grant access in System Settings under Privacy & Security > Files and Folders, or enable Full Disk Access for the entry. In either list, look for an entry named Claude Code, or one named for the path or file name of the `claude` binary. That file name can be a version number such as `2.1.316`. If `Operation not permitted` returns after Claude Code updates, look for a new entry, such as one named for the new version. If one is there, grant it access. -### - -​ - -Background sessions can’t reach local-network hosts on macOS +### Background sessions can’t reach local-network hosts on macOS On macOS 15 and later, the system blocks a process from reaching devices on your local network until you grant Local Network permission, so a command targeting a LAN address can fail with `connect: no route to host` in a background session even though it works in a foreground terminal. The first command in a background session that connects to a local-network address triggers the macOS Local Network permission prompt for Claude Code. Grant it once and those commands reach LAN hosts the same way they do in a foreground terminal. -### - -​ - -A session is slow to respond after attaching +### A session is slow to respond after attaching When a session that has finished or is waiting for your next message stays unattached for about an hour, the supervisor stops its process to free resources. Attaching starts a fresh process from where it left off and switches to the session immediately while the process restarts. Sessions that are working, paused on a permission prompt or other dialog, or pinned aren’t stopped this way, so pin a session with `Ctrl+T` to keep it responsive. While the process starts, Claude Code shows the tail of the session’s transcript formatted the way the live session renders it, with markdown, highlighted code blocks, and tool calls as dimmed rows, above a dimmed prompt area with a `Session is starting` note. The live session replaces it as soon as it’s ready. -### - -​ - -`.claude/worktrees/` is filling up +### `.claude/worktrees/` is filling up Deleting a session in agent view removes the worktree Claude created for it, but some deletes keep the worktree or leave its directory on disk, so leftover directories can accumulate. Directories git no longer recognizes don’t appear in `git worktree list`, so remove those by hand. List leftover entries with `git worktree list` in the project directory and remove each with `git worktree remove <path>`. See [Clean up worktrees](</docs/en/worktrees#clean-up-worktrees>). -## - -​ - -Limitations +## Limitations Agent view is in research preview with the following limitations: @@ -1007,11 +763,7 @@ * **Sessions are local** : background sessions run on your machine. They are preserved across sleep but stop if the machine shuts down. * **Claude-created worktrees are deleted with the session in agent view** : commit changes before deleting a session that edited files in its own worktree. Some deletes keep the worktree instead. -## - -​ - -Related resources +## Related resources For other ways to run Claude in parallel, and for passing findings between the sessions you run, see: @@ -1021,11 +773,7 @@ * [Use Claude Code in the cloud](</docs/en/claude-code-on-the-web>): run sessions in a managed cloud environment instead of locally * [Projects](</docs/en/claude-projects>): have Claude coordinate parallel cloud sessions from one conversation and tell you which need you -## - -​ - -Version history +## Version history Agent view has evolved quickly during research preview. If you are on an older Claude Code version, some behavior on this page may differ; in particular, `claude agents` rejects flags it doesn’t yet support with an `unknown option` error. The table below lists when each flag and behavior was added.
modified Run agents in parallel View current →
--- a/agents.md +++ b/agents.md @@ -22,11 +22,7 @@ Running several sessions or subagents at once multiplies token usage. See [Costs](</docs/en/costs>) for usage and rate limit details. -## - -​ - -Choose an approach +## Choose an approach The right approach depends on who coordinates the work, whether the workers need to communicate, and whether they edit the same files: @@ -38,11 +34,7 @@ * **Do the workers need to talk to each other?** Claude can pass findings with [cross-session messaging](</docs/en/cross-session-messaging>) between sessions you run yourself, including the sessions you dispatch from agent view. Subagents report results back to the conversation that spawned them, and agent view sessions report results only to you. Teammates in an agent team message each other directly and, when they [have the Task tools](</docs/en/tools-reference#task-tool-availability>), share a task list. * **Do the tasks touch the same files?** Isolate the work with [worktrees](</docs/en/worktrees>). Subagents and sessions you run yourself can each use a separate worktree. Agent teams don’t isolate teammates in worktrees, so [partition the work](</docs/en/agent-teams#avoid-file-conflicts>) so each teammate owns a different set of files. -## - -​ - -Check on running work +## Check on running work The command for checking on running work depends on which approach you used: @@ -53,11 +45,7 @@ For a desktop view of all your sessions, see [parallel sessions in the desktop app](</docs/en/desktop#work-in-parallel-with-sessions>). -## - -​ - -Learn more +## Learn more Each guide below covers setup and configuration for one approach:
modified Claude Code on Amazon Bedrock View current →
Show diff (480 lines)
--- a/amazon-bedrock.md +++ b/amazon-bedrock.md @@ -1,8 +1,4 @@ -## - -​ - -Prerequisites +## Prerequisites Before configuring Claude Code with Amazon Bedrock, ensure you have: @@ -13,11 +9,7 @@ To sign in with your own Amazon Bedrock credentials, follow Sign in with Amazon Bedrock below. To deploy Claude Code across a team, use the manual setup steps and pin your model versions before rolling out. -## - -​ - -Sign in with Bedrock +## Sign in with Bedrock If you have AWS credentials and want to start using Claude Code through Amazon Bedrock, the login wizard walks you through it. You complete the AWS-side prerequisites once per account; the wizard handles the Claude Code side. @@ -41,19 +33,11 @@ After you’ve signed in, run `/setup-bedrock` any time to reopen the wizard and change your credentials, region, or model pins. The model pin step starts from your currently pinned models. The wizard writes to `~/.claude/settings.json`, or to `$CLAUDE_CONFIG_DIR/settings.json` when [`CLAUDE_CONFIG_DIR`](</docs/en/env-vars#variables>) is set. -## - -​ - -Set up manually +## Set up manually To configure Amazon Bedrock through environment variables instead of the wizard, for example in CI or a scripted enterprise rollout, follow the steps below. -### - -​ - -1\. Submit use case details +### 1\. Submit use case details Before you invoke an Anthropic model for the first time, submit use case details. You do this once per AWS account. @@ -64,11 +48,7 @@ If you use AWS Organizations, you can submit the form once from the management account using the [`PutUseCaseForModelAccess` API](<https://docs.aws.amazon.com/bedrock/latest/APIReference/API_PutUseCaseForModelAccess.html>). This call requires the `bedrock:PutUseCaseForModelAccess` IAM permission. Approval extends to child accounts automatically. -### - -​ - -2\. Configure AWS credentials +### 2\. Configure AWS credentials Claude Code uses the default AWS SDK credential chain. If the machine already supplies credentials to that chain, such as an Amazon EC2 instance profile or Amazon ECS task credentials, skip to step 3. AWS [warns against using an IAM user’s access keys](<https://docs.aws.amazon.com/cli/latest/userguide/cli-authentication-user.html>) when you develop purpose-built software or work with real data. Set up your credentials with one of these methods: @@ -78,11 +58,7 @@ * AWS Management Console credentials: sign in through your browser with your AWS Management Console credentials and get temporary credentials. AWS [recommends this method](<https://docs.aws.amazon.com/signin/latest/userguide/command-line-sign-in.html>) if you access your AWS account as the root user, as an IAM user, or through federation with IAM. * Amazon Bedrock API key: authenticate with a bearer token that works only for Amazon Bedrock, instead of AWS credentials -#### - -​ - -Use `aws configure` +#### Use `aws configure` Run `aws configure` and enter your access key ID, secret access key, and default region when prompted: @@ -90,11 +66,7 @@ The AWS CLI saves the key to the `default` profile in `~/.aws/credentials`, where the credential chain reads it. -#### - -​ - -Export an access key +#### Export an access key Export your access key as environment variables. `AWS_SESSION_TOKEN` is required only with temporary credentials, so leave that line out if your access key belongs to an IAM user: @@ -102,11 +74,7 @@ export AWS_SECRET_ACCESS_KEY=your-secret-access-key export AWS_SESSION_TOKEN=your-session-token -#### - -​ - -Use an SSO profile +#### Use an SSO profile Create a profile with `aws configure sso` if you don’t have one. Then sign in to IAM Identity Center and set `AWS_PROFILE` so the credential chain uses that profile. Replace `your-profile-name` with the name of your AWS profile before running these commands. @@ -116,11 +84,7 @@ Claude Code requests role credentials from the IAM Identity Center region named by the profile’s `sso_region`, which doesn’t need to match the region you run Amazon Bedrock in. -#### - -​ - -Use AWS Management Console credentials +#### Use AWS Management Console credentials The `aws login` command requires AWS CLI 2.32.0 or later. For the IAM policy your identity needs, see the [AWS instructions for `aws login`](<https://docs.aws.amazon.com/signin/latest/userguide/command-line-sign-in.html>). Run the command to sign in through your browser with your AWS Management Console credentials: @@ -128,11 +92,7 @@ The session is valid for up to 12 hours, after which you run `aws login` again. -#### - -​ - -Use an Amazon Bedrock API key +#### Use an Amazon Bedrock API key An Amazon Bedrock API key is a bearer token that authenticates your requests in place of AWS credentials. AWS issues [two types of key](<https://docs.aws.amazon.com/bedrock/latest/userguide/api-keys.html>): @@ -145,19 +105,11 @@ When `AWS_BEARER_TOKEN_BEDROCK` is set, Claude Code authenticates with the key and doesn’t resolve the credential chain, even if other AWS credentials are present. [Learn more about Amazon Bedrock API keys](<https://aws.amazon.com/blogs/machine-learning/accelerate-ai-development-with-amazon-bedrock-api-keys/>). -#### - -​ - -Credential caching and resolution timeout +#### Credential caching and resolution timeout Claude Code resolves the AWS default credential provider chain once and keeps the resolved credentials in memory. It reuses them until five minutes before they expire, or for one hour when they carry no expiration, so an SSO-backed profile requests credentials from IAM Identity Center about once per credential lifetime. A credential error from the API clears the cache, and the retry resolves fresh credentials. The cache covers every credential method listed at the start of this step except an Amazon Bedrock API key, which doesn’t use the provider chain. To resolve the chain on every request instead, set [`CLAUDE_CODE_SKIP_AWS_CRED_CACHE=1`](</docs/en/env-vars>). The resolve that fills the cache times out after 60 seconds. If a step in the chain stalls, for example a `credential_process` helper that waits for input it can’t receive, the request fails with [`AWS default-chain credential resolve timed out`](</docs/en/errors#aws-default-chain-credential-resolve-timed-out>). If your chain runs an interactive sign-in that legitimately needs longer, such as browser-based SSO with MFA through a wrapper like `aws-vault`, raise the limit in milliseconds with [`CLAUDE_CODE_AWS_CHAIN_RESOLVE_TIMEOUT_MS`](</docs/en/env-vars>). With `CLAUDE_CODE_SKIP_AWS_CRED_CACHE=1` set, each API request resolves the chain without this limit. Except when you authenticate with an Amazon Bedrock API key, the setup wizard applies the same limit to each AWS call it makes while verifying your credentials, and to the credential lookup before each model check. During credential verification, a check that exceeds it fails with [`Timed out after 60s waiting for AWS`](</docs/en/errors#bedrock-setup-verification-timed-out-waiting-for-aws>). -#### - -​ - -Advanced credential configuration +#### Advanced credential configuration Claude Code supports automatic credential refresh for AWS SSO and corporate identity providers. Add these settings to your Claude Code settings file (see [Settings](</docs/en/settings>) for file locations). These two settings have different trigger conditions: @@ -190,11 +142,7 @@ The flat output from `aws configure export-credentials --format process` is also accepted, with the same keys at the top level instead of nested under `Credentials`. `Expiration` is optional. When the command returns a valid ISO 8601 `Expiration`, Claude Code caches the credentials until five minutes before that time. Without it, credentials are cached for one hour. When you configure `awsCredentialExport` without `awsAuthRefresh`, Claude Code uses the exported credentials directly and doesn’t re-resolve the AWS default credential provider chain at startup. -### - -​ - -3\. Configure Claude Code +### 3\. Configure Claude Code Set the following environment variables to enable Amazon Bedrock: @@ -222,11 +170,7 @@ * The WebSearch tool is not available on Amazon Bedrock. See [WebSearch tool behavior](</docs/en/tools-reference#websearch-tool-behavior>). * You can use settings files for environment variables like `AWS_PROFILE` that you don’t want to leak to other processes. See [Settings](</docs/en/settings>) for more information. -### - -​ - -4\. Pin model versions +### 4\. Pin model versions Pin specific model versions when deploying to multiple users. Without pinning, model aliases such as `sonnet` and `opus` resolve to Claude Code’s built-in default for Amazon Bedrock, which can lag the newest release and may not yet be available in your account. Claude Code falls back to an earlier or lower-tier model at startup when the default is unavailable, but pinning lets you control when your users move to a new model. @@ -276,11 +220,7 @@ Prompt caching may not be available in all Amazon Bedrock regions. If cache token counts stay at zero, check [supported models, regions, and limits](<https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html#prompt-caching-models>) in the Amazon Bedrock documentation. -#### - -​ - -Map each model version to an inference profile +#### Map each model version to an inference profile The `ANTHROPIC_DEFAULT_*_MODEL` environment variables configure one inference profile per model family. If your organization needs to expose several versions of the same family in the `/model` picker, each routed to its own application inference profile ARN, use the `modelOverrides` setting in your [settings file](</docs/en/settings#where-settings-live>) instead. This example maps four Opus versions to distinct ARNs so users can switch between them without bypassing your organization’s inference profiles: @@ -295,11 +235,7 @@ When a user selects one of these versions in `/model`, Claude Code calls Amazon Bedrock with the mapped ARN. The same mapping applies when you pass the Anthropic model ID directly through `--model` or `ANTHROPIC_MODEL`. Versions without an override fall back to the built-in Amazon Bedrock model ID or any matching inference profile discovered at startup. Before v2.1.200, `--model` and `ANTHROPIC_MODEL` values reached Amazon Bedrock as-is without going through the override map. See [Override model IDs per version](</docs/en/model-config#override-model-ids-per-version>) for details on how overrides interact with `availableModels` and other model settings. -## - -​ - -Startup model checks +## Startup model checks When Claude Code starts with Amazon Bedrock configured, it verifies that the models it intends to use are accessible in your account. You may have pinned a model version that is older than the current Claude Code default. If your account can invoke the newer version, Claude Code prompts you to update the pin. Accepting writes the new model ID to your [user settings file](</docs/en/settings>) and restarts Claude Code. Declining is remembered until the next default version change. Claude Code doesn’t check or prompt for these pins: @@ -308,30 +244,18 @@ If the update prompt still appears for a pin in managed settings, update Claude Code to v2.1.314 or later. Before v2.1.314, the managed pin stayed in effect after you accepted, so the prompt came back at the next start. If you have not pinned a model and the current default is unavailable in your account, Claude Code falls back for the current session and shows a notice. It tries earlier versions of the default model first and, when the default is an Opus model and no Opus version is available, falls back to the default Sonnet model. The fallback is not persisted. Enable the newer model in your Amazon Bedrock account or pin a version to make the choice permanent. -### - -​ - -Start a session on a specific model +### Start a session on a specific model When you start the session on a specific Sonnet or Opus version, for example with `--model`, `ANTHROPIC_MODEL`, or the [`model` setting](</docs/en/settings-reference#model>), that version acts as the session’s pinned default for the matching `sonnet` or `opus` alias. Claude Code skips the availability check for the built-in default your model replaces and starts on the model you configured, with no fallback notice. These don’t act as pins when you start a session on them: * A model alias such as `opus` * A model ID Claude Code doesn’t recognize, such as an application inference profile ARN -### - -​ - -Remembered model refusals +### Remembered model refusals When the startup model checks find a model your account can’t invoke, Claude Code can remember the refusal on this machine for up to a day. Once ten minutes have passed since the last check, Claude Code checks a remembered refusal of a current default model again at launch. A default your administrator re-enables then comes back. To turn the memory off, set [`CLAUDE_CODE_SKIP_MODEL_ACCESS_MEMORY=1`](</docs/en/env-vars>). -### - -​ - -When your organization enforces a model allowlist +### When your organization enforces a model allowlist If you set [`enforceAvailableModels`](</docs/en/model-config#enforce-the-allowlist-for-the-default-model>) in managed settings, the startup model checks use only models your `availableModels` list permits. This applies on the Amazon Bedrock Invoke API and requires Claude Code v2.1.287 or later. A list without `enforceAvailableModels` doesn’t restrict these checks. The checks compare each entry with the inference profile ID they would send, including its region prefix, so write the list in those IDs. This example permits Opus 4.8 and Sonnet 4.5 for a deployment whose models resolve to `us.` profiles: @@ -342,19 +266,16 @@ For aliases, version prefixes, and `modelOverrides` entries, see [Pin models for third-party deployments](</docs/en/model-config#pin-models-for-third-party-deployments>). -### - -​ - -When a model is disabled mid-session - -If your account loses access to the model your session is running on, for example because an administrator disables it in your Amazon Bedrock account, Claude Code switches the session to another model instead of failing each request, and shows `Switched to <fallback> because <model> is not available`. It tries the same models as the startup fallback: earlier versions of the same tier first and, for an Opus session with no Opus version available, the default Sonnet model. The switch applies only to a tier you haven’t pinned, the same condition as the startup fallback. A session on a specific version you picked, or on an application inference profile ARN, keeps its model and, without a fallback model chain, the request fails instead. In [auto mode](</docs/en/permission-modes#enable-auto-mode-on-bedrock-agent-platform-or-foundry>), Claude Code switches only to a model auto mode supports on Amazon Bedrock. If none of those models is available either, the request fails with [AWS authentication failed](</docs/en/errors#aws-authentication-failed>) and a hint to enable the model. A [fallback model chain](</docs/en/model-config#fallback-model-chains>) you configure replaces the tier switch: on these refusals Claude Code switches to your configured fallback instead. To have refused requests fail rather than switch, set [`CLAUDE_CODE_DISABLE_MODEL_ACCESS_FALLBACK=1`](</docs/en/env-vars>). A fallback chain you configured still switches on these refusals; remove the chain as well if you want every refused request to fail. - -## - -​ - -Cross-region inference profile prefixes +### When a model is disabled mid-session + +When Amazon Bedrock rejects your session’s model as unavailable to your account, Claude Code switches your session to another model, and you can keep working. You see a message that starts with `Switched to <fallback> because <model> is not available`. This happens, for example, when an administrator disables the model or the newest model isn’t yet available to your account. If you configured a [fallback model chain](</docs/en/model-config#fallback-model-chains>), Claude Code switches to your configured fallback instead. Without a chain, the request fails in cases such as these: + + * Your session is on a pinned model, a specific version you picked, or an application inference profile ARN + * None of the models Claude Code tries is available. In [auto mode](</docs/en/permission-modes#enable-auto-mode-on-bedrock-agent-platform-or-foundry>), Claude Code only switches to a model auto mode supports on Amazon Bedrock. + +To keep working, run `/model` in the session and press `s` on a model your account can use, which leaves your default unchanged. A `403` shows as [AWS authentication failed](</docs/en/errors#aws-authentication-failed>). To have rejected requests fail instead of switching, set [`CLAUDE_CODE_DISABLE_MODEL_ACCESS_FALLBACK=1`](</docs/en/env-vars>). If you configured a fallback model chain, remove it as well, because Claude Code still moves to that fallback. + +## Cross-region inference profile prefixes On the Amazon Bedrock [Invoke API](<https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithResponseStream.html>), Claude Code resolves its built-in default models to [cross-region inference profile](<https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html>) IDs; to route model versions through your own inference profiles instead, see Map each model version to an inference profile. This table shows the prefix Claude Code prefers for each resolved AWS region: @@ -385,11 +306,7 @@ * In AWS GovCloud regions, Claude Code always uses `us-gov.`, the only prefix that routes within the GovCloud partition. * When you set a value that isn’t one of the valid values, Claude Code falls back to the region-derived preferred prefix. -## - -​ - -IAM configuration +## IAM configuration Create an IAM policy with the required permissions for Claude Code: @@ -432,19 +349,11 @@ Create a dedicated AWS account for Claude Code to simplify cost tracking and access control. -## - -​ - -1M token context window +## 1M token context window Fable models, Sonnet 5 and later, and Opus 4.7 and later run with the [1M token context window](<https://platform.claude.com/docs/en/build-with-claude/context-windows#context-window-sizes-by-model>) by default on Amazon Bedrock, on both the Invoke API and the Mantle endpoint, with no `[1m]` suffix needed. An application inference profile ARN gets the 1M window when a `modelOverrides` entry maps its model to it. To keep a 200K window instead, set [`CLAUDE_CODE_DISABLE_1M_CONTEXT=1`](</docs/en/model-config#turn-off-1m-context>). Opus 4.6 and Sonnet 4.6 on the Invoke API reach the 1M window when you select their `[1m]` variant. The setup wizard offers a 1M context option when it pins models. To enable it for a manually pinned model instead, append `[1m]` to the model ID. See [Pin models for third-party deployments](</docs/en/model-config#pin-models-for-third-party-deployments>) for details, including how to use the 1M window without changing the pin. Before v2.1.287, the Fable models and Opus 4.7 and later ran with a 200K window by default on the Invoke API and reached the 1M window there through a `[1m]` suffix. -## - -​ - -Service tiers +## Service tiers [Amazon Bedrock service tiers](<https://docs.aws.amazon.com/bedrock/latest/userguide/service-tiers-inference.html>) let you trade off cost against latency. Set `ANTHROPIC_BEDROCK_SERVICE_TIER` to `default`, `flex`, or `priority`: @@ -452,11 +361,7 @@ Claude Code sends this as the `X-Amzn-Bedrock-Service-Tier` header on every [Invoke API](<https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithResponseStream.html>) request from a session that has the variable, except its model access checks. Setting it has no effect on requests to the Mantle endpoint or through a [Claude apps gateway](</docs/en/claude-apps-gateway>). Tier availability varies by model and region. Reserved capacity uses a [provisioned throughput](<https://docs.aws.amazon.com/bedrock/latest/userguide/prov-throughput.html>) ARN as the model ID instead of this setting. To cover [background sessions](</docs/en/agent-view#settings-and-provider>) you start from a terminal, set `ANTHROPIC_BEDROCK_SERVICE_TIER` in the [`env`](</docs/en/settings-reference#env>) block of your settings. Those sessions get the value you export only when the shell that started the [supervisor](</docs/en/agent-view#the-supervisor-process>) exported it. -## - -​ - -AWS Guardrails +## AWS Guardrails [Amazon Bedrock Guardrails](<https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails.html>) let you implement content filtering for Claude Code. Create a Guardrail in the [Amazon Bedrock console](<https://console.aws.amazon.com/bedrock/>) and publish a version. Enable Cross-Region inference on your Guardrail if you’re using cross-region inference profiles. To apply the Guardrail through a [Claude apps gateway](</docs/en/claude-apps-gateway>), follow [Apply an Amazon Bedrock guardrail](</docs/en/claude-apps-gateway-config#apply-an-amazon-bedrock-guardrail>). Without a Claude apps gateway, add the Guardrail headers to your [settings file](</docs/en/settings>). Example settings file configuration: @@ -468,19 +373,11 @@ When the guardrail blocks a response partway through, the text streamed so far stays and the reply ends with the message configured on the guardrail for blocked responses. -## - -​ - -Use the Mantle endpoint +## Use the Mantle endpoint Mantle is an Amazon Bedrock endpoint that serves Claude models through the native Anthropic API shape rather than the Amazon Bedrock Invoke API. It uses the same AWS credentials and `awsAuthRefresh` configuration. Mantle has its own IAM actions under the `bedrock-mantle:` prefix, so the `bedrock:` actions in IAM configuration don’t cover it. Grant your IAM identity `bedrock-mantle:CreateInference` for inference and `bedrock-mantle:CountTokens` for token counting. See [Making inference requests](<https://docs.aws.amazon.com/bedrock/latest/userguide/inference.html>) and [Counting tokens](<https://docs.aws.amazon.com/bedrock/latest/userguide/count-tokens.html>) in the AWS documentation, and the [service authorization reference](<https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonbedrockpoweredbyawsmantle.html>) for every Mantle action. -### - -​ - -Enable Mantle +### Enable Mantle With AWS credentials already configured, set `CLAUDE_CODE_USE_MANTLE` and your AWS region: @@ -489,23 +386,15 @@ Claude Code constructs the endpoint URL from the AWS region, resolved with the same precedence as Amazon Bedrock above. To override the URL for a custom endpoint or gateway, set `ANTHROPIC_BEDROCK_MANTLE_BASE_URL`. Run `/status` inside Claude Code to confirm. The provider line shows `Amazon Bedrock (Mantle)` when Mantle is active. -### - -​ - -Select a Mantle model +### Select a Mantle model Mantle uses model IDs prefixed with `anthropic.` and without a version suffix, for example `anthropic.claude-sonnet-5` or `anthropic.claude-haiku-4-5`. The models available to your account depend on what your organization has been granted; additional model IDs are listed in your onboarding materials from AWS. Contact your AWS account team to request access to allowlisted models. Set the model with the `--model` flag or with `/model` inside Claude Code: claude --model anthropic.claude-haiku-4-5 -### - -​ - -Run Mantle alongside the Invoke API - -The models available to you on Mantle may not include every model you use today. Setting both `CLAUDE_CODE_USE_BEDROCK` and `CLAUDE_CODE_USE_MANTLE` lets Claude Code call both endpoints from the same session. Model IDs that match the Mantle format are routed to Mantle, and all other model IDs go to the Amazon Bedrock Invoke API. +### Run Mantle alongside the Invoke API + +The models available to you on Mantle may not include every model you use today. If you connect without a gateway, set both `CLAUDE_CODE_USE_BEDROCK` and `CLAUDE_CODE_USE_MANTLE` to call Mantle and the Invoke API from the same session. Model IDs that match the Mantle format are routed to Mantle, and all other model IDs go to the Amazon Bedrock Invoke API. export CLAUDE_CODE_USE_BEDROCK=1 export CLAUDE_CODE_USE_MANTLE=1 @@ -518,11 +407,7 @@ Entries with the `anthropic.` prefix are added as custom picker options, and the ones that match the Mantle format are routed to Mantle. Replace `anthropic.claude-haiku-4-5` with the model ID your account has been granted. See [Restrict model selection](</docs/en/model-config#restrict-model-selection>) for how `availableModels` interacts with other model settings. When both providers are active, `/status` shows `Amazon Bedrock + Amazon Bedrock (Mantle)`. -### - -​ - -Route Mantle through a gateway +### Route Mantle through a gateway If your organization routes model traffic through a centralized [LLM gateway](</docs/en/llm-gateway>) that injects AWS credentials server-side, disable client-side authentication so Claude Code sends requests without SigV4 signatures or `x-api-key` headers: @@ -530,11 +415,7 @@ export CLAUDE_CODE_SKIP_MANTLE_AUTH=1 export ANTHROPIC_BEDROCK_MANTLE_BASE_URL=https://your-gateway.example.com -### - -​ - -Mantle environment variables +### Mantle environment variables These variables are specific to the Mantle endpoint. See [Environment variables](</docs/en/env-vars>) for the full list. @@ -545,25 +426,13 @@ `CLAUDE_CODE_SKIP_MANTLE_AUTH`| Skip client-side authentication for proxy setups `ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION`| Override AWS region for the Haiku-class model (shared with Amazon Bedrock) -## - -​ - -Troubleshooting - -### - -​ - -Authentication loop with SSO and corporate proxies +## Troubleshooting + +### Authentication loop with SSO and corporate proxies If browser sign-in tabs keep opening when you use AWS SSO, remove the `awsAuthRefresh` setting from your [settings file](</docs/en/settings>). The loop can occur when corporate VPNs or TLS inspection proxies interrupt the SSO browser flow. Claude Code treats the interrupted connection as an authentication failure. When a later request finds the credentials still expired, Claude Code re-runs `awsAuthRefresh`, which opens another tab. If your network environment interferes with automatic browser-based SSO flows, use `aws sso login` manually before starting Claude Code instead of relying on `awsAuthRefresh`. -### - -​ - -Certificate errors behind a TLS-inspecting proxy +### Certificate errors behind a TLS-inspecting proxy Claude Code applies your [CA certificate store](</docs/en/network-config#ca-certificate-store>) configuration to its requests to AWS, including: @@ -574,11 +443,7 @@ For these requests, a corporate root certificate in your OS trust store or `NODE_EXTRA_CA_CERTS` bundle needs no Amazon Bedrock-specific setup. Before v2.1.260, Claude Code applied your CA configuration to these requests only when they went through a configured proxy, and on a direct connection they trusted only the runtime’s default certificate store. Before v2.1.261, the credential lookup behind the setup wizard’s model checks with the **Use credentials already in my environment** option still trusted only the runtime’s default certificate store. Behind a TLS-inspecting proxy whose root certificate is only in the OS store, the affected requests failed with `unable to get local issuer certificate`, or the wizard showed models as `unreachable`, while inference requests succeeded. Update to v2.1.261 or later. -### - -​ - -Region issues +### Region issues If you encounter region issues: @@ -590,40 +455,27 @@ * Specify the model as an [inference profile](<https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html>) ID -### - -​ - -Streaming errors behind a gateway or proxy +### Streaming errors behind a gateway or proxy Amazon Bedrock streams `InvokeModelWithResponseStream` responses in a binary event-stream format with the header `Content-Type: application/vnd.amazon.eventstream`. A gateway or proxy between Claude Code and Amazon Bedrock must forward the response body and its headers, including `Content-Type`, as Amazon Bedrock sent them. If the gateway rewrites `Content-Type` to another value, Claude Code rejects the response with an error that begins `Bedrock streaming response has content-type`, naming the value it received. The common rewrite is `text/event-stream`, from an integration that re-emits the stream as server-sent events. For the `CLAUDE_CODE_DISABLE_BEDROCK_CONTENT_TYPE_GUARD` variable that the error message names, see [Bedrock streaming response has an unexpected content-type](</docs/en/errors#bedrock-streaming-response-has-an-unexpected-content-type>). If the gateway drops or blanks the header instead, Claude Code assumes the body is Amazon Bedrock’s event stream and decodes it, so a body the gateway passed through unmodified keeps streaming. If a gateway that drops the header also re-emits the stream as server-sent events, Claude Code can’t decode the body and falls back to a slower non-streaming path on every turn: each response appears only once it is complete instead of streaming in. In that case, set [`CLAUDE_CODE_DISABLE_BEDROCK_CONTENT_TYPE_DEFAULT=1`](</docs/en/env-vars>) so Claude Code reads the body as server-sent events instead. To fix the error or the fallback, configure the gateway to forward the `InvokeModelWithResponseStream` response body and its `Content-Type` header unmodified. A gateway that converts the stream to server-sent events is no longer serving the Amazon Bedrock API. If it also accepts Anthropic Messages API requests, connect to it as an [LLM gateway](</docs/en/llm-gateway-connect>) with `ANTHROPIC_BASE_URL` instead of `CLAUDE_CODE_USE_BEDROCK`. -### - -​ - -Zero token counts in /context +### Zero token counts in /context The `/context` command counts tokens for each tool group by sending the tool schemas to the Amazon Bedrock count-tokens API. On Claude Code versions before v2.1.196, Amazon Bedrock rejected that request because the schemas carried fields its count-tokens API doesn’t accept, so every tool group showed 0 tokens. Other rows in the breakdown, such as messages and memory files, aren’t affected. Update to v2.1.196 or later. -### - -​ - -Mantle endpoint errors +### Mantle endpoint errors If `/status` does not show `Amazon Bedrock (Mantle)` after you set `CLAUDE_CODE_USE_MANTLE`, the variable is not reaching the process. Confirm it is exported in the shell where you launched `claude`, or set it in the `env` block of your [settings file](</docs/en/settings>). What a `403` from the Mantle endpoint means depends on whether the error names an IAM action: * If the error names a `bedrock-mantle:` action, grant your IAM identity that action. * If the error names no action and your credentials are valid, your AWS account has not been granted access to the model you requested. Contact your AWS account team to request access. -A `400` that names the model ID means that model isn’t served on Mantle. Mantle has its own model lineup separate from the standard Amazon Bedrock catalog, so inference profile IDs such as `us.anthropic.claude-sonnet-4-6` don’t work. Use a Mantle-format ID, or enable both endpoints so Claude Code sends inference profile IDs to the Invoke API. - -## - -​ - -Additional resources +A `400` that names the model ID means that model isn’t served on Mantle. Mantle has its own model lineup separate from the standard Amazon Bedrock catalog, so inference profile IDs such as `us.anthropic.claude-sonnet-4-6` don’t work. To clear the error: + + * **Without a gateway** : use a Mantle-format ID that Mantle serves, or run Mantle alongside the Invoke API to send IDs in other formats to that API. + * **Through a gateway** : ask its operator which model IDs to use. + +## Additional resources * [Amazon Bedrock documentation](<https://docs.aws.amazon.com/bedrock/>) * [Amazon Bedrock pricing](<https://aws.amazon.com/bedrock/pricing/>)
modified Track team usage with analytics View current →
Show diff (254 lines)
--- a/analytics.md +++ b/analytics.md @@ -7,11 +7,7 @@ Code Review has its own dashboard. For review activity and spend, see [View usage](</docs/en/code-review-costs#view-usage>). -## - -​ - -Access analytics for Team and Enterprise +## Access analytics for Team and Enterprise Navigate to [claude.ai/analytics/claude-code](<https://claude.ai/analytics/claude-code>). Admins and Owners can view the dashboard. The Team and Enterprise dashboard includes: @@ -22,11 +18,7 @@ For per-user token counts and cost estimates, configure [OpenTelemetry export](</docs/en/monitoring-usage>), or export the [spend report](<https://support.claude.com/en/articles/12883420-view-usage-analytics-for-team-and-enterprise-plans>) from your organization’s analytics settings, which lists token usage and estimated usage-credit spend per user and per model. -### - -​ - -Enable contribution metrics +### Enable contribution metrics Contribution metrics are in public beta and available on Claude for Teams and Claude for Enterprise plans. These metrics only cover users within your claude.ai organization. Usage through the Claude Console API or third-party integrations is not included. @@ -65,11 +57,7 @@ Contribution metrics cover repositories hosted on github.com. For repositories on [GitHub Enterprise Server](</docs/en/github-enterprise-server>), the analytics dashboard shows usage metrics only. -### - -​ - -Review summary metrics +### Review summary metrics These metrics are deliberately conservative and represent an underestimate of Claude Code’s actual impact. Only lines and PRs where there is high confidence in Claude Code’s involvement are counted. @@ -81,30 +69,18 @@ * **Suggestion accept rate** : percentage of times users accept Claude Code’s code editing suggestions, including Edit, Write, and NotebookEdit tool usage * **Lines of code accepted** : total lines of code that Claude Code’s Edit and Write tools added or removed in accepted edits. This excludes rejected suggestions, and lines deleted later don’t reduce the total. -### - -​ - -Explore the charts +### Explore the charts The dashboard includes several charts to visualize trends over time. -#### - -​ - -Track adoption +#### Track adoption The Adoption chart shows daily usage trends: * **users** : daily active users * **sessions** : number of active Claude Code sessions per day -#### - -​ - -Measure PRs per user +#### Measure PRs per user This chart displays individual developer activity over time: @@ -113,11 +89,7 @@ Use this to understand how individual productivity changes as Claude Code adoption increases. -#### - -​ - -View pull requests breakdown +#### View pull requests breakdown The Pull requests chart shows a daily breakdown of merged PRs: @@ -126,11 +98,7 @@ Toggle to **Lines of code** view to see the same breakdown by lines of code rather than PR count. -#### - -​ - -Find top contributors +#### Find top contributors The Leaderboard shows the top 10 users ranked by contribution volume. Toggle between: @@ -139,19 +107,11 @@ Click **Export all users** to download complete contribution data for all users as a CSV file. The export includes all users, not just the top 10 displayed. -### - -​ - -PR attribution +### PR attribution When contribution metrics are enabled, Claude Code analyzes merged pull requests to determine which code was written with Claude Code assistance. This is done by matching Claude Code session activity against the code in each PR. -#### - -​ - -Attribution process +#### Attribution process When a pull request is merged: @@ -162,19 +122,11 @@ Before comparison, lines are normalized: whitespace is trimmed, multiple spaces are collapsed, quotes are standardized, and text is converted to lowercase. Merged pull requests containing Claude Code-assisted lines are labeled as `claude-code-assisted` in GitHub. -#### - -​ - -Time window +#### Time window Sessions from 21 days before to 2 days after the PR merge date are considered for attribution matching. -#### - -​ - -Excluded files +#### Excluded files Certain files are automatically excluded from analysis because they are auto-generated: @@ -184,11 +136,7 @@ * Test fixtures: snapshots, cassettes, mock data * Lines over 1,000 characters, which are likely minified or generated -#### - -​ - -Attribution notes +#### Attribution notes Keep these additional details in mind when interpreting attribution data: @@ -196,19 +144,11 @@ * Sessions outside the 21-day window are not considered * The algorithm does not consider the PR source or destination branch when performing attribution -### - -​ - -Get the most from analytics +### Get the most from analytics Use contribution metrics to demonstrate ROI, identify adoption patterns, and find team members who can help others get started. -#### - -​ - -Monitor adoption +#### Monitor adoption Track the Adoption chart and user counts to identify: @@ -216,11 +156,7 @@ * Overall adoption trends across your organization * Dips in usage that may indicate friction or issues -#### - -​ - -Measure ROI +#### Measure ROI Contribution metrics help answer “Is this tool worth the investment?” with data from your own codebase: @@ -228,11 +164,7 @@ * Compare PRs and lines of code shipped with vs. without Claude Code * Use alongside [DORA metrics](<https://dora.dev/>), sprint velocity, or other engineering KPIs to understand changes from adopting Claude Code -#### - -​ - -Identify power users +#### Identify power users The Leaderboard helps you find team members with high Claude Code adoption who can: @@ -240,19 +172,11 @@ * Provide feedback on what’s working well * Help onboard new users -#### - -​ - -Access data programmatically +#### Access data programmatically On the Enterprise plan, the [Claude Enterprise Analytics API](<https://platform.claude.com/docs/en/api/admin/analytics>) returns per-user engagement, usage, and cost reports for your organization across Claude surfaces, including Claude Code. A Primary Owner creates a key with the `read:analytics` scope at [claude.ai/analytics/api-keys](<https://claude.ai/analytics/api-keys>). The API is not available on the Teams plan. To query contribution data through GitHub instead, search for PRs labeled with `claude-code-assisted`. -## - -​ - -Access analytics for API customers +## Access analytics for API customers API customers using the Claude Console can access analytics at [platform.claude.com/claude-code](<https://platform.claude.com/claude-code>). You need the UsageView permission to access the dashboard. The Developer, Billing, Admin, Owner, and Primary Owner roles have this permission. To pull daily per-user metrics programmatically, use the [Claude Code Analytics API](<https://platform.claude.com/docs/en/build-with-claude/claude-code-analytics-api>) with an Admin API key. @@ -265,11 +189,7 @@ * **Active users** and **Sessions** : daily counts of active users and Claude Code sessions. * **Spend** : daily API costs in dollars. -### - -​ - -View team insights +### View team insights The team insights table shows these per-user columns for the date range you select at the top of the dashboard, by default the last 30 days: @@ -279,11 +199,7 @@ Spend figures in the Console dashboard are estimates for analytics purposes. For actual costs, refer to the [Cost page](<https://platform.claude.com/cost>). -## - -​ - -Related resources +## Related resources * [Monitoring with OpenTelemetry](</docs/en/monitoring-usage>): export real-time metrics and events to your observability stack * [Manage costs effectively](</docs/en/costs>): set spend limits and optimize token usage
modified Anthropic's marketplaces View current →
--- a/anthropic-marketplaces.md +++ b/anthropic-marketplaces.md @@ -10,11 +10,7 @@ * To distinguish the two marketplaces by repository, marketplace name, and how you get each one, see Anthropic’s marketplaces. * To find a plugin in the official marketplace, see Find plugins in the official marketplace. -## - -​ - -Anthropic’s marketplaces +## Anthropic’s marketplaces A marketplace is a catalog of plugins that a repository defines in its `.claude-plugin/marketplace.json` file. The official and community marketplaces each come from their own GitHub repository. Anthropic also publishes topic-specific marketplaces, such as `anthropics/skills` and `anthropics/knowledge-work-plugins`, which you add in a Claude Code session with `/plugin marketplace add <owner>/<repo>`. This table gives each marketplace’s repository and marketplace name, which is what you type after `@` when you install a plugin from that marketplace. The community marketplace’s name is `claude-community`, not its repository name. @@ -27,11 +23,7 @@ If you wrote a plugin and want other people to install it, see [Publish a plugin](</docs/en/plugins/publish>), which covers your own marketplace and submitting to Anthropic’s directory. -### - -​ - -Deprecated `claude-code-plugins` marketplace +### Deprecated `claude-code-plugins` marketplace The `claude-code-plugins` marketplace in `anthropics/claude-code` is deprecated. To add a plugin, run `claude plugin install <plugin>@claude-plugins-official` in your shell, and skip any tutorial step that runs `/plugin marketplace add anthropics/claude-code`. @@ -42,19 +34,11 @@ If any other plugin stopped working, see [Plugin installed but not working](</docs/en/plugins/troubleshooting#plugin-installed-but-not-working>). -## - -​ - -Find plugins in the official marketplace +## Find plugins in the official marketplace By default, Claude Code adds the official marketplace, `claude-plugins-official`, for you. Most of what it lists comes from partners and other authors rather than from Anthropic: tool vendors publish plugins that connect Claude Code to their services, and Anthropic maintains a smaller set of its own, such as `commit-commands`, `code-review`, `feature-dev`, and the [language server plugins](</docs/en/plugins/code-intelligence>). The catalog changes often, so this page doesn’t list it. To see what’s in it, use the **Discover** tab of `/plugin` in a Claude Code session, which you can search, or browse [Claude Marketplace](<https://claude.com/marketplace/plugins>) on the web. -## - -​ - -Browse and install from Anthropic’s marketplaces +## Browse and install from Anthropic’s marketplaces You can search Anthropic’s marketplaces for a plugin in Claude Code, on the web, or on GitHub: @@ -65,27 +49,15 @@ Anthropic’s directory is separate from these marketplaces. The directory is the catalog on claude.ai. A plugin you add from the directory on claude.ai reaches Claude Code through [account sync](</docs/en/plugins/loading#synced-plugins>). To list your own plugin there, see [Submit to Anthropic’s directory](</docs/en/plugins/publish#submit-to-anthropics-directory>). To install from the desktop app or from a script, or to see what a cloud session loads, see [Install plugins](</docs/en/plugins/install>). -### - -​ - -Add the community marketplace +### Add the community marketplace The community marketplace isn’t registered until you add it. In a Claude Code session, run `/plugin marketplace add anthropics/claude-plugins-community`, then install with the `@claude-community` suffix. If `claude-plugins-official` isn’t on the **Marketplaces** tab of `/plugin`, add it the same way with `/plugin marketplace add anthropics/claude-plugins-official`. For `not found` errors and marketplaces that won’t add, see [Troubleshoot plugins](</docs/en/plugins/troubleshooting#install-a-plugin>). -## - -​ - -Third-party marketplaces +## Third-party marketplaces Many popular plugins aren’t in any Anthropic marketplace. They’re in their authors’ own marketplaces, usually a GitHub repository with a `.claude-plugin/marketplace.json` at its root. Anthropic doesn’t review third-party marketplaces, so read [Plugin security and trust](</docs/en/plugins/security>) before you add one. To use a third-party marketplace, add its repository in a Claude Code session with `/plugin marketplace add <owner>/<repo>`, then install with `/plugin install <plugin>@<marketplace-name>`. The marketplace name is the `name` field of that `marketplace.json`, and Claude Code prints it once it has added the marketplace. For other ways to add a marketplace, see [Add a marketplace](</docs/en/plugins/install#add-a-marketplace>). -## - -​ - -Next steps +## Next steps * [Install and manage plugins](</docs/en/plugins/install>): install a plugin from one of these marketplaces and choose a scope * [Plugin security and trust](</docs/en/plugins/security>): what a plugin can do on your machine and how to review one before you install it
modified Use the mods API View current →
Show diff (284 lines)
--- a/api.md +++ b/api.md @@ -1,18 +1,10 @@ The mods API is the set of methods a mod calls to act: add commands and tools, call a model, run work between events, and reach the file system, processes, and the network. Every hook receives it as its first argument, `$`, with the methods grouped in namespaces such as `$.ui` and `$.fs`. [Events](</docs/en/plugins/mods/events>) decide when a hook runs, and the mods API is what the hook calls once it does. Build your [first mod](</docs/en/plugins/mods/create>) before you start here. For every method, see [mods API methods](</docs/en/plugins/mods/reference#mods-api-methods>) or read [the types for your build](</docs/en/plugins/mods/create#get-the-types-for-your-build>). -## - -​ - -Add a command or a tool +## Add a command or a tool A mod can add a command for the user to run and a tool for Claude to call. Register both in a [`session.start`](</docs/en/plugins/mods/reference#session>) hook. Claude Code waits for that hook before the first prompt, so what you register is available from the first turn. -### - -​ - -Add a command +### Add a command A command is for the user. Register it, then handle [`command.run`](</docs/en/plugins/mods/reference#commands-and-configuration>) for its name. This example adds a `/standup` command that takes an optional number of days: @@ -30,11 +22,7 @@ After the session starts, `/standup` appears with its description in the list you see when you type `/`. The `argumentHint` shows in the prompt after you type the command and a space, as in `/standup [days]`. When you run `/standup 3`, the second hook returns `Summary for the last 3 day(s): ...`, and the transcript shows that text after the plugin’s name. The hook never calls `next`, because the command has no behavior other than yours. The `text` you return prints in the transcript and Claude reads it. To print nothing, as a command that only opens a [pane](</docs/en/plugins/mods/interface#pick-where-to-draw>) does, return `{}`. To let the command run while Claude is working, add `immediate: true` to the registration. Pick a name that no built-in command uses. Type `/` in a session to see them. `$.command.register` throws for a taken name, with a message such as `"/focus" refused: it is the built-in /focus`. A hook that throws is skipped, so the rest of your `session.start` hook doesn’t run either. Register commands last in that hook, or wrap the call in `try` and `catch`. -### - -​ - -Add a tool +### Add a tool A tool is for Claude. Register it with a name, a description Claude reads, and a JSON Schema for its input. Claude sees it under a longer name made of `mcp__`, your plugin’s name, two underscores, and the name you registered. You handle its calls in a [`tool.call`](</docs/en/plugins/mods/events#guard-or-change-a-tool-call>) hook filtered to that full name. This example, from a plugin named `my-mod`, registers `ticket`, so the full name is `mcp__my-mod__ticket`. It gives Claude a tool that looks up a ticket in an issue tracker: @@ -61,11 +49,7 @@ When [MCP tool search](</docs/en/mcp#scale-with-mcp-tool-search>) defers a registered tool, Claude sees its name but not its description until it searches for it. If Claude should consider the tool on every turn, add [`isDeferred: false`](</docs/en/plugins/mods/reference#tools>) to the registration to [load the full tool upfront](</docs/en/mcp#exempt-a-server-from-deferral>). The field requires Claude Code v2.1.293 or later, and earlier versions ignore it. -## - -​ - -Call a model +## Call a model 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: @@ -79,11 +63,7 @@ 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 +### 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: @@ -104,11 +84,7 @@ 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 +### 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`. @@ -134,11 +110,7 @@ * **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` +#### 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: @@ -148,11 +120,7 @@ `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 +#### 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: @@ -161,11 +129,7 @@ * **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 +### 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: @@ -175,11 +139,7 @@ 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. -## - -​ - -Run work in the background +## Run work in the background Work that outlives one event, such as checking on something once a minute, runs on a timer you start from `session.start`. A hook itself runs for one event and has a [time limit](</docs/en/plugins/mods/reference#limits>) on its own execution time. Time spent waiting on `next` or on a mods API call doesn’t count, except a `$.clock.sleep`. `$.clock.every` and `$.clock.after` take the place of `setInterval` and `setTimeout`, with the delay in milliseconds first: `$.clock.after(5000, fn)` calls `fn` once, five seconds from now. Each returns a timer with a `cancel()` method, and `await $.clock.now()` gives the time in milliseconds. This hook looks up a pull request’s checks once a minute and shows the result under the prompt. `summarize` is a function of your own that turns the command’s JSON output into a few words: @@ -196,11 +156,7 @@ The session starts as usual. A minute later, a line appears under the prompt with a `⚠`, the mod’s name, and then `checks:` and your summary. It’s replaced once a minute after that. The timer’s callback runs outside any event, so it keeps running between turns and doesn’t start one. If the callback throws, the error goes to the [debug log](</docs/en/plugins/mods/troubleshoot#read-the-debug-log>) and the timer runs again at the next interval. -### - -​ - -Show something without starting a turn +### Show something without starting a turn A background job can show the user something without starting a turn. Each of these calls puts text in a different place: @@ -236,35 +192,19 @@ In the [VS Code extension](</docs/en/plugins/mods/interface#draw-in-the-vs-code-extension>), status lines and toasts show above the prompt box instead, and log lines in the conversation. -### - -​ - -Start a turn from a background job +### Start a turn from a background job When a background job finds something that needs Claude’s attention, it can start a turn by submitting a prompt with `$.prompt.submit({ text })`. Claude reads the text after a sentence that names your mod as the sender. To send it as the user’s own words, without that sentence, add `asUser: true`. The call waits until the session is idle and then starts a new turn. It resolves when that turn starts, so don’t `await` it in a handler that runs while Claude is working. -### - -​ - -Stop background work +### Stop background work Timers stop after the module reloads. For long-running work inside a hook, [`next.signal`](</docs/en/plugins/mods/reference#the-hook-function>) is an `AbortSignal` that aborts when the event your hook is handling is abandoned, for example when the user interrupts. Pass it to anything long-running. -### - -​ - -Calls and background work after the user interrupts a turn +### Calls and background work after the user interrupts a turn The reason `the session was stopped and nobody has sent input since` in a result or error means the user stopped a running turn, such as with Esc or **Stop**. After that interruption, calls that start new work in the session are refused until the user’s next input, such as a message at the prompt. Apart from `$.prompt.submit` and `$.command.run`, this handling of calls and background work after an interruption requires Claude Code v2.1.304 or later. -#### - -​ - -Retry a refused or dropped call +#### Retry a refused or dropped call Make a refused or dropped call again from a [`turn.complete`](</docs/en/plugins/mods/events#follow-a-turn>) hook. Calls stay refused until the user’s next input, and nothing queues or repeats them for you. When a call’s result or error contains one of these strings, keep its arguments for a later retry: @@ -305,11 +245,7 @@ Before the user’s next input, `turn.complete` can fire for the interrupted turn itself and for a subagent’s turn, and calls made then are refused again. In that case `submitPrompt` keeps the text for a later `turn.complete`. For a call that rejects, such as `$.command.run`, catch the error and test its message the way `submitPrompt` tests `reason`. -#### - -​ - -What refused calls return +#### What refused calls return In the results, `<reason>` stands for the reason the call was refused. After an interruption, that’s `the session was stopped and nobody has sent input since`. For other reasons, see Calls refused in `claude -p` runs and Agent SDK sessions. @@ -324,11 +260,7 @@ When one of these `$.session.send` or `$.tool.call` calls is refused after an interruption in an interactive session, the user can see the [`Stopped:` toast](</docs/en/plugins/mods/troubleshoot#stopped-type-a-message-to-continue>). -#### - -​ - -Work your mod started before the interruption +#### Work your mod started before the interruption After the user stops a running turn, for example with Esc, some work your mod had already started is dropped and some waits for the user’s next input. @@ -344,11 +276,7 @@ When a scheduled job comes due or a monitor raises an event before the user’s next input, the user can see the [`Stopped:` toast](</docs/en/plugins/mods/troubleshoot#stopped-type-a-message-to-continue>). -### - -​ - -Calls refused in `claude -p` runs and Agent SDK sessions +### Calls refused in `claude -p` runs and Agent SDK sessions In a `claude -p` run or an [Agent SDK](</docs/en/agent-sdk/overview>) session, a result such as `{ drop: 'the run reached its --max-turns limit' }` means the run refused your mod’s call. A refused `$.prompt.submit` resolves with `{ drop: '<reason>' }`. Other refused calls, such as `$.command.run` and `$.agent.spawn`, give the results shown in What refused calls return with the reason in place of `<reason>`. Find your `<reason>` below for what to do about it: @@ -357,11 +285,7 @@ * **`the host has ended its input`** : for example, the SDK application ended its [streaming input](</docs/en/agent-sdk/streaming-vs-single-mode>), or stdin closed on a run started with [`--input-format stream-json`](</docs/en/cli-reference#cli-flags>). The run is ending and takes no more input, so a retry returns the same reason. Have your mod stop making the refused call. If you start the run yourself, next time keep that input open until your mod has no more calls to make. * **`the session was stopped and nobody has sent input since`** : the run was interrupted, for example with the Agent SDK’s [`interrupt()`](</docs/en/agent-sdk/typescript#query-object>). To make the call again after the next message from the user or the SDK application, follow Retry a refused or dropped call. -### - -​ - -A `claude -p` run with your mod never exits +### A `claude -p` run with your mod never exits If your mod submits a prompt at the end of every turn, each prompt starts another turn. Without [`--max-turns`](</docs/en/cli-reference#cli-flags>) or `--max-budget-usd`, a `claude -p` run that loads the mod goes on until you stop it yourself. To make the run end on its own, add either flag to the command in your shell. If other people start the run, have your mod stop submitting prompts once its work is done. This command adds `--max-turns`: @@ -369,11 +293,7 @@ Once the run reaches that limit, the mod’s next prompt is refused instead of starting a turn, and the run ends. If the run still goes past the limit, run `claude --version` in your shell, and [update Claude Code](</docs/en/setup#update-claude-code>) if yours is earlier than v2.1.304. The mod’s prompts are refused at the limit from v2.1.299. If your mod spawns subagents, their turns count toward `--max-turns` from v2.1.304. -## - -​ - -Send and receive messages between sessions +## Send and receive messages between sessions A mod can send a plain-text message to another of your sessions, to one of this session’s subagents, or to a teammate in its [agent team](</docs/en/agent-teams>). It can also observe the messages that arrive and leave. To send one, call `$.session.send({ to, text })`, which makes the same delivery the SendMessage tool makes. Set `to` by who receives the message: @@ -401,11 +321,7 @@ A session set to [refuse inbound messages](</docs/en/cross-session-messaging#control-inbound-messages>) refuses a message before `session.receive` fires, so a hook never sees it. A message that’s held for your approval reaches the hook first, so a mod can read a message you haven’t approved yet. The hook’s `next(e)` rejects when the message isn’t delivered. The sender’s name on a received message is whatever the sender wrote, so don’t base a decision on it. -## - -​ - -Reach files, processes, and the network +## Reach files, processes, and the network A mod reaches the file system, processes, and the network through the mods API, with the same permissions as the user running Claude Code. The hooks module itself has no Node.js APIs, no timer globals such as `setTimeout`, and no network or file access of its own. Standard JavaScript and web APIs such as `URL`, `TextEncoder`, `AbortController`, and `crypto.subtle` are available. Each namespace below covers one kind of access: @@ -432,11 +348,7 @@ * **`$.process.spawn started, and a plugin withheld its result:`** : the refusing mod hadn’t read the command’s output to the end. Claude Code stops the command if it’s still running. * **`$.process.spawn ran, and a plugin withheld its result:`** : the refusing mod had read the command’s output to the end, so the command had exited -### - -​ - -Read all settings, one source, or one key +### Read all settings, one source, or one key `$.settings.read()` resolves to one object that holds the settings from all sources in use, merged by [precedence](</docs/en/settings#settings-precedence>). Pass `{ source }` to read one source instead, `{ key }` to read one key, or both: @@ -457,11 +369,7 @@ For `key`, pass the exact name of one top-level key, not a dotted path into a nested object. The `key` argument requires Claude Code v2.1.304 or later. -## - -​ - -Next steps +## Next steps * [React to events](</docs/en/plugins/mods/events>): hook tool calls, prompts, and turns * [Draw in the interface](</docs/en/plugins/mods/interface>): show what your mod collects in a pane or above the prompt
modified Share session output as artifacts View current →
Show diff (466 lines)
--- a/artifacts.md +++ b/artifacts.md @@ -2,11 +2,7 @@ An [artifact](<https://claude.com/features/artifacts>) is a live, interactive web page that Claude Code publishes from your session to a private URL on claude.ai. You open it in a browser, and it updates in place as the session continues. Share it from the page header when you want someone else to see it too. -## - -​ - -When to use an artifact +## When to use an artifact Use an artifact when terminal text is the wrong medium for what Claude produced: output that is easier to look at and interact with than to read line by line. Claude builds the page from anything your session can reach, including your codebase and data it pulls through your [connected tools](</docs/en/mcp>), so the page can show things that would take paragraphs to describe. For example, ask Claude to: @@ -19,19 +15,11 @@ See What you can build for prompts that match these, and Pull live data with MCP connectors for the connector-backed board’s prompt. -### - -​ - -What an artifact is not +### What an artifact is not An artifact is a capture of work: one self-contained page with no backend, so it can’t serve multiple routes. For a hosted internal tool with a backend, deploy it on your own infrastructure instead. See Page constraints for the full set of limits. -## - -​ - -Create an artifact +## Create an artifact Claude may publish an artifact on its own when the output suits a page, or you can ask for one directly. To ask, name the feature or describe the visual output you want in plain language. A good candidate is anything easier to see than to read as text, such as an annotated diff, a chart, or a set of options to compare. The prompts below are two examples; see What you can build for more patterns. @@ -48,11 +36,7 @@ Claude picks the artifact’s title and a browser-tab icon that matches what the page is, such as a chart or a calendar. The title appears in your gallery of artifacts on claude.ai and in shared links. Ask Claude for a specific title or tab icon if you want one. If Claude responds that it can’t publish, or writes a local HTML file without a link, artifacts aren’t enabled for your session. Check the Availability requirements. If the terminal shows `Artifacts need a claude.ai login`, see [that error’s entry](</docs/en/errors#artifacts-need-a-claude-ai-login>) for how to sign in. -### - -​ - -When Claude Code asks before publishing +### When Claude Code asks before publishing A new artifact that Claude publishes in response to a prompt you type goes through without a permission prompt or classifier review. In these cases Claude Code asks you first, or in [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) has the classifier review the publish: @@ -67,11 +51,7 @@ To let Claude read a file outside your [working directories](</docs/en/permissions#working-directories>) without your approval, add its folder as a working directory with [`--add-dir`](</docs/en/cli-reference#cli-flags>) at launch or `/add-dir` during the session. Claude already reads files in those directories, and in the temporary directory it writes pages to, without asking. If a publish prompt includes a sentence such as `Also makes 1 edit to that file on disk.`, Claude is changing the artifact’s file and publishing it in one step. When you approve the prompt, Claude Code publishes the page, then writes the change to your file. -## - -​ - -Update an artifact +## Update an artifact Ask Claude to revise the page, or let a long-running task republish as it makes progress. Claude edits the underlying file and publishes again to the same URL. @@ -81,11 +61,7 @@ Update https://claude.ai/code/artifact/5fbea6f3-... with today's numbers. -### - -​ - -Turn off one-step artifact updates +### Turn off one-step artifact updates A one-step update is a small change Claude makes to an artifact’s file as part of a publish, instead of through an `Edit` or `Write` call. To turn one-step updates off, set [`CLAUDE_CODE_ARTIFACT_PUBLISH_EDITS`](</docs/en/env-vars>) to `0`. This example adds the variable to the `env` block in `~/.claude/settings.json`: @@ -97,11 +73,7 @@ Then quit and relaunch Claude Code, because a running session doesn’t reread the variable. -## - -​ - -Find an artifact again +## Find an artifact again Run `/artifacts` in Claude Code to list the artifacts you own and the ones shared with you. The current session’s artifacts come first, under **This session**. Select an artifact, then press one of these keys: @@ -112,11 +84,7 @@ Claude Code reads the list from your claude.ai account, so `/artifacts` works in a new session and after `/clear`, when an artifact’s link has scrolled out of the terminal. -## - -​ - -Share an artifact +## Share an artifact A new artifact is visible only to you. To share it, open the artifact in your browser and use the **Share** control in the page header. The header also links to your gallery at [claude.ai/code/artifacts](<https://claude.ai/code/artifacts>), which lists every artifact you have created. Viewers in your organization can see who published the page: on an artifact shared within your organization, your name is in the title menu, and on a public artifact it’s in the page header for signed-in viewers in your organization. A viewer who opens a public link without signing in, or from outside your organization, sees the label `Content is user-generated and unverified.` instead of your name. Who you can share with depends on your plan: @@ -124,11 +92,7 @@ * **People with access to a shared folder** : on Team and Enterprise plans, move the artifact to a folder that you own or are an editor of. Move it from the [Artifacts page](<https://claude.ai/artifacts>), which is available if you can use claude.ai chat. Everyone with access to the folder can then open it, and the folder’s owner and editors can change it. * **Publicly** : share a link that anyone on the internet can open, with no claude.ai sign-in required. On Team and Enterprise plans, public sharing is off until an Owner enables it for the organization. -### - -​ - -Link to a specific view +### Link to a specific view If a page has several views, such as tabs or sections, you can link to one of them directly. Ask Claude for the links: @@ -136,19 +100,11 @@ Each link is the artifact’s link with an anchor on the end, such as `#overview`. -### - -​ - -Let someone edit with you +### Let someone edit with you People you share with are viewers by default: they see each version you publish but can’t change the page. On Team and Enterprise plans, you can also make someone an editor. In the share dialog, add a person and switch their role from **viewer** to **editor**. An editor publishes new versions the same way you update the artifact from another session: they give Claude the artifact’s URL, or attach it from `/artifacts`, and Claude pulls the current content and republishes with their changes. Everyone with the page open sees each update live. If an editor publishes while Claude holds an older copy of the page, Claude Code refuses a publish built on that copy. Claude then merges its changes onto the newer version and publishes again. -## - -​ - -Read an artifact shared with you +## Read an artifact shared with you When someone shares an artifact with you, you can have Claude read it: give Claude its URL, or attach it from `/artifacts`. Claude reads a page someone else wrote the way it reads a web page with [WebFetch](</docs/en/tools-reference#webfetch-tool-behavior>): it gets a summary of what it asked about rather than the raw page, and the summary reports instructions written into the page instead of relaying them. Claude Code also saves the page’s full source to a local file, which Claude can open when it needs the exact content, such as to republish the artifact as an editor. Claude Code asks for your approval before Claude reads the artifact in these cases, in addition to any prompt your permission mode or rules call for: @@ -159,11 +115,7 @@ When Claude reads the artifact with WebFetch, WebFetch’s own [prompting rules](</docs/en/tools-reference#webfetch-tool-behavior>) still apply. -## - -​ - -Collect comments on an artifact +## Collect comments on an artifact When you share an artifact within your organization, the people you share it with can leave comments on the page, and you can have Claude read those comments and reply to them. You need Claude Code v2.1.221 or later. Claude reads the comments in two cases: @@ -180,11 +132,7 @@ * You’re not in your first session since you installed Claude Code or upgraded from a version before v2.1.221. In that [first session after an install or upgrade](</docs/en/env-vars#first-session-after-an-install-or-upgrade>), Claude might not be able to read comments yet; start a new session and ask again. * You haven’t turned feature-flag fetching off. -### - -​ - -Let Claude reply to comments on its own +### Let Claude reply to comments on its own After your session publishes an artifact, Claude Code watches that artifact for comments. When someone who can edit the artifact sends a comment to Claude, it reaches your session right away, and Claude can read the thread and reply without you asking. You need Claude Code v2.1.228 or later. If you turned [feature-flag fetching](</docs/en/env-vars#features-that-need-feature-flag-fetching>) off, Claude Code doesn’t watch for comments. Your [permission mode](</docs/en/permission-modes>) decides what Claude does when a sent comment arrives: @@ -200,11 +148,7 @@ A watch that Claude Code started on its own can end after the artifact goes several hours without activity. To start the watch again, publish the artifact again or ask Claude to watch it. If the service that delivers comments becomes unavailable or stops answering, Claude Code keeps trying to reconnect for a while, then stops watching each artifact your session was watching. -## - -​ - -Pull live data with MCP connectors +## Pull live data with MCP connectors An artifact can call [MCP connectors](</docs/en/mcp#use-mcp-servers-from-claude-ai>) each time someone views it, so the page shows current data rather than a snapshot from the session that built it. Connector calls from artifacts are available on Pro, Max, Ultra, Team, and Enterprise plans and require Claude Code v2.1.209 or later. On earlier versions, Claude publishes the page with whatever data the session gathered while building it. To create a connector-backed page, name the connector and the data you want in your prompt: @@ -212,11 +156,7 @@ Claude declares which connectors the page may call as part of publishing, and the page can’t call connectors outside that declaration. Only connectors from your claude.ai account qualify: Claude names them in the declaration, and when someone views the page, each call runs through the viewing account’s own connection to that connector. Local MCP servers you configure in Claude Code, such as servers from `.mcp.json`, can supply data while Claude builds the page, but the published page can’t call them. The page fetches data when it loads and can refresh on an interval or when a viewer uses a refresh control on the page. Responses are cached in the viewer’s browser, so a reopened page renders from the cached responses immediately, then updates with fresh results. -### - -​ - -How connector calls work for viewers +### How connector calls work for viewers When a published page calls a connector, the call uses the account of the person viewing the page, not the account of the person who published it: @@ -226,11 +166,7 @@ When you plan to share a connector-backed page, ask Claude to include a fallback message in each live section that names the connector it needs. A viewer who’s missing the connection then sees what to connect instead of an empty section. You can share a connector-backed page within your organization or publicly, as your plan and organization settings allow. Connector calls don’t run for a viewer who opens the public link without signing in to claude.ai, or from outside your organization. That viewer sees the page without its live sections. -### - -​ - -The page shows no live data for a viewer +### The page shows no live data for a viewer When a connector-backed page renders but its live sections stay empty for a viewer in your organization, work through these causes: @@ -239,11 +175,7 @@ * **Connector calls are turned off for the organization** : an Owner controls the **Enable artifact connectors** toggle in admin settings. * **The page calls tool names the connector doesn’t expose** : the affected sections stay empty for everyone, including you. This can happen when a page names the individual tools behind a gateway-style connector that exposes only a few tools of its own. Ask Claude to fix the tool names the page calls and publish it again. When Claude publishes the page and that connector’s tools are available in your session, Claude Code checks the tool names the page declares against them, warns Claude about names that don’t match, and refuses the publish when none do. Before v2.1.265, it published the page without checking them. -## - -​ - -Offer a file download +## Offer a file download An artifact can offer viewers a file the page generates, such as a CSV export of a table or a PNG of a chart. The viewer saves it through a download control on the page, such as a button. File downloads are a runtime capability that claude.ai enables per account, so Claude checks whether your account has it before it builds the control. Viewers can’t save a file from an ordinary download link or a script on the page, because the artifact viewer on claude.ai blocks any download the page starts itself, including links to `data:` or `blob:` URLs. If a page has download buttons built that way, ask Claude to rebuild them with the downloads capability. To offer a file, ask for the control and the file format in your prompt: @@ -251,69 +183,41 @@ Claude declares the downloads capability as part of publishing, the same way it declares connectors. -## - -​ - -What you can build +## What you can build An artifact is a single HTML page, so anything you can express in HTML, CSS, and inline JavaScript is in scope. The patterns below come up most often. -### - -​ - -Walk through a change +### Walk through a change Ask for a page that renders a diff or a design change with annotations beside the relevant lines, so reviewers can read your reasoning next to the code instead of reconstructing it from a description. Make an artifact that walks through this PR. Render the diff with margin annotations and color-code findings by severity. -### - -​ - -Compare alternatives +### Compare alternatives Ask for several variants on one page so you can evaluate them against each other. This works for layouts, copy, API shapes, or implementation plans. Make an artifact with four distinctly different layouts for the settings panel. Vary density and grouping, and lay them out as a grid with a one-line tradeoff under each. -### - -​ - -Tune with interactive controls +### Tune with interactive controls Ask for sliders, toggles, or input fields bound to whatever you are adjusting, so you can explore values directly instead of describing them. Build an artifact with sliders for the easing curve, duration, and delay so I can try values on this transition. Show the animation live as I move them. -### - -​ - -Bring the result back to your session +### Bring the result back to your session An artifact can act as a lightweight editor for a decision you then send back to Claude. Ask for an export control that produces text you can paste into the terminal, so the result of interacting with the page flows back into the session instead of staying on the page. Make a triage board artifact with each open issue as a draggable card across Now, Next, Later, and Cut columns. Add a "Copy as prompt" button that gives me the final ordering to paste back here. -### - -​ - -Track work in progress +### Track work in progress Ask Claude to keep an artifact current while a long task runs, so anyone with the link can follow along without reading the terminal. Turn this migration plan into a checklist artifact. Check items off as you complete them and add a note for anything you skip. -## - -​ - -Improve the visual design +## Improve the visual design Claude applies a built-in design skill when it builds an artifact, so pages get a deliberate palette, typography, and layout without extra prompting. That skill also looks for an existing design system in your project before choosing its own. Design tokens are the named color, typography, and spacing values your design system reuses. To keep artifacts consistent with your product’s branding, record them where Claude can find them, such as the project’s [CLAUDE.md](</docs/en/memory>) or a theme file in your repository: @@ -325,21 +229,13 @@ Claude treats your design system as higher precedence than its own choices, and your prompt as higher precedence than both. The heading and format above are an example; any clear list of colors, fonts, and spacing works. For typography, Claude can load a typeface from Google Fonts, the one external font source an artifact page can load from. Claude inlines any other typeface as a `@font-face` data URI and gives every typeface a fallback stack, so the page still renders if a font doesn’t load. To use a specific typeface, name it in your prompt or your design system. -## - -​ - -Start from a Slides, Design, or Docs template +## Start from a Slides, Design, or Docs template Instead of building a page from scratch, Claude can start an artifact from one of the templates on your claude.ai account: [Claude Slides](<https://support.claude.com/en/articles/17153992-what-are-artifacts-and-how-do-i-use-them#h_11d5a9a5fa>) for a presentation, [Claude Design](<https://support.claude.com/en/articles/14604416-get-started-with-claude-design>) for a visual design, or [Claude Docs](<https://support.claude.com/en/articles/16923645-get-started-with-claude-docs>) for a document other people will read and edit. Each opens in its own editor on claude.ai, where you and your teammates change it directly or ask Claude to, and export it to formats such as PowerPoint, PDF, or Word. To start from a template, describe what you want, such as “turn the migration notes into a deck for Thursday’s review” or “write this plan up as a doc for the team”. Claude picks the matching template, fills it from your request and from what the session already has, and gives you the link. For a deck or a design you can also run `/slides` or `/design` with a brief. Templates are in beta. They’re on by default on Pro, Max, Ultra, and Team plans. On Enterprise plans, an Owner [turns each template on](<https://support.claude.com/en/articles/16994751-artifacts-admin-guide-for-team-and-enterprise-plans>) under **Organization settings > Artifacts**. If your organization has the Slides template turned off, `/slides` doesn’t appear; if it has the Design template turned off, `/design` doesn’t draft designs. Both commands require Claude Code v2.1.265 or later and a session where artifacts are available. -### - -​ - -Make a slide deck +### Make a slide deck Run `/slides` with a brief that says what the deck covers and who it’s for: @@ -347,11 +243,7 @@ Claude creates a Claude Slides artifact and gives you the link. Open it in a desktop browser to edit or present the deck. If you run `/slides` without a brief, Claude asks what the deck should be about before creating anything. -### - -​ - -Draft a design canvas +### Draft a design canvas To mock up a UI, a screen flow, a landing page, or a poster rather than build a page, run `/design` with a brief. Claude drafts the design as artboards on one canvas and publishes the canvas as a Claude Design artifact. The brief names what you want drawn: @@ -359,19 +251,11 @@ Open the published artifact in a desktop browser to review the artboards. Select an element on an artboard and change it, and your edits save automatically. You can export each artboard as PNG or PDF. -### - -​ - -Write a document with Claude Docs +### Write a document with Claude Docs Claude Docs reaches Claude Code as a claude.ai [connector](</docs/en/mcp#use-mcp-servers-from-claude-ai>) rather than a command. When it’s connected, `/mcp` lists it as `claude.ai Claude Docs`. A request for a document meant for other people then goes to Claude Docs instead of an artifact page: a spec, a proposal, or a write-up of the plan you worked through in the session. Claude gives you the doc’s link when it’s drafted. A document that belongs in the codebase, such as a README, stays a file. To get a file for something Claude would otherwise put in Claude Docs, name the format, such as `.docx` or a Markdown file in the repository. To turn off only the `claude.ai Claude Docs` connector, see [Disable claude.ai connectors](</docs/en/mcp#disable-claude-ai-connectors>). -## - -​ - -Page constraints +## Page constraints Each artifact is one self-contained page. Claude Code wraps the file you publish in an HTML document shell and serves it under a strict Content Security Policy (CSP), which shapes what the page can do. @@ -391,11 +275,7 @@ * Omit interactivity you do not need * Have the page summarize large datasets rather than inline them in full -## - -​ - -Availability +## Availability Artifacts require every condition below. When one is not met, Claude writes a local HTML file or says it cannot publish instead. @@ -409,11 +289,7 @@ Whether artifacts are allowed for your organization comes from your organization’s policy, which Claude Code loads from `api.anthropic.com`. When Claude Code can’t load the policy, artifacts are unavailable. When you ask for one, Claude says why. If a proxy, VPN, or web filter is involved, ask your IT admin to let `api.anthropic.com` through. Claude Code keeps retrying in the background, and artifacts become available once the policy loads and allows them. -## - -​ - -Disable artifacts +## Disable artifacts To turn artifacts off for your own sessions regardless of your organization’s setting, use any of: @@ -426,67 +302,35 @@ Once you turn artifacts off in a [`--settings`](</docs/en/cli-reference#cli-flags>) file or with `CLAUDE_CODE_DISABLE_ARTIFACT`, or your administrator turns them off in [managed settings](</docs/en/server-managed-settings>), no settings file turns them back on. You can also set `"enableArtifact": false` in a project’s `.claude/settings.json` or `.claude/settings.local.json` to turn artifacts off for sessions in that project. An `"enableArtifact": true` in either file doesn’t turn them back on. Honoring the key in project and local settings requires Claude Code v2.1.242 or later. If you add a `WebFetch` deny or ask rule with no `domain:` part, it doesn’t turn artifacts off or block artifact reads. A [`WebFetch(domain:claude.ai)` rule in `deny` or `ask` does apply to artifact reads](</docs/en/permissions#allow-or-deny-every-fetch>). -## - -​ - -Manage artifacts for your organization +## Manage artifacts for your organization Owners on Team and Enterprise plans control artifacts from [claude.ai admin settings](<https://claude.ai/admin-settings/artifacts>). Artifact content is stored on Anthropic-operated infrastructure and is visible only to authenticated members of the publishing organization and the people they share it with, unless the artifact is shared publicly. -### - -​ - -Enable or disable artifacts +### Enable or disable artifacts To enable or disable artifacts for the whole organization, go to [**Organization settings > Artifacts**](<https://claude.ai/admin-settings/artifacts>) and use the **Artifacts** toggle. On Enterprise plans with role-based access control, you can additionally scope artifacts to specific roles: go to [**Organization settings > Roles**](<https://claude.ai/admin-settings/roles>), edit a role, and set the **Artifacts** permission. -### - -​ - -Control connector calls from artifacts +### Control connector calls from artifacts Connector calls from artifacts have their own toggle, separate from the **Artifacts** toggle that turns artifacts on or off. Go to [**Organization settings > Capabilities**](<https://claude.ai/admin-settings/capabilities>) and use the **Enable artifact connectors** toggle. The same toggle governs connector calls from artifacts created in claude.ai conversations. -### - -​ - -Control public sharing +### Control public sharing Public sharing is off by default on Team and Enterprise plans. To let members publish artifacts to public links that anyone can view without signing in, go to [**Organization settings > Artifacts**](<https://claude.ai/admin-settings/artifacts>) and turn on **External sharing** under the **Artifacts** toggle. Turning it back off blocks access through existing public links without changing each artifact’s audience; access resumes if you re-enable it. -### - -​ - -Set a retention policy +### Set a retention policy To set how long artifacts are kept before automatic deletion, go to [**Organization settings > Data and privacy**](<https://claude.ai/admin-settings/data-privacy-controls>). You can set separate retention periods for artifacts that are still private to their author and artifacts that have been shared. -### - -​ - -Review the audit log +### Review the audit log Publishing, sharing, and deleting an artifact each appear in your organization’s audit log under the `claude_artifact_*` event types, the same family used for artifacts created in claude.ai conversations. -### - -​ - -Allowlist the viewer domain +### Allowlist the viewer domain The viewer on claude.ai loads each artifact from a sandboxed `*.claudeusercontent.com` origin. If your organization restricts outbound network access, add that domain to your allowlist alongside `claude.ai`. See [Network access requirements](</docs/en/network-config#network-access-requirements>) for the full list. An artifact that loads a typeface from Google Fonts also requests `fonts.googleapis.com` and `fonts.gstatic.com`. Both hosts are optional. If you block them, artifacts render in fallback typefaces. Block with a fast rejection rather than a silent drop so the font request fails immediately instead of delaying the page’s first render. Artifacts can also load JavaScript libraries, such as React or a charting package, from `cdnjs.cloudflare.com`, `cdn.jsdelivr.net`, `cdn.tailwindcss.com`, `code.jquery.com`, and `unpkg.com`, and from no other external host. If you block those hosts, the parts of an artifact that depend on a library don’t work, and unlike a blocked font, a blocked library has no fallback. Block with a fast rejection here too, so a blocked library request fails at once rather than hanging until it times out. -### - -​ - -List and delete artifacts with the Compliance API +### List and delete artifacts with the Compliance API The [Compliance API](<https://docs.claude.com/en/api/compliance>) provides endpoints to list an organization’s artifacts, retrieve a specific version’s content, and delete an artifact: @@ -498,11 +342,7 @@ For the request and response schemas, see the [Compliance API reference](<https://platform.claude.com/docs/en/api/compliance/apps/code/artifacts>). -## - -​ - -Related resources +## Related resources * Browse [prompting patterns and workflows](</docs/en/prompt-library>) that pair with artifacts * Turn an artifact prompt you reuse into a [skill](</docs/en/skills>) so you can invoke it as a command
modified Authentication View current →
Show diff (205 lines)
--- a/authentication.md +++ b/authentication.md @@ -1,10 +1,6 @@ Claude Code supports multiple authentication methods depending on your setup. Individual users can log in with a claude.ai account, while teams can use Claude for Teams or Enterprise, the Claude Console, or a cloud provider like Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry. -## - -​ - -Log in to Claude Code +## Log in to Claude Code After [installing Claude Code](</docs/en/setup#install-claude-code>), run `claude` in your terminal. Claude Code opens a browser window for you to log in on first launch, except in cases such as these, where it can skip the login prompt: @@ -21,11 +17,7 @@ Admins can direct which login method developers use and require claude.ai logins to belong to a specific organization; see Restrict login to your organization. To log out and re-authenticate, type `/logout` at the Claude Code prompt. Logging out also resets your first-launch setup state, so the next time you run `claude` it walks you through login and setup again. If you’re having trouble logging in, see [authentication troubleshooting](</docs/en/troubleshoot-install#login-and-authentication>). -### - -​ - -Login prompt still appears after an earlier sign-in +### Login prompt still appears after an earlier sign-in If you signed in earlier and first-launch setup shows the login prompt instead of skipping it, check for causes such as these: @@ -34,11 +26,7 @@ * **Required login method** : your sign-in isn’t the kind that [`forceLoginMethod`](</docs/en/settings-reference#forceloginmethod>) in a settings file requires. With `"claudeai"`, an API key from an earlier Claude Console login doesn’t count as an existing sign-in. With `"console"`, a claude.ai account doesn’t. Log in with the kind of account that setting names. * **Older version** : before v2.1.290, the prompt appeared during setup whether or not you were signed in. [Update Claude Code](</docs/en/setup#update-claude-code>) to skip it. -### - -​ - -Log in with multiple accounts +### Log in with multiple accounts To stay signed in to multiple accounts at once, such as work and personal accounts, give each account its own configuration directory. When you start `claude`, set the [`CLAUDE_CONFIG_DIR`](</docs/en/env-vars#variables>) environment variable to the directory for the account you want to use. Each directory has its own settings, session history, and claude.ai login or API key. For example, in Bash or Zsh, add this alias to `~/.bashrc` or `~/.zshrc` so that `claude-work` uses your work account while `claude` keeps your personal one: @@ -46,11 +34,7 @@ After you open a new terminal and run `claude-work` for the first time, Claude Code walks you through login and setup for the new directory. Separate directories don’t keep two Claude Console sign-ins without an API key apart, because Claude Code stores that kind of sign-in outside the configuration directory. -## - -​ - -Set up team authentication +## Set up team authentication For teams and organizations, you can configure Claude Code access in one of these ways: @@ -61,11 +45,7 @@ * [Google Cloud’s Agent Platform](</docs/en/google-vertex-ai>) * [Microsoft Foundry](</docs/en/microsoft-foundry>) -### - -​ - -Claude for Teams or Enterprise +### Claude for Teams or Enterprise [Claude for Teams](<https://claude.com/pricing?utm_source=claude_code&utm_medium=docs&utm_content=authentication_teams#team-&-enterprise>) and [Claude for Enterprise](<https://anthropic.com/contact-sales?utm_source=claude_code&utm_medium=docs&utm_content=authentication_enterprise>) provide the best experience for organizations using Claude Code. Team members get access to both Claude Code and Claude on the web with centralized billing and team management. @@ -90,11 +70,7 @@ Team members install Claude Code and log in with their claude.ai accounts. -### - -​ - -Claude Console authentication +### Claude Console authentication For organizations that prefer API-based billing, you can set up access through the Claude Console. @@ -133,11 +109,7 @@ * [Install Claude Code](</docs/en/setup#install-claude-code>) * Log in with Console account credentials -#### - -​ - -Sign in without an API key +#### Sign in without an API key You can sign in to your Console account without creating an API key, even when your organization doesn’t let developers create them. Choose the Anthropic Console account at the `/login` prompt and Claude Code asks how you want to sign in. Requires Claude Code v2.1.242 or later. Both routes sign you in to Console in the browser and differ in what Claude Code stores afterwards: @@ -159,11 +131,7 @@ Everything else about profiles applies to this sign-in, including where it ranks against your other credentials, the `Profile` row you get in `/status`, and the features that need a claude.ai login. See Anthropic profiles and federation credentials. -#### - -​ - -Stop offering the keyless sign-in on managed machines +#### Stop offering the keyless sign-in on managed machines To stop Claude Code offering the keyless sign-in, use your device management tooling to deploy [`forceLoginOrgUUID`](</docs/en/settings-reference#forceloginorguuid>) in [managed settings](</docs/en/managed-settings>) to each developer’s machine. Set it to your [Console organization ID](<https://platform.claude.com/settings/organization>). Before you deploy it, make sure each developer has a role that can create API keys. Once you deploy it, a developer without that role can’t sign in to Console at `/login`. With only `forceLoginMethod` set to `"console"`, developers can retry a failed sign-in and choose the keyless option. Once `forceLoginOrgUUID` is deployed, the login screen drops that option, but developers can still use an Anthropic profile they have or create with [`ant auth login`](<https://platform.claude.com/docs/en/cli-sdks-libraries/cli/authentication>). After you deploy it, handle these credentials and logins on each machine: @@ -171,11 +139,7 @@ * **Environment and helper credentials** : Claude Code refuses sessions that authenticate with `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, or `apiKeyHelper`, even when managed settings supply them. Remove those credentials, then have developers run `/login` to create a saved API key. * **claude.ai logins** : Claude Code refuses a login to an organization you haven’t listed, including one already in use on the machine. To keep one, add it to a `forceLoginOrgUUID` array. -### - -​ - -Cloud provider authentication +### Cloud provider authentication For teams using Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry: @@ -197,11 +161,7 @@ Users can [install Claude Code](</docs/en/setup#install-claude-code>). -### - -​ - -Restrict login to your organization +### Restrict login to your organization To require that developers’ claude.ai logins belong to a specific Anthropic organization, set [`forceLoginMethod`](</docs/en/settings-reference#forceloginmethod>) and [`forceLoginOrgUUID`](</docs/en/settings-reference#forceloginorguuid>) in [managed settings](</docs/en/managed-settings>). Set `forceLoginOrgUUID` to your organization ID, shown in [claude.ai admin settings](<https://claude.ai/admin-settings/organization>) for Claude for Teams or Enterprise organizations. Claude Code reports an error for a claude.ai login to any other organization and exits at startup if the claude.ai credential in use belongs to an organization that isn’t listed. For Claude Console logins, Claude Code uses `forceLoginOrgUUID` to pre-select the organization on the Console sign-in page when you set it to a single Console organization ID, shown at [platform.claude.com/settings/organization](<https://platform.claude.com/settings/organization>). It doesn’t check which organization the resulting Console credential belongs to, at login or at startup. A developer who logged in with a Console account before you deployed the keys stays logged in, and that saved key is blocked on a machine that also requires the [gateway](</docs/en/claude-apps-gateway>) sign-in or in a session that selects a cloud provider. If you set `forceLoginOrgUUID` in any settings file, Claude Code stops offering the keyless Console sign-in in the sessions that file applies to and creates an API key instead. To direct developers to claude.ai sign-in instead, set `forceLoginMethod` to `"claudeai"`. On Claude Code v2.1.212 or later, every login path listed here applies `forceLoginMethod`. On the terminal’s interactive login screen, reached by `/login` or first-run onboarding, Claude Code pre-selects a `claudeai` or `console` method without enforcing it, so even with `forceLoginMethod` set to `"claudeai"`, a developer can still complete a Console login there. The paths differ on `forceLoginOrgUUID`: @@ -215,11 +175,7 @@ * **Cloud provider sessions such as Amazon Bedrock** : blocked only while an `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, or `apiKeyHelper` credential, or an API key saved by an earlier Claude Console login, is still present on the machine. Remove it and the session starts. These sessions authenticate against your cloud provider, whose access policies govern them * **Anthropic profile or federation credentials** : not blocked unless an `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, or `apiKeyHelper` credential, or an API key saved by an earlier Claude Console login, is also present on the machine. The keys don’t check which organization the profile belongs to -### - -​ - -Restrict which API providers a machine may use +### Restrict which API providers a machine may use [`allowedProviders`](</docs/en/settings-reference#allowedproviders>) in [managed settings](</docs/en/managed-settings>) lists which services a managed machine may reach Claude through, such as the Anthropic API, Amazon Bedrock, or an LLM gateway. It complements `forceLoginMethod` and `forceLoginOrgUUID`, which govern which account a session uses when it talks to Anthropic. Requires Claude Code v2.1.285 or later. @@ -237,11 +193,7 @@ * **Deploy on managed machines** : put the list in the managed source that carries the rest of your policy. The entry’s [Scope note](</docs/en/settings-reference#allowedproviders>) says how a server-managed list combines with it. * **Server-managed settings only** : a list you set only in [server-managed settings](</docs/en/server-managed-settings>) reaches only sessions that fetch your organization’s settings, so treat it as a convenience for machines you can’t reach with device management, not as enforcement. [Platform availability](</docs/en/server-managed-settings#platform-availability>) lists which sessions fetch them. -## - -​ - -Credential management +## Credential management Claude Code securely manages your authentication credentials: @@ -259,19 +211,11 @@ `apiKeyHelper`, `ANTHROPIC_API_KEY`, and `ANTHROPIC_AUTH_TOKEN` apply to the CLI and the surfaces that wrap it, including the VS Code extension, the Agent SDK, and GitHub Actions. Claude Desktop and cloud sessions do not call `apiKeyHelper` or read these environment variables: they use OAuth, except desktop sessions running a [third-party inference configuration](</docs/en/llm-gateway-connect#desktop-app>), which authenticate with that configuration’s credential. -### - -​ - -Renew an expiring login +### Renew an expiring login When the login you created with `/login` is within three days of expiring, Claude Code shows a warning at startup: `Your login expires in 3 days · run /login to renew`. Run `/login` to renew. The warning is informational and never blocks a request: authentication keeps working until the login actually expires. Once the stored login expires and can’t be refreshed, each model request fails with [`Login expired · Please run /login`](</docs/en/errors#login-expired>) until you sign in again. You can check for this state before a request fails: [`/status`](</docs/en/commands>) shows a `Login` row reading `Expired — log in again`, plus the organization and email it has saved for the expired login. The row appears only when the saved claude.ai login is the active credential. The row requires Claude Code v2.1.210 or later. The warning appears only when a claude.ai login is the active credential, and not when a cloud provider, `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, or `apiKeyHelper` supplies the credential. Renewing early matters most for sessions that run unattended. A [background session in agent view](</docs/en/agent-view>) or a [Remote Control](</docs/en/remote-control>) session that outlives the login stops making progress once the credential expires and can’t recover until you sign in again. -### - -​ - -Authentication precedence +### Authentication precedence When multiple credentials are present, Claude Code chooses one in this order: @@ -285,11 +229,7 @@ A signed-in [Claude apps gateway](</docs/en/claude-apps-gateway>) session sits outside this list: it is a provider selection like Amazon Bedrock or Google Cloud’s Agent Platform, and it outranks them. When a gateway session exists, the CLI authenticates with the gateway token even if `CLAUDE_CODE_USE_BEDROCK`, `CLAUDE_CODE_USE_VERTEX`, or `CLAUDE_CODE_USE_FOUNDRY` is set, and credential sources above such as the bearer token, API key, `apiKeyHelper`, and profiles are not used. If your machine’s [managed settings](</docs/en/managed-settings>) set [`forceLoginMethod`](</docs/en/settings-reference#forceloginmethod>) to `"gateway"` or set [`forceLoginGatewayUrl`](</docs/en/settings-reference#forcelogingatewayurl>), and you don’t select a cloud provider through a variable such as `CLAUDE_CODE_USE_BEDROCK` or `CLAUDE_CODE_USE_VERTEX`, your session uses only the gateway sign-in. Claude Code skips the other credential sources and asks you to sign in with `/login`. See [Administrator policy requires a Cloud gateway sign-in](</docs/en/errors#administrator-policy-requires-a-cloud-gateway-sign-in>) for what you see with each leftover credential. Requires Claude Code v2.1.261 or later, or v2.1.265 or later on a machine that sets only `forceLoginGatewayUrl`. If you have an active Claude subscription but also have `ANTHROPIC_API_KEY` set in your environment, Claude Code uses the API key once you approve it. This can cause authentication failures if the key belongs to a disabled or expired organization. Run `unset ANTHROPIC_API_KEY` to fall back to your subscription, and check `/status` to confirm which method is active. When a login and an API key are both configured, `/status` marks the credential that isn’t in use. [Cloud sessions](</docs/en/claude-code-on-the-web>) always use your subscription credentials. If you set `ANTHROPIC_API_KEY` or `ANTHROPIC_AUTH_TOKEN` in the cloud environment, it doesn’t override your subscription credentials. -#### - -​ - -Anthropic profiles and federation credentials +#### Anthropic profiles and federation credentials A profile is a named credential configuration file in your [Anthropic configuration directory](<https://platform.claude.com/docs/en/manage-claude/wif-reference#configuration-directory>), by default `~/.config/anthropic` on macOS and Linux or `%APPDATA%\Anthropic` on Windows. A profile’s auth mode is `oidc_federation` when you set it up for [Workload Identity Federation (WIF)](<https://platform.claude.com/docs/en/manage-claude/workload-identity-federation>) or `user_oauth` when [`ant auth login`](<https://platform.claude.com/docs/en/cli-sdks-libraries/cli/authentication>) wrote it or you signed in to a Console account without an API key. Claude Code doesn’t read profiles or federation variables in [bare mode](</docs/en/headless#start-faster-with-bare-mode>), in Claude Desktop, or in cloud sessions. In those sessions, `/status` shows no `Profile` row. Claude Code checks three sources in this order and stops at the first one that is set. The table shows what sets each source and where it ranks against your `/login` credential. @@ -304,11 +244,7 @@ * **Named profile or federation variables** : unset `ANTHROPIC_PROFILE`, or unset either federation variable * **Active profile** : run `/logout` for a `user_oauth` profile whose current credential you wrote by signing in to a Console account without an API key, run `ant auth logout` for one whose current credential `ant auth login` wrote, or delete the profile’s file from `configs/` in your configuration directory for either auth mode -### - -​ - -Generate a long-lived token +### Generate a long-lived token For CI pipelines, scripts, or other environments where interactive browser login isn’t available, generate a one-year OAuth token with `claude setup-token`:
modified Auto mode classifier request charges View current →
--- a/auto-mode-classifier-billing.md +++ b/auto-mode-classifier-billing.md @@ -4,11 +4,7 @@ At the prompt, Claude Code holds the first action it would check that way until you answer. Auto mode keeps working, and its classifier requests are billed as they were before. The most common cause is an LLM gateway or proxy between Claude Code and the API, and when Claude Code can identify one, the notice names it. Press **Enter** to continue, or see Make the session eligible to keep it from appearing in new sessions. -## - -​ - -Respond to the notice +## Respond to the notice The notice holds the action until you answer it: @@ -17,11 +13,7 @@ To stop using auto mode instead, switch permission modes with `Shift+Tab` after you answer. Where the notice can’t wait for an answer, Claude Code reports the same text and the session continues in auto mode, unless a gateway acknowledgment on this machine in the last 24 hours has dismissed it. In [non-interactive mode](</docs/en/headless>) with `-p` it prints the text to stderr, and in `stream-json` output it emits a `system` warning message, which Agent SDK applications can read from the message stream. -## - -​ - -Make the session eligible +## Make the session eligible If a gateway keeps auto mode’s server-side checks from reaching your sessions and you don’t run it, send the requirements below to your company’s admin or your gateway provider. Where [the upstream accepts the format that the gateway receives](</docs/en/llm-gateway-protocol#format-mismatch-with-the-upstream>), Claude Code expects the gateway to pass requests and responses through unchanged, as the [gateway compatibility guide](</docs/en/llm-gateway-protocol#feature-pass-through>) describes: @@ -34,11 +26,7 @@ Classifier requests are then always Claude Code’s own, billed the same way, and the notice doesn’t appear. On a direct connection to the Anthropic API, the variable requires Claude Code v2.1.281 or later. Setting `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1` while `CLAUDE_CODE_AUTO_MODE_SERVER` is unset turns the server’s checks off as well, except as [Disable pre-release capabilities](</docs/en/llm-gateway-protocol#disable-pre-release-capabilities>) describes. `CLAUDE_CODE_AUTO_MODE_SERVER` is a temporary setting and may be removed in a later release. -## - -​ - -Why the notice appears +## Why the notice appears On a Pro, Max, Ultra, or Team plan, you never see the notice. To find out which sessions ask the server for the classifier checks, see [Server-side classifier review](</docs/en/permission-modes#server-side-classifier-review>). If you see the notice, check for these usual causes: @@ -47,11 +35,7 @@ To check a session that’s in auto mode, run `/status` at the Claude Code prompt: its **Auto mode server** row reads `Enabled` while the server’s checks decide the session’s actions and `Disabled` once the session has fallen back. When a gateway cuts responses short or rewrites the results into a form Claude Code can’t read, you get denials with no verdict in place of this notice; see [Server-side classifier review](</docs/en/permission-modes#server-side-classifier-review>). -## - -​ - -Related resources +## Related resources * [Auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>): what auto mode is and what it blocks by default * [Server-side classifier review](</docs/en/permission-modes#server-side-classifier-review>): which sessions ask the server to check actions, and the Claude Code version each one requires
modified Configure auto mode View current →
Show diff (209 lines)
--- a/auto-mode-config.md +++ b/auto-mode-config.md @@ -12,19 +12,11 @@ * Generate environment entries with `/auto-mode-setup` * Review denials so you know what to add next -## - -​ - -Common boundaries +## Common boundaries Auto mode allows pushes to any branch of the repository you’re working in, including the default branch, and pull request creation by default. A non-default branch whose name marks it as a deploy or publication target, such as `production`, `release`, or `gh-pages`, isn’t covered by that default: the classifier judges a push there on its own terms, including as a production deploy. The push’s content is also still checked, so a force push, a secret entering the commit, or a change that would send secrets outside the repository when CI or a deploy pipeline runs it stays blocked. If you want a human checkpoint before Claude’s push and pull request commands, add permission rules: the recipes below keep auto mode on for everything else. -### - -​ - -Add a human checkpoint +### Add a human checkpoint The most direct mechanism is [`permissions.ask`](</docs/en/permissions#permission-rule-syntax>). Content-scoped ask rules like the ones below are evaluated before the classifier and always force a permission prompt, even in auto mode, because an explicit ask rule is your stated intent to be prompted for that action. Add the rules in your [settings](</docs/en/settings#where-settings-live>): @@ -45,11 +37,7 @@ Never run the action| `permissions.deny`| Blocks before the classifier is consulted. Neither the classifier nor user intent can override it. One-off boundary for this session| State it in conversation, like “don’t push until I review”| The classifier blocks matching actions, but the boundary can be lost if [context compaction](</docs/en/costs#reduce-token-usage>) removes the message that stated it. Use an ask or deny rule for a durable guarantee. -## - -​ - -Where the classifier reads configuration +## Where the classifier reads configuration The classifier reads the same [CLAUDE.md](</docs/en/memory>) content Claude itself loads, so an instruction like “never force push” in your project’s CLAUDE.md steers both Claude and the classifier at the same time. Start there for project conventions and behavioral rules. For rules that apply across projects, such as trusted infrastructure or organization-wide deny rules, use the `autoMode` settings block. The classifier reads `autoMode` from the following scopes: @@ -63,11 +51,7 @@ The classifier is a second gate that runs after the [permissions system](</docs/en/permissions>). For actions that must never run regardless of user intent or classifier configuration, use `permissions.deny` in managed settings, which blocks the action before the classifier is consulted and can’t be overridden. -## - -​ - -Define trusted infrastructure +## Define trusted infrastructure For most organizations, `autoMode.environment` is the only field you need to set. It tells the classifier which repos, buckets, and domains are trusted: the classifier uses it to decide what “external” means, so any destination not listed is a potential exfiltration target. `claude auto-mode defaults` prints three kinds of environment entry. @@ -133,21 +117,13 @@ You don’t need to fill everything in at once. A reasonable rollout: start with the defaults and add your source control org and key internal services, which resolves the most common false positives like pushing to your own repos. Add trusted domains and cloud buckets next. Fill the rest as blocks come up. -## - -​ - -Generate environment entries with `/auto-mode-setup` +## Generate environment entries with `/auto-mode-setup` Run `/auto-mode-setup` to have Claude Code draft `autoMode.environment` entries, and sometimes rule entries too, from your project and your recent sessions in it. If you accept the draft, Claude Code writes it to `~/.claude/settings.json`. `/auto-mode-setup` is available on Pro, Max, Ultra, Team, and Enterprise plans and with a Claude Console API key. On a Pro, Max, Ultra, or Team plan, you need v2.1.228 or later, or v2.1.233 or later on native Windows. On an Enterprise plan or with a Claude Console API key, you need v2.1.283 or later. If the command is missing from your session, see `/auto-mode-setup` returns “Unknown command”. -### - -​ - -What `/auto-mode-setup` reads +### What `/auto-mode-setup` reads If `~/.claude/settings.json` already holds `autoMode` entries, Claude Code starts by asking whether to add to your environment list or replace it, and keeps the rules you wrote either way. Claude Code then asks how you use this project and offers two optional scans before it scans anything. In the scan, Claude Code always reads these sources: @@ -160,11 +136,7 @@ * The first word of each command in your shell history * The remote hosts and names of the repositories under your home directory -### - -​ - -Review and save the draft +### Review and save the draft Claude Code scans in the background, then shows you the draft. You accept or discard it as a whole, so edit `~/.claude/settings.json` afterwards to adjust single entries. When you accept, Claude Code writes the draft and reconciles it with the settings you already have: @@ -174,11 +146,7 @@ Then run `claude auto-mode config` to see the effective result. -### - -​ - -Turn off `/auto-mode-setup` +### Turn off `/auto-mode-setup` Once auto mode has blocked several actions and you still have no `autoMode.environment` entries, Claude Code shows a dialog titled “Teach auto mode about your environment?” at the end of a turn and offers to run `/auto-mode-setup` for you. To stop the offer but keep the command, select **Don’t show again** in that dialog. To turn off both the command and the offer, add this [`skillOverrides`](</docs/en/skills#override-skill-visibility-from-settings>) entry to `~/.claude/settings.json`: @@ -190,11 +158,7 @@ `/auto-mode-setup` is a built-in command rather than a [bundled skill](</docs/en/skills#bundled-skills>), so this `skillOverrides` entry still applies to it, but [`disableBundledSkills`](</docs/en/settings-reference#disablebundledskills>) doesn’t turn it off. -### - -​ - -`/auto-mode-setup` returns “Unknown command” +### `/auto-mode-setup` returns “Unknown command” If typing `/auto-mode-setup` at the Claude Code prompt prints `Unknown command: /auto-mode-setup`, check for these causes: @@ -204,11 +168,7 @@ In a [cloud session](</docs/en/claude-code-on-the-web>), the command prints `/auto-mode-setup isn't available in this environment.` instead. Run it in an interactive session in your terminal. -## - -​ - -Override the block and allow rules +## Override the block and allow rules Three additional fields let you replace the classifier’s built-in rule lists: @@ -255,19 +215,11 @@ Each section is evaluated independently, so setting `environment` alone leaves the default `allow`, `soft_deny`, and `hard_deny` lists intact. Only omit `"$defaults"` when you intend to take full ownership of the list. To do that safely, run `claude auto-mode defaults` to print the built-in rules, copy them into your settings file, then review each rule against your own pipeline and risk tolerance. -## - -​ - -Edit rules from `/permissions` +## Edit rules from `/permissions` To view and edit classifier rules and `environment` entries without opening a settings file, run [`/permissions`](</docs/en/permissions#manage-permissions>) and select the **Auto mode** tab. The tab requires Claude Code v2.1.246 or later, and it appears only when [auto mode is available](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) to your session. Claude Code shows entries from [managed settings](</docs/en/server-managed-settings>) or the `--settings` flag as read-only, and saves every change you make on the tab to `~/.claude/settings.json`. -## - -​ - -Route all shell commands through the classifier +## Route all shell commands through the classifier By default, narrow Bash and PowerShell allow rules such as `Bash(npm test)` stay in effect in auto mode. Claude Code resolves them before the classifier runs, unless the command carries [per-command allowed domains](</docs/en/sandboxing#per-command-allowed-domains-in-auto-mode>). Claude Code suspends only the broad rules that grant arbitrary code execution, such as `Bash(*)` or wildcarded interpreters, together with every rule that names [`Monitor`](</docs/en/tools-reference#monitor-tool>), because Monitor commands run through the shell. This means a narrow rule can still let a destructive argument through without the classifier seeing it, for example a script path or flag the rule’s prefix didn’t anticipate. Set `autoMode.classifyAllShell` to `true` to suspend every Bash and PowerShell allow rule while auto mode is active, so the classifier evaluates every shell command regardless of your allow list, except [critical-path removals](</docs/en/permission-modes#critical-paths>). @@ -279,11 +231,7 @@ This trades latency for coverage: a command that an allow rule would have approved instantly now waits for a classifier decision, and each shell command counts as a classifier call. The setting applies only while auto mode is active, and your allow rules behave normally in other permission modes. -## - -​ - -Inspect the defaults and your effective config +## Inspect the defaults and your effective config The `claude auto-mode` subcommands help you inspect, validate, and reset your configuration. Print the built-in `environment`, `allow`, `soft_deny`, and `hard_deny` rules as JSON: @@ -323,11 +271,7 @@ The command summarizes what it will remove and asks `Reset auto mode configuration to defaults?` before writing; pass `--yes` to skip the confirmation. Reset changes only `~/.claude/settings.json`: `autoMode` rules from [managed settings](</docs/en/server-managed-settings>) or the `--settings` flag still apply. -## - -​ - -Review denials +## Review denials To let Claude retry a blocked action, use the **Recently blocked** tab in `/permissions`: @@ -366,11 +310,7 @@ * **The row reads`This row can't be approved here`**: if you intended the action, tell Claude in your next message and Claude may try it again * **No row, and`Not run` or a classifier error in the conversation**: auto mode’s classifier gave no verdict. To see how to run the action, read [Auto mode cannot determine the safety of an action](</docs/en/errors#auto-mode-cannot-determine-the-safety-of-an-action>) -### - -​ - -Fix a denial with an allow rule, an environment entry, or a retry +### Fix a denial with an allow rule, an environment entry, or a retry Notices read like `bash blocked by auto mode · /permissions · Auto mode: [Data Exfiltration]`. To read the command or URL behind one, use the **Recently blocked** tab, a hook, or the conversation: @@ -386,19 +326,11 @@ You can add the environment entry or `allow` rule from the `/permissions` dialog’s **Auto mode** tab. The text in square brackets, such as `[Data Exfiltration]`, is the name of the rule the classifier matched. To read that rule’s full wording, see Inspect the defaults and your effective config. -### - -​ - -Fix repeated denials +### Fix repeated denials Repeated denials for the same destination usually mean the classifier is missing context. Add that destination to `autoMode.environment`, or run `/auto-mode-setup` to have Claude Code draft the entries, then run `claude auto-mode config` to confirm the change took effect. -## - -​ - -See also +## See also * [Permission modes](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>): what auto mode is, what it blocks by default, and which sessions start in it * [Managed settings](</docs/en/server-managed-settings>): deploy `autoMode` configuration across your organization
modified Best practices for Claude Code View current →
Show diff (360 lines)
--- a/best-practices.md +++ b/best-practices.md @@ -22,11 +22,7 @@ Setup for a whole team is on a separate page: [Set up Claude Code for your organization](</docs/en/admin-setup>). -## - -​ - -Deterministic and non-deterministic instructions +## Deterministic and non-deterministic instructions Every instruction you give Claude Code is one of these: @@ -52,11 +48,7 @@ If you keep adding emphasis to a `CLAUDE.md` line and Claude still misses it, that’s a sign the line belongs in a hook. The reverse holds too: if you have hooks for things that are only preferences, delete them and let Claude decide. -## - -​ - -Tell Claude what it can’t see +## Tell Claude what it can’t see Only write down what Claude can’t find by reading the repo, or what it would otherwise spend time rediscovering every session. @@ -73,11 +65,7 @@ If both are yes, leave it out. -### - -​ - -Write a specific prompt +### Write a specific prompt A specific prompt helps for the same reason, because it gives Claude information it doesn’t already have. If you name the file, describe the symptom, and say what “fixed” looks like up front, you usually save yourself a round of corrections later. The same goes for a preference between two reasonable approaches: Claude can’t read that from the code, so if you care which one it picks, say so up front. @@ -98,11 +86,7 @@ That’s telling Claude about scope, which only you know, rather than how hard to think. And when you’re exploring rather than fixing something specific, a vague prompt like `what would you improve in this file?` is completely fine. You’ll correct a bit more as you go, and that’s the trade-off. -### - -​ - -Brainstorm with Claude first +### Brainstorm with Claude first When you don’t know exactly what you want yet, you don’t have to work it all out before you prompt. Ask Claude to interview you instead: @@ -110,11 +94,7 @@ Claude comes back with multiple-choice questions about the parts you haven’t pinned down: per-user versus per-key limits, what happens to requests over the limit, what’s out of scope. It keeps asking until the answers add up to a spec. Once `SPEC.md` exists, start a fresh session to build from it, so the build begins with a clean context and a written definition of done. It’s also the file you’ll point the reviewer at later, in Give Claude a check to run. -### - -​ - -Keep CLAUDE.md short +### Keep CLAUDE.md short Claude Code loads [`CLAUDE.md`](</docs/en/memory>) into every session, which means every line in it takes a little of Claude’s attention on _every_ task, whether it’s relevant or not. That’s why the file works best when it only holds what Claude couldn’t work out from the code itself: @@ -149,11 +129,7 @@ If Claude keeps ignoring a line that _is_ in `CLAUDE.md`, adding IMPORTANT probably won’t fix it. Either the file has grown long enough that the line gets lost, or the line is a rule that can’t have exceptions, in which case it belongs in a hook. -### - -​ - -Scope rules to one part of the codebase +### Scope rules to one part of the codebase If a rule only matters in one part of the codebase, put it in [`.claude/rules/`](</docs/en/memory#path-specific-rules>) with a `paths:` filter so it only loads when Claude is actually working there. For example, this `.claude/rules/api.md` loads for TypeScript files under `src/api/`: @@ -166,11 +142,7 @@ - Validate request bodies with the zod schemas in src/api/schemas/, don't hand-roll checks - Every new endpoint needs an entry in openapi.yaml, CI fails without it -### - -​ - -Put team procedures in skills +### Put team procedures in skills A more capable model knows more about engineering, but not how _your_ team does a release, what your incident runbook says, or how you want API docs written. That kind of knowledge goes in a [skill](</docs/en/skills>): a procedure or a piece of team knowledge saved at `.claude/skills/<name>/SKILL.md`. Skills are also lighter on context than `CLAUDE.md` for this kind of thing. For a skill Claude can start on its own, it sees the name and description in every session, but only [reads the full file](</docs/en/skills#skill-content-lifecycle>) when the task calls for it. A long release procedure sitting in a skill doesn’t weigh on your unrelated bug fix the way it would in `CLAUDE.md`. @@ -190,11 +162,7 @@ 3. Summarize the PRs merged since the last tag into CHANGELOG.md, one line each, user-facing changes only. 4. Tag `v<new version>` and push the tag. CI publishes from there, never publish from your machine. -### - -​ - -Connect the tools Claude needs +### Connect the tools Claude needs Some of what Claude can’t see lives in another system entirely, like your issue tracker or your error dashboard. If that system has a CLI, that’s usually the easiest way in. With `gh` installed and signed in, for example, Claude will open pull requests and read review comments without any explanation from you. For a CLI it hasn’t seen before, pointing it at `--help` is enough. For systems without a CLI, there’s [MCP](</docs/en/mcp>). You add a server from your shell: @@ -202,11 +170,7 @@ The server then shows up under `/mcp` inside a session. Connected servers add their tool names and instructions to the context even when you’re not using them, so it’s worth [turning off the ones you don’t need](</docs/en/mcp#disable-a-server-without-removing-it>) there. And if you work in a typed language, a [code intelligence plugin](</docs/en/plugins/code-intelligence>) lets Claude jump straight to a definition instead of reading through many files to find it. -## - -​ - -Give Claude a check to run +## Give Claude a check to run Claude stops when the work looks done. If it has nothing to run that tells it whether the work actually _is_ done, “looks done” is all it has to go on. In practice that makes you the test suite, and every mistake sits there until you happen to notice it. If you give it something that comes back pass or fail, Claude can close that loop itself. It makes the change, runs the check, and if something broke it reads the output and fixes it before running the check again. @@ -231,11 +195,7 @@ Once Claude says it’s done, you can also run [`/verify`](</docs/en/skills#run-and-verify-your-app>) in the session, which has Claude build and run the app and look at the result. That catches the kind of problem that tests and typechecks miss. -### - -​ - -Review against your spec +### Review against your spec If you’d rather have the review check the work against your plan than hunt for bugs in general, write the review prompt yourself: @@ -243,11 +203,7 @@ Don’t drop the `skip style` part of that prompt. A reviewer that’s asked to find problems will always find _something_. If you fix every finding, you end up with extra abstraction layers and tests for cases that can’t happen. -### - -​ - -Enforce the check with a Stop hook +### Enforce the check with a Stop hook The `Stop` hook version of the typecheck rule is a few lines in `.claude/settings.json`. Exit code 2 is what blocks the stop. Whatever the command prints to stderr goes back to Claude as the reason it can’t finish yet, which is why the compiler output is redirected there: @@ -267,21 +223,13 @@ To see it work, ask Claude for a change that breaks a type: instead of finishing, it gets the compiler errors back and keeps going until `tsc` passes. If the hook blocks [eight stops in a row](</docs/en/hooks#stop-input>) with no tool call between them, Claude Code overrides the next block and ends the turn. To raise the cap, set [`CLAUDE_CODE_STOP_HOOK_BLOCK_CAP`](</docs/en/env-vars>). -## - -​ - -Enforce the rules that can’t have exceptions +## Enforce the rules that can’t have exceptions If something has to happen every time, make it a hook, a deny rule, or a managed setting. `CLAUDE.md` is for guidelines, and Claude is allowed to decide a guideline doesn’t apply. Take three rules you might have in `CLAUDE.md` today: `Never read .env`, `Always run the formatter after editing`, `Don't touch the migrations folder`. Claude will follow these almost every time. For the few where “almost” isn’t good enough, move them out of `CLAUDE.md` and into configuration that Claude Code (the harness) applies itself. From then on, the outcome doesn’t depend on what the model remembers or decides. -### - -​ - -Enforce steps with hooks +### Enforce steps with hooks [Hooks](</docs/en/hooks-guide>) run something of yours at fixed points in Claude’s loop: before or after a tool call, when Claude tries to stop, when a session starts, and so on. That something can be: @@ -300,7 +248,7 @@ { "matcher": "Edit|Write", "hooks": [ - { "type": "command", "command": "npx prettier --write --ignore-unknown \"$(jq -r '.tool_input.file_path')\"" } + { "type": "command", "command": "f=$(jq -r '.tool_input.file_path') && npx prettier --write --ignore-unknown \"$f\"" } ] } ] @@ -309,11 +257,7 @@ To check the hook, ask Claude to add a badly indented line to a file Prettier formats. The saved file comes back with the indentation fixed. The migrations rule becomes a [`PreToolUse` hook](</docs/en/hooks-guide#block-edits-to-protected-files>) that exits with code 2 for any path under `migrations/`. You don’t have to write it yourself: `write a hook that blocks edits to the migrations folder` works as a prompt, and `/hooks` shows the result. Don’t overdo it, though: a hook is for a rule with _zero_ exceptions, and `Prefer named exports` has plenty, so that one stays in `CLAUDE.md`. -### - -​ - -Limit access with permission rules and the sandbox +### Limit access with permission rules and the sandbox [Permission rules](</docs/en/permissions>) decide what Claude is allowed to run, read, and fetch. `deny` rules hold in every permission mode, including auto and `bypassPermissions`, which is exactly why the `.env` rule belongs there: @@ -337,11 +281,7 @@ Auto mode is a classifier model judging each action rather than a hard rule. It’s good at that, but like any judgment call it can be wrong. You can also tune what it treats as risky, and your org can turn it off entirely, so your “never” rules belong in deny rules or hooks. -### - -​ - -Choose who a rule applies to +### Choose who a rule applies to Where a rule lives decides who it applies to: @@ -351,11 +291,7 @@ Whatever the scope, keep the enforced set small. Every hook and deny rule will occasionally fire when it shouldn’t, and someone has to maintain each one. If you ever find yourself at forty of them, most are probably preferences that Claude could have weighed on its own. -## - -​ - -Change a default +## Change a default The defaults are good enough to leave alone until a task costs more time, tokens, or interruptions than it should. When that happens, run `/usage` in the session to see where it went. @@ -368,11 +304,7 @@ Most of the time you never think about these. When a task does cost more than it should, one of these four is usually why. -### - -​ - -Change the permission mode +### Change the permission mode Both ends of the permission range have a cost: @@ -413,11 +345,7 @@ If you’d rather see every edit and command before it happens, `Shift+Tab` in the session cycles through the permission modes, Manual included, or start with `claude --permission-mode manual` from your shell. And if Manual then asks too often, `/fewer-permission-prompts` scans your recent transcripts for common read-only Bash and MCP calls and adds them to an allowlist in `.claude/settings.json`. -### - -​ - -Change the model and effort +### Change the model and effort [Effort](</docs/en/model-config#adjust-effort-level>) is the main control for how long Claude thinks, and it replaces most of what people used to do with prompt wording. Claude Fable 5.2, Opus 5.5, Sonnet 5.5, and Haiku 5.5 default to `medium`, which is plenty for everyday feature work with a clear scope. The times you’d move it, with `/effort` in the session: @@ -428,11 +356,7 @@ For the model itself, the default Opus 5.5 handles most coding well and Sonnet costs less on routine work. To use [Claude Fable 5.2](</docs/en/model-config#work-with-fable>), run `/model fable`. Haiku is a good fit for subagents doing simple jobs. [Model configuration](</docs/en/model-config>) has the full list per plan and provider. -### - -​ - -Know what subagents cost +### Know what subagents cost Claude delegates to [subagents](</docs/en/sub-agents>) on its own: @@ -469,11 +393,7 @@ Ask Claude to `have the reviewer compare the rate limiter against SPEC.md` and the gaps come back into your session, where Claude can fix them. -### - -​ - -Keep cost and context down +### Keep cost and context down With a 1M-token window on most current models and compaction near the top of it, you’ll rarely run out of context. You can still _pay_ for context you don’t need, though. Every request sends the whole conversation, so a session that’s collected three unrelated tasks re-reads all three on every turn of the fourth. That’s [discounted while the cache is warm](</docs/en/costs#why-usage-climbs-in-a-long-session>) and full price once it expires. [`/usage`](</docs/en/costs>) is the first place to look. On Pro, Max, Ultra, Team, and Enterprise it breaks your usage down by skill, subagent, plugin, and MCP server. It also flags patterns like long context or frequent cache misses once one of them passes 10% of your usage. From there, the usual fixes: @@ -483,11 +403,7 @@ The [prompt cache](</docs/en/prompt-caching>) lasts about an hour on a subscription and five minutes on an API key, cloud provider, or usage credits. Subagents get five minutes unless you change it.On the one-hour cache, a session past about 200K tokens that sits idle is compacted shortly before the cache expires, so after lunch you continue from a summary. If you don’t need the history at all, a fresh session still costs less. -## - -​ - -Steer the session +## Steer the session Watch the first minute, press `Esc` the moment Claude drifts, and after two failed corrections run `/clear` and write a better prompt instead of a third. @@ -501,11 +417,7 @@ Two smaller ones: [`/btw`](</docs/en/interactive-mode#side-questions-with-%2Fbtw>) answers a quick question without adding anything to the history. And for work that spans several days, `/rename oauth-migration` in the session names it, so that [`claude --resume oauth-migration`](</docs/en/sessions#resume-by-session-id-or-name>) from your shell picks it back up later, checkpoints included. `claude --continue` resumes the most recent one. -## - -​ - -Let Claude run without you +## Let Claude run without you Before a run goes unattended, make sure it knows what done looks like, can check its own work, and can only touch what it should. Give it a cap on turns or spend, and have a person approve the result at the end. @@ -519,11 +431,7 @@ Once it’s going, Claude will carry a long task through on its own. The parts that stay with you are starting it, deciding what “done” means this time, and approving the merge at the end. -### - -​ - -Run Claude from a script +### Run Claude from a script [`claude -p "prompt"`](</docs/en/headless>) runs once and exits, which is how Claude Code ends up in CI jobs, git hooks, and shell loops. In a script you’ll almost always want a few more flags: @@ -543,11 +451,7 @@ When a run finishes, Claude replies `OK` or `FAIL`, and a run that hits the turn limit exits with an error instead. Try it on three files first, see what goes wrong, fix the prompt, then run the rest. Auto mode works with `-p` too if you pass `--permission-mode auto`. In a non-interactive run, a classifier block denies that one action and Claude carries on, and repeated blocks don’t pause the run the way they do in a terminal. Read [how the thresholds apply there](</docs/en/permission-modes#repeated-block-thresholds>) before you rely on it. -### - -​ - -Start runs on a schedule or an event +### Start runs on a schedule or an event Once a run is going, Claude can handle the rest by itself. The one thing it can’t do is decide to _start_ , so something has to: you, a timer, or an event like a failed CI check or a new PR. Inside an open session that’s [`/loop`](</docs/en/scheduled-tasks#run-a-prompt-repeatedly-with-%2Floop>), which repeats a prompt on an interval: @@ -557,11 +461,7 @@ Before you leave a cloud scheduled task running, protect `main` with a [GitHub branch rule the task can’t bypass](</docs/en/routines#repositories-and-branch-permissions>). And watch the first few runs of anything new before trusting it unattended. -### - -​ - -Run sessions in parallel +### Run sessions in parallel When you have separate pieces of work going at once, give each its own checkout so the edits can’t collide. [`claude -w feature-auth`](</docs/en/worktrees#start-claude-in-a-worktree>) starts a session in a new worktree, the [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>) runs several of these side by side, and [cloud sessions](</docs/en/claude-code-on-the-web>) run them in the cloud instead of on your machine. A worktree is a fresh checkout, which means gitignored files like `.env` aren’t there and dependencies aren’t installed. For the first, list the gitignored files you need in a [`.worktreeinclude`](</docs/en/worktrees#copy-gitignored-files-into-worktrees>) at the repo root (same syntax as `.gitignore`) and Claude Code copies them into every worktree it creates: @@ -581,11 +481,7 @@ For one big mechanical change across many files, [`/batch migrate every handler to the v2 response helpers`](</docs/en/commands>) splits the work into 5 to 30 units and shows you the plan. Once you approve it, each unit gets its own worktree and opens a PR or reports what happened. From your shell, [`claude agents`](</docs/en/agent-view>) (still a research preview) gives you one screen for everything running in the background on your machine. A second session is also the easiest independent reviewer you can get. One session writes the rate limiter, another reviews `@src/middleware/rateLimiter.ts` without having watched it being written, and you paste the findings back into the first. Same idea as `/code-review`, with you carrying the messages. -## - -​ - -What you can stop doing +## What you can stop doing Every one of these was good advice when it was written. Most were workarounds for something the model couldn’t reliably do yet, and the models have since caught up. If a few are still habits, here’s why it’s safe to drop them. @@ -601,11 +497,7 @@ If any other advice on this page ever starts to feel like busywork, that’s probably a sign it belongs in this table too. -## - -​ - -Related resources +## Related resources * [How Claude Code works](</docs/en/how-claude-code-works>): the loop, the tools, and what loads at startup * [Explore the context window](</docs/en/context-window>): what uses space in a session and when it loads
modified Champion kit View current →
Show diff (189 lines)
--- a/champion-kit.md +++ b/champion-kit.md @@ -1,10 +1,6 @@ This page is for individual engineers who are already using Claude Code and want to help their team adopt it. It covers what to share, how to answer the questions you will get, a thirty-day playbook, and responses to common concerns. Adoption of a developer tool rarely happens because of a rollout announcement. It happens because someone on the team begins using the tool well, talks about it openly, and makes it easy for others to follow. The work you do as a champion has a disproportionate effect: every example you share shortens the learning curve for the engineers who come after you, and every question you answer in public turns one person’s experience into something the whole team can build on. -## - -​ - -The champion role +## The champion role The role consists of three behaviors that reinforce one another. @@ -14,11 +10,7 @@ Be the person people ask| When a colleague asks how you accomplished something, respond with the actual prompt you used so they can apply it directly to their own task.| A concrete, runnable example removes the gap between curiosity and a first successful use, which is where most adoption efforts stall. Grow the circle| Establish a small number of lightweight, recurring habits, such as a dedicated channel or a weekly thread, so that momentum continues even when your attention is elsewhere.| Adoption that depends on a single person is fragile. Adoption that is carried by shared habits continues to compound on its own. -### - -​ - -What this should cost you +### What this should cost you Set expectations with yourself and with your lead. The activities below are intended to fit inside a normal working week, and the role should remain a multiplier on your existing work rather than an additional support responsibility. @@ -29,19 +21,11 @@ Hosting a weekly show-and-tell thread| About 5 minutes| You post the opening prompt; the team supplies the content. Optional pairing or walkthroughs| 0 to 30 minutes| Reserve this for colleagues who are blocked, and offer the [Quickstart](</docs/en/quickstart>) link before scheduling time. -## - -​ - -Share what you discover +## Share what you discover Your own experience is the most persuasive material your colleagues will encounter, because it is specific to the codebase, workflows, and problems you all share. Documentation tells people what is possible; your posts show them what is actually working in your environment. -### - -​ - -What is worth sharing +### What is worth sharing The most useful posts describe a technique a colleague can reuse tomorrow rather than an outcome that is already complete. Techniques compound as they spread through a team; status updates do not. Examples of reusable techniques: @@ -50,11 +34,7 @@ * “I configured a Stop hook so I receive a desktop notification when a long task completes. Configuration is in the thread.” * “Running `/init` generates a `CLAUDE.md` from the repository so the assistant stops re-asking about our conventions.” -### - -​ - -Where to share it +### Where to share it Post wherever your team already reads. The goal is to place examples in the path of normal work rather than to create a destination. @@ -65,11 +45,7 @@ Standups or weekly written updates| Normalizing usage with leads and skip-level managers| One sentence describing one concrete outcome Team wiki or internal documentation| Durable patterns, custom skills, and `CLAUDE.md` examples| A short page, linked from the channel topic so it remains discoverable -### - -​ - -The format that works +### The format that works A screenshot accompanied by a single line of context, or a brief before-and-after description, is generally the right level of detail. Keep each post short enough that someone scrolling past still absorbs the point. A long write-up tends to be saved for later and forgotten, whereas a short post with a screenshot tends to be copied and tried. The example posts below illustrate tone and length; adapt them rather than copying verbatim. @@ -85,19 +61,11 @@ Press Shift+Tab until you see "plan"; it lays out the changes it proposes without editing your source. -## - -​ - -Be the person people ask +## Be the person people ask Once you have shared a few examples, questions will follow. This is where a champion helps the most, because a good answer to one person frequently unblocks several others who are watching the same channel. -### - -​ - -Answer with a prompt rather than an explanation +### Answer with a prompt rather than an explanation When a colleague asks how you accomplished something, the most useful response is the prompt you actually used. They will learn more from running that prompt against their own problem than from any description you could write, and it gives them something they can act on immediately. @@ -107,19 +75,11 @@ out why," and it traced two unjoined promises in the scheduler. Try the same phrasing on your test. -### - -​ - -Point at the feature rather than the documentation +### Point at the feature rather than the documentation A response such as “Try plan mode, press `Shift+Tab` until you see it” is more useful in the moment than a link to the documentation. If the person needs more depth later they will find it on their own; right now they need the single thing that unblocks them. -### - -​ - -Questions you are likely to hear +### Questions you are likely to hear Question| Suggested response| Follow-up resource ---|---|--- @@ -131,19 +91,11 @@ ”Is this just autocomplete?”| Offer a brief demonstration in which Claude explains an unfamiliar file, traces a bug across services, or drafts a migration plan. These tasks require reasoning across the repository rather than completing a single line.| A two-minute live demonstration ”What about security and data handling?”| Refer this question to your administrator. Your organization’s deployment and data-handling policy is already configured, and champions should not improvise this answer.| [Security](</docs/en/security>) · [Data usage](</docs/en/data-usage>) -## - -​ - -Grow the circle +## Grow the circle The objective is to establish a small number of lightweight habits that allow momentum to continue after you have stopped actively driving it. You don’t need to build a program or own a rollout. When questions in the channel are being answered by people other than you, the role has done its job. -### - -​ - -Patterns that tend to work +### Patterns that tend to work Pattern| How to run it| Effort required ---|---|--- @@ -154,11 +106,7 @@ Pair on a first task| Offer a single fifteen-minute pairing session to anyone getting started. One successful outcome on their own code is more persuasive than any presentation.| About fifteen minutes per person Identify the next champion| The colleague who asks you the most questions is usually ready to take on this role. Forward them this page and divide the channel responsibilities between you.| Negligible -### - -​ - -Thirty-day playbook +### Thirty-day playbook If a loose plan is helpful, the sequence below reflects what tends to work across most teams. Adjust freely to fit your context. @@ -186,19 +134,11 @@ Identify a second champion and share a brief summary of what is working and what is not with your lead or administrator.**Signal that it is working:** questions in the channel are being answered by people other than you. -### - -​ - -When someone wants to go deeper +### When someone wants to go deeper You are the warm introduction rather than the onboarding program. When a colleague moves past “should I try this” into “how do I become effective with it,” point them to the [Quickstart](</docs/en/quickstart>) and [Common workflows](</docs/en/common-workflows>) pages. They contain short sections covering the features that are useful but difficult to discover on your own. -## - -​ - -Respond to common concerns +## Respond to common concerns Healthy skepticism is expected; engineers should be cautious about tools that touch their code. The most effective response is rarely to argue the general case. Instead, acknowledge the concern, offer a brief reframe, and propose one concrete demonstration on the person’s own code. Most concerns are resolved by a single successful experience. @@ -210,11 +150,7 @@ ”I tried it once and it hallucinated.”| This is usually a context problem rather than a model problem. @-mentioning the relevant files, running `/init`, and providing the actual error output typically resolves it.| Re-run their original prompt with proper `@`-context. ”We do not have time to learn another tool.”| Claude Code is a terminal command rather than a platform. If it does not return value within the first session, it is reasonable to set it aside.| A two-minute install followed by one real bug. -## - -​ - -Quick-reference sheet +## Quick-reference sheet The techniques below are the ones that most reliably move someone from a first trial to daily use. Pin this table in a channel or share it on its own.
modified Claude Code changelog View current →
Show diff (4077 lines)
--- a/changelog.md +++ b/changelog.md @@ -1,14 +1,320 @@ 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.323 + +November 12, 2026 + +**Added** + + * Added Code Mode, an experimental opt-in in which Claude writes JavaScript to call its tools; see <https://code.claude.com/docs/en/code-mode> to turn it on, or to turn it off for an organization + * Added `engines["claude-code"]` to `plugin.json`: plugins outside their stated Claude Code version range are not installed, updated or loaded, and install and update pick the newest version that fits + * Added type checking of a plugin’s TypeScript hooks module to `claude plugin validate`; each finding is a warning, and `--strict` fails on it + * Added to `claude plugin validate` the `$` nouns a mod’s `engine.create` hook adds, withholds or replaces + * Added support for `CLAUDE_CODE_AUTO_MODE_MODEL` in managed settings for Claude Desktop sessions on third-party providers (takes effect once Claude Desktop includes this version) + * Added an options menu (stop, switch to usage credits, upgrade) when a model needs usage credits that are turned off or used up + * Added a progress heartbeat every 30 seconds while hooks run long in `claude -p` and SDK sessions, so a host such as Claude Desktop won’t end the turn as hung (once it includes this version) + * Added `.docx` support to Artifact tool asset uploads + * Added a `/diff to close` hint to the diff panel, and the keys that focus and close a panel to the `?` shortcut guide + * Added a start-up warning for Bash allow rules with a `*` in a variable’s value, such as `Bash(PORT=* npm run dev)` + * Added a warning when a plugin’s language server can’t start, naming the server and what to check + * Added a one-time startup notice naming `CLAUDE_CODE_PERFORCE_MODE` when Perforce settings are found and the mode is off + * Added `CLAUDE_CODE_DISABLE_AGENT_PROGRESS_SUMMARIES` (available since 2.1.318): set it to `1` to turn off subagent progress summaries and the requests that write them (anthropics/claude-code#86879) + * Added `CLAUDE_CODE_RESUME_HINT_COMMAND`, which a program that starts Claude Code can set to have the exit hint name its own resume command + * Added `unsetOptionCount` to the `claude plugin install --json` result: how many `userConfig` options are not yet set + * Added `isPromptCovered` to the props a mod’s pane is drawn with, telling it when a dialog or a field above the prompt covers the prompt + * [VSCode] Added a Claude Code trust prompt before the first session in a folder you haven’t trusted; declining leaves the folder’s settings and MCP servers unused + * [VSCode] Added the live output of a running Bash or PowerShell command to the chat, under the command’s card + * [Claude Code on the web] Added a failure notification when a scheduled task’s run can’t start because its settings require a sandbox that isn’t available where it runs + * [Claude Code on the web] Added the No repository option to the repository picker for new sessions on a self-hosted environment + * [Claude Code on the web] Added a warning to a cloud session’s Delete dialog when deleting it will pause scheduled tasks that run in that session + * [Remote Control] Added a Try again button to the error shown when the computer running your session is signed out of Claude Code + * [Claude Tag] Added Claude Tag sessions started in Slack to the Compliance API on Enterprise plans, in beta: list the sessions and read their transcripts + * [Claude Tag] Added a confirmation step when an admin turns off Claude Tag for the organization, with a dialog that says what stops + * [Claude Tag] Added a Retry button to a Slack channel’s Configure page for when its settings fail to load + * [Claude Tag] Added a Scope filter to the Network events tab of Claude Tag’s Activity page, so admins can download one scope’s events instead of the whole organization’s + * [Code Review] Added a Download CSV button to Code Review admin settings: export review costs per repository by month, week or day, for one repository, one GitHub organization or all + +**Changed** + + * Self-hosted runner: Reverted the exit code of an on-demand runner whose work order was superseded to 1; 2.1.321 and 2.1.322 had changed it to 0 + * Changed `/security-review` to ask before Claude runs it, and skills’ inline git commands to stop in bare-repository worktrees and similar folders until you allow them, outside auto mode and bypass + * Changed how many messages each of your sessions on the same machine can send the others without a prompt from you, from about 20 to 100,000 + * Changed the number of messages a Claude Desktop Code tab session can send to your other sessions before it waits for you to type again from 20 to 100,000 + * Changed organization settings and policy requests to no longer use a proxy set only by `ALL_PROXY`; set `HTTPS_PROXY` if your network needs a proxy for them + * Changed the context window assumed for a model ID that Claude Code doesn’t recognize from 200K to 1M; use `/autocompact` to compact earlier, or `CLAUDE_CODE_DISABLE_1M_CONTEXT=1` to keep 200K + * Changed sessions on other vendors’ models with a smaller window: once full, they can fail every turn until `/clear`, so set `CLAUDE_CODE_DISABLE_1M_CONTEXT=1` before they fill + * Changed Claude Code’s own ripgrep and most internal git commands to run without most of its sign-in tokens and API keys, so a credential helper or hook under such a git command no longer finds them + * Changed `MCP_SDK_GENERATION=v1` to run the v2 MCP client in a compatibility mode (earlier handshake, relaxed OAuth sign-in checks), because the v1 MCP client is removed + * Changed the tool Claude uses to finish an MCP server sign-in so that it asks you to confirm, even in bypass and auto modes; where nobody can be asked, such as in `dontAsk` mode, use `/mcp` + * Self-hosted runner: Changed a session at a connector’s approval prompt or sign-in inside a running tool to be released as paused at the idle or lifetime limit; a late answer resumes from a fresh clone + * Changed artifact updates to ask first, even under an allow rule, when people outside your organization can see the artifact or Claude can’t check who can + * Changed `glab config set` without `--global` or `--host`, and `glab config edit --local`, to fail read-only inside the Bash sandbox; run them outside it + * Changed the Bash sandbox on macOS, Linux and WSL to ignore write access granted through a symlink in a writable folder that leads elsewhere or to a missing path; grant the real path instead + * Changed “don’t ask again” so an allow rule that looks like it holds a secret, or would be saved to a `settings.local.json` that git tracks, lasts for the session only and isn’t saved + * Changed the sandbox on macOS and Linux: `git worktree add`, `move` and `remove` now fail read-only, as do commits in a worktree the session wasn’t started in or given, even one inside the project + * Changed start-up to stop when a `--settings` file isn’t valid JSON and has a `sandbox` key, even one that turns the sandbox off + * Changed what happens when a tool’s permission check fails with an error after a `PreToolUse` hook returned “allow”: Claude Code now decides the call as if no hook had answered + * Changed what happens when a tool’s permission check fails on input that a `PermissionRequest` hook rewrote: Claude Code now asks again, or refuses the call where nobody can answer + * Changed the GitLab merge request badge to show only for the repository a sandboxed session opened in + * Changed the `claude mcp add --help` example to a local command + * Changed mods: a `*`, namespace or negated hook on `engine.create` now only observes. To add or withhold a `$` noun, hook `engine.create` by name + * Changed `claude plugin validate` to fail a mod whose `engine.create` hook isn’t written in the one accepted form; installed mods keep loading + * Changed marketplace and plugin installs to fail when a git submodule isn’t on the commit its repository records + * Changed project (`.mcp.json`) MCP server approvals to match the server’s exact name; an approval entry written in another spelling now asks again + * Changed self-hosted runners under `--trust-workspace false` and VS Code sessions in an untrusted folder: the repository’s settings can no longer disable your hooks or turn plugins on or off + * Changed `tool.list` plugin hooks so the tools they add or remove apply to the model and every agent + * Changed `claude plugin install` and `/plugin` to show a warning instead of success when a plugin’s install command writes to stderr + * Changed claude.ai chats and Cowork tasks to check a plugin file for secret keys before sending it, and to ask first if it may hold one + * Changed `claude rm` and the agents view to say a session is removed from the list, not deleted; `claude rm` help says the conversation is kept and `claude --resume` lists it + * Changed `/stickers` to say that the sticker pack is all claimed for now, instead of opening a page in the browser + * Changed a managed settings `policyHelper` to no longer take environment variables from user or `--settings` files; set what it needs in managed `env` or the launching shell + * Changed a `/skill` or `@file` typed between two files picked in claude.ai or the desktop app, or after a picked file and a link, to no longer take effect + * Changed split-pane agent teammates to check that requests come from their team lead: one that outlives its lead has its asks refused, and plan approvals must be re-sent after `/clear` or `/resume` + * Changed worktree creation to refuse checkouts whose `.git` folders are links or hold hard links, such as git-new-workdir layouts and `cp -al` copies; use a plain clone + * Changed what Claude is told after safeguards stop a forked skill or a workflow agent: retry with a narrower prompt or tell you, instead of doing the work itself + * Changed browser tool calls (Claude in Chrome, the desktop browser pane) to refuse some escaped or JSON-text inputs and tell Claude how to respell them + * Changed workflows so that a prompt an app marks as not typed no longer reaches their agents as your request + * Changed computer use on macOS to refuse key chords that hold Space with Control or Option, and more system shortcuts that need your grant + * Changed first-run setup in Terminal.app to name the “Use Option as Meta key” setting, what Option stops typing, and how to undo it before you agree + * Changed the maximum of `CLAUDE_CODE_OVERLOADED_RETRY_MAX_DELAY_MS` from 64000 to 300000 + * Changed workflows in the desktop app’s Code tab to pause at a usage limit and continue after it resets + * Changed the spend limit and 1M context errors, and `/usage-credits`, in cloud sessions and under Remote Control: they no longer give a web address + * Changed which MCP servers are reported by name in OpenTelemetry exports to follow the current connector directory + * Changed `/logout` in a background session, which had no effect: it now signs out every session on the computer, deletes stored MCP logins and plugin secrets, and ends the session, as in a terminal + * macOS: Changed the Bash sandbox so `lsof` and similar tools may show less about processes a command did not start + * Changed cloud scheduled tasks: a `PostToolUse` hook from your own settings can no longer replace the plan in `ExitPlanMode`’s result + * Changed `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` in Anthropic-hosted cloud sessions to stop applying to auto-memory extraction and, in some sessions, to `/btw`; the main conversation still follows it + * Removed the `subagentStatusLine` setting: subagent rows always use the default look, and settings files that still hold the key load as before + * Deprecated a plugin’s `agent` setting: it still applies, and now warns at startup, in `claude plugin list` and in `claude plugin validate` + * [VSCode] Changed opening a Claude Code on the web session in a folder where Claude Code’s sandbox is on: the extension no longer switches to the session’s branch for you, and the dialog says why + +Show 21 improvements + + * Improved sign-in errors in `/login` and `claude setup-token` for a rejected, unreachable or timed-out request: they now say what happened and what to check + * Improved Bash permission checks so the same command more reliably gets the same answer on a slow or busy machine + * Improved Bash permission checks: some commands that could run differently from how they were checked now ask for permission + * Improved `/mcp` to show how many of a server’s tools were left out because the API would reject their input schema, and why + * Improved the “Not now” choice when Claude Code asks to turn on the mods it writes in a session: it now says when they load + * Improved the error for an MCP tool call whose connector ID is mistyped by a character or two: for a server that the host application registered, it now names the tool to call + * Improved Claude Desktop and cloud sessions for claude.ai accounts with more than 2,000 plugins turned on: a shorter wait at startup, and Claude can now say why plugins are missing + * Improved memory use with many subagents: a finished subagent’s transcript is freed sooner instead of staying in memory while later subagents run + * Improved installing with the install script: the latest version is no longer downloaded twice + * Improved WebFetch speed and memory use on deeply nested pages + * Improved the `cleanupPeriodDays` cleanup to count folders it can’t read as errors + * Improved the Claude apps gateway’s `/v1/models` to state `max_input_tokens` for models whose context window is certain on every upstream + * Improved `ToolSearch` to say when a tool Claude searched for by its short name is already available, instead of only reporting no match + * Improved start-up on Linux when `/home` is an autofs map: Claude Code no longer looks up files in `/home` itself. Set `CLAUDE_CODE_AUTOMOUNT_ROOTS` for a map root deeper than one folder below `/` + * Improved the Fable limit message in `-p`, SDK, IDE and cloud sessions: it now says when the limit resets, along with how to continue + * [VSCode] Improved sign-in errors behind TLS-inspecting proxies: a certificate failure now says what to do, as the terminal does + * [Claude Code on the web] Improved the message when a file fails to upload to a cloud or Remote Control session: it now gives the reason, such as too many pages, a password or a time-out + * [Claude Code on the web] Improved adding a repository Claude can’t access to a cloud session: a short message and a Reconnect GitHub button replace the long error + * [Claude Code on the web] Improved the message when some network secrets can’t be added to a new cloud environment: it lists each host, says why where it can, and stays until you dismiss it + * [Claude Code on the web] Improved the new-session repository picker when GitHub single sign-on hides organizations: it now says so even with other repositories listed, and links to reconnect GitHub + * [Claude Code on the web] Improved the Git providers page when your GitHub sign-in has expired: it now asks you to reconnect instead of silently hiding organizations you can link + +Show 195 bug fixes + + * Fixed running `/compact` again, or after a command such as `/context`, summarizing away a message that Claude had not answered yet + * Fixed a resumed session joining your next message to an old interrupted message that was not resumed + * Fixed a memory spike at the next prompt after Claude changed a very large file + * Fixed a setting saved in a running session undoing a hand edit made to `settings.json` moments earlier; a settings file you delete during a session now stays deleted + * Fixed `claude plugin` commands and `claude mcp list` signing you out of a Console profile when they ended while the token was being renewed + * Fixed Edit and Bash running out of memory on certain `/proc` files, and Edit hanging or running out of memory on devices and named pipes + * Fixed Claude Code failing to start, or to clear stored credentials at sign-out, when saving its configuration file failed with “Out of memory” + * Fixed requests sent without streaming failing on errors that streamed requests recover from, such as a rejected image, thinking block or beta header + * Fixed `ExitWorktree`, the worktree exit dialog and `/resume` leaving the session in the wrong folder when the folder the shell was in before entering the worktree had been deleted + * Fixed accents and other combining marks sometimes landing left of the text, leaving stale copies on screen, or silently disappearing when text wraps + * Fixed the last key of a key chord, such as Enter in ctrl+x enter, acting on a dialog’s text field when the chord’s own action isn’t available there + * Fixed `ps` processes piling up when the process listing Claude Code runs before stopping a command takes too long + * Fixed subagent transcripts and large tool results being saved apart from the session’s transcript after entering a worktree created by a `WorktreeCreate` hook or belonging to a nested repository + * Fixed a session on a named Anthropic profile moving to another sign-in when `/fork`, the Left arrow or `--bg` continued it in the background; reopen any session that was open during the update + * Fixed a background session sending a conversation under another sign-in when its named Anthropic profile is missing, changed or overridden; it now stops and says so + * Fixed a session on an API key, auth token or workload identity from its shell (not a setup token) moving to another sign-in in the background; it now stops and says so + * Fixed MCP tool calls ending in the sign-in server’s error, such as `TOKEN_EXPIRED`, instead of asking you to sign in again + * Fixed an expired claude.ai login showing “Credit balance too low” when a saved Console key or `ant auth login` profile without credit was used instead + * Fixed a session on a named Anthropic profile being handed to an older background service that could not keep its sign-in; it now says to restart the service + * Fixed a background session’s sign-in leaving the previous account’s login or other credentials in place; it now clears them for every session on the computer, and a refused sign-in can leave no login + * Fixed background sessions moving between a profile and the stored login when an update restarted them + * Fixed sessions opened before a sign-in keeping signed-out feature flags after the sign-in + * Fixed sessions that kept failing after a Claude apps gateway sign-in expired: once you sign in again with `/login` in another terminal, they carry on at the next message + * Fixed the billing notice naming your `ant auth login` organization when a custom `X-Api-Key` header is set + * macOS: Fixed “Not logged in · Please run /login” coming back right after a successful `/login` or a token refresh when the keychain was slow to answer + * Fixed turns failing in Claude Desktop when an organization’s gateway answers an expired token with 403: Claude Code now asks Desktop for a fresh token and retries + * Fixed the error shown when Amazon Bedrock refuses your account a model: it no longer says to refresh your AWS credentials, it says to enable the model + * Fixed the `awsAuthRefresh` or `gcpAuthRefresh` command sometimes running twice for one request when three or more sessions needed a fresh sign-in at once + * Fixed the `claude -p` warning about an ended claude.ai login to say that `claude auth logout` also removes saved MCP server logins and plugin secrets + * Fixed Bash permission prompts offering “don’t ask again” for commands that write to sensitive paths such as `.git` or `.claude`, where the saved rule did not stop the next prompt + * Fixed a case where some `lsof` commands ran without a permission prompt + * Fixed Bash commands that write a file with `cat > file <<EOF` being shown as “Read 1 file” + * Fixed a case where Bash permission checks judged an `rm` from the wrong folder and skipped the dangerous-removal prompt under bypass permissions or a Bash allow rule + * Fixed `--permission-mode auto` or a settings `defaultMode: auto` starting in a mode that could allow more when auto mode was unavailable. It now starts in Manual mode, which asks first + * Fixed plan files sometimes being written outside the project when `plansDirectory` is set; a write that can’t be shown to stay inside the project is now refused + * Fixed a permission prompt when Claude read the output of its own background command or agent after entering a worktree + * Fixed a case where Bash permission checks missed part of a command + * Fixed a case where the Bash sandbox could switch off during a session + * Fixed Bash allow rules with an attached wildcard, such as `Bash(ls*)`, skipping the permission prompt in some cases; a rule that names a variable, such as `Bash(NODE_ENV*)`, now asks + * Fixed auto mode running behind a gateway at `ANTHROPIC_BASE_URL` on a model whose gateway name contains “haiku”; such a model, other than `claude-haiku-5-5`, is now refused, as Haiku 4.5 is + * Fixed Bash deny and ask rules missing some commands run through `sudo`, `env` and similar wrappers + * Fixed Bash allow rules written with combined `sudo` flags skipping the permission prompt in some cases + * Fixed `sandbox.excludedCommands` letting a command that it does not name run outside the sandbox in some cases + * Fixed a case where the Write and Edit tools could write to a path covered by a `Read` deny rule + * Fixed a case where a Bash command ran without a permission prompt for zsh users with certain non-default shell options set + * Fixed the Bash sandbox not fully protecting Claude Code’s own config on installs still using the legacy config file + * Fixed a permission prompt from a mod’s `tool.check` hook naming every plugin hooked on the tool instead of the one that asked + * Fixed sandboxed commands being able to read Claude Code’s file checkpoint copies under the config directory + * Fixed a rewind sometimes changing your permission mode + * Fixed project settings sometimes being read through a symbolic link that leads to a different folder than the one Claude Code checked + * Fixed HTTP hooks failing with HTTP 500 on Linux when `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB` is set and `sandbox.enabled` is off + * Fixed `claude -p` and the Agent SDK running Bash unsandboxed when `--settings` or SDK settings that turn the sandbox on fail validation; Claude Code now stops at start-up and names the invalid setting + * Fixed `/export` silently stopping early after a long run of calls to an MCP tool that is no longer loaded + * Fixed earlier MCP tool calls missing from a resumed conversation, and lines repeating in scrollback, when the server connects late + * Fixed `claude mcp add --help` splitting long example commands across lines in narrow terminals and pipes, so a pasted example ran without its header + * Fixed plugins with `defaultEnabled: false` staying off in a claude.ai chat’s cloud session after you turn them on in claude.ai + * Fixed `/fast on` and `/fast off` on Vertex not asking a plugin’s `config.set` hook, as the `/fast` menu does + * Fixed documents created through the Claude Docs connector not opening in your browser when you work in a terminal + * Fixed the misleading “not cached” error for a plugin only a repository’s settings enable: it now says it isn’t installed, gives the install command, and shows in text and stream-json `-p` runs + * Fixed mods being able to reword Claude Code’s own confirmation questions + * Fixed a mod’s hot reload sometimes ignoring a file created just after a failed reload + * Fixed marketplaces named `npm`, `pip`, `uv`, `cargo`, `github` or `gh` being refused as reserved names + * Fixed a stopped MCP call, or a stopped shell command in fullscreen, reading as “Called” or “Ran” in a collapsed tool group: it now says no result was recorded and shows its input + * Fixed load errors of plugins enabled by managed settings going only to the debug log in SDK and Desktop sessions: `init.plugin_errors` now lists them + * Fixed plugin installs hiding what a plugin’s install command wrote to stderr when that command succeeded, such as a note that the plugin has no skills yet + * Fixed one malformed entry in a plugin marketplace’s `renames` map making Claude Code ignore the marketplace’s other renames + * Fixed `claude --bg --safe-mode` sessions stopping at startup to ask about project MCP servers that safe mode never starts + * Fixed MCP link prompts offering Accept for non-http links without saying the link wouldn’t open + * Fixed `/mcp` and `/plugins` opening an MCP server’s page with the cursor on “Disable” when the server needs authentication but still holds its sign-in; the page now offers “Reconnect” and opens on it + * Fixed plugins with a version list in `enabledPlugins` staying off with no message: `/plugin` and `claude plugin list` now say why + * Fixed plugins and marketplaces failing to install on Windows when the path of a cloned file reaches 260 characters + * Fixed a Stop pressed right after sending a message showing as an error in remote and SDK sessions while a `UserPromptSubmit` or plugin prompt hook was still running + * Fixed an MCP server staying disconnected with no tools after an Agent SDK app or `claude -p` caller removed and re-added it, when a tool call had tried to reach it in between + * Fixed text-output `claude -p` runs printing nothing to stderr when a `--plugin-dir` mod’s hook hangs or crashes the hooks worker + * Fixed SDK sessions giving an MCP server named by `--allowedTools` or an `mcp_tool` hook less than 2s before the first turn when settings lowered `CLAUDE_CODE_MCP_STARTUP_WAIT_MS` after start-up + * Fixed headless sessions ending when an SDK host sent a null entry in an MCP server’s tools list + * Fixed WebFetch dropping empty table cells and shifting later values a column left + * Fixed temporary files of a session that had changed directory being left behind when the session expired under `cleanupPeriodDays` + * Fixed managed settings (`managed-settings.json`, `managed-settings.d`) sometimes being missed at start-up while another program was rewriting the file: start-up now reads such a file a second time + * Fixed `.claude/settings.local.json` not being ignored globally when the folder became a git repository later, or on a new machine + * Fixed `/diff` waiting for Claude to finish before closing the diff panel in fullscreen + * Fixed `/memory` showing wrong or roundabout paths for folders whose names start with the working directory’s or home folder’s name, and losing slashes in the file path on Windows + * Fixed a broken emoji character in a tool call’s parameter name being resent with later requests, which strict JSON parsers reject + * Fixed a collapsed tool call looking as if it ran after you rejected it with a reason: it now shows “Not run · rejected” + * Fixed a case where part of a saved session could be lost on NFS or FUSE file systems when Claude Code discarded a reply + * Fixed WebFetch not rechecking organization policy and `CLAUDE_CODE_DISABLE_WEB_FETCH` at each call + * Fixed file titles, app names and session names in @-mentions from claude.ai and the desktop app sometimes being treated as text you typed + * Fixed a multi-row status line being pushed off screen by a long prompt in the fullscreen renderer + * Fixed a case where certificate errors behind a TLS-inspecting proxy persisted when the proxy itself is reached over `https://` + * Fixed Pro and Max accounts being offered feedback drafts that their organization would refuse + * Fixed Claude in Chrome’s policy message telling people to contact their admin when no admin setting can turn it on + * Fixed the artifact preview sometimes opening a different artifact than the one Claude just published + * Fixed certificate name-constraint errors being retried for minutes; they now fail at once with a message that says what to fix + * Fixed `claude --teleport` opening an empty session when the server could not find the session’s history, and `claude -p --teleport` exiting without an error when the resume failed + * Fixed a misspelled keybinding modifier, such as `ctl+k`, binding the bare key; the binding is now ignored + * Fixed `/btw` answers and recaps sometimes including earlier replies from the conversation + * Fixed start-up requests switching from an organization’s managed proxy and CA settings to user-set ones when a read of the managed settings file failed + * Fixed Claude giving a wrong reason when a new message interrupted a file it was sending you + * Fixed `CLAUDE_CODE_RESUME_INTERRUPTED_TURN` re-running a turn that a hook’s `continue: false` had stopped + * Fixed Claude being told that automatic model switching is off when safeguards stopped a subagent whose model had no other model to switch to + * Fixed the changed-files list of remote sessions leaving out files added with `git add -N` before the first commit + * Fixed some Claude in Chrome tool calls, such as `browser_batch`, not showing the tool’s name in the fullscreen transcript (ctrl+o) or in a subagent’s progress + * Fixed subagent progress summaries skipping an update when the reply took between 10 and 20 seconds + * Fixed `claude doctor` and `/status` saying a linked managed settings file is still read when it could not be read + * Fixed an interactive `--chrome` session giving no reason for starting without Claude in Chrome when your organization’s policy turns it off: a line now says so + * Fixed the `/rewind` list on network paths and hung folders: it named every tracked file as changed, was slow to show labels, and showed none at all when a file read never returned + * Fixed `--debug` and `--debug-file` replacing a file named `latest` in the debug log’s folder + * Fixed a timed-out feedback send being reported as too large; it now says the request timed out + * Fixed screen reader mode cutting off an announcement when the system clock moved forward while it was being read + * Fixed screen reader mode dropping dictated or pasted text, and emoji, typed into an answer to a question or permission prompt + * Fixed the name label under permission and plan dialogs hiding part of some agent names + * Fixed a case where pressing Ctrl+C just as `claude update` finished removed the `claude` command + * Fixed the fullscreen header naming the session’s effort level for a viewed subagent on a different model, which that subagent doesn’t use + * Fixed the model picker and `/model` showing a picked effort level that `CLAUDE_CODE_EFFORT_LEVEL` overrides + * Fixed the tip after a slow worktree creation suggesting a `sparsePaths` list without `.claude`, which left worktrees without your project settings and rules + * Fixed the newest model’s highlight missing from the `/model` picker + * Fixed `/upgrade` and Ctrl+clicked links in fullscreen failing silently when no browser can open: the address is now shown + * Fixed the Claude apps gateway’s JSON logs escaping newlines and other control characters in a message twice + * Fixed terminal control sequences in a subagent’s message taking effect instead of showing as plain text when the message is expanded + * Fixed Claude in Chrome setup saying `/chrome` finishes the connection; it now tells you to restart with `claude --chrome` + * Fixed the Option-key hint appearing while typing ø or π inside words on Danish, Norwegian, Faroese and Greek keyboard layouts + * Fixed a Claude Desktop session getting stuck as busy after another of your sessions sent it the same message twice or many messages at once + * Fixed long tool results staying on disk after a session run with `--no-session-persistence`; they are now removed on normal exit, Ctrl+C or SIGTERM + * Fixed `PreCompact`, `PostCompact` and post-compaction `SessionStart` hooks not receiving `agent_id` and `agent_type` when a subagent compacts + * Fixed `CLAUDE_CODE_TRANSCRIPT_LOCAL_GC` dropping messages from the saved transcript when another process rewrote the file while it was being trimmed + * Fixed the “Now using usage credits” notice repeating or not showing past the weekly Fable limit when Claude Code made a quick side request on a smaller model, such as naming the session + * Fixed Fable’s weekly limit showing no reset time and no options menu in the terminal + * Fixed a wait chosen in the usage limit menu silently moving to a later reset when its request was refused; the menu now opens + * Fixed the spend limit menu offering a lower limit when your current limit couldn’t be loaded + * Fixed `/usage` hiding limit bars for setup tokens and `CLAUDE_CODE_OAUTH_TOKEN`: it keeps the session and weekly bars and says why the rest are missing + * Fixed `/usage` showing a whole-session percentage beside a subagent type’s name, and saying sessions ran 8 hours when it only counts hours with requests + * Remote Control: Fixed sessions showing as disconnected for a minute or more after a network change such as switching Wi-Fi or reconnecting a VPN + * Fixed Remote Control showing nothing while Claude Code asks whether to use usage credits: the question now also shows in the Claude app + * Fixed Remote Control showing a session as running while it waited on a permission prompt that can only be answered in the terminal + * Remote Control: Fixed `claude remote-control` reconnecting as a new computer when restarted in the same folder more than 4 hours after it stopped; it now keeps its identity for up to 30 days + * Remote Control: Fixed sessions left running at shutdown, and finished sessions holding their slot, when the disk stops responding + * Remote Control: Fixed other devices and phone notifications not showing what Claude is asking permission for when `DISABLE_TELEMETRY` or `DO_NOT_TRACK` is set + * Remote Control: Fixed the host exiting, or stopping reading a session’s output, in verbose or debug mode when a tool call’s `command` was a number, boolean or object + * Remote Control: Fixed a host that could stall after sessions failed to start in folders on a filesystem that had stopped responding + * Remote Control: Fixed sessions from the desktop app showing as idle on your phone while background subagents were still running + * Fixed the Agent SDK’s `managedSettings` ignoring the Remote Control, agent view, Workflows and Artifact off switches + * Fixed OpenTelemetry export failing silently when an `otlp` exporter had an endpoint but no `OTEL_EXPORTER_OTLP_PROTOCOL`: it now defaults to `http/protobuf` + * Fixed OpenTelemetry export to the default `localhost:4318` endpoint going through a configured proxy + * Fixed one malformed `OTEL_RESOURCE_ATTRIBUTES` entry dropping all of that variable’s attributes from the OpenTelemetry resource; the others are now kept, and `/status` names the one left off + * Fixed OpenTelemetry `user_prompt` events and interaction spans recording a background agent’s reply when `OTEL_LOG_ASSISTANT_RESPONSES=0` + * Fixed OpenTelemetry exports failing when a proxy took over 10 seconds to reach the collector; it now has 25 seconds, also the most that `OTEL_EXPORTER_OTLP_TIMEOUT` can allow (previously 30) + * Fixed OpenTelemetry `agent.name` showing a user-defined subagent’s name instead of `custom` when an official plugin’s skill launched it + * Fixed `claude agents` showing a status from an earlier turn after a session resumes + * Fixed read-only git commands needing approval, or being refused under `claude -p`, when `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB` is set on Linux + * Fixed `claude agents` losing a typed prompt: Esc now needs a second press to clear it, and ctrl+y restores it + * Fixed the move-to-background key doing nothing in `claude attach` and `claude agents` sessions; to detach with Ctrl+B d, press d within 800 ms of Ctrl+B + * Fixed background sessions ignoring a `DISABLE_ERROR_REPORTING` set only in your shell when the background service started without it + * Fixed false “needs input” notifications in `claude agents` after replying to a blocked session, and repeated ones after a background turn ended with no text and only basic tools such as Bash or Read + * Fixed `claude -p` silently using another model in text output when settings block the requested one; it now warns on stderr + * Fixed `claude -p` printing notes about `deniedModels` and `availableModels` entries on every run; `/status` and `claude doctor` still list them + * Windows: Fixed some file-reading Bash commands running without a permission prompt when given a wildcard or a list of files + * Windows: Fixed Claude Code running a `.cmd` or `.bat` wrapper found beside a program’s `.exe` in the same PATH folder (a `git.cmd` next to `git.exe`, say); it now runs the `.exe`, as `cmd.exe` would + * Windows: Fixed shell commands failing with “Working directory was deleted” on drives where a folder’s real path can’t be resolved + * Fixed a cloud session’s history becoming unreadable if its machine stopped just after the history was rewritten + * Fixed scheduled tasks from an ended session sometimes not running after another session in the same folder used `/clear`, `/resume` or `/branch` + * Fixed an approved plan being answered with “You are not in plan mode” when the approval arrived after the session’s process had restarted, in cloud, self-hosted runner and SDK sessions + * Cloud sessions: Fixed an answer to Claude’s question being lost after a restart in a long conversation + * Fixed a message dropping out of a cloud session’s conversation when the session restarted before Claude replied + * Cloud sessions: Fixed Claude saying an attached image is missing when the message names its file + * Fixed a resumed cloud session making a model call nobody asked for when files arrived right after a chat’s first reply + * Fixed streamed replies in cloud sessions missing text from the middle when the session’s container shut down partway through a reply + * Fixed skill files sent from Cowork cloud sessions sometimes failing to upload on the first try + * [VSCode] Fixed a response that was discarded because its tool call could not be parsed still showing after Claude retried + * [VSCode] Fixed a queued message missing from a conversation or fork when it directly followed a compaction summary + * [VSCode] Fixed the “Buy usage credits on claude.ai” button counting as agreement to pay for Fable while usage credits were off + * [VSCode] Fixed the “extensions want to relaunch the terminal” warning coming back on open terminals after every window reload or restart + * [VSCode] Fixed “Couldn’t load this conversation’s saved history” appearing in a new chat whose Claude process had restarted before the first prompt + * [VSCode] Fixed the sign-in screen showing the login choices again after a pasted code; it now shows “Signing in…” until the sign-in finishes + * [VSCode] Fixed the “You’ve hit your Fable limit” line staying in the VS Code and JetBrains panels after you pick another model + * [VSCode] Fixed the Fable usage warning in the VS Code and JetBrains panels naming usage credits when they’re off or used up + * [VSCode] Fixed the diff tab not opening for multi-line edits on files with CRLF line endings + * [VSCode] Fixed dictation continuing to record after switching sessions + * [Claude Code on the web] Fixed self-hosted sessions staying on “Starting Claude Code” after it had started, when you reopened a paused session without sending a message + * [Claude Code on the web] Fixed a paused session in a self-hosted environment sometimes still showing “Sending” and a Stop button under the “Session paused” banner + * [Claude Code on the web] Fixed pull request updates from GitHub Enterprise Server linking to github.com in cloud sessions; new updates link to your own server + * [Claude Code on the web] Fixed very large GitHub Actions job logs and run log archives failing to download or being cut off in cloud sessions + * [Claude Code on the web] Fixed new cloud sessions started from the iOS app with a repository not getting a branch of their own + * [Claude Code on the web] Fixed an open cloud or Remote Control session’s page staying “Disconnected” after a few minutes of failed connections; it now tries to reconnect by itself + * [Claude Code on the web] Fixed Try again on an open cloud or Remote Control session’s “Connection lost” card sending “Try again” as your message; it now tries to reconnect instead + * [Claude Code on the web] Fixed the Stop button disappearing from a cloud session five minutes into a reply that had shown nothing yet while Claude was still working + * [Claude Code on the web] Fixed an approval prompt sometimes disappearing from a tab left open after a self-hosted runner released the session while it waited for your answer + * [Claude Code on the web] Fixed removing a repository from a scheduled task silently moving its GitHub trigger to another repository; Save now waits until you pick one + * [Claude Code on the web] Fixed git clones and fetches that take longer than ten minutes in a cloud session sometimes being cut off at the very end + * [Remote Control] Fixed your own session saying its environment was deleted when you deleted nothing; it now says your computer is no longer connected + * [Remote Control] Fixed some sessions still showing as running in the session list after the computer disconnected before Claude started; they now show an error mark or as idle + * [Claude Tag] Fixed scheduled tasks in a Slack channel moved between Enterprise Grid workspaces failing to use Slack until someone posted there + * [Claude Tag] Fixed the Approve and post card in a DM with Claude appearing for private or Slack Connect channels, where Claude can’t post; Claude now gets the reason and shows no card + * [Claude Tag] Fixed Remove connector in Claude Tag admin settings being refused when access bundles also held its credentials; it now removes those set on the connector and leaves the bundles’ own + * [Claude Tag] Fixed the Channels tab in Claude Tag admin settings splitting a workspace from its channels across pages; channels now appear right under their workspace + * [Claude Tag] Fixed the Set for Claude Tag link on the Cloud environments admin page not leading to the environment setting; it now opens the Slack page’s Advanced tab, where you set it 2.1.322 November 10, 2026 * Added fast mode on Vertex in the global, us and eu regions, falling back to standard speed if Vertex refuses it - -​ 2.1.321 @@ -143,8 +449,6 @@ * Fixed a restarted cloud session leaving a subagent’s message to the main conversation unanswered * Fixed Claude not being told when you stop or pause a running workflow, so it no longer says the workflow is still running * [VSCode] Fixed a plugin’s permission request showing a name with hidden characters: it now reads “a plugin” - -​ 2.1.319 @@ -308,8 +612,6 @@ * [Claude Tag] Fixed Claude Tag setup blocking launch when the channel list couldn’t fully load; admins can now launch without picking a channel * [Claude Tag] Fixed saving auto mode allow rules in Claude Tag admin settings overwriting another admin’s changes; the save is now refused with a message -​ - 2.1.318 November 4, 2026 @@ -409,8 +711,6 @@ * [Cloud sessions] Fixed reading GitHub Actions logs in cloud sessions: `gh run view --log` and `gh api` log requests now get the log in most environments, not an unreachable redirect * [Remote Control] Fixed side-by-side checkouts of one repository looking identical in the environment menu’s Remote Control rows; each now shows its own folder name * [Claude Tag] Fixed keyboard focus and screen reader announcements in Claude Tag admin setup; pressing Escape in the connect form no longer also closes the Add dialog - -​ 2.1.317 @@ -515,8 +815,6 @@ * [Cloud sessions] Fixed new scheduled tasks ignoring your organization’s default environment: the form now starts on the one an admin chose instead of the Anthropic-hosted default * [Remote Control] Fixed the next message to an idle session going unanswered after you restart `claude remote-control`, when you sent it within a minute of your previous message -​ - 2.1.316 October 31, 2026 @@ -587,8 +885,6 @@ * [Claude Tag] Fixed Claude refusing to edit or append to a canvas it made in a Slack channel, from that channel, once the canvas was also shared to another channel or a DM * [Claude Tag] Fixed untagged replies going unanswered in a Slack Connect thread when both organizations have installed Claude and Slack delivered the reply to the other organization’s app * [Claude Tag] Fixed a cloud scheduled task’s live status checklist in Slack staying half-done; a run can now edit the top-level messages it posted during that run - -​ 2.1.314 @@ -725,8 +1021,6 @@ * [Claude Tag] Fixed Retry on plugin and skill pages in Claude Tag admin settings discarding unsaved access changes after a failed load; your edits now stay in place * [Claude Tag] Fixed the repositories control in Claude Tag admin settings showing the same action twice; its menu now lists only what the button doesn’t already do -​ - 2.1.312 October 27, 2026 @@ -781,8 +1075,6 @@ * [Claude Tag] Fixed Claude in Slack not replying in channels whose environment has network access set to None * [Claude Tag] Fixed Claude in Slack sometimes posting a file in the wrong thread when it was answering in another thread of the same channel * [Code Review] Fixed Code Review reviewing an outdated commit, or none at all, when GitHub delivered a push event late; it now reviews the pull request’s current commit - -​ 2.1.311 @@ -892,8 +1184,6 @@ * [Cloud sessions] Fixed a failed routine API token delete or regenerate showing nothing if the edit dialog had already closed; it now shows an error toast * [Cloud sessions] Fixed cloud environment dialogs, including the admin dialog, accepting duplicate names; they now refuse a name another listed environment already has -​ - 2.1.310 October 23, 2026 @@ -935,8 +1225,6 @@ * [Claude Tag] Fixed Claude Tag admin channel and workspace pages being replaced by a load error when a background refresh of the bundle list fails * [Claude Tag] Fixed Claude Tag’s spend limits page in admin settings reporting that no channels match a filter while channel names are still loading * [Code Review] Fixed the Code Review admin section hiding its repositories and switches after a failed refresh of the repository list - -​ 2.1.309 @@ -1033,15 +1321,11 @@ * [Code Review] Fixed a finished review showing no check on the pull request when earlier tries to create it failed; a final try now adds a completed check * [Code Review] Fixed a push queued behind a running review still starting a review after `@claude review stop`; its check now closes and says why -​ - 2.1.308 October 22, 2026 * Bug fixes and reliability improvements - -​ 2.1.307 @@ -1102,16 +1386,12 @@ * [Cloud sessions] Fixed the repository picker saying “No repositories match” while a search was still running; it now shows “Searching…” until the results arrive * [Cloud sessions] Fixed the “Waiting for a runner” status on self-hosted environments being cut off; with on-demand runners it now counts up from your last message and shows failed attempts -​ - 2.1.306 October 21, 2026 * Fixed `claude -p` inside cloud sessions reporting “Not logged in” when started without the session’s environment variables * Fixed an API error being replaced by “prompt is too long”, and an unneeded compaction, in sessions with many MCP tools - -​ 2.1.305 @@ -1166,8 +1446,6 @@ * [Claude Tag] Fixed a routine set up in a Slack DM thread no longer posting after another routine in that thread restarted the conversation; both now keep posting there * [Claude Tag] Fixed routines set up in a Slack thread reporting success without posting after the conversation ended; those runs are now skipped and the creator is told * [Code Review] Fixed Code Review sometimes not reviewing the newest commit when several pushes landed on a pull request during a review - -​ 2.1.304 @@ -1261,15 +1539,11 @@ * [Claude Tag] Fixed `@Claude !fork` typed outside a thread getting no visible reply; Claude now shows you a private note saying to run it from inside a thread * [Code Review] Fixed pull requests opened within a minute or two of an admin turning on Code Review being silently skipped; they are now retried and reviewed -​ - 2.1.303 October 18, 2026 * Bug fixes and reliability improvements - -​ 2.1.302 @@ -1350,8 +1624,6 @@ * [Claude Tag] Fixed links in Claude’s Slack replies absorbing the closing bold or italic marks, or full-width punctuation, right after them, which broke the link and the formatting * [Code Review] Fixed Code Review setup not resuming after you leave to connect GitHub; back in admin settings, it now reopens at the repository picker -​ - 2.1.301 October 15, 2026 @@ -1418,8 +1690,6 @@ * [VSCode] Fixed the chat panel slowing down during long thinking: it no longer re-parses the whole thinking text on every update * [VSCode] Fixed diagnostics showing “[object Object]” instead of the rule code (e.g. MD013) for some language servers * [VSCode] Fixed the native dictation audio module being loaded, to check microphone permission, where dictation is not offered (non-claude.ai sign-ins, remote windows) - -​ 2.1.300 @@ -1524,8 +1794,6 @@ * [Claude Tag] Fixed Claude in Slack not answering another app that tags it in a thread under a message Claude itself posted to the channel * [Code Review] Fixed Code Review ignoring `@claude review` comments from people with write access whose GitHub organization membership is private; their comments now start a review * [Code Review] Fixed Code Review’s “paused for this repository” comment sending admins to Code Review settings; it now says who can fix it and links the Git providers page - -​ 2.1.299 @@ -1733,8 +2001,6 @@ * [Claude Tag] Fixed Claude in Slack sometimes ending a turn without posting its answer when a self-hosted runner’s image has no python3 * [Code Review] Fixed Code Review’s monthly spend-limit comment and check-run card sending admins to Claude Code settings; they now link the Usage page, where that limit is set -​ - 2.1.296 October 9, 2026 @@ -1829,8 +2095,6 @@ * [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 - -​ 2.1.295 @@ -1991,16 +2255,12 @@ * [Code Review] Fixed Code Review still skipping a large CLAUDE.md’s rules when the pull request edits that file * Fixed web searches and `agent` hook evaluations taking much longer at `xhigh` and `max` effort -​ - 2.1.294 October 8, 2026 * Fixed `prompt` and `agent` hooks written as instructions (such as “Block commands that…”) allowing what they should block * Improved how `prompt` hooks on Stop and SubagentStop written as instructions (such as “Carry on if the build is broken”) are judged, so Claude is less likely to stop early - -​ 2.1.293 @@ -2073,8 +2333,6 @@ * [Claude Tag] Fixed Claude in Slack stopping mid-task in a channel when an admin changed the channel’s connectors, plugins, skills or rules; the change now applies once Claude finishes * [Claude Tag] Fixed asking Claude in Slack to run a thread’s routine now with extra notes starting a separate run that couldn’t post back; the run now continues in that thread * [Claude Tag] Fixed an access bundle’s Add a connector dialog in Claude Tag admin settings showing every Google connector as connected after one Google sign-in - -​ 2.1.292 @@ -2184,16 +2442,12 @@ * [Code Review] Fixed a queued review failing when the pull request moved to a new base branch and the old one was deleted; the commit is now re-queued for review * [Code Review] Fixed reviews ignoring a CLAUDE.md’s rules when the pull request edits that file; reviews now use its version from the base branch -​ - 2.1.291 October 6, 2026 * Fixed a regression in 2.1.290 where cloud sessions could drop answers to permission prompts * Fixed a regression in 2.1.288 where the last messages of a session could be lost when quitting - -​ 2.1.290 @@ -2401,8 +2655,6 @@ * [Code Review] Fixed blocking review comments sometimes opening with a “nit” label that contradicted their severity * [Code Review] Fixed tips to comment “@claude review” being posted on fork and Manual-mode pull requests in organizations that have turned Code Review off -​ - 2.1.289 October 3, 2026 @@ -2445,8 +2697,6 @@ * Fixed a failed plugin component showing `Error` or nothing as its reason when the failure carried no message * Fixed published artifact pages freezing or crashing the reader’s browser tab on short code blocks with many unclosed `<script>` tags * Fixed a mod’s Client region staying failed for the whole session after the terminal threw while drawing it - -​ 2.1.288 @@ -2552,8 +2802,6 @@ * [Cloud sessions] Fixed pressing Stop while a self-hosted runner was still starting not cancelling the queued message, which could then run once the runner was up * [Claude Tag] Fixed Claude Tag admin settings offering a “Remove this scope” option, which always failed, on channels whose settings were created automatically * Fixed `claude plugin test` reporting mods as turned off remotely when it had only read an out-of-date saved setting - -​ 2.1.287 @@ -2677,8 +2925,6 @@ * [Code Review] Fixed finding comments and their “Why this was flagged” text stopping mid-sentence; they now end on a complete sentence * [Code Review] Fixed Code Review skipping a pull request after a new push when its review had failed twice on the previous commit; it now reviews the latest commit -​ - 2.1.286 September 30, 2026 @@ -2782,8 +3028,6 @@ * [Claude Tag] Fixed a Slack channel losing its Claude settings when an Enterprise Grid admin moves it to another workspace and the first post afterward doesn’t mention Claude * [Claude Tag] Fixed Claude in a Slack thread occasionally starting over on a fresh machine, losing work it hadn’t pushed, when your reply answered a question it had just asked * [Claude Tag] Fixed public channel names on Claude Tag’s spend limits page in admin settings showing as raw Slack IDs in larger organizations - -​ 2.1.285 @@ -2937,8 +3181,6 @@ * [Claude Tag] Fixed the note under Claude’s Slack messages saying it answered on a fallback model, and why, disappearing when Claude later edited that message * [Code Review] Fixed the organization menu in Code Review’s “Add a repository” dialog showing only a few of your GitHub organizations; it now loads more as you scroll -​ - 2.1.284 September 28, 2026 @@ -3055,8 +3297,6 @@ * [Claude Tag] Fixed Claude staying silent in a channel whose environment declines to start it; it now posts one notice asking you to contact an admin, and retries when @-mentioned * [Code Review] Fixed Code Review giving up without posting a finished review when an unsubmitted review under its GitHub App was open on the pull request; it now retries the post first -​ - 2.1.283 September 25, 2026 @@ -3166,8 +3406,6 @@ * [Claude Tag] Fixed conversations in a channel set to “Channel only” all ending when a non-guest member joined and Slack was slow to confirm their membership * [Code Review] Fixed “@claude review” requests going silent when GitHub failed to return the pull request: the request is retried once, and a comment explains if it still fails * [Code Review] Fixed billing for a review that stopped at its time limit with nothing verified: it now shows as incomplete, isn’t charged, and is retried once - -​ 2.1.282 @@ -3270,8 +3508,6 @@ * [Claude Tag] Fixed removing a GitHub organization’s grant from an access bundle’s Repositories tab in Claude Tag admin settings failing to save after that GitHub organization was disconnected * [Claude Tag] Fixed Claude always replying “Couldn’t check this channel just now” in a channel shared with a Grid workspace it isn’t added to; the notice now says which workspace needs the app * [Claude Tag] Fixed the cost and token totals in Claude’s reply footer reading many times too high after the session’s cloud worker restarted - -​ 2.1.281 @@ -3466,8 +3702,6 @@ * [Claude Tag] Fixed the Plugins sections in Claude Tag admin settings failing to load for organization admins and listing attached plugins as raw IDs; they now load and show each plugin’s name * [Code Review] Fixed a pull request getting no review when its reviewed commit was force-pushed away while a failed review was being retried in a repository not set to review every push -​ - 2.1.280 September 22, 2026 @@ -3598,16 +3832,12 @@ * [Claude Tag] Fixed a bullet in Claude’s Slack reply whose text starts with +, - or * rendering as an empty bullet with a stray nested item; it now shows as one bullet with the character kept * [Claude Tag] Fixed the Slack notice for a failed cloud environment setup script sometimes being a generic “mention me to retry”; it now names the setup script and says to fix it first -​ - 2.1.278 September 19, 2026 * Changed auto mode for Claude API and Enterprise users, and on Bedrock, Vertex, Foundry and gateways, to default to the server-side classifier, which does not charge for classifier overhead (`CLAUDE_CODE_AUTO_MODE_SERVER=0` opts out on Bedrock, Vertex, Foundry and gateways); warns on billed fallback. See <https://code.claude.com/docs/en/auto-mode-classifier-billing> * Added an `Auto mode server` row to `/status` showing whether this session’s auto mode classifier runs on the server - -​ 2.1.277 @@ -3712,15 +3942,11 @@ * [Claude Tag] Fixed Google Cloud credential forms in Claude Tag access bundles: a refused key file now says why, the website and scopes stay locked, and a rejected rotation keeps the pasted key * [Claude Tag] Fixed the network events log in Claude Tag admin settings showing no response status for requests through connections that use AWS signing, client certificates or a custom CA -​ - 2.1.276 September 18, 2026 * Fixed every request failing with `400 … Input tag 'advisor_20260301'` when `ANTHROPIC_BASE_URL` points at a proxy or gateway (2.1.275 regression) - -​ 2.1.275 @@ -3832,8 +4058,6 @@ * [Claude Tag] Fixed Claude sometimes replying twice when another app or bot @mentioned it in a top-level channel message * [Code Review] Fixed reviews occasionally dropping part of their analysis when one of the reviewing agents returned its findings in an unexpected format * [Code Review] Fixed pull requests with more than 100 Claude reviews getting a full re-review on every clean merge from the base branch instead of the lighter merge-focused review - -​ 2.1.274 @@ -3959,8 +4183,6 @@ * [Code Review] Fixed re-reviews occasionally leaving a fixed finding’s thread open when the new review also filed a lower-severity note under it * [Code Review] Fixed rare reviews ending with “Code review encountered an error” when GitHub or an internal service failed transiently at launch; they now wait and retry -​ - 2.1.273 September 15, 2026 @@ -4041,15 +4263,11 @@ * [Code Review] Fixed `/ultrareview --post` so a retry after a GitHub error posts the findings comment exactly once instead of never or twice; the comment now names the reviewed commit * [Code Review] Fixed empty or content-identical pushes being re-reviewed on GitHub repositories whose owner or name contains a capital letter; these pushes are now skipped -​ - 2.1.272 September 15, 2026 * Bug fixes and reliability improvements - -​ 2.1.271 @@ -4163,15 +4381,11 @@ * [Code Review] Fixed reopening a finished /ultrareview cloud session in the Claude app starting the whole review over again unprompted * Windows: Fixed PowerShell commands failing with “Exit code 1” and no output when the session’s temp output path reaches 260 characters -​ - 2.1.270 September 12, 2026 * Fixed read-only git commands in Bash unexpectedly asking for permission after a session had been running for a while (regression in 2.1.269) - -​ 2.1.269 @@ -4287,8 +4501,6 @@ * [Claude Tag] Fixed plugin rows in Slack access settings showing an unlabeled raw ID with no way to turn the plugin off; they now show its name and link to the bundle that manages it * [Claude Tag] Fixed the shared-session banner and Share dialog on sessions started from Slack claiming the whole organization could open the link; they now name the Slack channel’s audience -​ - 2.1.268 September 10, 2026 @@ -4401,8 +4613,6 @@ * [Code Review] Fixed a push-triggered review that was queued behind a running review still posting after the pull request had been converted to draft * [Code Review] Fixed reviews ignoring a directory’s CLAUDE.md conventions when the PR edited a root file (e.g. README.md) that only shares a name with a file that CLAUDE.md lists -​ - 2.1.267 September 9, 2026 @@ -4472,15 +4682,11 @@ * [Claude Tag] Fixed thread requests to edit or delete a message Claude posted at the channel’s top level being answered with a correction instead of reaching the session that posted it * [Claude Tag] Fixed **Connect** on Tool access requests under Admin settings > Review requests failing with “Authorization failed” or showing the requested access bundle as deleted -​ - 2.1.266 September 8, 2026 * Fixed a 2.1.265 regression affecting LLM-gateway and proxy setups: the undocumented `CLAUDE_CODE_USE_GATEWAY` environment variable, previously ignored unless `ANTHROPIC_BASE_URL` and `ANTHROPIC_AUTH_TOKEN` were both set, began forcing Cloud-gateway sign-in on its own in 2.1.265, so configurations that set it alongside an API key, `apiKeyHelper`, or custom auth headers failed every request with “Not signed in to the Cloud gateway”. The variable on its own is ignored again; no configuration change is needed - -​ 2.1.265 @@ -4548,15 +4754,11 @@ * [VSCode] Fixed the sidebar chat coming back blank after Reload Window or a restart when the conversation had been open for more than 10 minutes * [VSCode] Fixed the timeline dot sitting below the text on the “Remote Control is active” message -​ - 2.1.263 September 6, 2026 * Bug fixes and reliability improvements - -​ 2.1.261 @@ -4641,8 +4843,6 @@ * [VSCode] Fixed “Enable Remote Control for all sessions” so flipping it also applies right away to sessions open in other VS Code windows * [VSCode] Fixed the session list’s Open filter for sessions continued from claude.ai whose tab was still recorded under the web session, and labeled the filter menu’s sections for screen readers -​ - 2.1.260 September 3, 2026 @@ -4725,8 +4925,6 @@ * [VSCode] Fixed a half-finished message, an empty tool card or an extra “Thought for” line staying on screen after Claude Code retried a dropped response * [VSCode] Fixed “Enable Remote Control for all sessions” not applying to a session tab that was still starting when the toggle was flipped -​ - 2.1.259 September 2, 2026 @@ -4780,16 +4978,12 @@ * Fixed worktree-isolated sessions refusing common Bash loops, xargs pipelines and launcher-wrapped commands that cannot reach the main checkout * Fixed remote and scheduled sessions doing nothing after a connector-tool permission prompt was approved while the session was paused -​ - 2.1.258 September 1, 2026 * Fixed Claude Code failing to launch on macOS 12 (Monterey), a regression introduced in 2.1.255 * Fixed remote and scheduled sessions failing with “user messages must have non-empty content” after a re-sent permission approval could not be applied - -​ 2.1.257 @@ -4911,8 +5105,6 @@ * [VSCode] Fixed the “Enable Remote Control for all sessions” toggle so turning it on or off applies to sessions that are already open, not only to new ones * [VSCode] Fixed screen reader announcements: a control character before a fence or heading no longer drops visible lines from speech, and bold markers spanning a heading are no longer mis-paired -​ - 2.1.252 August 31, 2026 @@ -4921,8 +5113,6 @@ * Fixed “always allow” not saving in a project that has no .claude/settings.local.json yet * Fixed Remote Control sessions hosted by Claude Desktop or VS Code stalling for minutes after a tool finished when the connection to claude.ai was degraded * Fixed background task notifications with very large failure output (for example git errors on a full disk) making the conversation exceed the API request size limit - -​ 2.1.251 @@ -5011,15 +5201,11 @@ * Fixed cloud session creation advising GitHub setup after a transient GitHub connection failure — the message now says to retry instead * [VSCode] Fixed the sign-in screen’s “Bedrock, Foundry, or Vertex” button opening the docs at the top of the page instead of the third-party provider setup section -​ - 2.1.250 August 28, 2026 * Bug fixes and reliability improvements - -​ 2.1.248 @@ -5086,8 +5272,6 @@ * Fixed rate-limit, usage, and fast-mode messages telling you to run `/usage-credits` when that command isn’t available for your organization (e.g. hidden with `DISABLE_EXTRA_USAGE_COMMAND`) * [VSCode] Fixed a chat tab getting stuck on “No conversation found” when its session was never saved; it now starts a new conversation instead -​ - 2.1.247 August 26, 2026 @@ -5136,8 +5320,6 @@ * Fixed first-run setup exiting with “Unable to connect to Anthropic services” when managed settings configure Claude apps gateway sign-in and Anthropic endpoints are unreachable * Fixed cloud sessions (Claude Code on the web, desktop and mobile apps) sometimes showing the previous permission mode when you switch modes right after sending a message * Fixed cloud sessions going silent when the session’s container restarts between turns while a background agent, shell, or monitor is still running — the resumed session now reports the lost work - -​ 2.1.246 @@ -5216,15 +5398,11 @@ * Fixed the self-hosted runner ending its live sessions or exiting when a work-poll response is malformed (e.g. an intercepting proxy’s HTML page); it now retries the poll * Fixed the command sandbox’s filesystem configuration not respecting `--setting-sources` -​ - 2.1.245 August 25, 2026 * Fixed a crash on startup on Linux distributions that ship glibc 2.44 (for example Arch Linux, CachyOS and Fedora Rawhide) - -​ 2.1.243 @@ -5302,23 +5480,17 @@ * Fixed `claude remote-control` exiting and stranding attached Remote Control sessions when the server drops its environment mid-session; it now recovers * Fixed Remote Control sessions served by `claude remote-control` sometimes getting stuck after it was stopped and restarted, for Team and Enterprise members without an admin or owner role -​ - 2.1.241 August 23, 2026 * Bug fixes and reliability improvements -​ - 2.1.240 August 22, 2026 * Bug fixes and reliability improvements - -​ 2.1.239 @@ -5395,8 +5567,6 @@ * Fixed Ctrl+Backspace deleting one character instead of a word in search boxes * Fixed a request rejected by an organization policy check being re-sent before the rejection was shown -​ - 2.1.238 August 20, 2026 @@ -5452,16 +5622,12 @@ * Fixed `ListAgents`/`SendMessage` reporting “Remote Control is not connected” in sessions run by `claude remote-control` (server mode) or Desktop/IDE hosts; they now list and reach Remote Control peers * Fixed `ListAgents` and `SendMessage` exposing the idle worker that the agent view pre-warms for your next background session; it now appears only once a task claims it -​ - 2.1.237 August 20, 2026 * Fixed prompt caching for sessions using an LLM gateway or custom base URL * Added a built-in “Concise” output style: Claude leads with results and skips preamble and narration, while doing the work just as thoroughly. Select it under Output style in /config. - -​ 2.1.236 @@ -5512,8 +5678,6 @@ * Fixed the Clawd mascot’s eyes and feet rendering unevenly in iTerm2 at some font sizes * Fixed occasional runaway session recaps: recap text (automatic and `/recap`) is now capped at 400 characters, cut at a word boundary -​ - 2.1.235 August 18, 2026 @@ -5548,8 +5712,6 @@ * Fixed the prompt footer not showing the “Update installed” restart notice after a background auto-update * Fixed the expanded task list (`ctrl+t`) always starting collapsed when resuming or relaunching into a session that still has open tasks * [VSCode] Fixed focus jumping between open Claude tabs on its own when a window with several Claude panels is restored or reloaded - -​ 2.1.234 @@ -5618,8 +5780,6 @@ * Fixed: provider API tokens that mask on permission previews now mask even when directly followed by shell delimiters * Fixed Claude Desktop inter-session messages being silently dropped by the recipient session when cross-session messaging read as disabled, which left the sender’s query “thinking” for many minutes -​ - 2.1.233 August 14, 2026 @@ -5655,8 +5815,6 @@ * Fixed skill/command argument substitution to prevent argument values from being re-expanded as template markers * Fixed Windows paths spelled with the NT `\??\` device prefix bypassing UNC path validation, closing an NTLM credential-leak vector * Windows: fixed auto mode repeatedly stopping for manual approval on ordinary `cd <dir> && <command> > file` Bash commands (a 2.1.232 regression) - -​ 2.1.232 @@ -5723,15 +5881,11 @@ * Fixed usage-limit guidance suggesting unavailable slash commands in SDK and remote sessions * Fixed the consent message for interactive `--advisor fable` launches, which told you to run `/model fable` in an interactive session that had just exited -​ - 2.1.231 August 13, 2026 * Fixed MCP OAuth sign-in failing with a redirect URI mismatch for servers that use a pre-registered OAuth client, such as Slack - -​ 2.1.229 @@ -5781,8 +5935,6 @@ * Fixed self-hosted runner and other remote sessions exiting at startup when `managed-mcp.json` is deployed and the server delivers MCP servers; those servers are now skipped with a warning * Fixed self-hosted runner repository preparation hanging on a Git Credential Manager prompt; git now fails fast when credentials are missing -​ - 2.1.228 August 11, 2026 @@ -5814,8 +5966,6 @@ * Fixed a settings-merge issue where a marketplace entry redefined in a higher-precedence settings tier could inherit another tier’s custom headers; marketplace entries now merge as whole entries * Fixed the deferred-tools reminder occasionally being sent to the model twice after a skill invocation -​ - 2.1.227 August 10, 2026 @@ -5826,15 +5976,11 @@ * Improved slash-command menu: blue now marks only the selected row, matched characters are bolded instead of recolored, and emoji or accented names keep their glyphs * Improved performance: fewer event-loop stalls on file-not-found suggestions and at-mention size checks -​ - 2.1.226 August 8, 2026 * Bug fixes and reliability improvements - -​ 2.1.225 @@ -5865,8 +6011,6 @@ * Fixed `claude self-hosted-runner` registering and then failing every session when `--base-dir` cannot be created or written; it now exits at startup with a clear error * Fixed Claude Code on the web sessions being misreported as stuck, re-sending a growing event backlog on every reconnect * [VSCode] Fixed Focus view folding away the latest to-do list, a pending question’s context, and settled answers; thinking-only folds show “Thought for Ns” and re-collapse when their turn completes - -​ 2.1.224 @@ -5915,8 +6059,6 @@ * Fixed a session resume silently reconnecting Remote Control after the user turned it off (`--resume`, SDK hosts, and the VS Code extension) * [VSCode] Fixed sessions not honoring `remoteControlAtStartup` when explicitly enabled -​ - 2.1.223 August 6, 2026 @@ -5948,8 +6090,6 @@ * Fixed forked background agents getting stuck “already resuming” for the rest of the session when rebuilding the fork’s parent prompt failed during resume * Fixed a resumed session failing every turn, or leaving the interactive app on an unresponsive error screen, when its history held a malformed diagnostics attachment * Fixed a rare hang when parsing unusual `git push` output - -​ 2.1.222 @@ -5984,8 +6124,6 @@ * Fixed rare crashes when a file watcher hit a filesystem error or during file-watcher teardown * Fixed screen readers re-reading the whole input line on every backspace in `--ax-screen-reader` mode — end-of-line deletions now echo just the deleted characters * Fixed host model-selection keys not taking precedence over a stale on-disk `managed-settings.json` when `CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST` is set - -​ 2.1.221 @@ -6042,15 +6180,11 @@ * Fixed Vim mode: the yank register now survives dialogs, history search, and the transcript view instead of being silently emptied * Fixed Vim mode: undoing back to an empty prompt now arms the “press ← again” confirm before returning to the agent view -​ - 2.1.220 July 25, 2026 * Bug fixes and reliability improvements - -​ 2.1.219 @@ -6091,8 +6225,6 @@ * Fixed `CLAUDE_CODE_GIT_BASH_PATH` on Windows exiting or being used as bash when the path isn’t a bash/sh binary; it’s now ignored with a warning * Fixed Vim mode: pressing ← on an empty prompt now returns to the agent view from NORMAL mode, not just INSERT * Fixed screen-reader mode rewriting the entire input line on every keystroke instead of echoing only the typed character - -​ 2.1.218 @@ -6146,8 +6278,6 @@ * Fixed a resumed session failing every turn, or crashing on resume, when its history held a malformed delta attachment * Fixed remote sessions continuing to send heartbeats after their worker was replaced, which left long-lived desktop and IDE processes retrying a rejected request every few seconds forever -​ - 2.1.217 July 21, 2026 @@ -6183,8 +6313,6 @@ * Fixed a `CLAUDE.md` or `SKILL.md` paths frontmatter value with many brace groups OOM-killing or stalling the CLI at startup — brace expansion is now budget-bounded * Fixed the transcript preview sitting flush against the input area when attaching to a starting background session; it now leaves the same one-line gap as the live layout, so the transcript no longer shifts when the session takes over * Fixed `--max-budget-usd` not stopping background subagents: once the cap is reached, new spawns are denied and running background agents are halted - -​ 2.1.216 @@ -6242,15 +6370,11 @@ * [VSCode] Fixed right-to-left text (Arabic, Hebrew, Persian) rendering in the wrong order when mixed with English or code * Fixed cloud sessions dropping the in-flight message when the session’s container restarts mid-turn — the interrupted turn now re-runs on resume instead of leaving the session unresponsive -​ - 2.1.215 July 19, 2026 * Claude no longer runs the `/verify` and `/code-review` skills on its own; invoke them with `/verify` or `/code-review` when you want them - -​ 2.1.214 @@ -6286,7 +6410,7 @@ * Fixed Bash permission checks treating zsh variable subscripts and modifiers in `[[ ]]` comparisons as inert text — these commands now prompt for approval * Fixed Bash permission checks to no longer auto-approve certain `help` and `man` commands that could run unsafe options, command substitutions, or backslash paths * Fixed permission prompts on remote sessions that could proceed before the local confirmation dialog - * Fixed a crash when a GrowthBook feature evaluates to null, and a bug where a malformed flag payload could wipe the cached feature flags + * Fixed a crash when a feature flag evaluates to null, and a bug where a malformed flag payload could wipe the cached feature flags * Fixed Bash tool killing the Claude session when a `pkill -f` pattern accidentally matched the CLI’s own process (Linux) * Fixed unbounded memory growth when `--settings` points at a device file or multi-GB file; oversized (>2 MiB) settings files now fail at startup with a clear error * Fixed streaming turns failing with “Socket is closed” behind corporate proxies on Windows @@ -6314,8 +6438,6 @@ * Fixed hooks with exit code 2 not blocking as documented when the hook’s stdout JSON fails schema validation * Fixed OTel log events emitted outside the turn’s async context missing the interaction span’s trace context * Fixed MCP transient errors during prompts/resources refresh clearing the server’s slash commands and resources - -​ 2.1.212 @@ -6381,8 +6503,6 @@ * Fixed conversations with many images incorrectly failing with “Request too large” errors, and improved the error message to explain the actual cause * Fixed web search and web fetch returning “API Error” text as search results or page content when the API was overloaded -​ - 2.1.211 July 15, 2026 @@ -6436,8 +6556,6 @@ * Fixed routines with no schedule reporting a next run time in the year 1 * Fixed a prompt-caching regression on Bedrock, Vertex, Mantle, and Foundry that billed the trailing system context block as fresh input tokens on every request. -​ - 2.1.210 July 14, 2026 @@ -6487,15 +6605,11 @@ * Fixed returning to the agents view from a session leaving overlapping ghost frames with `CLAUDE_CODE_DISABLE_ALTERNATE_SCREEN=1` * Fixed late-appearing `.claude/*` symlinks not being reconciled into the sandbox deny-write list -​ - 2.1.209 July 14, 2026 * Fixed /model and other dialogs being blocked in `claude agents` background sessions (reverts an overly broad guard) - -​ 2.1.208 @@ -6559,8 +6673,6 @@ * Fixed multi-second per-turn slowdowns in sessions with many permission deny/ask rules — rule matchers are now compiled once and cached * Fixed Bedrock auth failing with “Session token not found or invalid” for AWS SSO profiles whose sso_region differs from the Bedrock region (2.1.207 regression) -​ - 2.1.207 July 11, 2026 @@ -6597,8 +6709,6 @@ * Fixed Bedrock repeatedly requesting fresh AWS SSO credentials from IAM Identity Center on every API request * Fixed an indefinite hang on Windows when AWS credential resolution stalls (e.g. a stuck `credential_process`): the 60-second stall guard now fires instead of waiting forever. * Fixed `/usage-credits` amount inputs silently stripping malformed values (e.g. a pasted timestamp) to digits; malformed amounts are now rejected with an error, and amounts over $1,000 require a typed confirmation - -​ 2.1.206 @@ -6643,8 +6753,6 @@ * Fixed the fullscreen jump-to-bottom pill suggesting Ctrl+End on macOS, not showing rebound chords, and wrapping over the transcript * Bedrock: fixed a multi-minute startup hang when using an `awsCredentialExport` helper on networks with restricted egress -​ - 2.1.205 July 8, 2026 @@ -6684,15 +6792,11 @@ * Fixed background tasks in the web and mobile Remote Control panels showing stale “Running” status by forwarding full task state on every membership change * Fixed Cowork VM-mode local-agent sessions failing to start with “Not logged in · Please run /login” on CLI 2.1.203+ -​ - 2.1.204 July 8, 2026 * Fixed hook events not streaming during SessionStart hooks in headless sessions, which could cause remote workers to be idle-reaped mid-hook - -​ 2.1.203 @@ -6747,8 +6851,6 @@ * Fixed literal `^[[I` / `^[[O` escape codes being printed when reattaching to a background session * Fixed LSP-only plugins being incorrectly flagged for disuse when their language servers deliver diagnostics or answer navigation requests -​ - 2.1.202 July 6, 2026 @@ -6783,15 +6885,11 @@ * Fixed installer and updater downloads failing immediately with “aborted” when a proxy or network drops the connection mid-download — transient connection drops now retry * Fixed re-invoking an already-loaded skill appending a duplicate copy of its instructions to context -​ - 2.1.201 July 3, 2026 * Claude Sonnet 5 sessions no longer use the mid-conversation system role for harness reminders - -​ 2.1.200 @@ -6822,8 +6920,6 @@ * Fixed `/mcp` server list not tracking focus for screen readers and magnifiers * Fixed voice dictation showing a misleading “Voice connection failed” message when a recording captures no audio * Fixed rendering flicker under tmux 3.4+ by enabling synchronized terminal output - -​ 2.1.199 @@ -6859,8 +6955,6 @@ * Fixed Claude in Chrome repeatedly opening the reconnect page when sessions run from different builds or config directories * Fixed plan mode not prompting for state-changing browser tool calls; read-only `browser_batch` calls are now correctly auto-allowed -​ - 2.1.198 July 1, 2026 @@ -6910,15 +7004,11 @@ * Fixed plan mode not auto-allowing read-only tool calls when a session starts in plan mode * Fixed `/branch` deriving its default fork name from the compaction summary instead of the first real prompt -​ - 2.1.197 June 30, 2026 * Introducing Claude Sonnet 5: now the default model in Claude Code, with a native 1M-token context window and promotional pricing of $2/$10 per Mtok through August 31. Update to version 2.1.197 for access. <https://www.anthropic.com/news/claude-sonnet-5> - -​ 2.1.196 @@ -6963,8 +7053,6 @@ * Fixed `claude agents` session status: completed rows no longer flip between “Done” and “Needs your input”, stalled agents are now labeled “Needs attention”, and results that mention a PR show a clickable link * Fixed voice dictation swallowing spaces and spuriously starting a recording during very fast typing when voice mode is enabled -​ - 2.1.195 June 26, 2026 @@ -6990,8 +7078,6 @@ * Fixed reopening a crashed background task showing a blank screen for up to 5 seconds instead of its restart * Fixed background agent daemons running unreachable when the control socket fails to start, blocking restarts -​ - 2.1.193 June 25, 2026 @@ -7019,8 +7105,6 @@ * Fixed pinned background agents being re-prompted to “Continue from where you left off” after every auto-update * Fixed backgrounding the main turn spawning a phantom “general-purpose (resumed)” subagent that re-ran the main conversation * Fixed agent panel hiding sibling agents when viewing a subagent - -​ 2.1.191 @@ -7058,15 +7142,11 @@ * Fixed the welcome splash art overflowing the default 80×24 macOS Terminal window * Fixed managed settings: `forceRemoteSettingsRefresh` now takes effect when set via MDM or file policy, and the fetch sends `Cache-Control: no-cache` to prevent proxies from serving stale responses -​ - 2.1.190 June 24, 2026 * Bug fixes and reliability improvements - -​ 2.1.187 @@ -7101,8 +7181,6 @@ * Fixed `claude --help` not listing the `--bg`/`--background` flag * Fixed Esc, Ctrl-C, and Ctrl-D not working while `/share` is uploading * [VSCode] Fixed extension becoming unresponsive when resuming a large session - -​ 2.1.186 @@ -7153,15 +7231,11 @@ * Fixed agent teams: teammates spawned via tmux/pane backends now inherit the leader’s `--effort` level * Fixed Workflow `agent({schema})` subagents looping forever on repeated schema validation failures instead of aborting after 5 attempts -​ - 2.1.185 June 20, 2026 * The stream-stall hint now reads “Waiting for API response · will retry in …” instead of “No response from API · Retrying in …”, and triggers after 20s of silence instead of 10s - -​ 2.1.183 @@ -7195,8 +7269,6 @@ * Fixed background tasks started by a teammate being killed when the teammate finishes a turn * Fixed scheduled task and webhook trigger deliveries being treated as keyboard input; they now classify as task notifications and can no longer approve a pending action or set the session title in auto mode * Fixed focus mode showing “Ran N PostToolUse hooks” timing lines under each response - -​ 2.1.181 @@ -7253,8 +7325,6 @@ * Fixed user prompts queued mid-turn not showing a full-width background highlight in the transcript * Fixed the activity spinner’s pulse dwelling on the wrong glyph size in Ghostty -​ - 2.1.179 June 16, 2026 @@ -7268,8 +7338,6 @@ * Fixed clicking the prompt input not returning focus from the subagent/footer panel * Fixed remote session background tasks appearing stuck as “still running” between turns * Improved plugin loading performance in remote sessions - -​ 2.1.178 @@ -7310,8 +7378,6 @@ * Fixed vim mode undo: `u` now steps through NORMAL/VISUAL-mode commands one at a time instead of merging commands in quick succession into a single undo step * Fixed statusline links with custom URI schemes (e.g. `vscode://`) not opening when clicked in `claude agents` * [VSCode] Fixed pressing Esc to dismiss a CJK IME candidate window canceling the running Claude task - -​ 2.1.176 @@ -7351,15 +7417,11 @@ * Fixed the Windows background-service daemon not starting when `~/.claude/daemon` has the ReadOnly attribute set * Fixed cloud sessions failing with “Could not resolve authentication method” when idle for too long before being claimed -​ - 2.1.175 June 12, 2026 * Added `enforceAvailableModels` managed setting — when enabled, the `availableModels` allowlist also constrains the Default model (a Default that would resolve to a disallowed model now falls back to the first allowed model), and user or project settings can no longer widen a managed `availableModels` list - -​ 2.1.174 @@ -7384,16 +7446,12 @@ * Fixed Workflow tool `agent()` subagents missing per-agent attribution headers * Fixed pre-warmed background workers failing with “Could not resolve authentication method” when claimed after sitting idle -​ - 2.1.173 June 11, 2026 * Fixed Fable 5 model names with a `[1m]` suffix not being normalized — Fable 5 includes 1M context by default, so the suffix is now stripped automatically * Fixed a spurious “sandbox dependencies missing” startup warning on Windows when sandbox was enabled in settings - -​ 2.1.172 @@ -7441,16 +7499,12 @@ * Fixed the `/plugin` marketplace list losing its cursor after backing out of a long plugin list, and Esc from the plugin browser returning to the wrong tab * [VSCode] Fixed PowerShell tool calls rendering as raw JSON instead of a proper command display and permission dialog, and stripped ANSI escape codes from displayed shell output -​ - 2.1.170 June 9, 2026 * Introducing Claude Fable 5: a Mythos-class model that we’ve made safe for general use. Fable’s capabilities exceed those of any model we’ve ever made generally available. Update to version 2.1.170 for access. <https://www.anthropic.com/news/claude-fable-5-mythos-5> * Fixed sessions not saving transcripts (and not appearing in —resume) when launched from the VS Code integrated terminal or any shell that inherited Claude Code environment variables. - -​ 2.1.169 @@ -7498,23 +7552,17 @@ * Fixed plugin `.in_use` PID lock files accumulating without bound; stale markers from crashed sessions are now swept once per day * Fixed untrusted project settings being able to set OTEL client-certificate paths without trust confirmation -​ - 2.1.168 June 6, 2026 * Bug fixes and reliability improvements -​ - 2.1.167 June 6, 2026 * Bug fixes and reliability improvements - -​ 2.1.166 @@ -7550,15 +7598,11 @@ * Fixed the cursor sticking at the end of the first line when typing a multiline prompt in the `claude agents` dispatch and reply inputs * Fixed blank lines appearing between background agent rows in the task list on terminals without Unicode support -​ - 2.1.165 June 5, 2026 * Bug fixes and reliability improvements - -​ 2.1.163 @@ -7594,8 +7638,6 @@ * Fixed hook `if: "Bash(...)"` conditions firing on every Bash command containing `$()` or `$VAR`; the pattern now matches against commands inside subshells and backticks too * Fixed deny rules on home-directory paths (e.g. `Read(~/Desktop/**)`) not blocking Bash commands that reference the path via `$HOME` * Fixed a stray “(no content)” line left in the transcript after closing panel dialogs like /mcp and /plugins - -​ 2.1.162 @@ -7638,8 +7680,6 @@ * Fixed cross-session messaging (`SendMessage`) silently breaking when `CLAUDE_CODE_TMPDIR` or `$TMPDIR` points at a deep directory * Fixed opening a running background session from `claude agents` stalling for 5 seconds before attaching -​ - 2.1.161 June 2, 2026 @@ -7677,8 +7717,6 @@ * Fixed a potential crash when rendering Write tool results after resuming a session * Fixed completed subagents getting stuck showing as running when an error occurs while finalizing their result * Fixed `EADDRINUSE` errors from tools that bind Unix sockets under `$TMPDIR` when `CLAUDE_CODE_TMPDIR` is set to a deep path - -​ 2.1.160 @@ -7723,23 +7761,17 @@ * Fixed Claude’s past replies disappearing from scrollback when resuming a brief mode session with brief mode turned off * Fixed vim mode `p` pasting on the line below instead of at the cursor when the register was yanked with `v$` -​ - 2.1.159 May 31, 2026 * Internal infrastructure improvements (no user-facing changes) -​ - 2.1.158 May 30, 2026 * Auto mode is now available on Bedrock, Vertex, and Foundry for Opus 4.7 and Opus 4.8. Opt in by setting `CLAUDE_CODE_ENABLE_AUTO_MODE=1` - -​ 2.1.157 @@ -7790,15 +7822,11 @@ * [IDE] Fixed clicking Stop while a background subagent is running not actually stopping it * [VSCode] Fixed the fast mode indicator not appearing on Opus 4.8 -​ - 2.1.156 May 29, 2026 * Fixed an issue when using Opus 4.8 where thinking blocks were modified, leading to API errors. - -​ 2.1.154 @@ -7859,8 +7887,6 @@ * Fixed /mcp tools list and tool detail rendering when MCP servers have long or multi-line tool names or long descriptions * Fixed the /model picker not showing fast mode pricing on the Default option for API (pay-as-you-go) users when fast mode is on * Fixed auto mode incorrectly blocking actions with “could not evaluate this action” when the safety classifier ran out of output tokens while reasoning - -​ 2.1.153 @@ -7911,8 +7937,6 @@ * Fixed Windows update rollback: if a Windows update fails, Claude Code now restores the original executable by copy and tells you how to recover * [VSCode] Fixed Claude Code processes not shutting down cleanly when VS Code closed on Windows, causing false “unclean exit” reports and orphaned MCP servers -​ - 2.1.152 May 27, 2026 @@ -7959,15 +7983,11 @@ * Fixed the PushNotification tool incorrectly reporting “Mobile push not sent (Remote Control inactive)” in SDK-hosted sessions when Remote Control is enabled * Fixed sessions getting stuck after a model or login switch left stale thinking-block signatures in history; now stripped proactively with a retry safety-net -​ - 2.1.150 May 23, 2026 * Internal infrastructure improvements (no user-facing changes) - -​ 2.1.149 @@ -8011,15 +8031,11 @@ * Fixed a race where a just-submitted prompt could appear twice in the up-arrow history * Fixed tapping the “Jump to bottom” pill in fullscreen mode not dismissing it immediately -​ - 2.1.148 May 22, 2026 * Fixed the Bash tool returning exit code 127 on every command for some users (a regression introduced in 2.1.147) - -​ 2.1.147 @@ -8067,8 +8083,6 @@ * Fixed several spacing and layout glitches in the `/plugin`, `/status`, `/mobile`, `/sandbox`, and `/permissions` menus * Fixed stripped images prompting the model to repeatedly re-read media that was no longer present -​ - 2.1.145 May 19, 2026 @@ -8104,8 +8118,6 @@ * Fixed `/review` using a deprecated `projectCards` GraphQL query that errored on repos with Classic Projects * Fixed `claude plugin validate` not flagging `skills:` entries that point at a file instead of a directory — the error now suggests the parent directory * Fixed an infinite loop where a skill using `context: fork` could repeatedly re-invoke itself instead of running - -​ 2.1.144 @@ -8173,8 +8185,6 @@ * Fixed markdown links in `claude agents` attached sessions rendering as plain text instead of clickable hyperlinks * Fixed custom `spinnerVerbs` applying to the post-turn duration message — past-tense built-ins like “Worked for 5s” are restored there -​ - 2.1.143 May 15, 2026 @@ -8221,8 +8231,6 @@ * Fixed: background daemon spawn now falls back to the running binary when the `~/.local/bin/claude` launcher is missing or non-executable * Fixed `claude agents --allow-dangerously-skip-permissions` defaulting dispatched sessions to bypass mode instead of making it available in the permission cycle -​ - 2.1.142 May 14, 2026 @@ -8262,8 +8270,6 @@ * Fixed plugin cache cleanup deleting the active plugin version directory when no installation metadata is present * Fixed `/plugin` browse pane showing “0 installs” for newly published plugins * Fixed plugin advisories not naming every `plugin.json` key that shadows a default folder - -​ 2.1.141 @@ -8342,8 +8348,6 @@ * Fixed SDK “Claude Code native binary not found” on Linux when both glibc and musl platform packages are installed * [VSCode] Fixed in-chat mic showing no feedback when the microphone produced only silence — now shows “No audio detected” -​ - 2.1.140 May 12, 2026 @@ -8369,8 +8373,6 @@ * Fixed a recurring event-loop stall on Windows when a missing executable (e.g. `gh`) triggered synchronous `where.exe` re-spawns on every check * Fixed `Read` tool calls failing validation when `offset` is passed as a whitespace-padded or `+`-prefixed string * Fixed native terminal cursor not staying at the input caret when the terminal loses focus - -​ 2.1.139 @@ -8435,23 +8437,17 @@ * Fixed `claude_code.active_time.total` OpenTelemetry metric not being emitted in `--print` mode * Fixed `claude plugin update` not preserving cross-plugin symlinks inside a marketplace -​ - 2.1.138 May 9, 2026 * Internal fixes -​ - 2.1.137 May 9, 2026 * [VSCode] Fixed extension failing to activate on Windows - -​ 2.1.136 @@ -8521,8 +8517,6 @@ * Fixed “Chat about this” on an `AskUserQuestion` dialog erasing the question text * Fixed MCP tool results being invisible when the server returns content blocks -​ - 2.1.133 May 7, 2026 @@ -8555,8 +8549,6 @@ * Fixed `/effort` in one session unexpectedly changing the effort level of other concurrent sessions, and a related issue where an IDE effort change could be silently dropped * Fixed subagents not discovering project, user, or plugin skills via the Skill tool * [VSCode] Fixed `claudeCode.claudeProcessWrapper` failing with “Unsupported platform” when the extension build doesn’t bundle a Claude binary - -​ 2.1.132 @@ -8602,16 +8594,12 @@ * Fixed unauthorized claude.ai MCP connectors showing as “failed” instead of “needs auth”, and headless `-p` mode retrying non-transient 4xx connection failures * Fixed Bedrock and Vertex 400 errors when `ENABLE_PROMPT_CACHING_1H` is set -​ - 2.1.131 May 6, 2026 * Fixed VS Code extension failing to activate on Windows due to a hardcoded build path in the bundled SDK (`createRequire` polyfill bug) * Fixed Mantle endpoint authentication failing with missing `x-api-key` header - -​ 2.1.129 @@ -8652,8 +8640,6 @@ * Fixed `deniedMcpServers` patterns with a `*://` scheme wildcard not matching mixed-case hostnames * Fixed harmless WebSocket warning being logged as an error in `--debug` during voice mode * [VSCode] Fixed `/clear` not clearing the conversation context and displayed transcript - -​ 2.1.128 @@ -8702,8 +8688,6 @@ * Fixed `/plugin update` never detecting new versions of npm-sourced plugins * Fixed sub-agent summaries firing repeatedly while a sub-agent’s transcript is static, capping worst-case token cost on idle sub-agents -​ - 2.1.126 May 1, 2026 @@ -8746,15 +8730,11 @@ * Fixed Remote Control failure notification not showing the error reason for initial connection failures * Fixed Agent SDK hang when the model emits a malformed tool name in a parallel tool call batch -​ - 2.1.123 April 29, 2026 * Fixed OAuth authentication failing with a 401 retry loop when `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1` is set - -​ 2.1.122 @@ -8786,8 +8766,6 @@ * Fixed remote control session idle status redrawing twice per second, which could flood `tmux -CC` control pipes and pause the terminal * Fixed assistant messages appearing blank in some sessions due to a stale view preference * Fixed a malformed hooks entry in `settings.json` no longer invalidating the entire file - -​ 2.1.121 @@ -8841,8 +8819,6 @@ * Fixed `/focus` showing “Unknown command” when the fullscreen renderer is off — now explains how to enable it * Fixed embedded grep/find/rg shell wrappers failing when the running binary is deleted mid-session — now falls back to installed tools -​ - 2.1.120 April 28, 2026 @@ -8877,8 +8853,6 @@ * Fixed slash command picker jumping while typing, and improved highlight to only match contiguous substrings in blue * Fixed `/plugin` marketplace failing to load when one entry uses an unrecognized source format — that entry is shown but installing it prompts you to update * Fixed `find` in the Bash tool exhausting open file descriptors on large directory trees, causing host-wide crashes (macOS/Linux native builds) - -​ 2.1.119 @@ -8944,8 +8918,6 @@ * Fixed `/doctor` warning about MCP server entries overridden by a higher-precedence scope * [VSCode] Fixed voice dictation’s first recording producing nothing on macOS while the microphone permission prompt is showing -​ - 2.1.118 April 23, 2026 @@ -8993,8 +8965,6 @@ * Fixed Remote Control sessions getting archived on transient CCR initialization blips during JWT refresh * Fixed subagents resumed via `SendMessage` not restoring the explicit `cwd` they were spawned with -​ - 2.1.117 April 22, 2026 @@ -9036,8 +9006,6 @@ * [VSCode] Fixed “Manage Plugins” panel breaking when multiple large marketplaces are configured * Fixed Opus 4.7 sessions showing inflated `/context` percentages and autocompacting too early — Claude Code was computing against a 200K context window instead of Opus 4.7’s native 1M -​ - 2.1.116 April 20, 2026 @@ -9073,15 +9041,11 @@ * Fixed `/plugin` Installed tab showing the same item twice when it appears under Needs attention or Favorites * Fixed `/update` and `/tui` not working after entering a worktree mid-session -​ - 2.1.114 April 18, 2026 * Fixed a crash in the permission dialog when an agent teams teammate requested tool permission - -​ 2.1.113 @@ -9137,15 +9101,11 @@ * Fixed Remote Control sessions not being archived when Claude Code exits * Fixed `thinking.type.enabled is not supported` 400 error when using Opus 4.7 via a Bedrock Application Inference Profile ARN -​ - 2.1.112 April 16, 2026 * Fixed “claude-opus-4-7 is temporarily unavailable” for auto mode - -​ 2.1.111 @@ -9197,8 +9157,6 @@ * Fixed 429 rate-limit errors on Bedrock/Vertex/Foundry referencing status.claude.com (it only covers Anthropic-operated providers) * Fixed feedback surveys appearing back-to-back after dismissing one * Fixed bare URLs in bash/PowerShell/MCP tool output being unclickable when the terminal wraps them across lines - -​ 2.1.110 @@ -9249,15 +9207,11 @@ * Fixed Remote Control sessions showing a generic error instead of prompting for re-login when the session is too old * Fixed Remote Control session renames from claude.ai not persisting the title to the local CLI session -​ - 2.1.109 April 15, 2026 * Improved the extended-thinking indicator with a rotating progress hint - -​ 2.1.108 @@ -9299,15 +9253,11 @@ * Fixed diacritical marks (accents, umlauts, cedillas) being dropped from responses when the `language` setting is configured * Fixed policy-managed plugins never auto-updating when running from a different project than where they were first installed -​ - 2.1.107 April 14, 2026 * Show thinking hints sooner during long operations - -​ 2.1.105 @@ -9361,8 +9311,6 @@ * Fixed `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` in one project’s settings permanently disabling usage metrics for all projects on the machine * Fixed washed-out 16-color palette when using Ghostty, Kitty, Alacritty, WezTerm, foot, rio, or Contour over SSH/mosh * Fixed Bash tool suggesting `acceptEdits` permission mode when exiting plan mode would downgrade from a higher permission level - -​ 2.1.101 @@ -9425,8 +9373,6 @@ * Fixed several Remote Control issues: worktrees removed on session crash, connection failures not persisting in the transcript, spurious “Disconnected” indicator in brief mode for local sessions, and `/remote-control` failing over SSH when only `CLAUDE_CODE_ORGANIZATION_UUID` is set * Fixed `/insights` sometimes omitting the report file link from its response * [VSCode] Fixed the file attachment below the chat input not clearing when the last editor tab is closed - -​ 2.1.98 @@ -9501,8 +9447,6 @@ * [VSCode] Fixed false-positive “requires git-bash” error on Windows when `CLAUDE_CODE_GIT_BASH_PATH` is set or Git is installed at a default location * Fixed `CLAUDE_CODE_MAX_CONTEXT_TOKENS` to honor `DISABLE_COMPACT` when it is set. -​ - 2.1.97 April 8, 2026 @@ -9565,15 +9509,11 @@ * Fixed Korean/Japanese/Unicode text becoming garbled when copied in no-flicker mode on Windows * Fixed Bedrock SigV4 authentication failing when `AWS_BEARER_TOKEN_BEDROCK` or `ANTHROPIC_BEDROCK_BASE_URL` are set to empty strings (as GitHub Actions does for unset inputs) -​ - 2.1.96 April 8, 2026 * Fixed Bedrock requests failing with `403 "Authorization header is missing"` when using `AWS_BEARER_TOKEN_BEDROCK` or `CLAUDE_CODE_SKIP_BEDROCK_AUTH` (regression in 2.1.94) - -​ 2.1.94 @@ -9616,8 +9556,6 @@ * Fixed CJK and other multibyte text being corrupted with U+FFFD in stream-json input/output when chunk boundaries split a UTF-8 sequence * [VSCode] Fixed dropdown menus selecting the wrong item when the mouse was over the list while typing or using arrow keys -​ - 2.1.92 April 4, 2026 @@ -9655,8 +9593,6 @@ * Fixed idle-return “/clear to save X tokens” hint showing cumulative session tokens instead of current context size * Fixed plugin MCP servers stuck “connecting” on session start when they duplicate a claude.ai connector that is unauthenticated -​ - 2.1.91 April 2, 2026 @@ -9685,8 +9621,6 @@ * Fixed plan mode in remote sessions losing track of the plan file after a container restart, which caused permission prompts on plan edits and an empty plan-approval modal * Fixed JSON schema validation for `permissions.defaultMode: "auto"` in settings.json * Fixed Windows version cleanup not protecting the active version’s rollback copy - -​ 2.1.90 @@ -9722,8 +9656,6 @@ * Fixed click-to-expand hover text being nearly invisible on light terminal themes * Fixed UI crash when malformed tool input reached the permission dialog * Fixed headers disappearing when scrolling `/model`, `/config`, and other selection screens - -​ 2.1.89 @@ -9793,15 +9725,11 @@ * Fixed PowerShell tool incorrectly reporting failures when commands like `git push` wrote progress to stderr on Windows PowerShell 5.1 * Fixed a potential out-of-memory crash when the Edit tool was used on very large files (>1 GiB) -​ - 2.1.87 March 29, 2026 * Fixed messages in Cowork Dispatch not getting delivered - -​ 2.1.86 @@ -9844,8 +9772,6 @@ * Fixed memory growth in long sessions from markdown/highlight render caches retaining full content strings * [VSCode] Fixed extension incorrectly showing “Not responding” during long-running operations * [VSCode] Fixed extension defaulting Max plan users to Sonnet after the OAuth token refreshes (8 hours after login) - -​ 2.1.85 @@ -9893,8 +9819,6 @@ * Fixed stale content bleeding through when scrolling up during streaming * Fixed terminal left in enhanced keyboard mode after exit in Ghostty, Kitty, WezTerm, and other terminals supporting the Kitty keyboard protocol — Ctrl+C and Ctrl+D now work correctly after quitting -​ - 2.1.84 March 26, 2026 @@ -9950,8 +9874,6 @@ * Fixed native terminal cursor not tracking the text input caret, so IME composition (CJK input) now renders inline and screen readers can follow the input position * Fixed spurious “Not logged in” errors on macOS caused by transient keychain read failures * Fixed cold-start race where core tools could be deferred without their bypass active, causing Edit/Write to fail with InputValidationError on typed parameters - -​ 2.1.83 @@ -10045,8 +9967,6 @@ * [VSCode] Fixed session history not loading correctly when reopening a session via URL or after restart * [VSCode] Fixed “Fork conversation from here” and rewind actions failing silently after the session cache goes stale -​ - 2.1.81 March 20, 2026 @@ -10090,8 +10010,6 @@ * Fixed Remote Control `/exit` not reliably archiving the session * [VSCode] Fixed Windows PATH inheritance for Bash tool when using Git Bash (regression in v2.1.78) -​ - 2.1.80 March 19, 2026 @@ -10124,8 +10042,6 @@ * Fixed `/remote-control` appearing for gateway and third-party provider deployments where it cannot function * Fixed `/sandbox` tab switching not responding to Tab or arrow keys * Fixed managed settings (`enabledPlugins`, `permissions.defaultMode`, policy-set env vars) not being applied at startup when `remote-settings.json` was cached from a prior session - -​ 2.1.79 @@ -10160,8 +10076,6 @@ * Fixed `SessionEnd` hooks not firing when using interactive `/resume` to switch sessions * [VSCode] Fixed the thinking pill showing “Thinking” instead of “Thought for Ns” after a response completes * [VSCode] Fixed missing session diff button when opening sessions from the left sidebar - -​ 2.1.78 @@ -10204,8 +10118,6 @@ * Fixed queued prompts being concatenated without a newline separator * [VSCode] Fixed a brief flash of the login screen when opening the sidebar while already authenticated * [VSCode] Fixed “API Error: Rate limit reached” when selecting Opus — model dropdown no longer offers 1M context variant to subscribers whose plan tier is unknown - -​ 2.1.77 @@ -10267,8 +10179,6 @@ * Fixed teammate panes not closing when the leader exits * Fixed iTerm2 auto mode not detecting iTerm2 for native split-pane teammates -​ - 2.1.76 March 14, 2026 @@ -10320,8 +10230,6 @@ * Fixed slash commands not found when typing the exact name of a soft-hidden command * [VSCode] Fixed gitignore patterns containing commas silently excluding entire filetypes from the @-mention file picker -​ - 2.1.75 March 13, 2026 @@ -10356,8 +10264,6 @@ * Fixed Esc not closing the `/status` dialog after visiting the Config tab * Fixed input handling when accepting or rejecting a plan * Fixed footer hint in agent teams showing ”↓ to expand” instead of the correct “shift + ↓ to expand” - -​ 2.1.74 @@ -10391,8 +10297,6 @@ * Fixed Hebrew, Arabic, and other RTL text not rendering correctly in Windows Terminal, conhost, and VS Code integrated terminal * Fixed LSP servers not working on Windows due to malformed file URIs * [VSCode] Fixed delete button not working for Untitled sessions - -​ 2.1.73 @@ -10435,8 +10339,6 @@ * Fixed “media_type: Field required” API error when receiving images via Remote Control * Fixed `/heapdump` failing on Windows with `EEXIST` error when the Desktop folder already exists * VSCode: Fixed HTTP 400 errors for users behind proxies or on Bedrock/Vertex with Claude 4.5 models - -​ 2.1.72 @@ -10505,8 +10407,6 @@ * VSCode: Fixed scroll speed in integrated terminals not matching native terminals * VSCode: Fixed Shift+Enter submitting input instead of inserting a newline for users with older keybindings -​ - 2.1.71 March 7, 2026 @@ -10550,8 +10450,6 @@ * Fixed `--print` hanging forever when team agents are configured — the exit loop no longer waits on long-lived `in_process_teammate` tasks * Fixed ”❯ Tool loaded.” appearing in the REPL after every `ToolSearch` call * Fixed prompting for `cd <cwd> && git ...` on Windows when the model uses a mingw-style path - -​ 2.1.70 @@ -10597,8 +10495,6 @@ * Fixed `permissions.defaultMode` settings values other than `acceptEdits` or `plan` being applied in Claude Code Remote environments — they are now ignored * Fixed skill listing being re-injected on every `--resume` (~600 tokens saved per resume) * Fixed teleport marker not rendering in VS Code teleported sessions - -​ 2.1.69 @@ -10684,7 +10580,7 @@ * Fixed teammates accidentally spawning nested teammates via the Agent tool’s `name` parameter * Fixed `CLAUDE_CODE_MAX_OUTPUT_TOKENS` being ignored during conversation compaction * Fixed `/compact` summary rendering as a user bubble in SDK consumers (Claude Code Remote web UI, VSCode extension) - * Fixed voice space bar getting stuck after a failed voice activation (module loading race, cold GrowthBook) + * Fixed voice space bar getting stuck after a failed voice activation (module loading race, feature flags not yet fetched) * Fixed worktree file copy on Windows * Fixed global `.claude` folder detection on Windows * Fixed symlink bypass where writing new files through a symlinked parent directory could escape the working directory in `acceptEdits` mode @@ -10719,8 +10615,6 @@ * Fixed Voice input showing all 5 spaces during warmup instead of capping at ~2 (aligning with the “keep holding…” hint) * [VSCode] Fixed RTL text (Arabic, Hebrew, Persian) rendering reversed in the chat panel (regression in v2.1.63) -​ - 2.1.68 March 4, 2026 @@ -10729,15 +10623,11 @@ * Re-introduced the “ultrathink” keyword to enable high effort for the next turn * Removed Opus 4 and 4.1 from Claude Code on the first-party API — users with these models pinned are automatically moved to Opus 4.6 -​ - 2.1.66 March 4, 2026 * Reduced spurious error logging - -​ 2.1.63 @@ -10781,23 +10671,17 @@ * Fixed a memory leak where MCP server fetch caches were not cleared on disconnect, causing growing memory usage with servers that reconnect frequently * Fixed `/clear` not resetting cached skills, which could cause stale skill content to persist in the new conversation -​ - 2.1.62 February 27, 2026 * Fixed prompt suggestion cache regression that reduced cache hit rates -​ - 2.1.61 February 26, 2026 * Fixed concurrent writes corrupting config file on Windows - -​ 2.1.59 @@ -10812,31 +10696,23 @@ * Fixed shell commands not showing a clear error message when the working directory has been deleted * Fixed config file corruption that could wipe authentication when multiple Claude Code instances ran simultaneously -​ - 2.1.58 February 25, 2026 * Expand Remote Control to more users -​ - 2.1.56 February 25, 2026 * VS Code: Fixed another cause of “command ‘claude-vscode.editor.openLast’ not found” crashes -​ - 2.1.55 February 25, 2026 * Fixed BashTool failing on Windows with EINVAL error - -​ 2.1.53 @@ -10851,15 +10727,11 @@ * Fixed a crash in the WebAssembly interpreter on Linux x64 & Windows x64 * Fixed a crash that sometimes occurred after 2 minutes on Windows ARM64 -​ - 2.1.52 February 24, 2026 * VS Code: Fixed extension crash on Windows (“command ‘claude-vscode.editor.openLast’ not found”) - -​ 2.1.51 @@ -10884,8 +10756,6 @@ * Fixed a security issue where `statusLine` and `fileSuggestion` hook commands could execute without workspace trust acceptance in interactive mode. * Fixed a bug where duplicate `control_response` messages (e.g. from WebSocket reconnects) could cause API 400 errors by pushing duplicate assistant messages into the conversation. * Fixed slash command autocomplete crashing when a plugin’s SKILL.md description is a YAML array or other non-string type - -​ 2.1.50 @@ -10928,8 +10798,6 @@ * Fixed memory leak in CircularBuffer where cleared items were retained in the backing array * Fixed memory leak in shell command execution where ChildProcess and AbortController references were retained after cleanup -​ - 2.1.49 February 19, 2026 @@ -10972,8 +10840,6 @@ * Fixed unbounded memory growth during long-running sessions caused by Yoga WASM linear memory never shrinking * Fixed `disableAllHooks` setting to respect managed settings hierarchy — non-managed settings can no longer disable managed hooks set by policy (#26637) * Fixed `--resume` session picker showing raw XML tags for sessions that start with commands like `/clear`. Now correctly falls through to the session ID fallback. - -​ 2.1.47 @@ -11059,16 +10925,12 @@ * Fixed Edit tool silently corrupting Unicode curly quotes (\u201c\u201d \u2018\u2019) by replacing them with straight quotes when making edits (anthropics/claude-code#26141) * Fixed OSC 8 hyperlinks only being clickable on the first line when link text wraps across multiple terminal lines. -​ - 2.1.46 February 18, 2026 * Fixed orphaned CC processes after terminal disconnect on macOS * Added support for using claude.ai MCP connectors in Claude Code - -​ 2.1.45 @@ -11098,16 +10960,12 @@ * Fixed excessive `.claude.json.backup` files accumulating on every startup * Fixed plugin-provided commands, agents, and hooks not being available immediately after installation without requiring a restart -​ - 2.1.44 February 16, 2026 * Fixed ENAMETOOLONG errors for deeply-nested directory paths * Fixed auth refresh errors - -​ 2.1.43 @@ -11116,8 +10974,6 @@ * Fixed AWS auth refresh hanging indefinitely by adding a 3-minute timeout * Fixed spurious warnings for non-agent markdown files in `.claude/agents/` directory * Fixed structured-outputs beta header being sent unconditionally on Vertex/Bedrock - -​ 2.1.42 @@ -11128,8 +10984,6 @@ * Added one-time Opus 4.6 effort callout for eligible users * Fixed /resume showing interrupt messages as session titles * Fixed image dimension limit errors to suggest /compact - -​ 2.1.41 @@ -11166,8 +11020,6 @@ * Fixed clear stale permission rules when settings change on disk * Fixed hook blocking errors showing stderr content in UI -​ - 2.1.39 February 10, 2026 @@ -11177,8 +11029,6 @@ * Fixed process hanging after session close * Fixed character loss at terminal screen boundary * Fixed blank lines in verbose transcript view - -​ 2.1.38 @@ -11192,23 +11042,17 @@ * Improved heredoc delimiter parsing to prevent command smuggling * Blocked writes to `.claude/skills` directory in sandbox mode -​ - 2.1.37 February 7, 2026 * Fixed an issue where /fast was not immediately available after enabling /extra-usage -​ - 2.1.36 February 7, 2026 * Fast mode is now available for Opus 4.6. Learn more at <https://code.claude.com/docs/en/fast-mode> - -​ 2.1.34 @@ -11216,8 +11060,6 @@ * Fixed a crash when agent teams setting changed between renders * Fixed a bug where commands excluded from sandboxing (via `sandbox.excludedCommands` or `dangerouslyDisableSandbox`) could bypass the Bash ask permission rule when `autoAllowBashIfSandboxed` was enabled - -​ 2.1.33 @@ -11251,8 +11093,6 @@ * Fixed `/resume` session picker showing raw XML markup instead of clean titles for sessions started with slash commands * VSCode: Fixed scroll-to-bottom under-scrolling on initial session load and session switch -​ - 2.1.32 February 5, 2026 @@ -11278,8 +11118,6 @@ * Fixed Thai/Lao spacing vowels (สระ า, ำ) not rendering correctly in the input field * VSCode: Fixed slash commands incorrectly being executed when pressing Enter with preceding text in the input field -​ - 2.1.31 February 4, 2026 @@ -11306,8 +11144,6 @@ * Fixed a crash that made sessions unusable after entering plan mode when project config in `~/.claude.json` was missing default fields * Fixed `temperatureOverride` being silently ignored in the streaming API path, causing all streaming requests to use the default temperature (1) regardless of the configured override * Fixed LSP shutdown/exit compatibility with strict language servers that reject null params - -​ 2.1.30 @@ -11344,15 +11180,11 @@ * Fixed a regression where Windows users with a `.bashrc` file could not run bash commands * [VSCode] Fixed duplicate sessions appearing in the session list when starting a new conversation -​ - 2.1.29 January 31, 2026 * Fixed startup performance issues when resuming sessions that have `saved_hook_context` - -​ 2.1.27 @@ -11368,15 +11200,11 @@ * Windows: Fixed console windows flashing when spawning child processes * VSCode: Fixed OAuth token expiration causing 401 errors after extended sessions -​ - 2.1.25 January 29, 2026 * Fixed beta header validation error for gateway users on Bedrock and Vertex, ensuring `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1` avoids the error - -​ 2.1.23 @@ -11405,15 +11233,11 @@ * Fixed ripgrep search timeouts silently returning empty results instead of reporting errors * [IDE] Fixed model options displaying incorrect region strings for Bedrock users in headless mode -​ - 2.1.22 January 28, 2026 * Fixed structured outputs for non-interactive (-p) mode - -​ 2.1.21 @@ -11437,8 +11261,6 @@ * Fixed task IDs potentially being reused after deletion * Fixed file search not working in VS Code extension on Windows * [VSCode] Fixed message action buttons having incorrect background colors - -​ 2.1.20 @@ -11484,8 +11306,6 @@ * Fixed syntax highlighting for diffs occurring within multiline constructs like Python docstrings * Fixed crashes when cancelling tool use -​ - 2.1.19 January 23, 2026 @@ -11513,23 +11333,17 @@ * Fixed backgrounded hook commands not returning early, potentially causing the session to wait on a process that was intentionally backgrounded * Fixed file write preview omitting empty lines -​ - 2.1.18 January 23, 2026 * Added customizable keyboard shortcuts. Configure keybindings per context, create chord sequences, and personalize your workflow. Run `/keybindings` to get started. Learn more at <https://code.claude.com/docs/en/keybindings> -​ - 2.1.17 January 22, 2026 * Fixed crashes on processors without AVX instruction support - -​ 2.1.16 @@ -11543,8 +11357,6 @@ * Fixed session titles on the resume screen not respecting the user’s language setting * [IDE] Fixed a race condition on Windows where the Claude Code sidebar view container would not appear on start -​ - 2.1.15 January 21, 2026 @@ -11553,8 +11365,6 @@ * Improved UI rendering performance with React Compiler * Fixed the “Context left until auto-compact” warning not disappearing after running `/compact` * Fixed MCP stdio server timeout not killing child process, which could cause UI freezes - -​ 2.1.14 @@ -11585,23 +11395,17 @@ * Fixed inconsistent back navigation in plugin marketplace when only one marketplace is configured * Fixed iTerm2 progress bar not clearing properly on exit, preventing lingering indicators and bell sounds -​ - 2.1.12 January 17, 2026 * Fixed message rendering bug -​ - 2.1.11 January 17, 2026 * Fixed excessive MCP connection requests for HTTP/SSE transports - -​ 2.1.10 @@ -11614,8 +11418,6 @@ * Improved file suggestions to show as removable attachments instead of inserting text when accepted * [VSCode] Added install count display to plugin listings * [VSCode] Added trust warning when installing plugins - -​ 2.1.9 @@ -11631,8 +11433,6 @@ * Fixed MCP server reconnection hanging when cached connection promise never resolves * Fixed Ctrl+Z suspend not working in terminals using Kitty keyboard protocol (Ghostty, iTerm2, kitty, WezTerm) -​ - 2.1.7 January 14, 2026 @@ -11663,8 +11463,6 @@ * Fixed plugins with git submodules not being fully initialized when installed * Fixed bash commands failing on Windows when temp directory paths contained characters like `t` or `n` that were misinterpreted as escape sequences * [VSCode] Fixed `claudeProcessWrapper` setting passing the wrapper path instead of the Claude binary path - -​ 2.1.6 @@ -11707,15 +11505,11 @@ * Fixed visual artifacts in ink2 mode when nodes become hidden via `display:none` * [VSCode] Fixed usage indicator not updating after manual compact -​ - 2.1.5 January 12, 2026 * Added `CLAUDE_CODE_TMPDIR` environment variable to override the temp directory used for internal temp files, useful for environments with custom temp directory requirements - -​ 2.1.4 @@ -11723,8 +11517,6 @@ * Added `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` environment variable to disable all background task functionality including auto-backgrounding and the Ctrl+B shortcut * Fixed “Help improve Claude” setting fetch to refresh OAuth and retry when it fails due to a stale OAuth token - -​ 2.1.3 @@ -11754,8 +11546,6 @@ * Fixed sub-agents using the wrong model during conversation compaction * Fixed web search in sub-agents using incorrect model * Fixed trust dialog acceptance when running from the home directory not enabling trust-requiring features like hooks during the session - -​ 2.1.2 @@ -11794,8 +11584,6 @@ * Fixed remote session URL and teleport being broken when using `/tasks` command * Fixed MCP tool names being exposed in analytics events by sanitizing user-specific server configurations * [VSCode] Fixed usage display not updating after manual compact - -​ 2.1.0 @@ -11922,23 +11710,17 @@ * [VSCode] Fixed scrolling in the extension inadvertently scrolling the parent iframe * [Windows] Fixed issue with improper rendering -​ - 2.0.76 January 7, 2026 * Fixed issue with macOS code-sign warning when using Claude in Chrome integration -​ - 2.0.75 January 7, 2026 * Minor bugfixes - -​ 2.0.74 @@ -11965,8 +11747,6 @@ * Fixed visual bug in `/plugins discover` where list selection indicator showed while search box was focused * Fixed macOS keyboard shortcuts to display ‘opt’ instead of ‘alt’ * [Windows] Fixed issue with improper rendering - -​ 2.0.73 @@ -11982,8 +11762,6 @@ * Improved search UX across resume session, permissions, and plugins screens with a unified SearchBox component * [VSCode] Added tab icon badges showing pending permissions (blue) and unread completions (orange) -​ - 2.0.72 December 17, 2025 @@ -12009,8 +11787,6 @@ * Fixed `/context` command not respecting custom system prompts in non-interactive mode * Fixed order of consecutive Ctrl+K lines when pasting with Ctrl+Y - -​ 2.0.71 @@ -12024,8 +11800,6 @@ * Bedrock: Environment variable `ANTHROPIC_BEDROCK_BASE_URL` is now respected for token counting and inference profile listing * New syntax highlighting engine for native build -​ - 2.0.70 December 15, 2025 @@ -12054,15 +11828,11 @@ * Fixed diff view not updating when terminal is resized * Fix thinking mode toggle in /config not persisting correctly -​ - 2.0.69 December 13, 2025 * Minor bugfixes - -​ 2.0.68 @@ -12074,8 +11844,6 @@ * Fixed Option+Arrow word navigation treating entire CJK (Chinese, Japanese, Korean) text sequences as a single word instead of navigating by word boundaries * Improved plan mode exit UX: show simplified yes/no dialog when exiting with empty or missing plan instead of throwing an error * Add support for enterprise managed settings. Contact your Anthropic account team to enable this feature. - -​ 2.0.67 @@ -12101,8 +11869,6 @@ * Fixed consecutive @~/ file references in CLAUDE.md being incorrectly parsed due to markdown strikethrough interference * Windows: Fixed plugin MCP servers failing due to colons in log directory paths -​ - 2.0.65 December 11, 2025 @@ -12114,8 +11880,6 @@ * Fixed prompt not being saved to history when aborting a query with Escape * Fixed Read tool image handling to identify format from bytes instead of file extension -​ - 2.0.64 December 10, 2025 @@ -12145,8 +11909,6 @@ * Fixed auto-loading .env when using native installer * Fixed `--system-prompt` being ignored when using `--continue` or `--resume` flags * VSCode: Fixed extension not working on Windows ARM64 by falling back to x64 binary via emulation - -​ 2.0.62 @@ -12160,15 +11922,11 @@ * Fixed running versions getting removed because lock file incorrectly going stale * Fixed IDE diff tab not closing when rejecting file changes -​ - 2.0.61 December 7, 2025 * Reverted VSCode support for multiple terminal clients due to responsiveness issues. - -​ 2.0.60 @@ -12181,8 +11939,6 @@ * Updated Fetch to skip summarization for pre-approved websites * VSCode: Added support for multiple terminal clients connecting to the IDE server simultaneously -​ - 2.0.59 December 4, 2025 @@ -12191,8 +11947,6 @@ * Added `agent` setting to configure main thread with a specific agent’s system prompt, tool restrictions, and model * VS Code: Fixed .claude.json config file being read from incorrect location -​ - 2.0.58 December 3, 2025 @@ -12201,8 +11955,6 @@ * Fixed timer duration showing “11m 60s” instead of “12m 0s” * Windows: Managed settings now prefer `C:\Program Files\ClaudeCode` if it exists. Support for `C:\ProgramData\ClaudeCode` will be removed in a future version. -​ - 2.0.57 December 3, 2025 @@ -12210,16 +11962,12 @@ * Added feedback input when rejecting plans, allowing users to tell Claude what to change * VSCode: Added streaming message support for real-time response display -​ - 2.0.56 December 2, 2025 * Added setting to enable/disable terminal progress bar (OSC 9;4) * VSCode Extension: Added support for VS Code’s secondary sidebar (VS Code 1.97+), allowing Claude Code to be displayed in the right sidebar while keeping the file explorer on the left. Requires setting sidebar as Preferred Location in the config. - -​ 2.0.55 @@ -12230,16 +11978,12 @@ * Improved AskUserQuestion tool to auto-submit single-select questions on the last question, eliminating the extra review screen for simple question flows * Improved fuzzy matching for `@` file suggestions with faster, more accurate results -​ - 2.0.54 November 26, 2025 * Hooks: Enable PermissionRequest hooks to process ‘always allow’ suggestions and apply permission updates * Fix issue with excessive iTerm notifications - -​ 2.0.52 @@ -12249,8 +11993,6 @@ * Fixed `/usage` command progress bars to fill up as usage increases (instead of showing remaining percentage) * Fixed image pasting not working on Linux systems running Wayland (now falls back to wl-paste when xclip is unavailable) * Permit some uses of `$!` in bash commands - -​ 2.0.51 @@ -12266,8 +12008,6 @@ * Fixed handling of thinking errors * Fixed performance regression -​ - 2.0.50 November 21, 2025 @@ -12277,8 +12017,6 @@ * Improved ultrathink text display * Improved clarity of 5-hour session limit warning message -​ - 2.0.49 November 21, 2025 @@ -12286,8 +12024,6 @@ * Added readline-style ctrl-y for pasting deleted text * Improved clarity of usage limit warning message * Fixed handling of subagent permissions - -​ 2.0.47 @@ -12298,15 +12034,11 @@ * Fixed race condition with history entry not getting logged at exit * Fixed Vertex AI configuration not being applied from `settings.json` -​ - 2.0.46 November 19, 2025 * Fixed image files being reported with incorrect media type when format cannot be detected from metadata - -​ 2.0.45 @@ -12315,8 +12047,6 @@ * Added support for Microsoft Foundry! See <https://code.claude.com/docs/en/azure-ai-foundry> * Added `PermissionRequest` hook to automatically approve or deny tool permission requests with custom logic * Send background tasks to Claude Code on the web by starting a message with `&` - -​ 2.0.43 @@ -12331,15 +12061,11 @@ * Fixed some visual flickers * Fixed NotebookEdit tool inserting cells at incorrect positions when cell IDs matched the pattern `cell-N` -​ - 2.0.42 November 15, 2025 * Added `agent_id` and `agent_transcript_path` fields to `SubagentStop` hooks. - -​ 2.0.41 @@ -12366,8 +12092,6 @@ * Fixed broken security documentation links in trust dialogs and onboarding * Fixed issue where pressing ESC to close the diff modal would also interrupt the model -​ - 2.0.37 November 11, 2025 @@ -12376,8 +12100,6 @@ * Hooks: Added matcher values for Notification hook events * Output Styles: Added `keep-coding-instructions` option to frontmatter -​ - 2.0.36 November 7, 2025 @@ -12385,8 +12107,6 @@ * Fixed: DISABLE_AUTOUPDATER environment variable now properly disables package manager update notifications * Fixed queued messages being incorrectly executed as bash commands * Fixed input being lost when typing while a queued message is processed - -​ 2.0.35 @@ -12398,8 +12118,6 @@ * Migrated `ignorePatterns` from project config to deny permissions in the localSettings. * Fixed menu navigation getting stuck on items with empty string or other falsy values (e.g., in the `/hooks` menu) -​ - 2.0.34 November 5, 2025 @@ -12409,8 +12127,6 @@ * Fixed infinite token refresh loop that caused MCP servers with OAuth (e.g., Slack) to hang during connection * Fixed memory crash when reading or writing large files (especially base64-encoded images) -​ - 2.0.33 November 4, 2025 @@ -12419,8 +12135,6 @@ * Fixed `claude doctor` incorrectly detecting Homebrew vs npm-global installations by properly resolving symlinks * Fixed `claude mcp serve` exposing tools with incompatible outputSchemas -​ - 2.0.32 November 4, 2025 @@ -12428,8 +12142,6 @@ * Un-deprecate output styles based on community feedback * Added `companyAnnouncements` setting for displaying announcements on startup * Fixed hook progress messages not updating correctly during PostToolUse hook execution - -​ 2.0.31 @@ -12441,8 +12153,6 @@ * Fixed a bug with subagents and MCP servers related to “Tool names must be unique” error * Fixed issue causing `/compact` to fail with `prompt_too_long` by making it respect existing compact boundaries * Fixed plugin uninstall not removing plugins - -​ 2.0.30 @@ -12472,8 +12182,6 @@ * Fixed MCP tools not being available to sub-agents * Fixed hooks and plugins not executing when using —dangerously-skip-permissions flag * Fixed delay when navigating through typeahead suggestions with arrow keys - -​ 2.0.28 @@ -12489,8 +12197,6 @@ * Fixed a bug where macOS permission prompts would show up upon initial launch when launching from home directory * Various other bug fixes -​ - 2.0.27 October 24, 2025 @@ -12501,15 +12207,11 @@ * VSCode Extension: Add config setting to include .gitignored files in file searches * VSCode Extension: Bug fixes for unrelated ‘Warmup’ conversations, and configuration/settings occasionally being reset to defaults -​ - 2.0.25 October 21, 2025 * Removed legacy SDK entrypoint. Please migrate to @anthropic-ai/claude-agent-sdk for future SDK updates: <https://platform.claude.com/docs/en/agent-sdk/migration-guide> - -​ 2.0.24 @@ -12520,8 +12222,6 @@ * Sandbox: Releasing a sandbox mode for the BashTool on Linux & Mac * Bedrock: Display awsAuthRefresh output when auth is required -​ - 2.0.22 October 17, 2025 @@ -12530,8 +12230,6 @@ * IDE: Add toggle to enable/disable thinking. * Fix bug causing duplicate permission prompts with parallel tool calls * Add support for enterprise managed MCP allowlist and denylist - -​ 2.0.21 @@ -12543,15 +12241,11 @@ * Added Haiku 4.5 as a model option for Pro users * Fixed an issue where queued commands don’t have access to previous messages’ output -​ - 2.0.20 October 16, 2025 * Added support for Claude Skills - -​ 2.0.19 @@ -12559,8 +12253,6 @@ * Auto-background long-running bash commands instead of killing them. Customize with BASH_DEFAULT_TIMEOUT_MS * Fixed a bug where Haiku was unnecessarily called in print mode - -​ 2.0.17 @@ -12573,16 +12265,12 @@ * OTEL: support HTTP_PROXY and HTTPS_PROXY * `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` now disables release notes fetching -​ - 2.0.15 October 14, 2025 * Fixed bug with resuming where previously created files needed to be read again before writing * Fixed bug with `-p` mode where @-mentioned files needed to be read again before writing - -​ 2.0.14 @@ -12596,15 +12284,11 @@ * Several improvements to rendering * Plugins UI polish -​ - 2.0.13 October 9, 2025 * Fixed `/plugin` not working on native build - -​ 2.0.12 @@ -12624,8 +12308,6 @@ * Avoid mentioning hooks in `/resume` summaries * Changes to the “verbose” setting in `/config` now persist across sessions -​ - 2.0.11 October 8, 2025 @@ -12634,8 +12316,6 @@ * IDE: Fixed keyboard shortcuts and focus issues for smoother interaction * Fixed Opus fallback rate limit errors appearing incorrectly * Fixed /add-dir command selecting wrong default tab - -​ 2.0.10 @@ -12648,15 +12328,11 @@ * Press Ctrl-G to edit your prompt in your system’s configured text editor * Fixes for bash permission checks with environment variables in the command -​ - 2.0.9 October 6, 2025 * Fix regression where bash backgrounding stopped working - -​ 2.0.8 @@ -12668,8 +12344,6 @@ * Improve message rendering for users with light themes on dark terminals * Remove deprecated .claude.json allowedTools, ignorePatterns, env, and todoFeatureEnabled config options (instead, configure these in your settings.json) -​ - 2.0.5 October 4, 2025 @@ -12679,16 +12353,12 @@ * Fix unhandled OAuth expiration 401 API errors * SDK: Added SDKUserMessageReplay.isReplay to prevent duplicate messages -​ - 2.0.1 September 30, 2025 * Skip Sonnet 4.5 default model setting change for Bedrock and Vertex * Various bug fixes and presentation improvements - -​ 2.0.0 @@ -12710,16 +12380,12 @@ * Hooks: Reduced PostToolUse ‘tool_use’ ids were found without ‘tool_result’ blocks errors * SDK: The Claude Code SDK is now the Claude Agent SDK -​ - 1.0.126 September 26, 2025 * Enable /context command for Bedrock and Vertex * Add mTLS support for HTTP-based OpenTelemetry exporters - -​ 1.0.124 @@ -12730,8 +12396,6 @@ * No longer inform Claude of the list of allowed tools when permission is denied * Fixed security vulnerability in Bash tool permission checks * Improved VSCode extension performance for large files - -​ 1.0.123 @@ -12745,8 +12409,6 @@ * Fixed a bug where resuming a conversation in headless mode would sometimes enable thinking unnecessarily * Migrated —debug logging to a file, to enable easy tailing & filtering -​ - 1.0.120 September 19, 2025 @@ -12757,8 +12419,6 @@ * Fixed IDE compatibility issue by removing worktree support check * Fixed security vulnerability where Bash tool permission checks could be bypassed using prefix matching -​ - 1.0.119 September 19, 2025 @@ -12767,8 +12427,6 @@ * Support dynamic headers for MCP servers via headersHelper configuration * Fix thinking mode not working in headless sessions * Fix slash commands now properly update allowed tools instead of replacing them - -​ 1.0.117 @@ -12779,8 +12437,6 @@ * Add sed command to auto-allowed commands in acceptEdits mode * Fix Windows PATH comparison to be case-insensitive for drive letters * Add permissions management hint to /add-dir output - -​ 1.0.115 @@ -12793,16 +12449,12 @@ * Fix visual feedback when loading state completes * Improve UI consistency for permission request dialogs -​ - 1.0.113 September 13, 2025 * Deprecated piped input in interactive mode * Move Ctrl+R keybinding for toggling transcript to Ctrl+O - -​ 1.0.112 @@ -12814,16 +12466,12 @@ * Added `spinnerTipsEnabled` setting to disable spinner tips * IDE: Various improvements and bug fixes -​ - 1.0.111 September 10, 2025 * /model now validates provided model names * Fixed Bash tool crashes caused by malformed shell syntax parsing - -​ 1.0.110 @@ -12833,31 +12481,23 @@ * MCP: OAuth tokens now proactively refresh before expiration * Fixed reliability issues with background Bash processes -​ - 1.0.109 September 9, 2025 * SDK: Added partial message streaming support via `--include-partial-messages` CLI flag -​ - 1.0.106 September 5, 2025 * Windows: Fixed path permission matching to consistently use POSIX format (e.g., `Read(//c/Users/...)`) -​ - 1.0.97 August 29, 2025 * Settings: /doctor now validates permission rule syntax and suggests corrections - -​ 1.0.94 @@ -12868,8 +12508,6 @@ * SDK: Add custom tools as callbacks * Added /todos command to list current todo items -​ - 1.0.93 August 26, 2025 @@ -12877,15 +12515,11 @@ * Windows: Add alt + v shortcut for pasting images from clipboard * Support NO_PROXY environment variable to bypass proxy for specified hostnames and IPs -​ - 1.0.90 August 25, 2025 * Settings file changes take effect immediately - no restart required - -​ 1.0.88 @@ -12897,8 +12531,6 @@ * Introduced `ANTHROPIC_DEFAULT_SONNET_MODEL` and `ANTHROPIC_DEFAULT_OPUS_MODEL` for controlling model aliases opusplan, opus, and sonnet. * Bedrock: Updated default Sonnet model to Sonnet 4 -​ - 1.0.86 August 22, 2025 @@ -12907,16 +12539,12 @@ * SDK: Added UUID support for all SDK messages * SDK: Added `--replay-user-messages` to replay user messages back to stdout -​ - 1.0.85 August 19, 2025 * Status line input now includes session cost info * Hooks: Introduced SessionEnd hook - -​ 1.0.84 @@ -12927,16 +12555,12 @@ * @-mention: Add ~/.claude/* files to suggestions for easier agent, output style, and slash command editing * Use built-in ripgrep by default; to opt out of this behavior, set USE_BUILTIN_RIPGREP=0 -​ - 1.0.83 August 18, 2025 * @-mention: Support files with spaces in path * New shimmering spinner - -​ 1.0.82 @@ -12948,8 +12572,6 @@ * MCP: Improve tool name consistency * Bash: Fix crash when Claude tries to automatically read large files -​ - 1.0.81 August 14, 2025 @@ -12957,15 +12579,11 @@ * Released output styles, including new built-in educational output styles “Explanatory” and “Learning”. Docs: <https://code.claude.com/docs/en/output-styles> * Agents: Fix custom agent loading when agent files are unparsable -​ - 1.0.80 August 14, 2025 * UI improvements: Fix text contrast for custom subagent colors and spinner rendering issues - -​ 1.0.77 @@ -12975,8 +12593,6 @@ * SDK: Add session support and permission denial tracking * Fix token limit errors in conversation summarization * Opus Plan Mode: New setting in `/model` to run Opus only in plan mode, Sonnet otherwise - -​ 1.0.73 @@ -12988,15 +12604,11 @@ * UI: Enhanced spinner animations and status line visual hierarchy * Linux: Added support for Alpine and musl-based distributions (requires separate ripgrep installation) -​ - 1.0.72 August 11, 2025 * Ask permissions: have Claude Code always ask for confirmation to use specific tools with /permissions - -​ 1.0.71 @@ -13004,8 +12616,6 @@ * Background commands: (Ctrl-b) to run any Bash command in the background so Claude can keep working (great for dev servers, tailing logs, etc.) * Customizable status line: add your terminal prompt to Claude Code with /statusline - -​ 1.0.70 @@ -13015,15 +12625,11 @@ * Windows: Fixed native file search, ripgrep, and subagent functionality * Added support for @-mentions in slash command arguments -​ - 1.0.69 August 5, 2025 * Upgraded Opus to version 4.1 - -​ 1.0.68 @@ -13037,16 +12643,12 @@ * Added `disableAllHooks` setting * Improved file suggestions performance in large repos -​ - 1.0.65 July 31, 2025 * IDE: Fixed connection stability issues and error handling for diagnostics * Windows: Fixed shell environment setup for users without .bashrc files - -​ 1.0.64 @@ -13058,15 +12660,11 @@ * SDK: Fixed user input tracking across multi-turn conversations * Added hidden files to file search and @-mention suggestions -​ - 1.0.63 July 29, 2025 * Windows: Fixed file search, @agent mentions, and custom slash commands functionality - -​ 1.0.62 @@ -13076,8 +12674,6 @@ * Hooks: Added SessionStart hook for new session initialization * /add-dir command now supports typeahead for directory paths * Improved network connectivity check reliability - -​ 1.0.61 @@ -13092,15 +12688,11 @@ * IDE: Added `CLAUDE_CODE_AUTO_CONNECT_IDE=false` for disabling IDE auto-connection * Added `CLAUDE_CODE_SHELL_PREFIX` for wrapping Claude and user-provided shell commands run by Claude Code -​ - 1.0.60 July 24, 2025 * You can now create custom subagents for specialized tasks! Run /agents to get started - -​ 1.0.59 @@ -13112,8 +12704,6 @@ * Hooks: UserPromptSubmit now supports additionalContext in advanced JSON output * Fixed issue where some Max users that specified Opus would still see fallback to Sonnet -​ - 1.0.58 July 23, 2025 @@ -13122,8 +12712,6 @@ * MCP: Improved server health status display in ‘claude mcp list’ * Hooks: Added CLAUDE_PROJECT_DIR env var for hook commands -​ - 1.0.57 July 23, 2025 @@ -13132,8 +12720,6 @@ * Improved permission messages to help Claude understand allowed tools * Fix: Remove trailing newlines from bash output in terminal wrapping -​ - 1.0.56 July 23, 2025 @@ -13141,8 +12727,6 @@ * Windows: Enabled shift+tab for mode switching on versions of Node.js that support terminal VT mode * Fixes for WSL IDE detection * Fix an issue causing awsRefreshHelper changes to .aws directory not to be picked up - -​ 1.0.55 @@ -13152,8 +12736,6 @@ * Windows: fixed Ctrl+Z crash * SDK: Added ability to capture error logging * Add —system-prompt-file option to override system prompt in print mode - -​ 1.0.54 @@ -13165,8 +12747,6 @@ * Windows: mode switching now uses alt + m, and plan mode renders properly * Shell: Switch to in-memory shell snapshot to fix file-related errors -​ - 1.0.53 July 18, 2025 @@ -13174,15 +12754,11 @@ * Updated @-mention file truncation from 100 lines to 2000 lines * Add helper script settings for AWS token refresh: awsAuthRefresh (for foreground operations like aws sso login) and awsCredentialExport (for background operation with STS-like response). -​ - 1.0.52 July 18, 2025 * Added support for MCP server instructions - -​ 1.0.51 @@ -13198,8 +12774,6 @@ * Custom slash commands: Fixed user-level commands in subdirectories * Plan mode: Fixed issue where rejected plan from sub-task would get discarded -​ - 1.0.48 July 10, 2025 @@ -13212,8 +12786,6 @@ * Hooks: Added a PreCompact hook * Vim mode: Added c, f/F, t/T -​ - 1.0.45 July 10, 2025 @@ -13225,8 +12797,6 @@ * Stop Hooks: Fixed transcript path after /clear and fixed triggering when loop ends with tool call * Custom slash commands: Restored namespacing in command names based on subdirectories. For example, .claude/commands/frontend/component.md is now /frontend:component, not /component. -​ - 1.0.44 July 7, 2025 @@ -13236,8 +12806,6 @@ * MCP: tool annotations and tool titles now display in /mcp view * Changed Ctrl+Z to suspend Claude Code. Resume by running `fg`. Prompt input undo is now Ctrl+U. -​ - 1.0.43 July 3, 2025 @@ -13245,15 +12813,11 @@ * Fixed a bug where the theme selector was saving excessively * Hooks: Added EPIPE system error handling -​ - 1.0.42 July 3, 2025 * Added tilde (`~`) expansion support to `/add-dir` command - -​ 1.0.41 @@ -13265,39 +12829,29 @@ * Fixed a bug where MCP tools would display twice in tool list * New tool parameters JSON for Bash tool in `tool_decision` event -​ - 1.0.40 July 3, 2025 * Fixed a bug causing API connection errors with UNABLE_TO_GET_ISSUER_CERT_LOCALLY if `NODE_EXTRA_CA_CERTS` was set -​ - 1.0.39 July 3, 2025 * New Active Time metric in OpenTelemetry logging -​ - 1.0.38 June 30, 2025 * Released hooks. Special thanks to community input in <https://github.com/anthropics/claude-code/issues/712>. Docs: <https://code.claude.com/docs/en/hooks> -​ - 1.0.37 June 30, 2025 * Remove ability to set `Proxy-Authorization` header via ANTHROPIC_AUTH_TOKEN or apiKeyHelper - -​ 1.0.36 @@ -13306,23 +12860,17 @@ * Web search now takes today’s date into context * Fixed a bug where stdio MCP servers were not terminating properly on exit -​ - 1.0.35 June 25, 2025 * Added support for MCP OAuth Authorization Server discovery -​ - 1.0.34 June 24, 2025 * Fixed a memory leak causing a MaxListenersExceededWarning message to appear - -​ 1.0.33 @@ -13332,8 +12880,6 @@ * Added prompt input undo functionality (Ctrl+Z and vim ‘u’ command) * Improvements to plan mode -​ - 1.0.32 June 24, 2025 @@ -13341,15 +12887,11 @@ * Updated loopback config for litellm * Added forceLoginMethod setting to bypass login selection screen -​ - 1.0.31 June 24, 2025 * Fixed a bug where ~/.claude.json would get reset when file contained invalid JSON - -​ 1.0.30 @@ -13360,15 +12902,11 @@ * Added timestamps in Ctrl-r mode and fixed Ctrl-c handling * Enhanced jq regex support for complex filters with pipes and select -​ - 1.0.29 June 24, 2025 * Improved CJK character support in cursor navigation and rendering - -​ 1.0.28 @@ -13380,8 +12918,6 @@ * Performance optimizations for memory usage * New attributes (terminal.type, language) in OpenTelemetry logging -​ - 1.0.27 June 18, 2025 @@ -13391,8 +12927,6 @@ * MCP resources can now be @-mentioned * /resume slash command to switch conversations within Claude Code -​ - 1.0.25 June 16, 2025 @@ -13402,8 +12936,6 @@ * Improved support for Ghostty * Improved web search reliability -​ - 1.0.24 June 16, 2025 @@ -13411,8 +12943,6 @@ * Improved /mcp output * Fixed a bug where settings arrays got overwritten instead of merged -​ - 1.0.23 June 16, 2025 @@ -13420,15 +12950,11 @@ * Released TypeScript SDK: import @anthropic-ai/claude-code to get started * Released Python SDK: pip install claude-code-sdk to get started -​ - 1.0.22 June 12, 2025 * SDK: Renamed `total_cost` to `total_cost_usd` - -​ 1.0.21 @@ -13437,8 +12963,6 @@ * Improved editing of files with tab-based indentation * Fix for tool_use without matching tool_result errors * Fixed a bug where stdio MCP server processes would linger after quitting Claude Code - -​ 1.0.18 @@ -13453,8 +12977,6 @@ * Added auto-reconnection for MCP SSE connections on disconnect * Fixed issue where pasted content was lost when dialogs appeared -​ - 1.0.17 June 9, 2025 @@ -13463,8 +12985,6 @@ * Fixed crashes when the VS Code diff tool is invoked multiple times quickly * MCP server list UI improvements * Update Claude Code process title to display “claude” instead of “node” - -​ 1.0.11 @@ -13476,16 +12996,12 @@ * Improved shell configuration error handling * Improved todo list handling during compaction -​ - 1.0.10 June 4, 2025 * Added markdown table support * Improved streaming performance - -​ 1.0.8 @@ -13498,8 +13014,6 @@ * Added support for triggering thinking non-English languages * Improved compacting UI -​ - 1.0.7 June 2, 2025 @@ -13511,8 +13025,6 @@ * Improved error handling for /install-github-app * Bugfixes, UI polish, and tool reliability improvements -​ - 1.0.6 June 2, 2025 @@ -13523,15 +13035,11 @@ * Added support for symlinks in @file typeahead * Bugfixes, UI polish, and tool reliability improvements -​ - 1.0.4 May 28, 2025 * Fixed a bug where MCP tool errors weren’t being parsed correctly - -​ 1.0.1 @@ -13541,8 +13049,6 @@ * Improved model references to show provider-specific names (Sonnet 3.7 for Bedrock, Sonnet 4 for Console) * Updated documentation links and OAuth process descriptions -​ - 1.0.0 May 22, 2025 @@ -13550,16 +13056,12 @@ * Claude Code is now generally available * Introducing Sonnet 4 and Opus 4 models -​ - 0.2.125 May 21, 2025 * Breaking change: Bedrock ARN passed to `ANTHROPIC_MODEL` or `ANTHROPIC_SMALL_FAST_MODEL` should no longer contain an escaped slash (specify `/` instead of `%2F`) * Removed `DEBUG=true` in favor of `ANTHROPIC_LOG=debug`, to log all requests - -​ 0.2.117 @@ -13569,8 +13071,6 @@ * Introduced settings.cleanupPeriodDays * Introduced CLAUDE_CODE_API_KEY_HELPER_TTL_MS env var * Introduced —debug mode - -​ 0.2.108 @@ -13583,15 +13083,11 @@ * Deprecated MCP wizard interface in favor of other MCP commands * Lots of other bugfixes and improvements -​ - 0.2.107 May 9, 2025 * CLAUDE.md files can now import other files. Add @path/to/file.md to ./CLAUDE.md to load additional files on launch - -​ 0.2.106 @@ -13599,8 +13095,6 @@ * MCP SSE server configs can now specify custom headers * Fixed a bug where MCP permission prompt didn’t always show correctly - -​ 0.2.105 @@ -13611,8 +13105,6 @@ * Added word movement keybindings for Vim * Improved latency for startup, todo tool, and file edits -​ - 0.2.102 May 5, 2025 @@ -13621,8 +13113,6 @@ * Improved @mention reliability for images and folders * You can now paste multiple large chunks into one prompt -​ - 0.2.100 May 2, 2025 @@ -13630,23 +13120,17 @@ * Fixed a crash caused by a stack overflow error * Made db storage optional; missing db support disables —continue and —resume -​ - 0.2.98 May 1, 2025 * Fixed an issue where auto-compact was running twice -​ - 0.2.96 May 1, 2025 * Claude Code can now also be used with a Claude Max subscription (<https://claude.ai/upgrade>) - -​ 0.2.93 @@ -13655,16 +13139,12 @@ * Resume conversations from where you left off from with “claude —continue” and “claude —resume” * Claude now has access to a Todo list that helps it stay on track and be more organized -​ - 0.2.82 April 25, 2025 * Added support for —disallowedTools * Renamed tools for consistency: LSTool -> LS, View -> Read, etc. - -​ 0.2.75 @@ -13676,8 +13156,6 @@ * Run one-off MCP servers with `claude --mcp-config <path-to-file>` * Improved performance for filename auto-complete -​ - 0.2.74 April 18, 2025 @@ -13685,15 +13163,11 @@ * Added support for refreshing dynamically generated API keys (via apiKeyHelper), with a 5 minute TTL * Task tool can now perform writes and run bash commands -​ - 0.2.72 April 18, 2025 * Updated spinner to indicate tokens loaded and tool usage - -​ 0.2.70 @@ -13703,8 +13177,6 @@ * Claude can now run multiple web queries in parallel * Pressing ESC once immediately interrupts Claude in Auto-accept mode -​ - 0.2.69 April 17, 2025 @@ -13712,15 +13184,11 @@ * Fixed UI glitches with improved Select component behavior * Enhanced terminal output display with better text truncation logic -​ - 0.2.67 April 17, 2025 * Shared project permission rules can be saved in .claude/settings.json - -​ 0.2.66 @@ -13729,15 +13197,11 @@ * Print mode (-p) now supports streaming output via —output-format=stream-json * Fixed issue where pasting could trigger memory or bash mode unexpectedly -​ - 0.2.63 April 17, 2025 * Fixed an issue where MCP tools were loaded twice, which caused tool call errors - -​ 0.2.61 @@ -13747,8 +13211,6 @@ * Enhanced image detection for more reliable clipboard paste functionality * Fixed an issue where ESC key could crash the conversation history selector -​ - 0.2.59 April 2, 2025 @@ -13757,8 +13219,6 @@ * Improved progress indicators for bash and fetch tools * Bugfixes for non-interactive mode (-p) -​ - 0.2.54 April 2, 2025 @@ -13767,8 +13227,6 @@ * Press ctrl+r to see full output for long tool results * Added support for MCP SSE transport -​ - 0.2.53 April 2, 2025 @@ -13776,23 +13234,17 @@ * New web fetch tool lets Claude view URLs that you paste in * Fixed a bug with JPEG detection -​ - 0.2.50 April 2, 2025 * New MCP “project” scope now allows you to add MCP servers to .mcp.json files and commit them to your repository -​ - 0.2.49 April 2, 2025 * Previous MCP server scopes have been renamed: previous “project” scope is now “local” and “global” scope is now “user” - -​ 0.2.47 @@ -13802,15 +13254,11 @@ * Press Shift + Tab to toggle auto-accept for file edits * Automatic conversation compaction for infinite conversation length (toggle with /config) -​ - 0.2.44 April 2, 2025 * Ask Claude to make a plan with thinking mode: just say ‘think’ or ‘think harder’ or even ‘ultrathink’ - -​ 0.2.41 @@ -13819,8 +13267,6 @@ * MCP server startup timeout can now be configured via MCP_TIMEOUT environment variable * MCP server startup no longer blocks the app from starting up -​ - 0.2.37 April 2, 2025 @@ -13828,8 +13274,6 @@ * New /release-notes command lets you view release notes at any time * `claude config add/remove` commands now accept multiple values separated by commas or spaces -​ - 0.2.36 April 2, 2025 @@ -13837,15 +13281,11 @@ * Import MCP servers from Claude Desktop with `claude mcp add-from-claude-desktop` * Add MCP servers as JSON strings with `claude mcp add-json <n> <json>` -​ - 0.2.34 April 2, 2025 * Vim bindings for text input - enable with /vim or /config - -​ 0.2.32 @@ -13854,16 +13294,12 @@ * Interactive MCP setup wizard: Run “claude mcp add” to add MCP servers with a step-by-step interface * Fix for some PersistentShell issues -​ - 0.2.31 April 2, 2025 * Custom slash commands: Markdown files in .claude/commands/ directories now appear as custom slash commands to insert prompts into your conversation * MCP debug mode: Run with —mcp-debug flag to get more information about MCP server errors - -​ 0.2.30 @@ -13873,8 +13309,6 @@ * Fixed issue where slash command arguments weren’t being sent properly * (Mac-only) API keys are now stored in macOS Keychain -​ - 0.2.26 April 2, 2025 @@ -13883,8 +13317,6 @@ * Word-level diff display for improved code readability * Fuzzy matching for slash commands -​ - 0.2.21 April 2, 2025
modified Push events into a running session with channels View current →
Show diff (111 lines)
--- a/channels.md +++ b/channels.md @@ -2,11 +2,7 @@ A channel is an MCP server that pushes events into your running Claude Code session, so Claude can react to things that happen while you’re not at the terminal. Channels can be two-way: Claude reads the event and replies back through the same channel, like a chat bridge. Events only arrive while the session is open, so for an always-on setup you run Claude in a background process or persistent terminal. Unlike integrations that spawn a fresh cloud session or wait to be polled, the event arrives in the session you already have open: see how channels compare. You install a channel as a plugin and configure it with your own credentials. Telegram, Discord, and iMessage are included in the research preview. When Claude replies through a channel, you see the inbound message in your terminal but not the reply text. The terminal shows the tool call and a confirmation (like “sent”), and the actual reply appears on the other platform. If you manage a Team, Enterprise, or Console organization, see Enable channels for your organization. To build your own channel, see the [Channels reference](</docs/en/channels-reference>). -## - -​ - -Supported channels +## Supported channels Each supported channel is a plugin that requires [Bun](<https://bun.sh>). For a hands-on demo of the plugin flow before connecting a real platform, try the fakechat quickstart. @@ -200,11 +196,7 @@ Handles are phone numbers in `+country` format or Apple ID emails like `user@example.com`. -## - -​ - -Quickstart +## Quickstart Fakechat is an officially supported demo channel that runs a chat UI on localhost, with nothing to authenticate and no external service to configure. Once you install and enable fakechat, you can type in the browser and the message arrives in your Claude Code session. Claude replies, and the reply shows up back in the browser. After you’ve tested the fakechat interface, try out [Telegram](<https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/telegram>), [Discord](<https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/discord>), or [iMessage](<https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/imessage>). To try the fakechat demo, you’ll need: @@ -251,11 +243,7 @@ If Claude hits a permission prompt while you’re away from the terminal, the session pauses until you respond. Channel servers that declare the [permission relay capability](</docs/en/channels-reference#relay-permission-prompts>) can forward these prompts to you so you can approve or deny remotely. For unattended use, [`--dangerously-skip-permissions`](</docs/en/permission-modes#skip-all-checks-with-bypasspermissions-mode>) bypasses most prompts, but only use it in environments you trust. Even then, the [actions no mode auto-approves](</docs/en/permission-modes#actions-no-mode-auto-approves>) still apply. When you run channels in non-interactive mode with `-p`, tools that need terminal input, such as multiple-choice questions and plan mode approval, are disabled so the session never stalls waiting for input. -## - -​ - -Security +## Security Every approved channel plugin maintains a sender allowlist: only IDs you’ve added can push messages, and everyone else is silently dropped. Telegram and Discord bootstrap the list by pairing: @@ -266,11 +254,7 @@ iMessage works differently: texting yourself bypasses the gate automatically, and you add other contacts by handle with `/imessage:access allow`. On top of that, you control which servers are enabled each session with `--channels`, and your organization controls availability with `channelsEnabled` on claude.ai Team and Enterprise plans and on Console organizations that deploy managed settings. Being in `.mcp.json` isn’t enough to push messages: a server also has to be named in `--channels`. The allowlist also gates [permission relay](</docs/en/channels-reference#relay-permission-prompts>) if the channel declares it. Anyone who can reply through the channel can approve or deny tool use in your session, so only allowlist senders you trust with that authority. -## - -​ - -Enterprise controls +## Enterprise controls Admins control availability through two [managed settings](</docs/en/settings>) that users cannot override. The default depends on how you authenticate: @@ -286,19 +270,11 @@ Pro, Max, and Ultra users without an organization skip these checks entirely: channels are available and users opt in per session with `--channels`. -### - -​ - -Enable channels for your organization +### Enable channels for your organization Enable channels for your organization from [**Organization settings > Claude Code > Channels**](<https://claude.ai/admin-settings/claude-code>), which requires the Owner role, or by setting `channelsEnabled` to `true` in managed settings. Once enabled, users in your organization can use `--channels` to opt channel servers into individual sessions. If the setting is disabled or unset, the MCP server still connects and its tools work, but channel messages won’t arrive. A startup warning tells the user to have an admin enable the setting. -### - -​ - -Restrict which channel plugins can run +### Restrict which channel plugins can run By default, any plugin on the Anthropic-maintained allowlist can register as a channel. Admins on Team and Enterprise plans can replace that allowlist with their own by setting `allowedChannelPlugins` in managed settings. Use this to restrict which official plugins are allowed, approve channels from your own internal marketplace, or both. Each entry names a plugin and the marketplace it comes from: @@ -313,19 +289,11 @@ If you set an empty array, you block all channel plugins from the allowlist, but `--dangerously-load-development-channels` can still bypass that block for local testing. To block channels entirely including the development flag, leave `channelsEnabled` unset instead. This setting requires `channelsEnabled: true`. If a user passes a plugin to `--channels` that isn’t on your list, Claude Code starts normally but the channel doesn’t register, and the startup notice explains that the plugin isn’t on the organization’s approved list. On the v2 MCP client runtime, a channel can also fail to register because Claude Code [doesn’t register a channel server that negotiates protocol revision 2026-07-28](</docs/en/mcp#push-messages-with-channels>). -## - -​ - -Research preview +## Research preview Channels are a research preview feature. Availability is rolling out gradually, and the `--channels` flag syntax and protocol contract may change based on feedback. Neither `--channels` nor `--dangerously-load-development-channels` appears in `claude --help` while the feature is in preview. The flags work even though they aren’t listed. During the preview, `--channels` only accepts plugins from an Anthropic-maintained allowlist, or from your organization’s allowlist if an admin has set `allowedChannelPlugins`. The channel plugins in [claude-plugins-official](<https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins>) are the default approved set. If you pass something that isn’t on the effective allowlist, Claude Code starts normally but the channel doesn’t register, and the startup notice tells you why. To test a channel you’re building, pass it to `--dangerously-load-development-channels` in the `plugin:<name>@<marketplace>` or `server:<name>` form. See [Test during the research preview](</docs/en/channels-reference#test-during-the-research-preview>) for information about testing custom channels that you build. Report issues or feedback on the [Claude Code GitHub repository](<https://github.com/anthropics/claude-code/issues>). -## - -​ - -How channels compare +## How channels compare Several Claude Code features connect to systems outside the terminal, each suited to a different kind of work: @@ -341,11 +309,7 @@ * **Chat bridge** : ask Claude something from your phone via Telegram, Discord, or iMessage, and the answer comes back in the same chat while the work runs on your machine against your real files. * **[Webhook receiver](</docs/en/channels-reference#example-build-a-webhook-receiver>)** : a webhook from CI, your error tracker, a deploy pipeline, or other external service arrives where Claude already has your files open and remembers what you were debugging. -## - -​ - -Next steps +## Next steps Once you have a channel running, explore these related features:
modified Channels reference View current →
Show diff (188 lines)
--- a/channels-reference.md +++ b/channels-reference.md @@ -13,22 +13,14 @@ To use an existing channel instead of building one, see [Channels](</docs/en/channels>). Telegram, Discord, iMessage, and fakechat are included in the research preview. -## - -​ - -Overview +## Overview A channel is an [MCP](<https://modelcontextprotocol.io>) server that runs on the same machine as Claude Code. Claude Code spawns it as a subprocess and communicates over stdio. Your channel server is the bridge between external systems and the Claude Code session: * **Chat platforms** (Telegram, Discord): your plugin runs locally and polls the platform’s API for new messages. When someone DMs your bot, the plugin receives the message and forwards it to Claude. No URL to expose. * **Webhooks** (CI, monitoring): your server listens on a local HTTP port. External systems POST to that port, and your server pushes the payload to Claude. -## - -​ - -What you need +## What you need The only hard requirement is the [`@modelcontextprotocol/sdk`](<https://www.npmjs.com/package/@modelcontextprotocol/sdk>) package and a Node.js-compatible runtime. [Bun](<https://bun.sh>), [Node](<https://nodejs.org>), and [Deno](<https://deno.com>) all work. The pre-built plugins in the research preview use Bun, but your channel doesn’t have to. Your server needs to: @@ -38,11 +30,7 @@ The Server options and Notification format sections cover each of these in detail. See Example: build a webhook receiver for a full walkthrough. During the research preview, custom channels aren’t on the [approved allowlist](</docs/en/channels#supported-channels>). Use `--dangerously-load-development-channels` to test locally. See Test during the research preview for details. -## - -​ - -Example: build a webhook receiver +## Example: build a webhook receiver This walkthrough builds a single-file server that listens for HTTP requests and forwards them into your Claude Code session. By the end, anything that can send an HTTP POST, like a CI pipeline, a monitoring alert, or a `curl` command, can push events to Claude. This example uses [Bun](<https://bun.sh>) as the runtime for its built-in HTTP server and TypeScript support. You can use [Node](<https://nodejs.org>) or [Deno](<https://deno.com>) instead; the only requirement is the [MCP SDK](<https://www.npmjs.com/package/@modelcontextprotocol/sdk>). @@ -147,11 +135,7 @@ The [fakechat server](<https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/fakechat>) extends this pattern with a web UI, file attachments, and a reply tool for two-way chat. -## - -​ - -Test during the research preview +## Test during the research preview During the research preview, every channel must be on the [approved allowlist](</docs/en/channels#research-preview>) to register. The development flag bypasses the allowlist for specific entries after a confirmation prompt. This example shows both entry types: @@ -165,11 +149,7 @@ This flag skips the allowlist only. The `channelsEnabled` organization policy still applies. Don’t use it to run channels from untrusted sources. -## - -​ - -Server options +## Server options A channel sets these options in the [`Server`](<https://modelcontextprotocol.io/docs/learn/server-concepts>) constructor. The `instructions` and `capabilities.tools` fields are [standard MCP](<https://modelcontextprotocol.io/docs/learn/server-concepts>); `capabilities.experimental['claude/channel']` and `capabilities.experimental['claude/channel/permission']` are the channel-specific additions: @@ -196,11 +176,7 @@ }, ) -## - -​ - -Notification format +## Notification format Your server emits `notifications/claude/channel` with two params: @@ -227,11 +203,7 @@ Claude Code doesn’t acknowledge notifications. The `await` on `mcp.notification()` resolves when the message is written to the transport, not when Claude has processed it. If the session hasn’t loaded your server as a channel, or the organization policy blocks it, Claude Code drops the events silently and returns no error to your server. If you need delivery confirmation, track event state in your server and expose a reply tool that Claude can call to report status back. Events queue into the session and are processed in order. If several notifications arrive while Claude is busy, they’re delivered together on the next turn and Claude handles them as a group. To process independent event streams concurrently, run separate sessions. -## - -​ - -Expose a reply tool +## Expose a reply tool If your channel is two-way, like a chat bridge rather than an alert forwarder, expose a standard [MCP tool](<https://modelcontextprotocol.io/docs/concepts/tools>) that Claude can call to send messages back. Nothing about the tool registration is channel-specific. A reply tool has three components: @@ -393,11 +365,7 @@ The [fakechat server](<https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/fakechat>) shows a more complete example with file attachments and message editing. -## - -​ - -Gate inbound messages +## Gate inbound messages An ungated channel is a prompt injection vector. Anyone who can reach your endpoint can put text in front of Claude. A channel listening to a chat platform or a public endpoint needs a real sender check before it emits anything. Check the sender against an allowlist before calling `mcp.notification()`. This example drops any message from a sender not in the set: @@ -411,19 +379,11 @@ Gate on the sender’s identity, not the chat or room identity: `message.from.id` in the example, not `message.chat.id`. In group chats, these differ, and gating on the room would let anyone in an allowlisted group inject messages into the session. The [Telegram](<https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/telegram>) and [Discord](<https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/discord>) channels gate on a sender allowlist the same way. They bootstrap the list by [pairing](</docs/en/channels#security>). See either implementation for the full pairing flow. The [iMessage](<https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/imessage>) channel takes a different approach: it detects the user’s own addresses from the Messages database at startup and lets them through automatically, with other senders added by handle. -## - -​ - -Relay permission prompts +## Relay permission prompts When Claude calls a tool that needs approval, the local terminal dialog opens and the session waits. A two-way channel can opt in to receive the same prompt in parallel and relay it to you on another device. Both stay live: you can answer in the terminal or on your phone, and Claude Code applies whichever answer arrives first and closes the other. Relay covers tool-use approvals like `Bash`, `Write`, and `Edit`. Project trust and MCP server consent dialogs don’t relay; those only appear in the local terminal. Claude Code v2.1.234 and later sends permission requests only to servers it registered as channels for the session, so relay sits behind the same [session opt-in and organization controls](</docs/en/channels#security>) as message delivery. Relay also requires you to opt the server in with `--channels` or the development flag, and requires the server to declare the permission capability. -### - -​ - -How relay works +### How relay works When a permission prompt opens, the relay loop has four steps: @@ -434,11 +394,7 @@ The local terminal dialog stays open through all of this. If someone at the terminal answers before the remote verdict arrives, that answer is applied instead and the pending remote request is dropped. -### - -​ - -Permission request fields +### Permission request fields The outbound notification from Claude Code is `notifications/claude/channel/permission_request`. Like the channel notification, the transport is standard MCP but the method and schema are Claude Code extensions. The `params` object has four string fields your server formats into the outgoing prompt: @@ -463,11 +419,7 @@ Masking doesn’t change who receives the fields. Whatever stays unmasked goes only to servers you opted in with `--channels` or the development flag. Treat both fields as untrusted unless you control the client fleet. The verdict your server sends back is `notifications/claude/channel/permission` with two fields: `request_id` echoing the ID above, and `behavior` set to `'allow'` or `'deny'`. Allow lets the tool call proceed; deny rejects it. Neither verdict affects future calls. -### - -​ - -Add relay to a chat bridge +### Add relay to a chat bridge Adding permission relay to a two-way channel takes three components: @@ -566,11 +518,7 @@ * **The ID is wrong** : your server emits a verdict, but Claude Code finds no open request with that ID and drops it silently. * **The ID was used by an earlier prompt** : your server emits a verdict with the ID from the request, but an earlier prompt in the session had the same ID. Once an ID repeats, Claude Code drops any channel verdict carrying it, so that a reply meant for one prompt can’t approve the other. An ID is five random letters, so a repeat is rare. Answer at the terminal instead. -### - -​ - -Full example +### Full example The assembled `webhook.ts` below combines all three extensions from this page: the reply tool, sender gating, and permission relay. If you’re starting here, you’ll also need the project setup and `.mcp.json` entry from the initial walkthrough. To make both directions testable from curl, the HTTP listener serves two paths: @@ -737,19 +685,11 @@ * **Outbound paths** : the `reply` tool handler is what Claude calls for conversational responses; the `PermissionRequestSchema` notification handler is what Claude Code calls when a permission dialog opens. Both call `send()` to broadcast over `/events`, but they’re triggered by different parts of the system. * **HTTP handler** : `GET /events` holds an SSE stream open so curl can watch outbound live; `POST` is inbound, gated on the `X-Sender` header. A `yes <id>` or `no <id>` body goes to Claude Code as a verdict notification and never reaches Claude; anything else is forwarded to Claude as a channel event. -## - -​ - -Package as a plugin +## Package as a plugin To make your channel installable and shareable, wrap it in a [plugin](</docs/en/plugins/overview>) and publish it to a [marketplace](</docs/en/plugins/overview>). Users install it with `/plugin install`, then enable it per session with `--channels plugin:<name>@<marketplace>`. A channel published to your own marketplace still needs `--dangerously-load-development-channels` to run, since it isn’t on the [approved allowlist](</docs/en/channels#supported-channels>). The default allowlist is the channel plugins in `claude-plugins-official`. The community marketplace is not on the channel allowlist. If you are working with an Anthropic partner contact, reach out to them to coordinate an official-marketplace listing. On Team and Enterprise plans, an admin can instead include your plugin in the organization’s own [`allowedChannelPlugins`](</docs/en/channels#restrict-which-channel-plugins-can-run>) list, which replaces the default Anthropic allowlist. -## - -​ - -See also +## See also * [Channels](</docs/en/channels>) to install and use Telegram, Discord, iMessage, or the fakechat demo, and to enable channels for a Team or Enterprise org * [Working channel implementations](<https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins>) for complete server code with pairing flows, reply tools, and file attachments
modified Checkpointing View current →
Show diff (155 lines)
--- a/checkpointing.md +++ b/checkpointing.md @@ -1,18 +1,10 @@ Claude Code automatically tracks Claude’s file edits as you work, allowing you to quickly undo changes and rewind to previous states if anything gets off track. -## - -​ - -How checkpoints work +## How checkpoints work As you work with Claude, checkpointing automatically captures the state of your code before each prompt you send that starts a turn. -### - -​ - -Automatic tracking +### Automatic tracking Claude Code tracks all changes made by its file editing tools: @@ -21,11 +13,7 @@ * Claude Code saves checkpoints with the conversation, so you can still run `/rewind` after you resume a session * Claude Code deletes a session’s file snapshots in the [retention sweep](</docs/en/claude-directory#cleaned-up-automatically>), by default about 30 days after the session last saved one. Rewinding to a checkpoint whose snapshots are gone can fail with [`No files were restored`](</docs/en/errors#no-files-were-restored>). To keep snapshots longer, set [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>). -### - -​ - -Rewind and summarize +### Rewind and summarize Run `/rewind`, or press `Esc` twice when the prompt input is empty, to open the rewind menu. @@ -42,37 +30,21 @@ The two code restore options appear only when the selected checkpoint has tracked file changes to revert. If no file edits were captured after that point, the menu offers only **Restore conversation** , the summarize options, and **Never mind**. After restoring the conversation or choosing Summarize from here, the original prompt from the selected message is restored into the input field so you can re-send or edit it. Choosing Summarize up to here leaves you at the end of the conversation with the input empty. With either summarize option, a **Summarized conversation** marker appears in the conversation where the compressed messages were. -#### - -​ - -Rewound messages can return if you exit before your next prompt +#### Rewound messages can return if you exit before your next prompt To remove the returned messages again, run `/rewind` in the session and select the same prompt, then **Restore conversation**. Before you exit, send Claude a prompt, because Claude Code saves the rewound conversation together with that prompt. Files you restored stay as the rewind left them. -#### - -​ - -Rewind past a cleared conversation +#### Rewind past a cleared conversation If you ran `/clear` earlier in the same Claude Code process, the rewind menu shows an additional entry at the top of the list labeled `/resume <session-id> (previous session)`. Select it to resume the conversation that was active before `/clear` ran. The entry is available until you exit Claude Code or resume a different session. -#### - -​ - -Guide a summary +#### Guide a summary Summarizing doesn’t change files on disk, and the original messages stay in the session transcript, so Claude can still reference the details. To guide what the summary focuses on, highlight a **Summarize** option with the arrow keys and type instructions where the row reads **add context (optional)** , then press `Enter`. Selecting the option with its number key summarizes immediately without instructions. Summarize keeps you in the same session and compresses context, like a targeted `/compact`. To branch off and try a different approach while preserving the original session intact, use [`/branch`](</docs/en/sessions#branch-a-session>) or `claude --continue --fork-session` instead. -## - -​ - -Common use cases +## Common use cases Checkpoints are particularly useful when: @@ -81,68 +53,36 @@ * **Iterating on features** : experiment with variations knowing you can revert to working states * **Freeing context space** : summarize a verbose debugging session from the midpoint forward, keeping your initial instructions intact -## +## Limitations -​ - -Limitations - -### - -​ - -Bash command changes not tracked +### Bash command changes not tracked Once Claude has edited a file with its file editing tools in your conversation, `/rewind` undoes changes that Bash commands make to that file afterward. A file that only Bash commands changed isn’t tracked and stays as it is. To revert it, use version control, such as Git. Under each prompt, the rewind menu counts changes to files Claude had already edited, whatever made them. A prompt where a shell command changed such a file lists file changes too. -### - -​ - -Subagent edits not restored +### Subagent edits not restored A [subagent](</docs/en/sub-agents>) makes edits with Claude’s file editing tools, but Claude Code usually doesn’t capture those edits in your session’s checkpoints. Whether rewinding restores them depends on how the subagent runs: * **Foreground forked skill** : a [skill with `context: fork`](</docs/en/skills#run-skills-in-a-subagent>) that runs in the foreground edits your working tree during your own turn, so rewinding restores its edits as usual. Set `background: false` to run a fork in the foreground; a few situations, [listed on the skills page](</docs/en/skills#run-skills-in-a-subagent>), run it there regardless of the setting. * **Any other subagent** : rewinding restores only the files Claude had already edited in your conversation. The subagent’s edits to other files stay, so use version control, such as Git, to revert them. This includes a forked skill that runs in the background, the default, and a background [`/code-review --fix`](</docs/en/code-review-local>) run. -### - -​ - -External changes not tracked +### External changes not tracked Checkpointing only tracks files that have been edited within the current session. Manual changes you make to files outside of Claude Code and edits from other concurrent sessions are normally not captured, unless they happen to modify the same files as the current session. -### - -​ - -Messages sent mid-turn not checkpointed +### Messages sent mid-turn not checkpointed In the rewind menu, a message you [typed while Claude was still working](</docs/en/interactive-mode#queue-messages-while-claude-works>) can be marked **No code restore**. The marked message has no checkpoint of its own. To undo the file edits Claude made after that message, select the prompt that started the turn and choose **Restore code** or **Restore code and conversation**. That reverts Claude’s file edits from the whole turn, including the ones from before your message arrived. -### - -​ - -Symlinked and hard-linked paths not restored +### Symlinked and hard-linked paths not restored Checkpointing doesn’t rewind symlinked or hard-linked files. When you pick **Restore code** or **Restore code and conversation** from the `/rewind` menu, Claude Code skips any tracked path that is a symlink or hard link and shows a `Restored the code, but skipped N files` warning. The skipped files keep their current contents. To undo the session’s changes to one of them, ask Claude to reverse the edit or edit the file yourself. Config files a dotfile manager symlinks into your project and files pnpm hard-links into place both fall into this category. To see which paths a restore skips, turn on debug logging with `/debug` before you restore: the debug log at `~/.claude/debug/<session-id>.txt` names each skipped path. For every skip reason and the recovery steps, see [the skipped-files entry in the error reference](</docs/en/errors#restored-the-code-but-skipped-files>). -### - -​ - -Not a replacement for version control +### Not a replacement for version control Checkpoints are designed for quick, session-level recovery. For permanent version history and collaboration, continue using version control, such as Git, for commits, branches, and long-term history. -## - -​ - -See also +## See also * [Interactive mode](</docs/en/interactive-mode>) \- Keyboard shortcuts and session controls * [Commands](</docs/en/commands>) \- Accessing checkpoints using `/rewind`
modified Use Claude Code with Chrome View current →
Show diff (339 lines)
--- a/chrome.md +++ b/chrome.md @@ -5,11 +5,7 @@ Chrome integration works with Google Chrome and Microsoft Edge. Claude Code also detects the extension and sets up the connection in other Chromium-based browsers, including Brave, Arc, Vivaldi, and Opera. Chrome integration isn’t supported in Windows Subsystem for Linux (WSL). -## - -​ - -Capabilities +## Capabilities With Chrome connected, you can chain browser actions with coding tasks in a single workflow: @@ -22,11 +18,7 @@ * **File uploads** : attach files from your machine to upload fields on web pages * **Session recording** : record browser interactions as GIFs to document or share what happened -## - -​ - -Prerequisites +## Prerequisites Before using Claude Code with Chrome, you need: @@ -39,11 +31,7 @@ Chrome integration is not available through third-party providers like Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry. If you access Claude exclusively through a third-party provider, you need a separate claude.ai account to use this feature. -## - -​ - -Get started in the CLI +## Get started in the CLI 1 @@ -68,11 +56,7 @@ Run `/chrome` at any time to check the connection status, manage permissions, reconnect the extension, or choose which connected browser to use. The integration is working when the status panel shows “Status: Enabled” and “Extension: Installed”. If more than one browser is connected, you choose which one Claude uses. When a browser action starts before you’ve chosen, Claude prompts you to pick one. To switch browsers later, run `/chrome` and select **Select browser…**. Claude keeps using your choice even when another browser connects. For VS Code, see [browser automation in VS Code](</docs/en/vs-code#automate-browser-tasks-with-chrome>). -### - -​ - -Install the extension when Claude asks +### Install the extension when Claude asks When Claude needs your browser in an interactive session and Claude Code doesn’t detect the extension, Claude Code shows an install prompt titled “Claude wants to use your browser”. Claude Code asks at most once per session. The prompt offers three choices: @@ -85,21 +69,13 @@ * If your organization blocks the `claude-in-chrome` MCP server with the [`deniedMcpServers` managed setting](</docs/en/managed-mcp#policy-based-control-with-allowlists-and-denylists>), Claude Code doesn’t show the install prompt. * If your organization deploys a [`managed-mcp.json`](</docs/en/managed-mcp#exclusive-control-with-managed-mcp-json>) file without [allowing Claude in Chrome alongside the managed set](</docs/en/managed-mcp#allow-claude-in-chrome-alongside-the-managed-set>), Claude Code doesn’t show the install prompt. -### - -​ - -Enable Chrome by default +### Enable Chrome by default To connect Chrome without passing `--chrome` each time, run `/chrome` in a CLI session and select **Enabled by default**. In the [VS Code extension](</docs/en/vs-code#automate-browser-tasks-with-chrome>), type `/chrome` in the prompt box and turn on the **Enabled by default** switch. The two share one setting, so turning it on in either place turns it on for both the CLI and VS Code. With the setting on and Claude Code v2.1.287 or later, each VS Code session connects to your browser as it starts, so Claude can use it before you type `@browser`. On earlier versions, or with the setting off, a VS Code session connects when you type `@browser`. Claude Code starts normally when Chrome isn’t running. Enabling Chrome by default increases context usage since the browser tools and their instructions are always loaded. If you notice increased context consumption, turn the setting off and connect only when needed, with `--chrome` in the CLI or by typing [`@browser`](</docs/en/vs-code#automate-browser-tasks-with-chrome>) in the VS Code prompt box. -### - -​ - -Answer the startup dialog +### Answer the startup dialog If the “Claude in Chrome extension detected” dialog appears when you start `claude`, your answer changes the **Enabled by default** setting: @@ -108,43 +84,23 @@ To change your answer for later sessions, run `/chrome`. -### - -​ - -Manage site permissions +### Manage site permissions Site-level permissions are inherited from the Chrome extension. Manage permissions in the Chrome extension settings to control which sites Claude can browse, click, and type on. In [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>), when the auto mode classifier itself approves a browser call to a site, the extension skips its own per-site check for that call, unless your permission rules deny any site to Claude in Chrome. -### - -​ - -Permission prompts in VS Code sessions +### Permission prompts in VS Code sessions 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. -### - -​ - -Browser tools in plan mode +### 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 or opens a new tab. 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. -## - -​ - -Example workflows +## Example workflows These examples show common ways to combine browser actions with coding tasks. Run `/mcp`, select `claude-in-chrome`, then select **View tools** to see the full list of available browser tools. -### - -​ - -Test a local web application +### Test a local web application When developing a web app, ask Claude to verify your changes work correctly: @@ -154,11 +110,7 @@ Claude navigates to your local server, interacts with the form, and reports what it observes. -### - -​ - -Debug with console logs +### Debug with console logs Claude can read console output to help diagnose problems. Tell Claude what patterns to look for rather than asking for all console output, since logs can be verbose: @@ -167,11 +119,7 @@ Claude reads the console messages and can filter for specific patterns or error types. -### - -​ - -Automate form filling +### Automate form filling Speed up repetitive data entry tasks: @@ -181,11 +129,7 @@ Claude reads your local file, navigates the web interface, and enters the data for each record. -### - -​ - -Upload files to web pages +### Upload files to web pages Claude can attach files from your machine to upload fields on a page. Claude Code reads the file and sends its contents to the browser, so uploads work in both local and remote sessions. This example attaches a log file to a form: @@ -199,11 +143,7 @@ * **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. -### - -​ - -Draft content in Google Docs +### Draft content in Google Docs Use Claude to write directly in your documents without API setup: @@ -212,11 +152,7 @@ Claude opens the document, clicks into the editor, and types the content. This works with any web app you’re logged into: Gmail, Notion, Sheets, and more. -### - -​ - -Extract data from web pages +### Extract data from web pages Pull structured information from websites: @@ -225,11 +161,7 @@ Claude navigates to the page, reads the content, and compiles the data into a structured format. -### - -​ - -Run multi-site workflows +### Run multi-site workflows Coordinate tasks across multiple websites: @@ -239,11 +171,7 @@ Claude works across tabs to gather information and complete the workflow. -### - -​ - -Record a demo GIF +### Record a demo GIF Create shareable recordings of browser interactions: @@ -252,11 +180,7 @@ Claude records the interaction sequence and saves it as a GIF file. The recording captures everything visible in the browser, including account details on logged-in pages, so review it before sharing it outside your team. -### - -​ - -Save screenshots to disk +### Save screenshots to disk Ask Claude to keep a screenshot as a file: @@ -264,17 +188,9 @@ Claude saves the image to disk and reports the file path. -## - -​ - -Troubleshooting - -### - -​ - -Extension not detected +## Troubleshooting + +### Extension not detected If Claude Code can’t detect the Chrome extension: @@ -298,11 +214,7 @@ Other Chromium-based browsers read the same file from their own configuration directory, named after the browser. For example, Brave on macOS uses `~/Library/Application Support/BraveSoftware/Brave-Browser/NativeMessagingHosts/`, and on Windows each browser has its own registry key, such as `HKCU\Software\BraveSoftware\Brave-Browser\NativeMessagingHosts\`. -### - -​ - -Project settings can’t turn on Chrome +### 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: @@ -314,11 +226,7 @@ * **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 +### Browser not responding If Claude’s browser commands stop working: @@ -326,19 +234,11 @@ 2. Ask Claude to create a new tab and try again 3. Restart the Chrome extension by disabling and re-enabling it in `chrome://extensions` -### - -​ - -Connection drops during long sessions +### 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”. 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 +### 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. @@ -346,11 +246,7 @@ To change the extension’s organization, log out in the extension’s settings, then log in and select the organization that `/status` shows. -### - -​ - -Windows-specific issues +### Windows-specific issues On Windows, you may encounter: @@ -358,11 +254,7 @@ * **Native messaging host errors** : if the native messaging host crashes on startup, try reinstalling Claude Code to regenerate the host configuration. * **Setup pages fail to open** : update Claude Code. Before v2.1.211, the browser tab prompting you to connect the extension could fail to open on Windows. -### - -​ - -Common error messages +### Common error messages These are the most frequently encountered errors and how to resolve them: @@ -374,11 +266,7 @@ ”Receiving end does not exist”| Extension service worker went idle| Run `/chrome` and select “Reconnect extension" "No browsers are connected”| Chrome isn’t open with the extension signed in to the same claude.ai account and organization as Claude Code, or Claude Code can’t reach `bridge.claudeusercontent.com`| Confirm Chrome is open and the extension is signed in to the same claude.ai account and organization as Claude Code. If so, check that your network lets Claude Code reach `bridge.claudeusercontent.com`, listed under [Network access requirements](</docs/en/network-config#network-access-requirements>) -## - -​ - -See also +## See also * [Computer use](</docs/en/computer-use>): control native macOS apps when a task can’t be done in a browser * [Use Claude Code in VS Code](</docs/en/vs-code#automate-browser-tasks-with-chrome>): browser automation in the VS Code extension
modified Claude apps gateway for Amazon Bedrock, Claude Platform on AWS, Google Cloud, and Microsoft Foundry View current →
Show diff (283 lines)
--- a/claude-apps-gateway.md +++ b/claude-apps-gateway.md @@ -9,11 +9,7 @@ Companion pages go deeper. The [configuration reference](</docs/en/claude-apps-gateway-config>) covers every option in the YAML file the quickstart writes, and the [deployment guide](</docs/en/claude-apps-gateway-deploy>) covers per-IdP setup, Kubernetes and Cloud Run deployment, and operations. -## - -​ - -Why Claude apps gateway +## Why Claude apps gateway The [gateway overview](</docs/en/gateways>) covers what a gateway does and why you’d run one. Claude apps gateway is Anthropic’s own gateway, built into the `claude` binary and tested alongside each Claude Code release, so it forwards the `anthropic-beta` values and request fields Claude Code sends without operators maintaining a separate allowlist. Once deployed it gives you: @@ -27,31 +23,19 @@ For which Claude Code features work through the gateway and what the server itself supports, see Availability and limitations below. For decisions such as cost, bypass, running multiple gateways, and serverless platforms, see the [deployment guide](</docs/en/claude-apps-gateway-deploy#deployment>). -### - -​ - -Other gateway implementations +### Other gateway implementations If you already run an LLM gateway or API gateway that meets your needs, keep using it; [Other LLM gateways](</docs/en/llm-gateway>) covers configuring Claude Code against it. The [gateway compatibility guide](</docs/en/llm-gateway-protocol>) documents what Claude Code expects from any gateway: the endpoints it calls, the headers and body fields to forward, and what stops working when they’re stripped. A running Claude apps gateway also serves its own protocol reference at `GET /protocol`, which describes the endpoints it exposes to Claude Code clients: SSO sign-in, inference, managed settings delivery, model discovery, and telemetry. Fetch it with `curl https://claude-gateway.internal.example.com/protocol` from any deployed gateway, such as the one the quickstart below produces. Breaking changes to the protocol are announced in advance, but indefinite backwards compatibility isn’t guaranteed. A gateway sign-in token identifies the developer who approved the sign-in, not the program that uses it. Claude Code signs in without a client ID or secret of its own, so a gateway has no way to verify which program is signing in. Any client can set `User-Agent` and other request fields, so use them for routing or metrics, not as proof that a request comes from Claude Code. -## - -​ - -Quickstart +## Quickstart This quickstart walks the minimal path: register an OAuth client in your IdP, write a `gateway.yaml`, run the gateway alongside Postgres with Docker Compose, and verify sign-in end to end. It uses an Amazon Bedrock upstream; Claude Platform on AWS, Google Cloud’s Agent Platform, Microsoft Foundry, and the Anthropic API are equally supported by swapping the `upstreams` block as shown in the [configuration reference](</docs/en/claude-apps-gateway-config#upstreams>). At the end you have a gateway a developer can `/login` to. **Deploy on your private network.** Claude Code only connects to a gateway whose address is private. This is a security guard, because a trusted gateway can push settings that run commands on developer machines. Put the gateway behind an internal load balancer or VPN and give it a hostname that resolves to private IPs only. If your internal network is numbered from public IPv4 space your organization owns, see Allow a gateway on public address space you own. -### - -​ - -Prerequisites +### Prerequisites Have these in place before you start: @@ -62,14 +46,12 @@ PostgreSQL 11 or later| Backs the device sign-in flow and rate-limit counters. A managed PostgreSQL service works, including the smallest tier; see [which databases are supported](</docs/en/claude-apps-gateway-deploy#postgres>). With [spend limits](</docs/en/claude-apps-gateway-spend-limits>), it also holds durable spend, audit, and identity tables that should be backed up. TLS via `?sslmode=require` is recommended. PostgreSQL 11, 12, and 13 require Claude Code v2.1.290 or later on the gateway server. The PostgreSQL project no longer maintains those versions, so use a newer one where you can. Model upstream| Amazon Bedrock credentials, Claude Platform on AWS credentials, Google Cloud credentials, a Microsoft Foundry resource, or an Anthropic API key. Multiple upstreams are supported with failover. HTTPS| The gateway must be reachable over `https://` from developer laptops and from any browser used for sign-in; the gateway serves the device-verification page on the same listener. Either provide a TLS cert via `listen.tls` or run behind a TLS-terminating ingress, and set `listen.public_url` to the external origin in both cases. At `/login`, Claude Code accepts a plain `http://` origin only when the gateway host is loopback: `localhost`, `127.0.0.1`, or `::1`. -Private-network address| At `/login`, Claude Code requires the gateway’s hostname or IP address to resolve only to private addresses: RFC 1918, link-local, CGNAT `100.64.0.0/10`, IPv6 ULA `fc00::/7`, or loopback. For a gateway you host, any public address outside a block you declare is rejected; see the [threat model](</docs/en/claude-apps-gateway-deploy#threat-model-summary>) in the deployment guide. If developer machines route HTTPS through a corporate proxy, sign-in also requires the proxy host to resolve to private addresses; if it doesn’t, add the gateway host to `NO_PROXY` so the CLI connects directly. If your internal network is numbered from public IPv4 space your organization owns, declare those blocks so `/login` accepts a gateway there. +Private-network address| Claude Code’s `/login` requires the gateway’s hostname or IP address to resolve only to private addresses: RFC 1918 and link-local ranges, CGNAT `100.64.0.0/10`, IPv6 ULA `fc00::/7` and loopback. See the [threat model](</docs/en/claude-apps-gateway-deploy#threat-model-summary>). If your internal network is numbered from public IPv4 space your organization owns, declare those blocks so `/login` accepts a gateway there. Linux runtime| The gateway server runs only on the native Linux binary. macOS works for local development. Windows isn’t supported as a server platform. -### - -​ - -Steps +When `HTTPS_PROXY` or `HTTP_PROXY` applies to the gateway host, sign-in also needs either a proxy whose hostname resolves to private addresses or the gateway host in `NO_PROXY` on developer machines. If those machines also set `no_proxy`, add the gateway host there too, or model requests still go through the proxy. + +### Steps 1 @@ -221,11 +203,7 @@ 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. -## - -​ - -Connect developers +## Connect developers Developers connect from their own laptops with one browser sign-in, using their corporate work account. They don’t need a claude.ai account, an API key, or a subscription, because requests to the model go through the gateway using the organization’s upstream credential. Connection is driven by the [client-side managed settings](</docs/en/claude-apps-gateway-config#client-side-managed-settings>) you push via MDM, and this section covers what the admin configures. The CLI fingerprints the gateway’s TLS leaf certificate on first connect and pins it per hostname. It checks that pin again during sign-in, on silent session refreshes, and on managed-settings fetches, while inference requests use standard TLS validation without the pin. Requests routed through an HTTPS proxy skip the pin check, so add the gateway host to `NO_PROXY` to keep them direct. Publish the expected SHA-256 fingerprint alongside the gateway URL so developers have something to compare against. The `/login` prompt shows the first 16 characters of the fingerprint as lowercase hexadecimal with no colons. To print the full fingerprint in that form from the certificate file, run: @@ -233,11 +211,7 @@ When the certificate rotates, every developer sees the trust prompt again, so treat rotations as a planned event and republish the fingerprint. If your gateway policy includes [settings that need approval](</docs/en/server-managed-settings#security-approval-dialogs>), the developer also sees that approval dialog again after accepting the new certificate, because Claude Code keys [approval memory](</docs/en/server-managed-settings#approval-memory>) to the pinned certificate. A gateway can return the optional `email` field in its token response to name the account that a sign-in used. When it does, the developer confirms the account before Claude Code saves the credential. After a confirmed sign-in, `/status` shows the account. The confirmation requires Claude Code v2.1.275 or later on the developer machine; a client below that version ignores the field. The gateway server in the `claude` binary doesn’t return the field, so its sign-ins complete without the confirmation. Once the developer signs in, the [model picker](</docs/en/model-config>) shows the models in their `availableModels` allowlist. Managed settings apply at startup and refresh hourly, and telemetry routes to your collector. Sessions refresh silently before `ttl_hours` expiry. When a refresh fails after IdP deprovisioning, Claude Code prompts the developer to log in again. -### - -​ - -Set the gateway URL +### Set the gateway URL Three keys go in the per-OS [managed settings file](</docs/en/managed-settings#delivery-mechanisms>) you deploy via MDM or directly on disk. For a machine with no managed settings, see Set the gateway URL in user settings instead. `forceLoginMethod` and `forceLoginGatewayUrl` open `/login` directly on the **Cloud gateway** screen with the URL filled in, and `parentSettingsBehavior: "merge"` lets Claude Desktop deliver the gateway’s egress allowlist to the Claude Code sessions it launches, explained in Deliver policy to Claude Desktop sessions: @@ -249,11 +223,7 @@ The developer presses Enter to connect. The first-connect TLS fingerprint prompt still appears. Once the file is on a machine, a developer who hasn’t completed the gateway sign-in sees one of the messages described under [Administrator policy requires a Cloud gateway sign-in](</docs/en/errors#administrator-policy-requires-a-cloud-gateway-sign-in>). Developers who select a cloud provider through an environment variable such as `CLAUDE_CODE_USE_BEDROCK` don’t need the gateway sign-in. The login picker has no gateway option, and in managed settings `forceLoginMethod` alone, without a URL, leaves the developer at a “Contact your IT administrator” message. The login keys belong in the file you push to machines, not in the gateway’s `managed.policies[].cli` block, which only reaches clients that are already connected. -#### - -​ - -Set the gateway URL in user settings +#### Set the gateway URL in user settings On machines with no managed settings, have each developer add `forceLoginMethod` and `forceLoginGatewayUrl` to their own user settings file, `~/.claude/settings.json`. This requires Claude Code v2.1.295 or later on the developer machine. This example names a gateway at `claude-gateway.internal.example.com`: @@ -267,11 +237,7 @@ * **User settings only** : Claude Code reads the two keys from `~/.claude/settings.json`, not from a project’s `.claude/settings.json` or `.claude/settings.local.json`. * **Managed settings turn them off** : once an administrator’s settings reach the machine through a managed settings file, a macOS plist or Windows HKLM policy, or a [policy helper](</docs/en/settings-reference#policyhelper>), Claude Code ignores a gateway named in user settings. -### - -​ - -Allow a gateway on public address space you own +### Allow a gateway on public address space you own Some organizations number their internal network from a public IPv4 block they own, such as a carrier’s own address space or a legacy `/8`, so their gateway has no private address. List those blocks in the `gatewayInternalNetworks` managed setting. `/login` then accepts a gateway inside a listed block when the developer’s machine connects to it from an address inside the same block. This requires Claude Code v2.1.268 or later on the developer machine; earlier versions ignore the key and apply the private-address rule. @@ -298,27 +264,15 @@ When all three pass, the trust prompt adds a line naming the machine’s address, the gateway’s address, and the declared block that contains both. The key changes nothing for other gateways: sign-in to one on a private address works as before, and sign-in to one on a public address outside every listed block is refused as before. A declared block narrows who can sign in but doesn’t prove where a machine is, so declare only address space your organization controls. A block shared with other tenants, such as a cloud provider’s public range, lets anyone in it pass the same check. -### - -​ - -Deliver policy to Claude Desktop sessions +### Deliver policy to Claude Desktop sessions Claude Desktop runs its tabs 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`. That configuration holds 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"`. -#### - -​ - -Which machines need the opt-in +#### Which machines need the opt-in Machines that only run Claude Desktop need it. Claude Desktop applies the model list and the disabled-tools list to embedded sessions itself, but the egress allowlist reaches them only as parent settings, in the form of `WebFetch` domain rules and sandbox network rules. Without the opt-in, those sessions run without the egress restriction, and nothing warns you. The gateway still rejects inference requests for models the policy doesn’t grant. A plugin marketplace allowlist also reaches embedded sessions only as parent settings. When you turn user-added plugin marketplaces off in Claude Desktop’s managed configuration, Claude Desktop 2.16120.0 or later hides marketplaces your organization didn’t provision and refuses installs from them. To stop embedded sessions from loading plugins already installed from those marketplaces, it sends them a `strictKnownMarketplaces` list as parent settings. Without the opt-in, Claude Code ignores that list, and those plugins keep loading. Machines where developers sign in through `/login` don’t need it; each Claude Code session fetches its policy from the gateway. Fleets whose [`policyHelper`](</docs/en/settings-reference#policyhelper>) supplies managed settings can’t use it: Claude Code never merges parent settings on those fleets, because it reads managed settings from the helper’s output alone. -#### - -​ - -Set the opt-in +#### Set the opt-in Deploy the managed settings snippet from Set the gateway URL, mirror it to any client-side source that outranks the file, then verify. @@ -340,11 +294,7 @@ 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. -### - -​ - -Restrict parent settings +### Restrict parent settings Once you deploy `parentSettingsBehavior: "merge"`, any host process that launches Claude Code can supply parent settings, not only Claude Desktop but also an Agent SDK application or an IDE extension. Claude Code filters parent settings against an allowlist of restrictive keys, but some allowed keys can grant access rather than restrict it. Unless you set the `allowManaged*Only` locks, permission allow rules and sandbox allowlists supplied by the host still apply. Your policy’s deny and ask rules stay in force either way; [they’re evaluated before any allow rule](</docs/en/permissions#manage-permissions>). Claude Code forwards parent-supplied [`sandbox.credentials`](</docs/en/settings-reference#sandbox-credentials>) entries in stripped form: @@ -353,11 +303,7 @@ * **`envVars` entries with `mode: mask`**: not forwarded. `deny` is the only restriction the parent channel can express through `envVars` entries. * **[`awsPairs` and `sigv4`](</docs/en/sandboxing#re-sign-aws-requests>)**: forwarded restriction-only. From `sigv4`, only `deny` values are kept, and a parent that defines a `sigv4` block at all pins all three request forms, `streaming`, `presigned`, and `sigv4a`, to `deny`. An `awsPairs` pair is never forwarded in a form that can re-sign; a pair that names one of the conventional AWS variables is replaced by an inert entry that keeps the automatic pairing of `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_SESSION_TOKEN` suppressed. -#### - -​ - -Deploy the locks +#### Deploy the locks To keep parent settings as close to restriction-only as the filter supports, add all five `allowManaged*Only` locks, and the allowlists they govern, to the same sources as the merge opt-in: @@ -384,11 +330,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` 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. -#### - -​ - -Lock behavior across sources +#### Lock behavior across sources Setting one lock doesn’t restrict the others; each key is documented in the [settings reference](</docs/en/settings-reference#all-settings>). From an admin source below the winner, the two sandbox locks still apply, and `allowManagedPermissionRulesOnly` still blocks parent-supplied allow rules and `additionalDirectories`. On Claude Code v2.1.273 or later, the MCP server lock also applies from a source below the winner, and while it is on, the managed `allowedMcpServers` list comes from the highest-priority admin source that sets one. The hooks lock and `allowManagedPermissionRulesOnly`’s effect on the developer’s own rules need the winning source by default; under the `managedSourcesBehavior` merge opt-in in [how Claude Code combines managed sources](</docs/en/managed-settings#how-claude-code-combines-managed-sources>), Claude Code applies the strictest value any source sets for every lock. On [`policyHelper`](</docs/en/settings-reference#policyhelper>) fleets, Claude Code reads the locks from the helper’s output alone. Each lock makes Claude Code ignore the developer’s own entries for that setting, so include your organization’s allowlists next to the locks: @@ -396,11 +338,7 @@ * **MCP servers** : locking with no `allowedMcpServers` in any admin source or in the parent-supplied settings loads every server that `deniedMcpServers` doesn’t block. * **Read paths** : `allowRead` entries only re-allow paths inside `denyRead` regions, so pair them with a managed `denyRead`. -#### - -​ - -Settings the locks don’t cover +#### Settings the locks don’t cover These parent-supplied settings pass the filter even with all five locks set: @@ -414,11 +352,7 @@ If you set `managedSourcesBehavior` to `"merge"`, check [which source’s value applies for each kind of key](</docs/en/managed-settings#compose-every-managed-source>). -#### - -​ - -How hook and skill keys in parent settings take effect +#### How hook and skill keys in parent settings take effect Keys your application passes in the Agent SDK’s [`managedSettings`](</docs/en/agent-sdk/typescript#options>) option are parent settings. On a machine where an administrator deploys managed settings, Claude Code ignores parent settings unless the administrator [lets an embedding host add policy](</docs/en/managed-settings#let-an-embedding-host-add-policy>). If you pass [`disableAllHooks: true`](</docs/en/settings-reference#disableallhooks>) in `managedSettings`: @@ -434,27 +368,15 @@ Passing these keys in `managedSettings` requires Claude Code v2.1.309 or later, or TypeScript Agent SDK v0.3.309 or later. -### - -​ - -Connect Claude Desktop +### Connect Claude Desktop [Claude Desktop](</docs/en/desktop>) connects to the same gateway through a different MDM key: set `bootstrapUrl` in Claude Desktop’s [managed configuration](<https://claude.com/docs/third-party/claude-desktop/configuration>) to `<listen.public_url>/user/bootstrap`, and opt the user’s policy in with a `desktop` key. [Claude Desktop overlay](</docs/en/claude-apps-gateway-config#claude-desktop-overlay>) covers both halves. Requires Claude Code v2.1.203 or later on the gateway server. Once connected, Claude Desktop sends model requests from every enabled tab through the gateway. Claude Desktop signs the developer in through the gateway’s identity provider with the same browser SSO step, then fetches its configuration from the gateway instead of from Anthropic. Model access and policy follow the same per-group rules as the CLI. A developer who uses both the CLI and Claude Desktop signs in to each separately; the gateway session isn’t shared between them. -### - -​ - -CI pipelines and remote machines +### CI pipelines and remote machines There is no service-token flow for unattended pipelines. Gateway sign-in always runs the browser device flow, so a CI job with no developer to approve the sign-in can’t authenticate; configure those against your provider directly. Deploy `forceLoginMethod` and `forceLoginGatewayUrl` to developer machines and leave them off CI runners. On a machine whose managed settings set them, a session that authenticates with `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, or `apiKeyHelper` [exits at startup](</docs/en/errors#administrator-policy-requires-a-cloud-gateway-sign-in>). Once a developer has signed in, each Claude Code session on that machine uses the gateway session, including non-interactive `claude -p` runs and sessions started by the Agent SDK. Claude Code applies the [gateway policy](</docs/en/claude-apps-gateway-config#managed>) to each of them. The device flow separates the polling CLI from the approving browser, so a remote development box with no display still works: the developer runs `/login` over SSH on the remote machine and opens the verification link in the browser on their laptop. -### - -​ - -What’s enforced on developers +### What’s enforced on developers These guarantees apply to every session signed in through `/login`. The embedded sessions Claude Desktop launches get their policy as described in Deliver policy to Claude Desktop sessions, and the telemetry bullet says where their exports go. @@ -472,19 +394,11 @@ * When the gateway’s discovery document advertises a `revocation_endpoint` on the gateway URL’s own scheme, host, and port, `/logout` also sends the stored tokens to that endpoint so the gateway can end the session on its side. The request is best effort, so sign-out completes on the developer’s machine whether or not the endpoint answers. The revocation requires Claude Code v2.1.275 or later on the developer’s machine. * The gateway server in the `claude` binary advertises none, so a sign-out from it ends the session on the developer’s machine only. To force sessions out server-side, see [JWT secret rotation](</docs/en/claude-apps-gateway-deploy#jwt-secret-rotation>). -### - -​ - -What the organization can see +### What the organization can see Usage telemetry carries the developer’s identity, token counts, model, and latency to the organization’s collector. The gateway doesn’t log or store prompt or completion content. Whether richer telemetry such as logs and traces is collected, which can include commands and file paths, is the organization’s [per-destination choice](</docs/en/claude-apps-gateway-config#telemetry>). -## - -​ - -Availability and limitations +## Availability and limitations The table covers which Claude Code features work when developers connect through the gateway, and what the gateway server itself supports. Where something isn’t supported, the Notes column gives the alternative. The gateway delivers the [`anthropic-beta`](<https://platform.claude.com/docs/en/api/beta-headers>) values the CLI sends to every upstream, so operators don’t maintain a beta allowlist. For Amazon Bedrock, which ignores the header, the gateway moves the values into the request body’s `anthropic_beta` field; the other upstreams receive the header as sent. @@ -512,11 +426,7 @@ Helm chart| Not available| The gateway runs as a standard stateless Deployment; see the [deployment guide](</docs/en/claude-apps-gateway-deploy#kubernetes>) Admin UI| Spend limits only| In Claude Desktop 4.23118.0 or later connected to the gateway, members of [`admin.admin_groups`](</docs/en/claude-apps-gateway-config#admin>) can manage spend limits. Other configuration is the YAML file; redeploy to change it -## - -​ - -Next steps +## Next steps The quickstart leaves you with a minimal config running under Docker Compose. To take it further:
modified Claude apps gateway configuration View current →
Show diff (706 lines)
--- a/claude-apps-gateway-config.md +++ b/claude-apps-gateway-config.md @@ -1,10 +1,6 @@ A Claude apps gateway deployment is configured by one YAML file, conventionally `gateway.yaml`. The file defines everything the gateway does: where it listens, how developers sign in, where inference goes, and which policies and telemetry apply. This page is the reference for every option in that file. To write your first one, start from the [quickstart](</docs/en/claude-apps-gateway#quickstart>), which builds a minimal working config and runs it. Once you have a config you’re happy with, the [deployment guide](</docs/en/claude-apps-gateway-deploy>) covers containerizing and hosting it on Kubernetes, Cloud Run, or your own platform. The gateway reads the file once, at startup, with `claude gateway --config /path/to/gateway.yaml`. Every option is validated against a schema at boot, so a malformed config fails at start with a field-level error rather than at first use. The complete example at the end of this page exercises every section. -## - -​ - -File structure +## File structure Five sections are required. Every other section is optional, and an omitted section takes its defaults. Unknown keys fail boot, so a typo surfaces as a named error rather than a silently ignored setting. **Required sections:** @@ -26,11 +22,7 @@ * `access_control`, `limits`, `timeouts`, `rate_limits`: IP allow/deny, request size caps, upstream time-to-first-byte, and per-IP sign-in limits * `load_test_mode`: load testing the gateway without calling a model provider -## - -​ - -Secret expansion +## Secret expansion Don’t write secrets such as `client_secret`, `jwt_secret`, or `postgres_url` directly in `gateway.yaml`. Reference them with one of the forms below, and the gateway resolves the value at boot from an environment variable or a file: @@ -39,17 +31,9 @@ `${VAR}`| The environment variable `VAR`. Boot fails if undefined.| Container environment variables, AWS Secrets Manager via env injection `${file:/path}`| Contents of the file at that absolute path, trimmed. The reference must be the field’s entire value: unlike `${VAR}`, it isn’t expanded inside a longer string, so for a database password set `store.password` rather than embedding it in `postgres_url`.| Kubernetes Secret volume mounts, Vault Agent, SOPS -## - -​ - -Required sections - -### - -​ - -`listen` +## Required sections + +### `listen` The `listen` block controls where the gateway serves: the bind address and port, the externally visible origin, and optional TLS termination. @@ -63,11 +47,7 @@ List a frontend in `trusted_proxies` only if the last `X-Forwarded-For` entry that it passes on is one that no developer wrote. List no address or range that developers connect from. A frontend that appends the address of each connection it receives qualifies. One that passes the header on as developers send it doesn’t. `X-Forwarded-For` entries written as `ipv4:port` or `[ipv6]:port`, as some load balancers do, are read with the port dropped. An IPv6 address with a port appended and no brackets may be read as a different address or not read at all. Turn off the port option on any proxy that writes that form. -### - -​ - -`oidc` +### `oidc` The `oidc` block connects the gateway to your identity provider and decides who can sign in. It names the issuer and OAuth client, maps the claims that carry email and groups, and restricts sign-in by email domain or group. OpenID Connect (OIDC) is the SSO protocol the gateway uses with your identity provider; see [Identity provider setup](</docs/en/claude-apps-gateway-deploy#identity-provider-setup>) for what to register on the IdP side. @@ -96,11 +76,7 @@ `form_action_origins`| No| Additional origins for the `/device` page’s `Content-Security-Policy: form-action` directive. The gateway already allows `'self'` and the discovered `authorization_endpoint` origin, but Chrome enforces `form-action` against the entire redirect chain. If your IdP redirects through a second host, such as Azure AD federated to ADFS, hub-spoke Okta, or a corporate SSO interceptor, list every origin the authorization request may redirect through. `ca_cert_pem`| No| The PEM-encoded CA certificate itself, not a path to a file. It replaces the system trust store for IdP requests only. To load a mounted file, write `${file:/etc/gateway/idp-ca.pem}`. Use for Keycloak or Dex behind corporate PKI. -#### - -​ - -Certificate client authentication +#### Certificate client authentication If your identity provider authenticates OAuth clients with a certificate instead of a client secret, as Microsoft Entra does with certificate credentials, set `token_endpoint_auth_method: private_key_jwt`. Requires Claude Code v2.1.284 or later on the gateway server. With this configuration the gateway sends no secret. It authenticates to the IdP’s token endpoint with a short-lived JWT signed with the certificate’s private key when a developer signs in and each time the gateway refreshes their session. The JWT is signed with RS256 and identifies the certificate by `x5t` and `x5t#S256` thumbprint headers rather than a `kid`. Your IdP must be able to find the registered certificate by thumbprint. @@ -146,11 +122,7 @@ Compare the SHA-1 thumbprint with the one the IdP shows for the certificate you uploaded. If the certificate has expired or isn’t valid yet, the gateway still starts but logs a warning that sign-ins and refreshes will fail until you replace it. To confirm that the IdP accepts the certificate, have one developer sign in through the gateway. -#### - -​ - -Rotate the client certificate +#### Rotate the client certificate The gateway reads the key and certificate once at boot, so a changed file takes effect only after a restart. Rotate in this order so that no token request presents a certificate the IdP doesn’t have: @@ -158,19 +130,11 @@ 2. Replace the key and certificate files that `gateway.yaml` loads, then restart the gateway. If you run several replicas, a [rolling restart](</docs/en/claude-apps-gateway-deploy#upgrades>) works, because the IdP has both certificates until you remove the old one. 3. After every replica has restarted, remove the old certificate from the IdP. -#### - -​ - -IdP requests through a forward proxy +#### IdP requests through a forward proxy The inference upstreams honor `HTTPS_PROXY` and `HTTP_PROXY` on every version. The gateway’s own requests to the IdP, discovery, JWKS, token, and userinfo, go direct unless you set `oidc.use_proxy: true`, which requires v2.1.227 or later. When a proxy variable is set, `use_proxy` is unset, and the issuer isn’t covered by `NO_PROXY`, the gateway keeps those requests direct and logs a notice at boot asking you to choose; `use_proxy: false` keeps them direct and silences the notice. With `use_proxy: true`, the pod resolves each IdP endpoint’s hostname itself and asks the proxy to `CONNECT` to the resolved IP address, so the proxy must accept `CONNECT` to the IP address of every host the discovery document names, not only the issuer. Use an `http://` proxy URL. `ca_cert_pem` and the [SSRF guard](</docs/en/claude-apps-gateway-deploy#threat-model-summary>) apply on the proxied path as well. Proxy-only egress changes both of these: while it’s active, IdP requests follow the proxy unless you set `use_proxy: false`, and the gateway hands the proxy each IdP hostname without resolving it first. -#### - -​ - -Proxy-only egress +#### Proxy-only egress Set `CLAUDE_GATEWAY_PROXY_IS_EGRESS_BOUNDARY=1` in the gateway’s environment, next to `HTTPS_PROXY`, when the pod reaches other hosts only through that forward proxy and can’t resolve public DNS names itself, or when the proxy refuses `CONNECT` to an IP address. Requires v2.1.277 or later. It’s an environment variable rather than a `gateway.yaml` key so that nothing in the config file can relax the gateway’s address check. @@ -197,11 +161,7 @@ Turn this on only when the proxy’s allowlist is at least as strict as the gateway’s own check. The proxy must refuse cloud metadata endpoints such as `169.254.169.254` and `metadata.google.internal`, link-local addresses, and the proxy host’s own loopback, and it must refuse them by the address a name resolves to, not only by name, because the gateway no longer catches a hostname that resolves to one of them. A proxy that connects anywhere it’s asked removes the gateway’s [SSRF guard](</docs/en/claude-apps-gateway-deploy#threat-model-summary>) for these requests. -### - -​ - -`session` +### `session` The `session` block shapes the bearer tokens the gateway mints after sign-in: the secret that signs them and how long they live. @@ -210,11 +170,7 @@ `jwt_secret`| Yes| At least 32 bytes of entropy, for example from `openssl rand -base64 32`. Signs the gateway’s HS256 bearer tokens. Accepts a single string or an array for rotation: index 0 signs and all entries verify. To rotate, prepend a new secret, wait `ttl_hours`, then drop the old one. `ttl_hours`| No| Gateway bearer token lifetime. Default `1`. The CLI silently refreshes before expiry when the IdP issues refresh tokens. A shorter lifetime deprovisions faster; a longer one makes fewer IdP round-trips. If your IdP can’t issue refresh tokens because `offline_access` is unavailable, there is no silent refresh, so raise this to `8` or `12` to avoid sending developers back to the browser login every hour. -### - -​ - -`store` +### `store` The `store` block points the gateway at its PostgreSQL database, which holds device grants and rate-limit counters. @@ -229,19 +185,11 @@ For local development, point `postgres_url` at a throwaway Postgres container, for example `docker run --rm -p 5432:5432 -e POSTGRES_HOST_AUTH_METHOD=trust postgres`. -### - -​ - -`upstreams` +### `upstreams` `upstreams` is an ordered list. The gateway forwards inference to the first upstream that resolves the requested model, passing over any upstream whose `groups` list leaves the developer out. On `5xx`, `429`, `401`, `403`, `404`, or timeout the gateway fails over to the next upstream; other `4xx` doesn’t, because those errors are attributable to the request rather than the upstream. A `401` or `403` means the upstream rejected the credential the gateway used, or denied it access, for example to the requested model. A `404` means that upstream doesn’t serve the requested model, so a later upstream in the list still can. If you set `forward_user_identity: true` on an upstream, a `429` it returns to a request that carried the developer’s email doesn’t fail over. See how a per-user limit denial reaches the developer. Failover on `404` requires gateway v2.1.198 or later. Earlier releases returned the first `404` to the client even when a later upstream in the list served the model. Multiple upstreams of the same provider must set a distinct `name:`. Amazon Bedrock, Claude Platform on AWS, Google Cloud’s Agent Platform, and Microsoft Foundry clients are built once at startup, and their SDKs refresh credentials internally, so rotating cloud credentials doesn’t require a restart. Static Anthropic API keys and bearers are read at startup; see Anthropic API. -#### - -​ - -Upstream error messages +#### Upstream error messages The gateway returns one upstream’s error response, or its own `502`, depending on how the upstreams answered: @@ -256,11 +204,7 @@ For example, the gateway replaces Amazon Bedrock’s `Input is too long for requested model.` with `capability_rejected: prompt_too_long`. Claude Code [compacts automatically](</docs/en/errors#prompt-is-too-long>) on that token, as it does on `prompt is too long`. Keeping a cloud upstream’s `400` or `413` message, or replacing it with a `capability_rejected:` token, requires gateway v2.1.233 or later. -#### - -​ - -Anthropic API +#### Anthropic API The minimal Anthropic upstream is an API key from the [Claude Console](<https://platform.claude.com>): @@ -311,11 +255,7 @@ If you set `forward_user_identity` on an Amazon Bedrock upstream, the gateway exits at startup with `Unrecognized key(s) in object: 'forward_user_identity'`. If your proxy sits in front of Bedrock, list it as a `provider: anthropic` upstream instead. The gateway sends that upstream the Anthropic Messages format, so your proxy has to [translate requests for Bedrock](</docs/en/llm-gateway-protocol#format-mismatch-with-the-upstream>). To name each developer to AWS instead, see Per-developer AWS cost attribution. -#### - -​ - -Amazon Bedrock +#### Amazon Bedrock For the client-side Amazon Bedrock deployment that the gateway replaces or fronts, see [Claude Code on Amazon Bedrock](</docs/en/amazon-bedrock>). The gateway-side upstream: @@ -489,11 +429,7 @@ `session_name` selects which verified claim becomes the AWS `RoleSessionName`: `email` or `sub`. The gateway writes any character other than ASCII letters, digits, and `_+,.@-` as `=XX` hex per UTF-8 byte, and shortens a result longer than 64 characters to a prefix plus a hash, so each developer’s session name stays valid and unique. A request from a developer whose token lacks the claim isn’t sent through this upstream, and the operator log says to switch to `sub` or set `oidc.email_claim`. An active developer costs one STS call per hour per gateway replica, and concurrent first requests share one call. The gateway also makes one call of its own on this role: the token count for a request the client abandoned, so that [spend limits](</docs/en/claude-apps-gateway-spend-limits>) stay accurate. That count and its one-token fallback request are signed by the shared `claude-apps-gateway` session, so AWS attributes the fallback to `claude-apps-gateway` rather than to the developer. For strict per-developer attribution, set `assume_role` with `session_name` on every Bedrock upstream you list. An upstream without it signs the requests it serves with its own credentials. -#### - -​ - -Amazon Bedrock Mantle endpoint +#### Amazon Bedrock Mantle endpoint The `mantle` provider sends inference to Amazon Bedrock’s [Mantle endpoint](</docs/en/amazon-bedrock#use-the-mantle-endpoint>). It requires Claude Code v2.1.283 or later on the gateway server. Earlier gateway releases reject it at boot, so upgrade every replica before adding it. The example below puts Mantle first, with an Amazon Bedrock upstream behind it to serve every model the `models` field leaves out: @@ -523,11 +459,7 @@ For what Mantle’s own error responses mean, see [Mantle endpoint errors](</docs/en/amazon-bedrock#mantle-endpoint-errors>). -#### - -​ - -Claude Platform on AWS +#### Claude Platform on AWS Claude Platform on AWS serves the first-party Anthropic API on AWS infrastructure at `aws-external-anthropic.<region>.api.aws`. It uses first-party model IDs, honors `anthropic-beta` headers as sent, and serves `count_tokens`, so none of the Bedrock-specific translation applies. The `anthropicAws` provider requires Claude Code v2.1.198 or later; earlier gateway releases reject it at boot. For the client-side deployment of the same platform, see [Claude Code on Claude Platform on AWS](</docs/en/claude-platform-on-aws>). The gateway-side upstream: @@ -558,11 +490,7 @@ Because the platform resolves first-party model IDs, the built-in catalog routes to it with no `models:` block. When you curate a `models:` list, key the entry `anthropicAws:` with the first-party ID. -#### - -​ - -Google Cloud Agent Platform +#### Google Cloud Agent Platform For the equivalent client-side setup, see [Claude Code on Google Cloud](</docs/en/google-vertex-ai>). The gateway-side upstream: @@ -586,11 +514,7 @@ Cloud Run / GCE| Set the service’s service account to one with `roles/aiplatform.user`. `auth: {}` picks it up. Anywhere else| `auth: { service_account_json: /secrets/sa.json }`, the path to a JSON key file mounted as a secret. The field takes a file path, not the key contents, so no `${file:…}` expansion is involved. -#### - -​ - -Microsoft Foundry +#### Microsoft Foundry For the client-side Microsoft Foundry deployment, see [Claude Code on Microsoft Foundry](</docs/en/microsoft-foundry>). The gateway-side upstream: @@ -606,17 +530,13 @@ Setup| How ---|--- -RBAC| Grant the gateway’s identity `Azure AI User` or `Cognitive Services User` on the Microsoft Foundry resource +RBAC| Grant the gateway’s identity the `Foundry User` or `Cognitive Services User` role on the Microsoft Foundry resource Deployments| Microsoft Foundry uses admin-chosen deployment names, not canonical model IDs. Add a `models:` block mapping each canonical ID to your deployment name. AKS (workload identity)| Federate a User-Assigned Managed Identity with the cluster’s OIDC issuer and bind it to the gateway’s service account. `use_azure_ad: true` picks it up via `WorkloadIdentityCredential`. ACI / App Service| Enable system-assigned or user-assigned managed identity on the resource. `use_azure_ad: true` picks it up. Anywhere else| `auth: { api_key: "${FOUNDRY_API_KEY}" }`. Quote `${…}` inside `{ }`. -#### - -​ - -Static headers on upstream requests +#### Static headers on upstream requests To add fixed headers to the requests the gateway sends to one upstream, set `headers:` on that upstream. Use it when a proxy you run in front of the provider routes or attributes traffic by a header. `headers:` requires Claude Code v2.1.277 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 remove the key before you roll back to an earlier version. The headers go to the server that `base_url` names, or to the provider’s own endpoint when `base_url` is unset. The provider receives them too unless your proxy removes them. This example reaches a `provider: vertex` upstream through a proxy at `upstream-proxy.internal.example.com`. It sets the `x-source` header the proxy reads, and sends a token from the `PROXY_TOKEN` environment variable as `x-proxy-token`: @@ -645,11 +565,7 @@ * `host`, `content-type`, and `user-agent` * Any name starting with `anthropic-`, `x-goog-`, `x-amz-`, or `x-amzn-` -#### - -​ - -Multiple upstreams +#### Multiple upstreams The same provider can appear more than once with a distinct `name:`. This covers different regions, different accounts via different credential chains, provisioned throughput versus on-demand, and cross-provider fallback. The gateway tries upstreams in order. `5xx`, `429`, `401`, `403`, `404`, timeouts, and missing-endpoint (`501`) fail over; other `4xx` doesn’t. `429` is per-upstream capacity, so provisioned-throughput (PT) exhaustion fails over to on-demand. If you set `forward_user_identity: true` on an upstream, a `429` to a request that carried the developer’s email is a per-user denial instead and doesn’t fail over. A request moves past an upstream only in these cases: @@ -710,11 +626,7 @@ Failing over between cloud providers, or to the direct Anthropic API, changes which agreement, geography, and other terms govern the request. The CLI applies the same feature gating to gateways regardless of which upstream serves a given request, so by default failover doesn’t send a body field an upstream would reject. If you set the one-hour cache TTL in a policy, it goes to every upstream in the list, so set it only if all of them accept it. -#### - -​ - -Send each team to its own upstream +#### Send each team to its own upstream To send each team’s requests to its own AWS account or Google Cloud project, list one upstream per team and give each one a `groups` list. Only developers in a listed IdP group reach that upstream, on the first try and on failover. Every provider takes `groups`. Requires Claude Code v2.1.314 or later on the gateway server. This example gives the `payments-eng` and `search-eng` groups an AWS account each, and adds an upstream with no `groups` list that every developer can use: @@ -768,17 +680,9 @@ If your IdP’s userinfo endpoint returns the groups claim and `oidc.google_groups` isn’t set, set `oidc.userinfo_fallback` to `true` to fill in the groups from there. -## - -​ - -Optional sections - -### - -​ - -`login_notice` +## Optional sections + +### `login_notice` To show developers a notice when they sign in, set the top-level `login_notice` key to the notice text, up to 500 characters. This example says who the gateway is for and where to ask for access: @@ -786,11 +690,7 @@ Developers see the text under `Notice from <gateway hostname>` on the gateway’s verification page in the browser and on the interactive sign-in screen in the terminal. Line breaks in the text become spaces. The notice appears before sign-in, so anyone who can reach the gateway can read it. Requires Claude Code v2.1.319 or later on the gateway server, and also on the developer’s machine for the terminal screen. 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. -### - -​ - -`admin` +### `admin` Optional. Enables `/v1/organizations/spend_limits`, which mirrors Anthropic’s public Admin API, and per-developer spend enforcement on `/v1/messages`. See [Spend limits](</docs/en/claude-apps-gateway-spend-limits>) for how caps are set and enforced; this section covers the `gateway.yaml` keys that turn the feature on and tune it. @@ -824,11 +724,7 @@ `pooled_conflict_rule`| No| `default_order` (default) or `priority_list`. The order the gateway tries a developer’s pooled budgets in. See Pooled budget order. Requires v2.1.319 or later. `pooled_priority_order`| With `priority_list`| Up to 50 group names, each listed once and spelled as your IdP sends it. The groups whose pooled budgets the gateway tries first. See Pooled budget order. Requires v2.1.319 or later. -#### - -​ - -Pooled budget order +#### Pooled budget order A pooled budget is one monthly limit that a whole group spends against. To set one, add `pooled_budget` to the [request that sets the group’s monthly cap](</docs/en/claude-apps-gateway-spend-limits#set-a-cap>), as in `"pooled_budget": {"amount": "500000"}` for $5,000. The request also takes the group’s `scope`, `"period": "monthly"`, and `amount`, which stays each member’s own cap. For a developer in several such groups, each request counts against the first budget whose spend is below its limit, and is refused when every budget is used up. `pooled_conflict_rule` sets the order the gateway tries the budgets in: @@ -837,11 +733,7 @@ If you list groups without `pooled_conflict_rule: priority_list`, the gateway ignores the list and logs a warning at boot. A gateway server earlier than v2.1.319 refuses to start when it finds `pooled_conflict_rule` or `pooled_priority_order`. Upgrade every replica before you add either key, and remove both keys before you roll back. -### - -​ - -`enforcement` +### `enforcement` The `enforcement` block controls how spend-limit checks behave when the store is unavailable. @@ -849,11 +741,7 @@ ---|---|--- `fail_closed_on_error`| No| Default `false`. Spend enforcement fails open on a Postgres outage, so inference stays up. Set `true` to fail closed: over-cap developers are blocked, but so is everyone else if the store is unreachable. Requires an `admin:` block: spend enforcement only runs when `admin` is configured, and the gateway refuses to start if you set this `true` without one. -### - -​ - -`pricing` +### `pricing` The `pricing` block tells the spend meter what to charge instead of USD list price, so caps and [`/effective`](</docs/en/claude-apps-gateway-spend-limits#%2Feffective>) reflect your contracted rates. Amounts stay in USD and remain an estimate, not an invoice. Two prerequisites: @@ -885,11 +773,7 @@ For per-region rates, give each region its own named upstream and one row per upstream. -#### - -​ - -Mark prices up +#### Mark prices up With v2.1.271 or later on the gateway server, you can set `multiplier` above 1, up to 10, to meter more than the provider charges, for example an internal chargeback rate. This example meters every request at 120% of the price: @@ -898,11 +782,7 @@ With an `admin:` block, the markup also applies to spend limits. The meter counts 120% of the price, so developers reach their caps sooner. The gateway logs a warning at boot that says so. The multiplier doesn’t change what the upstream provider charges for the requests. If the gateway also sends the rates to signed-in clients, developers need Claude Code v2.1.271 or later to see the markup. Earlier clients ignore a `multiplier` above 1 and show costs without it. A gateway server earlier than v2.1.271 refuses to start if you set a `multiplier` above 1. -#### - -​ - -Send the rates to signed-in clients +#### Send the rates to signed-in clients With v2.1.268 or later on the gateway server, the gateway also puts the rates from `pricing` into the `managed` policies it serves, as the [`modelPricing`](</docs/en/settings-reference#modelpricing>) managed setting. Developers matched by a policy then see the `pricing` rates in `/usage`, the status line, and OpenTelemetry. A developer who matches no policy receives no managed settings, so their figures stay at list price. Clients apply the setting in Claude Code v2.1.242 or later. @@ -911,11 +791,7 @@ * Opt one policy out: set `modelPricing` to `{}` in that policy’s `cli` block, and its developers stay at list price. * Keep a policy’s own rates: a policy whose `cli` block sets `modelPricing` with its own `multiplier` or `overrides` keeps that `modelPricing` whole, and the gateway adds no rates of its own to it. -### - -​ - -`models` +### `models` The `models` block is an optional admin-curated model list, served at `/v1/models` and used to translate model IDs per upstream. It is required for non-US Amazon Bedrock regions, Amazon Bedrock provisioned-throughput ARNs, and Microsoft Foundry deployment names. @@ -929,13 +805,9 @@ bedrock: us.anthropic.claude-opus-4-8 # or an inference-profile ARN foundry: your-opus-deployment-name -Each key under `upstream_model` must match the `name` of a configured upstream, which defaults to the provider name. A key that matches no upstream fails boot, so omit the lines for providers you don’t use. - -### - -​ - -`managed` +Each key under `upstream_model` must match the `name` of a configured upstream, which defaults to the provider name. A key that matches no upstream fails boot, so omit the lines for providers you don’t use. To let developers use the `fable` alias with `auto_include_builtin_models: false`, add a `claude-fable-5` entry to `models`. That’s the ID the [`fable` alias](</docs/en/model-config#fable-alias-resolution>) resolves to for developers signed in to the gateway. Without it, their messages fail with an error that starts with `API Error: 400 model claude-fable-5 is not in the operator's model allowlist`. + +### `managed` The `managed` block defines role-based access policies keyed on IdP groups or email domain. Policies are evaluated in order; by default the first match is selected, then merged onto the `match: {}` catch-all base. A user who matches two role policies gets only the first, so the second policy’s deny rules don’t apply unless you apply every matching policy. Policies are served per-user at `GET /managed/settings` with ETag/304 caching. @@ -957,7 +829,11 @@ A `match: {}` catch-all, conventionally listed last, is treated as a base layer. Every other policy inherits any key it doesn’t set from the catch-all, so per-role entries only need to list what differs from the org default. The merge rules depend on the key type: * **Allow-lists** : `availableModels` and `permissions.allow`. A specific policy’s list fully replaces the base’s. - * **Deny-lists and hook arrays** : `permissions.deny`, `permissions.ask`, `disabledMcpjsonServers`, `deniedMcpServers`, `blockedMarketplaces`, `deniedModels`, and every `hooks` event-type array. These take the union of base and policy, so an org-wide deny or audit hook can’t be accidentally dropped by a per-role override. + * **Deny-lists and hook arrays** : these take the union of base and policy: + * `permissions.deny` and `permissions.ask` + * `disabledMcpjsonServers` and `deniedMcpServers` + * `blockedMarketplaces` and `deniedModels` + * The `hooks` event-type arrays * **Record-typed keys** : `env`, `modelOverrides`, and `skillOverrides`. These shallow-merge, so a per-role `env` block overrides keys it sets and inherits the rest from the base. `availableModels` is also enforced server-side at `/v1/messages`, so a denied model returns `400` regardless of what the client sends. An empty list denies every model. The check also covers the model a session starts on before the developer picks one, so start sessions on a model the policy allows. The gateway validates the `model` value itself before it relays a request, so a malformed value never reaches an upstream. It rejects the request with a `400` in two cases: @@ -981,11 +857,7 @@ Claude Desktop follows its own schedule. -#### - -​ - -Apply every matching policy +#### Apply every matching policy A user who matches several role policies gets only the first unless you set `policy_mode: layered` beside `policies`. With `layered`, every policy that matches the user applies, down to the first `match: {}` policy. `policy_mode` requires Claude Code v2.1.316 or later on the gateway server. A gateway on a version that lacks it 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. This example has one group that loses `WebFetch` and one that gains Opus: @@ -1025,11 +897,7 @@ * **A`!` pattern**: a [`!` negation](</docs/en/permissions#special-characters-and-negation>) in a `Read` or `Edit` rule in any policy’s `permissions.deny` or `permissions.ask` list, the `match: {}` policy’s included * **A limit on hooks outside the catch-all** : `disableAllHooks`, `allowedHttpHookUrls`, or `httpHookAllowedEnvVars` in any policy other than `match: {}` -#### - -​ - -Start sessions on a model the policy allows +#### Start sessions on a model the policy allows If `availableModels` leaves out Claude Code’s default model, sessions get `400` responses until the developer picks a listed model, for example with `/model`. In gateway sessions the default is the Opus model the `opus` alias resolves to, and `availableModels` on its own doesn’t change it. To fix this, set [`enforceAvailableModels: true`](</docs/en/model-config#enforce-the-allowlist-for-the-default-model>) in the same `cli` block, then check which kind of entry the list has: @@ -1048,11 +916,7 @@ env: ANTHROPIC_DEFAULT_OPUS_MODEL: restricted-claude-opus-4-8 # opus and Default resolve to the ID too -#### - -​ - -Matcher values that stop the gateway at boot +#### Matcher values that stop the gateway at boot At boot, the gateway checks the `match` block of every policy and the `admin_groups` list. Any of these values stops the gateway with an error that names the field: @@ -1068,11 +932,7 @@ * An `email_domain` containing `@`, whitespace, or a comma: the policy matched no one * An empty entry in `groups` or in `admin_groups`: the entry matched a user only when that user’s IdP `groups` claim also contained an empty entry. In `admin_groups`, that match granted admin access. If your `admin_groups` list never contained an empty entry, no one gained admin access this way. -#### - -​ - -Choose `cli` or `code` +#### Choose `cli` or `code` When a policy uses the `code` key, each of these stops the gateway from starting: @@ -1098,11 +958,7 @@ * **To cover the Code tab** : switch to `code`, once users’ machines meet the conditions in Apply `code` settings in the Code tab * **To stay on`cli`**: set `serve_to_desktop: false` beside `cli` in a policy to silence the warning -#### - -​ - -What goes in `cli` +#### What goes in `cli` 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: @@ -1158,19 +1014,11 @@ [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; 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. 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. 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`. -#### - -​ - -Test a policy before deployment +#### Test a policy before deployment To test a policy change, start the gateway against a throwaway Postgres database. The gateway connects to Postgres and applies its schema migrations before it checks the contents of `cli`, `code`, and `desktop` blocks. When it can’t reach the database, the start stops at `could not connect to Postgres` and reports nothing about their contents. -#### - -​ - -Context window in terminal sessions +#### Context window in terminal sessions Terminal sessions signed in through `/login` use the 1M context window for Opus 4.7 and later, Sonnet 5 and later, and the Fable models. The model ID needs no `[1m]` suffix, and sessions compact at about 967K tokens. Before Claude Code v2.1.287 on the developer’s machine, Claude Code treated the Opus and Fable models as having a 200K window unless the model ID ended in `[1m]`. To have terminal sessions compact at the 200K boundary instead, set the [auto-compact window](</docs/en/model-config#set-the-auto-compact-window>) in the policy’s `env`: @@ -1183,11 +1031,7 @@ Claude Code applies this variable without showing the developer the approval dialog. The variable applies to every model, including model IDs that end in `[1m]`. To turn off 1M context instead, set [`CLAUDE_CODE_DISABLE_1M_CONTEXT: "1"`](</docs/en/model-config#extended-context>) in the same `env` block. Claude Code then treats every model as having a 200K window. In interactive sessions, each developer approves this variable in the approval dialog before it takes effect. -#### - -​ - -One-hour prompt cache +#### One-hour prompt cache To request the one-hour [prompt cache TTL](</docs/en/prompt-caching#cache-lifetime>) instead of the default five minutes, add these keys to a policy’s existing `code`, `cli`, or `settings` block and restart the gateway. The keys need Claude Code v2.1.242 or later on the gateway server and on clients. `promptCacheTtl` covers the main conversation. `subagentPromptCacheTtl` is optional and covers subagents, workflows, and background requests. This example adds both to a `match: {}` policy keyed `cli`: @@ -1202,19 +1046,11 @@ To confirm `promptCacheTtl`, sign in to the gateway as a user the policy matches and [check which TTL your cache writes used](</docs/en/prompt-caching#choose-the-ttl-yourself>). Pass `--model` to repeat the check for each model the gateway serves. One-hour cache writes [cost more](</docs/en/prompt-caching#cache-lifetime>) than five-minute writes. For [spend limits](</docs/en/claude-apps-gateway-spend-limits#how-requests-are-priced>) to count that higher rate, you need v2.1.286 or later on the gateway server. -#### - -​ - -MCP servers in a policy +#### MCP servers in a policy To provide MCP servers to the Claude Code clients a policy matches, set [`managedMcpServers`](</docs/en/managed-mcp#provide-servers-through-managed-settings>) in that policy’s `cli` block. You need Claude Code v2.1.259 or later on the gateway server and on clients. The gateway checks each entry at boot with [the same rules Claude Code applies on the client](</docs/en/managed-mcp#what-an-entry-can-contain>), and if an entry fails a check, the gateway refuses to start and names the entry. If you write a `${VAR}` reference in `gateway.yaml`, the gateway resolves it from its environment at boot through secret expansion before it runs the entry checks, so every matching client receives the literal value and can read it. The [header guidance for provided servers](</docs/en/managed-mcp#provide-servers-through-managed-settings>) applies to the expanded value. The gateway rejects the `.mcp.json` spelling `mcpServers` in a `cli` block, and its boot error names `managedMcpServers` as the key to use. Before v2.1.259, the gateway rejected any MCP server definition in a `cli` block. -#### - -​ - -Claude Desktop overlay +#### Claude Desktop overlay If your organization also deploys [Claude Desktop](</docs/en/desktop>), the same gateway serves both clients. Point `bootstrapUrl`, in Claude Desktop’s [managed configuration](<https://claude.com/docs/third-party/claude-desktop/configuration>), at `<listen.public_url>/user/bootstrap`. Claude Desktop derives the OAuth issuer from that URL, runs the same device-code sign-in against this gateway, and fetches its configuration from the response. @@ -1304,11 +1140,7 @@ To shorten the 24 hours, set [`relaunchEnforcementHours`](<https://claude.com/docs/third-party/claude-desktop/configuration#relaunchenforcementhours>) in the policy’s `desktop` block. You need Claude Code v2.1.260 or later on the gateway server and Claude Desktop 1.40609.0 or later on members’ machines. With `0`, the dialog appears as soon as Claude Desktop finds the change. -#### - -​ - -Extended context in Claude Desktop +#### Extended context in Claude Desktop If you serve Claude Desktop from the gateway, its model picker offers a 1M context option for each listed model that can run with a 1M context window. These include Claude Opus 4.6 and later, Claude Sonnet 4.6 and later, and the Fable models. The option is the model’s `[1m]` variant, which [Extended context](</docs/en/model-config#extended-context>) describes. You need Claude Code v2.1.284 or later on the gateway server. A `models` entry gets no 1M option when: @@ -1340,19 +1172,11 @@ To remove the option from the picker, set `CLAUDE_CODE_DISABLE_1M_CONTEXT: "1"` in the `env` block under the policy’s `cli` key. If you also listed an entry whose `id` ends in `[1m]`, the gateway still serves it, so delete that entry too. The variable also reaches the terminal sessions of developers the policy matches. For what it changes there, see [Extended context](</docs/en/model-config#extended-context>). -#### - -​ - -Precedence with other managed sources +#### Precedence with other managed sources If a device also has an MDM-delivered policy or a local `managed-settings.json`, gateway-delivered settings rank first. [Precedence within the managed tier](</docs/en/managed-settings#precedence-within-the-managed-tier>) on the managed settings page says when the local sources apply, and has the [keys Claude Code reads from every admin source](</docs/en/managed-settings#keys-read-from-every-admin-source>) regardless of which source it selected, such as the sandbox lock keys, `forceRemoteSettingsRefresh`, and the per-variable `env` merge. A [`policyHelper`](</docs/en/settings-reference#policyhelper>) configured in an MDM profile or the managed settings file runs only when the gateway delivers no settings; the entry says what its output replaces. Embedding hosts such as [Claude Desktop](</docs/en/desktop>) can supply policy through the SDK `managedSettings` option. [Parent settings from embedding hosts](</docs/en/managed-settings#parent-settings-from-embedding-hosts>) says when Claude Code applies it, and [Restrict parent settings](</docs/en/claude-apps-gateway#restrict-parent-settings>) lists which allow-direction settings still apply without the `allowManaged*Only` locks. Gateway policies apply to every Claude Code invocation on the machine, including non-interactive `claude -p` runs and sessions spawned by the Agent SDK. If the gateway is unreachable at startup, signed-in sessions exit with an error rather than running without their policy. -### - -​ - -`telemetry` +### `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>). 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`. @@ -1395,11 +1219,7 @@ Without a `forward_to` destination for a signal, the gateway accepts and discards it. If developers already export Claude Code telemetry to one of your collectors, add it as a `forward_to` destination, with logs or traces enabled if they export those, so it keeps receiving their data after they sign in. To skip the relay instead, name the collector in a policy. [Traces](</docs/en/monitoring-usage#traces-beta>) also require `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1` on each client. Set it in a managed policy’s `env` block, since the gateway doesn’t push it. Developers approve it in the same security approval dialog that the pushed endpoint already triggers. Set it to `1` only in the policies whose groups you want traced. A policy that doesn’t set it inherits the value from your `match: {}` catch-all policy if that policy sets one, per the merge rules. To keep a group’s clients from sending traces even when a developer sets the variable locally, set it to `0` in that group’s policy. Both protobuf and JSON OTLP encodings are relayed, and any OpenTelemetry-compatible backend works as a destination. -#### - -​ - -Send cumulative metrics +#### Send cumulative metrics If your collector accepts only cumulative metrics, set [`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE`](</docs/en/monitoring-usage#common-configuration-variables>) to `cumulative`. Claude Code sends delta metrics by default, and the gateway relays them without converting them. Set the variable where each kind of session reads it: @@ -1410,11 +1230,7 @@ If you add the variable to a machine’s managed settings, also set [`parentSettingsBehavior: "merge"`](</docs/en/claude-apps-gateway#set-the-opt-in>) in the highest-priority source on that machine. Without it, Cowork sessions and Code tab sessions under a `cli` policy run without the egress allowlist and other policy that Claude Desktop passes them as parent settings. -#### - -​ - -Add your own labels +#### Add your own labels To put fixed labels such as `service.namespace` or `deployment.environment.name` on the telemetry of sessions signed in through the gateway, set `telemetry.resource_attributes`. Each label is an OpenTelemetry resource attribute, and every destination receives the same labels. Sessions get the labels only when you also set `telemetry.forward_to` and `listen.public_url`. This example adds two labels: @@ -1435,11 +1251,7 @@ 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 +#### 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: @@ -1451,11 +1263,7 @@ 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. -#### - -​ - -Export directly to your collector +#### Export directly to your collector To have sessions signed in through `/login` send telemetry straight to your collector instead of through the relay, set `OTEL_EXPORTER_OTLP_ENDPOINT` to the collector’s `https://` base URL in the `env` block of a managed policy. Claude Code appends `/v1/metrics`, `/v1/logs`, or `/v1/traces` to the URL you set, such as `https://otel-collector.example.com:4318`, and exports each signal there over OTLP/HTTP. Requires Claude Code v2.1.265 or later on each developer’s machine. Earlier clients export through the relay. To authenticate to the collector, set `OTEL_EXPORTER_OTLP_HEADERS` in the same `env` block. Sessions never send the developer’s gateway session token to a collector named this way. When you add or change this endpoint in a policy, Claude Code asks each developer to approve it in the security approval dialog before applying it in an interactive session. Claude Code checks the endpoint before it exports a signal directly, and keeps that signal on the relay when a check fails. The checks include: @@ -1472,19 +1280,11 @@ When the developer signs out, or signs in to a different gateway, exports to the collector stop and Claude Code drops each remaining batch rather than sending it. -#### - -​ - -When a destination fails +#### When a destination fails The gateway doesn’t buffer, retry, or store telemetry, so it drops an export that doesn’t reach a destination rather than delivering it late. Each destination succeeds or fails on its own, and the exporting client receives a success response either way, so a failed delivery appears only in the gateway’s log. After five consecutive failed deliveries to a destination, the gateway pauses forwarding to it in 30-second stretches, logging each pause, until a delivery succeeds. Any error response, timeout, or connection error counts as a failed delivery, except `400`, `413`, `415`, `422`, and `431`, which mean the collector refused that export’s payload as malformed or too large. A refused payload neither advances nor resets the failure count: the gateway keeps forwarding to the destination and logs a warning naming it and the status, on the destination’s first refusal and every hundredth after. -### - -​ - -HTTP tuning +### HTTP tuning Four optional top-level blocks, `access_control`, `limits`, `timeouts`, and `rate_limits`, tune the HTTP surface. The defaults suit most deployments. @@ -1505,11 +1305,7 @@ Both signals use the client address as the gateway resolves it. If a load balancer, port-forward, or tunnel relays traffic and isn’t listed in `listen.trusted_proxies`, the gateway sees the relay’s address, which is usually private, so neither the runtime warning nor a private allow list catches traffic relayed through it. If the relay belongs in `listen.trusted_proxies`, list it there. Keep the gateway and everything in front of it unreachable from the public internet regardless. -### - -​ - -`load_test_mode` +### `load_test_mode` The `load_test_mode` block lets you load test a gateway without calling a model provider. While it’s on, the gateway builds and signs each provider request as usual, discards it instead of sending it, and streams a canned reply back through its normal response path. The reply is filler text that begins with a sentence saying it is canned. Requires Claude Code v2.1.282 or later on the gateway server. An earlier gateway refuses to start when it finds the key. Upgrade every replica before you add the block, and remove the block before you roll back. The example below turns the mode on with the defaults, a reply of roughly 750 tokens of text streamed over about 10 seconds: @@ -1528,11 +1324,7 @@ Never turn this on for a gateway that developers use. Every request gets the canned reply and no model is called. The gateway logs a `load_test_mode is on` warning at boot and marks each `inference` [audit event](</docs/en/claude-apps-gateway-deploy#logs>) with `load_test: true` while the mode is on. -## - -​ - -Complete example +## Complete example This full reference config exercises every core section; the HTTP tuning blocks keep their defaults. Copy it, delete what you don’t need, and fill in your values. The config in the [Quickstart](</docs/en/claude-apps-gateway#quickstart>) is a minimal version of this. @@ -1700,11 +1492,7 @@ headers: Authorization: Bearer ${OTEL_TOKEN} -## - -​ - -Client-side managed settings +## Client-side managed settings Everything above configures the gateway server. You point developer machines at the gateway separately, on each device, through Claude Code’s [managed settings](</docs/en/managed-settings>). The gateway can’t push the login keys itself, because they’re what tell the client where the gateway is. For the CLI, set these keys in the per-OS `managed-settings.json`. The two login keys route each developer’s `/login` to your gateway: @@ -1716,11 +1504,7 @@ `parentSettingsBehavior: "merge"` keeps Claude Desktop’s delivery of the egress allowlist to its embedded Claude Code sessions working; [Deliver policy to Claude Desktop sessions](</docs/en/claude-apps-gateway#deliver-policy-to-claude-desktop-sessions>) explains the mechanism and where the opt-in must sit. To stop developers from bypassing the gateway with a cloud provider variable or an `ANTHROPIC_BASE_URL` of their own, add `"allowedProviders": ["gateway"]` to the same file. Claude Code then refuses every session on the machine that isn’t set up for a Cloud gateway, and admits a gateway only when it is the one `forceLoginGatewayUrl` names or one whose URL the file’s `env` block sets as `ANTHROPIC_BASE_URL`. `claude gateway` refuses to run on a machine that sets the list, so keep the key off the gateway host. See the [`allowedProviders`](</docs/en/settings-reference#allowedproviders>) entry in the settings reference. Requires Claude Code v2.1.285 or later. Deploy the `managed-settings.json` file to each device, typically via your MDM platform. The file path differs by platform. See [where each mechanism stores the policy](</docs/en/managed-settings#where-each-mechanism-stores-the-policy>). By default, a registry policy on Windows or a managed-preferences plist on macOS replaces the `managed-settings.json` file rather than merging with it, apart from the exception keys and cross-source checks above. All three keys in this snippet follow the highest-priority-source rule, so fleets that deliver policy through Group Policy or configuration profiles must put all three in that mechanism instead. For Claude Desktop, set the `bootstrapUrl` key in Claude Desktop’s own [managed configuration](<https://claude.com/docs/third-party/claude-desktop/configuration>) to `<listen.public_url>/user/bootstrap`. The sign-in flow and per-group policy then match the CLI’s once a policy opts in server-side with a `desktop` key; without the opt-in, `/user/bootstrap` returns 404. See Claude Desktop overlay for the server-side half. Claude Code honors [`forceLoginGatewayUrl`](</docs/en/settings-reference#forcelogingatewayurl>), [`gatewayInternalNetworks`](</docs/en/settings-reference#gatewayinternalnetworks>), and the `"gateway"` value of [`forceLoginMethod`](</docs/en/settings-reference#forceloginmethod>) from a managed source on the machine: `managed-settings.json`, the macOS plist or Windows HKLM registry, or a policy helper. Setting them in the gateway payload doesn’t configure the gateway sign-in. For a developer’s own `~/.claude/settings.json`, see [Set the gateway URL in user settings](</docs/en/claude-apps-gateway#set-the-gateway-url-in-user-settings>). Leave `forceLoginMethod` and `forceLoginOrgUUID` out of the payload. Claude Code still reads both keys from the payload for its startup credential check, so a developer who keeps an Anthropic-issued credential on the machine gets the startup exit described under [Administrator policy requires a Cloud gateway sign-in](</docs/en/errors#administrator-policy-requires-a-cloud-gateway-sign-in>) even after they sign in. -## - -​ - -Related +## Related * [Claude apps gateway overview](</docs/en/claude-apps-gateway>): quickstart and developer connection * [Deployment guide](</docs/en/claude-apps-gateway-deploy>): IdP setup, container image, Kubernetes and Cloud Run, and operations
modified Claude apps gateway deployment and operations View current →
Show diff (438 lines)
--- a/claude-apps-gateway-deploy.md +++ b/claude-apps-gateway-deploy.md @@ -9,11 +9,7 @@ If a sign-in or boot fails along the way, go straight to Troubleshooting, which is keyed on the error you see. -## - -​ - -Identity provider setup +## Identity provider setup Register a confidential OAuth/OpenID Connect (OIDC) web application with a single redirect URI, `https://<gateway>/oauth/callback`, and assign it to the users or groups who should have gateway access. The gateway authenticates to the IdP with the registration’s client secret, or with a certificate you upload to the registration if your IdP uses [certificate credentials](</docs/en/claude-apps-gateway-config#certificate-client-authentication>) instead. Any OIDC-compliant IdP works: Okta, Microsoft Entra ID, Google Workspace, Keycloak, Dex, PingFederate, and others. The IdP must meet three requirements: @@ -29,11 +25,7 @@ Refresh tokens let the gateway renew a developer’s session silently, without sending the developer back to the browser. They also drive deprovisioning, because when the IdP disables a user, the next refresh fails and the session ends within `ttl_hours`. The gateway requests `offline_access` by default to get a refresh token. If your IdP requires explicit consent for offline access, configure the OAuth client to allow it.If your IdP can’t issue refresh tokens at all, the gateway still works, but there is no silent renewal, so developers re-run the browser login when their session expires. To keep that from happening every hour, raise [`session.ttl_hours`](</docs/en/claude-apps-gateway-config#session>) to `8` or `12`. The tradeoff is deprovisioning latency, because without refresh tokens a disabled user keeps access until the longer TTL elapses. -## - -​ - -Deployment +## Deployment The gateway is a single stateless Linux binary that coordinates through Postgres, so deploy it the way you deploy any other stateless service in your environment. Keep it inside your network, where your developers can reach it over HTTPS and it can reach your IdP, and treat it like any service holding a production credential. A few decisions shape the deployment beyond where it runs: @@ -49,11 +41,7 @@ A default such as the ALB’s 60 seconds is enough to keep a quiet stream open. The [AWS worked example](</docs/en/claude-apps-gateway-on-aws#troubleshooting>) raises it to an hour anyway, and its troubleshooting row covers gateways older than v2.1.229, which sent nothing during quiet periods on the upstreams that now get pings. -### - -​ - -Choose an address for the gateway +### Choose an address for the gateway Claude Code accepts a gateway’s address in one of two ways: @@ -62,11 +50,7 @@ If no single block contains both, give the gateway a private address instead. -### - -​ - -Container image +### Container image Build your own image around the native `claude` binary from the standard Claude Code release: @@ -76,15 +60,11 @@ Mirror the release into your internal registry if your builds can’t reach the release host, and pin the version your fleet runs. Beyond the binary, the image needs: - * **A glibc-based image** : the glibc build’s only dynamic dependencies are glibc libraries. Musl-based images need the `linux-x64-musl` or `linux-arm64-musl` build plus additional packages; see [Alpine Linux setup](</docs/en/setup#alpine-linux-and-musl-based-distributions>). + * **A glibc-based image** : the glibc build’s only dynamic dependencies are glibc libraries. Musl-based images need the `linux-x64-musl` or `linux-arm64-musl` build, whose only dynamic dependency is musl. * **A writable state directory** : the gateway runs as any user, but minimal images have no writable home. Set `CLAUDE_CONFIG_DIR` to a writable path such as `/tmp/.claude`. * **The container command** : `claude gateway --config /etc/claude/gateway.yaml`, with the config file mounted read-only and secrets supplied as environment variables; the gateway listens on `listen.port`, default `8080`. -### - -​ - -Kubernetes +### Kubernetes Run the gateway as a Deployment, like any stateless service: @@ -94,11 +74,7 @@ For a complete worked example on AWS, covering ECS Fargate or EKS, Amazon RDS, and AWS Secrets Manager, see [Deploy on AWS](</docs/en/claude-apps-gateway-on-aws>). Prefer the platform’s workload identity over static keys; the [`upstreams` reference](</docs/en/claude-apps-gateway-config#upstreams>) has per-platform setup details. For a cross-cloud pairing, such as an Amazon Bedrock upstream on GKE, set explicit credentials in the upstream’s `auth` block instead. -### - -​ - -Cloud Run +### Cloud Run Configure the service as follows: @@ -109,19 +85,11 @@ For a complete worked example on Google Cloud, covering Cloud Run or GKE, Cloud SQL, and Secret Manager, see [Deploy on Google Cloud](</docs/en/claude-apps-gateway-on-gcp>). -### - -​ - -Push the gateway URL to developer machines +### Push the gateway URL to developer machines Once the gateway is serving, push `forceLoginMethod`, `forceLoginGatewayUrl`, and `parentSettingsBehavior: "merge"` to each developer’s machine through managed settings, via MDM or by writing the per-OS `managed-settings.json` directly. Once you deploy the keys, Claude Code stops using a leftover API key or claude.ai login on the machine, so plan the push together with your sign-in instructions. [Administrator policy requires a Cloud gateway sign-in](</docs/en/errors#administrator-policy-requires-a-cloud-gateway-sign-in>) describes the messages developers see. See [where each mechanism stores the policy](</docs/en/managed-settings#where-each-mechanism-stores-the-policy>) for the file paths, and [Client-side managed settings](</docs/en/claude-apps-gateway-config#client-side-managed-settings>) for the Claude Desktop `bootstrapUrl` equivalent. -### - -​ - -Large rollouts +### Large rollouts Sign-in is rate limited per client IP address, and the defaults suit a small team. Each address gets 30 sign-in starts and 10 code submissions every 10 minutes. A rollout to thousands of developers can reach those limits on the first morning, for one of two reasons: @@ -136,19 +104,11 @@ `device_verify` is what stops someone from guessing another developer’s sign-in code, so raise it only as far as your estimate needs. Even at these limits, a code is 8 characters from a 20-character alphabet and expires after 10 minutes, so guessing stays impractical; see User-code brute-force resistance. When your IdP issues refresh tokens, Claude Code renews sessions silently, so you can put the limit back after the rollout. Without refresh tokens, developers sign in again every [`session.ttl_hours`](</docs/en/claude-apps-gateway-config#session>). Size both limits for that steady rate too and leave them raised. When a limit is reached, Claude Code v2.1.274 or later shows `The gateway is limiting sign-in attempts right now`. A gateway on v2.1.274 or later shows `Too many attempts came from your network address` on the verification page, with the settings to check. It also writes a `sign-in refused` log line that names the setting to change. -## - -​ - -Operations +## Operations Once the gateway is serving traffic, day-to-day operation is reading its logs, probing its health, and rotating its secrets on your schedule. The subsections cover each, plus what Postgres holds and how upgrades and rollbacks behave. -### - -​ - -Logs +### Logs The gateway writes two streams to stderr, both JSON-friendly: @@ -164,11 +124,7 @@ * `admin.denied` records a rejected admin-API auth attempt with the client IP, method, path, and a reason, without the presented key material: `invalid_key` when an `x-api-key` was presented but matched no configured key, `bearer_rejected` when only an `Authorization` header was presented and it didn’t verify as a gateway session in `admin.admin_groups`, or `no_credentials` when neither header was presented * **Operational logs** : human-readable `[gateway]`-prefixed lines for boot, warnings, and upstream errors. The `CLAUDE_GATEWAY_LOG_LEVEL` environment variable controls verbosity and accepts `debug`, `info`, `warn`, or `error`, with `info` as the default. At `debug`, each sign-in and refresh also logs the names, not the values, of the claims in the id_token, plus the names of the userinfo claims when `userinfo_fallback` supplied any, so you can diagnose `email_claim` and `groups_claim` settings without logging PII. It doesn’t affect audit events, which are always emitted. -#### - -​ - -Write operational logs as JSON +#### Write operational logs as JSON If your log collector reads each line’s level from a JSON field, set `CLAUDE_GATEWAY_LOG_FORMAT=json` in the gateway’s environment. Requires Claude Code v2.1.319 or later on the gateway server. Each operational log line is then one object with `severity`, `time`, and `message`: @@ -176,19 +132,11 @@ `severity` is the log level in capitals, with `warn` written as `WARNING`. A failed start is an `ERROR` line. Audit events, which also go to stderr, don’t change. They carry `ts` and `evt`, and no `severity`. -### - -​ - -Health +### Health The gateway serves `GET /healthz` as a liveness probe and `GET /readyz` as a readiness probe. `/readyz` verifies the store is reachable. If you set [`store.readiness_grace_seconds`](</docs/en/claude-apps-gateway-config#store>), `/readyz` keeps reporting ready for up to that many seconds after the store stops answering. Both endpoints are exempt from `access_control.allow_cidrs`, so probes keep working on a locked-down listener. The OAuth discovery document at `/.well-known/oauth-authorization-server` also returns `200` only after config load, OIDC discovery, upstream client construction, and Postgres migration all succeed, so it doubles as an end-to-end boot check. -### - -​ - -Concurrent upstream requests +### Concurrent upstream requests By default, each gateway replica sends at most 256 requests upstream at the same time. A streaming response counts against the limit until the stream ends. A request that arrives while a replica is at the limit waits inside the gateway for a free slot. The developer sees a response that is slow to start or appears to hang. On a `provider: anthropic` upstream, a request that waits longer than [`timeouts.upstream_ttfb_ms`](</docs/en/claude-apps-gateway-config#http-tuning>) gives up on that upstream, and fails with a 502 when no later upstream serves it. The startup log line that contains `upstream requests:` shows the limit in effect. While a replica has more requests open than the limit, it also logs a warning that contains `client requests are open`, at most once a minute. To serve more requests at once, you have two options: @@ -201,11 +149,7 @@ In a load test with [`load_test_mode`](</docs/en/claude-apps-gateway-config#load_test_mode>), requests don’t wait at this limit, but a replica still logs the `client requests are open` warning. -### - -​ - -Keep `API_TIMEOUT_MS` above the gateway’s time to first byte +### Keep `API_TIMEOUT_MS` above the gateway’s time to first byte If you lower [`API_TIMEOUT_MS`](</docs/en/network-config#streaming-idle-watchdogs>) to retry an unanswered request sooner, keep it above the time the gateway takes to send the first bytes of a streaming response. A request that waits longer times out, and so does each retry that waits as long, until the turn ends with `Request timed out` unless the first-byte deadline ends it. @@ -214,11 +158,7 @@ On top of that time, allow for any wait for a free slot and for the wait on a down upstream before [failover](</docs/en/claude-apps-gateway-config#multiple-upstreams>). Keep the value above the longest [non-streaming request](</docs/en/network-config#streaming-idle-watchdogs>) too. -### - -​ - -Retry an unanswered request sooner with the first-byte deadline +### Retry an unanswered request sooner with the first-byte deadline To make Claude Code retry an unanswered streaming request sooner, give it a first-byte deadline by setting [`CLAUDE_STREAM_FIRST_BYTE_TIMEOUT_MS`](</docs/en/env-vars>) on your developers’ machines. The deadline limits how long the first attempt waits for response headers. Without it, that attempt can wait 5 to 6 minutes. Requires Claude Code v2.1.307 or later on the developer’s machine. Set the variable to a positive whole number of milliseconds, in a gateway policy’s `env` block or a developer’s shell. Keep the value above your gateway’s longest time to first byte, or Claude Code can abort and re-send healthy requests whose headers take longer. This example sets 60 seconds in a developer’s shell: @@ -226,11 +166,7 @@ An unanswered re-send can wait 5 to 6 minutes, until the [body idle timeout](</docs/en/network-config#streaming-idle-watchdogs>) ends it and Claude Code retries it within the [retry budget](</docs/en/errors#tune-retry-behavior>). If you lowered `API_TIMEOUT_MS` only to retry sooner, remove that value, or one unanswered re-send can end the turn with [No response from API](</docs/en/errors#no-response-from-api>). To confirm the deadline fired, have a developer start Claude Code with [debug logging](</docs/en/network-config#verify-your-configuration>), then search the log for `[first-byte] no response headers`. -### - -​ - -Outage behavior +### Outage behavior If Postgres goes down, the gateway itself keeps serving signed-in developers and new sign-ins fail. Whether developers actually keep working depends on how your orchestrator handles readiness: @@ -241,19 +177,11 @@ If your IdP goes down, existing sessions work until `ttl_hours` and new logins fail. A session refresh gets a try-again answer and succeeds once the IdP is back. Set a longer `ttl_hours` if your IdP has frequent maintenance windows. -#### - -​ - -Readiness grace period +#### Readiness grace period To keep signed-in developers working through a short Postgres outage such as a database failover, set [`store.readiness_grace_seconds`](</docs/en/claude-apps-gateway-config#store>) to longer than the failover takes, for example `300`. With spend limits on and the default fail-open behavior, requests through a replica that stays ready are unmetered until Postgres recovers, so keep the value as low as covers your failover. If you set [`enforcement.fail_closed_on_error: true`](</docs/en/claude-apps-gateway-config#enforcement>), the gateway refuses signed-in developers’ inference with the `429` `spend limit unavailable` message until Postgres recovers, even while replicas still pass their readiness check. The setting requires Claude Code v2.1.282 or later on the gateway server. An earlier gateway refuses to start when it finds the key, so upgrade every replica before you add it. Upgrades covers rolling back. If you point the readiness probe at `/healthz` instead, replicas also keep passing it through an outage, but `/healthz` never reports not-ready, so a replica whose Postgres connection doesn’t recover keeps passing too. -### - -​ - -JWT secret rotation +### JWT secret rotation Rotate the signing secret in stages so existing sessions stay valid: @@ -263,11 +191,7 @@ Rotation is also the only way to force sessions out before they expire: bearer tokens validate locally against the JWT secret, so there is no per-session revocation. Replacing the secret outright, without keeping the old one in the array, invalidates every outstanding session at once. For individual offboarding, deprovision the user in your IdP; their session ends within `ttl_hours`. -### - -​ - -Postgres +### Postgres The gateway stores its state in a PostgreSQL database: @@ -286,11 +210,7 @@ A 30-second loop expires `kv` rows past their TTL, and an hourly sweep enforces the retention windows on the spend tables, so nothing grows without bound. Without [spend limits](</docs/en/claude-apps-gateway-spend-limits>) configured, only `kv` is written. The gateway applies its own schema migrations at boot and on every upgrade, so its database role needs rights to create and alter tables. Point it at a database or schema dedicated to the gateway to keep that grant narrow. With spend limits in use, a lost database means lost spend tracking and caps, not only developer re-logins, so run regular backups. To erase one departed developer immediately rather than waiting on retention, run `DELETE FROM principal_emails WHERE principal = '<sub>'` directly; that removes the only table holding their email, name, and groups. `spend` and `admin_audit` rows reference the pseudonymous OIDC `sub` only. -#### - -​ - -Size the connection pool +#### Size the connection pool Each replica opens up to [`store.max_connections`](</docs/en/claude-apps-gateway-config#store>) Postgres connections, five by default. Keep replicas × `store.max_connections` at or below the connections the database has left for the gateway: @@ -303,11 +223,7 @@ * **The replicas** : run fewer, or have your orchestrator start fewer extra replicas in a rolling update * **The pool** : lower `store.max_connections`, but with [spend limits](</docs/en/claude-apps-gateway-spend-limits>) on, keep it large enough for each replica’s load. Otherwise spend checks can [time out](</docs/en/claude-apps-gateway-spend-limits#postgres-availability>) waiting for a connection, and the gateway logs `spend check failed: spend precheck timed out`. -### - -​ - -Upgrades +### Upgrades Replicas are stateless, so a rolling restart loses no gateway state. The gateway runs schema migrations at boot, which means deploying the new binary self-migrates the database. Concurrent replicas serialize on a Postgres advisory lock, so only one applies each migration. When your orchestrator stops a replica with `SIGTERM`, as in a rolling restart or a scale-in, the gateway stops accepting new connections and lets requests and streams already in flight finish before it exits. It waits up to 25 seconds, called the drain window, then closes whatever is still open. A `SIGINT`, such as Ctrl+C in a terminal, starts the same drain, and a second signal during the drain closes the open requests and exits right away. Draining requires gateway v2.1.274 or later. Long generations can stream for minutes. On Kubernetes and Amazon ECS, raise both of these together to give those streams more time: @@ -325,19 +241,11 @@ Because you pin the gateway’s version in your own image, fixes in new Claude Code releases, including security fixes, reach your deployment only when you update the pin and redeploy. Include the gateway in the same patching cadence you use for other services that hold production credentials. -## - -​ - -Security +## Security This section answers the questions a security review asks: what data flows through the gateway and where it goes, which attacks the design defends against, and which answers belong in a compliance questionnaire. -### - -​ - -Data flow +### Data flow Data| Path| Sent to Anthropic by the gateway ---|---|--- @@ -347,11 +255,7 @@ Managed settings| Your gateway YAML → CLI| Never Audit log| Gateway stderr → your aggregator| Never -### - -​ - -Threat model summary +### Threat model summary The gateway sits inside your network perimeter, but individual developer laptops aren’t treated as trusted. The design accounts for this in three ways: @@ -364,19 +268,11 @@ * **A compromised gateway host** : the host both holds the upstream credential and distributes [managed settings](</docs/en/claude-apps-gateway-config#managed>) to every connected developer, so control over the gateway’s configuration is comparable to control over your MDM. The CLI’s [approval dialog](</docs/en/server-managed-settings#approval-memory>) for shell-capable settings limits silent changes but doesn’t replace host security. * **A malicious OIDC provider** : the provider signs the id_tokens the gateway trusts, so it can assert any identity. Vetting and securing your IdP is your responsibility. -### - -​ - -User-code brute-force resistance +### User-code brute-force resistance The `user_code` a developer types into the `/device` verification page is 8 characters drawn from a 20-character alphabet, which yields 20⁸ or about 2.56×10¹⁰ combinations, and it expires after 10 minutes. The gateway applies per-IP rate limits on the device-grant endpoints, configurable via [`rate_limits`](</docs/en/claude-apps-gateway-config#http-tuning>). Raise the limits if many developers sign in from a single shared corporate NAT address. Large rollouts shows how to size them. The limits apply only to the sign-in flow, not to inference. -### - -​ - -Compliance posture +### Compliance posture * **Data residency** : the gateway’s own data plane sends nothing to Anthropic unless the Anthropic API is a configured upstream; when it is, your existing data-handling agreement applies to the inference path. Telemetry, audit, identity, and settings go only to the destinations you configure. * **Host-process traffic** : the host process is the Claude Code CLI. `claude gateway` runs under the same third-party rules as Amazon Bedrock and Google Cloud’s Agent Platform deployments and sends nothing to Anthropic. Before v2.1.227, the host process sent startup telemetry such as product version and platform, which setting `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1` in the container environment turned off. Those releases also sent one `HEAD` request at boot, with no body or credentials, to `/api/hello` on `https://api.anthropic.com`, or on `ANTHROPIC_BASE_URL` when the environment set it, unless the environment also set a proxy variable such as `HTTPS_PROXY` or an mTLS client certificate. They ignored the response, so blocking that request at the egress firewall didn’t affect the gateway. @@ -389,11 +285,7 @@ * **TLS** : serve `public_url` over HTTPS in production, either from the gateway’s own listener via `listen.tls` or from a TLS-terminating ingress in front of plain-HTTP replicas, with `listen.public_url` set in both cases. The gateway doesn’t refuse plain HTTP. The IdP must serve HTTPS in production, and Postgres supports `?sslmode=require`. Set `Strict-Transport-Security` at your ingress. * **Vulnerability disclosure** : follow [Reporting security issues](</docs/en/security#reporting-security-issues>) -### - -​ - -Plugin marketplace requests +### Plugin marketplace requests Claude Code fetches plugin marketplaces directly from each developer’s machine, not through the gateway. [Network access requirements](</docs/en/network-config#network-access-requirements>) lists the hosts. The first time a developer starts an interactive terminal session, Claude Code registers the official marketplace, `claude-plugins-official`. It downloads the catalog from `downloads.claude.ai` and, if that fails, clones it from `github.com`. [Which marketplaces and plugins auto-update](</docs/en/plugins/loading#which-marketplaces-and-plugins-auto-update>) covers later refreshes. `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1` doesn’t stop the first registration. Either of these managed settings does: @@ -402,11 +294,7 @@ 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>). -## - -​ - -Troubleshooting +## Troubleshooting For questions and feedback, use [Claude Code support](<https://support.claude.com/en/collections/14445694-claude-code>), or open an issue on the [Claude Code GitHub repository](<https://github.com/anthropics/claude-code/issues>). You can also contact your Anthropic account team. When reporting a problem, include: @@ -465,11 +353,7 @@ The `Cloud gateway sign-in was not completed` message names the gateway hostname. When Claude Code has both the pinned fingerprint and the presented one, the message also shows the first 16 characters of each. If Claude Code reports `couldn't load your organization's managed settings` after a gateway sign-in, Claude Code names the reason, restarts in place, and resumes the conversation. If Claude Code can’t restart, for example in a background session, Claude Code ends the session and keeps the sign-in. -### - -​ - -Request headers too large after sign-in +### Request headers too large after sign-in A developer’s requests can fail with a `431` error after sign-in when the developer belongs to many IdP groups. The gateway answers `431` when a request’s headers total more than 256 KiB, or more than [`limits.max_request_header_bytes`](</docs/en/claude-apps-gateway-config#http-tuning>) if you set it. It writes no log line or audit event for these requests. Gateway versions before v2.1.284 answer `431` above 16 KiB. Start with the first of these that applies to your gateway: @@ -485,11 +369,7 @@ * **`groups` on an [upstream](</docs/en/claude-apps-gateway-config#send-each-team-to-its-own-upstream>)**: decides which upstreams serve a developer * **`rbac_group` [spend caps](</docs/en/claude-apps-gateway-spend-limits>)**: decide which group caps apply to a developer -### - -​ - -Long thinking ends in proxy timeouts +### Long thinking ends in proxy timeouts If your upstream is `provider: anthropic`, use Long thinking on an Anthropic API upstream instead: you raise `CLAUDE_STREAM_IDLE_TIMEOUT_MS` there too, but the times and errors differ. If turns fail after long thinking and your proxy logs one request open for about 12.5 minutes, then a run of `504` errors, raise [`CLAUDE_STREAM_IDLE_TIMEOUT_MS`](</docs/en/env-vars>) in a gateway policy. For example, with a 240-second idle timeout on the proxy, the run is 10 requests, each cut at 240 seconds. @@ -498,11 +378,7 @@ You don’t need a longer proxy timeout for this fix. If you raise only the proxy’s timeout, requests without streaming still fail once a reply takes longer than Claude Code’s own wait, 300 seconds by default. -#### - -​ - -Confirm the cause +#### Confirm the cause Have a developer reproduce the failure with `claude --debug-file ./claude-debug.txt`, then search that file for this line: @@ -510,11 +386,7 @@ If your developers already set [`CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK`](</docs/en/env-vars>) to `1`, you see no requests without streaming, and the turn ends with `API Error: Stream idle timeout - no chunks received`. The same fix applies. -#### - -​ - -Pick a value +#### Pick a value Pick a `CLAUDE_STREAM_IDLE_TIMEOUT_MS` value whose second column covers your longest thinking pause, or start with `1800000` if you don’t know it. A stream can stay on pings alone for about 7.5 minutes longer than the value: @@ -526,11 +398,7 @@ If an upstream hangs while the gateway keeps sending pings, your developers also wait that long before Claude Code gives up on the stream. A connection that goes fully silent still ends after 5 to 6 minutes, because the [body idle timeout](</docs/en/network-config#streaming-idle-watchdogs>) doesn’t follow this variable. -#### - -​ - -Deliver the value in a policy +#### Deliver the value in a policy Add the `env` entry to each policy in `gateway.yaml` that already delivers Claude Code settings to the developers you want to cover. Put it under the `code`, `cli`, or `settings` key that policy already has. To try the value first, start with a policy that matches one group. See [`managed`](</docs/en/claude-apps-gateway-config#managed>) for how policies match and inherit. This example adds the entry to a `match: {}` policy keyed `cli`: @@ -543,11 +411,7 @@ With the `cli` key, you cover terminal, IDE extension, and Agent SDK sessions. For Claude Desktop’s Code tab, see [Choose `cli` or `code`](</docs/en/claude-apps-gateway-config#choose-cli-or-code>). Restart the gateway so that it reads the edited file. Then have developers restart Claude Code to get `CLAUDE_STREAM_IDLE_TIMEOUT_MS`. -### - -​ - -Long thinking on an Anthropic API upstream +### Long thinking on an Anthropic API upstream If `provider: anthropic` is the model’s only upstream and your proxy logs one request open for about 20 minutes, then `502` or `504` errors, raise [`CLAUDE_STREAM_IDLE_TIMEOUT_MS`](</docs/en/env-vars>) in a gateway policy. @@ -556,11 +420,7 @@ To confirm the cause, see Confirm the cause. Pick the value whose time covers your longest thinking pause: about 20 minutes at the default, 30 at `900000`, and 45 at `1800000`. Then follow Deliver the value in a policy. -## - -​ - -Related +## Related * [Claude apps gateway overview](</docs/en/claude-apps-gateway>): quickstart and developer connection * [Configuration reference](</docs/en/claude-apps-gateway-config>): every `gateway.yaml` option
modified Deploy Claude apps gateway on AWS View current →
Show diff (186 lines)
--- a/claude-apps-gateway-on-aws.md +++ b/claude-apps-gateway-on-aws.md @@ -4,11 +4,7 @@ Bedrock isn’t the only Claude upstream on AWS. The gateway also supports Claude Platform on AWS, the Anthropic-operated Claude API with AWS authentication and AWS Marketplace billing, in place of Bedrock or alongside it. Its upstream entry, credentials, and IAM permissions differ from this page’s Bedrock-scoped ones; the [Claude Platform on AWS upstream reference](</docs/en/claude-apps-gateway-config#claude-platform-on-aws>) covers what changes, and the rest of this page applies unchanged. -## - -​ - -Architecture +## Architecture The example architecture, with Amazon Bedrock as the model upstream. A Claude Platform on AWS upstream occupies the same position. @@ -21,11 +17,7 @@ * **IAM role** with `bedrock:InvokeModel`, `bedrock:InvokeModelWithResponseStream`, and `bedrock:CountTokens`, attached as the ECS task role or bound via IAM Roles for Service Accounts (IRSA) on EKS * **Internal Application Load Balancer** for HTTPS -## - -​ - -Prerequisites +## Prerequisites The walkthrough creates the gateway’s own resources, but it builds on network and identity infrastructure you already have. Before you start, you need: @@ -35,11 +27,7 @@ * An Okta OIDC web application with redirect URI `https://<gateway-host>/oauth/callback`; see [Identity provider setup](</docs/en/claude-apps-gateway-deploy#identity-provider-setup>) * A TLS hostname for the gateway, typically an internal DNS name in a [Route 53 private hosted zone](<https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/hosted-zones-private.html>) pointing at the load balancer, with an [ACM certificate](<https://docs.aws.amazon.com/acm/latest/userguide/gs.html>) for that name, imported or issued by [AWS Private CA](<https://docs.aws.amazon.com/privateca/latest/userguide/PcaWelcome.html>) -### - -​ - -Set your environment variables +### Set your environment variables Every command on this page reads four values from your shell: `AWS_REGION`, `ACCOUNT_ID`, `VPC_ID`, and `PRIVATE_SUBNETS`. Pick a US region where Bedrock serves the Claude models you need. The walkthrough relies on the gateway’s built-in model catalog, which resolves to `us.anthropic.*` inference profiles, and the IAM policy grants those ARNs. In a non-US region, add a [`models:` block](</docs/en/claude-apps-gateway-config#models>) with that geo’s inference-profile IDs and change the IAM policy’s ARN prefix to match. If you don’t have the VPC ID at hand, list your VPCs with `aws ec2 describe-vpcs`, then list that VPC’s subnets to find two private ones in different Availability Zones: @@ -53,11 +41,7 @@ export VPC_ID=<your-vpc-id> export PRIVATE_SUBNETS="<subnet-id-a> <subnet-id-b>" -## - -​ - -Deploy the gateway +## Deploy the gateway The steps below provision the full deployment with `aws` commands. @@ -412,11 +396,7 @@ 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. -## - -​ - -Terraform reference +## Terraform reference The companion bundle at [`examples/gateway/aws`](<https://github.com/anthropics/claude-code/tree/main/examples/gateway/aws>) packages this page as code: @@ -427,11 +407,7 @@ Like this page, the bundle is a working example for customer-managed infrastructure rather than a supported production deployment; review and adapt it to your own environment before relying on it. -## - -​ - -Troubleshooting +## Troubleshooting For gateway boot and login errors, see the platform-agnostic [troubleshooting table](</docs/en/claude-apps-gateway-deploy#troubleshooting>). The entries below are specific to AWS. @@ -446,59 +422,31 @@ Gateway boot exits with a Postgres TLS certificate verification error| The connection string sets `sslmode=verify-full` but the image doesn’t trust the RDS CA bundle: the bundle wasn’t copied into the image, or `NODE_EXTRA_CA_CERTS` doesn’t point at it| Add the build step’s two Dockerfile lines that copy the bundle and set `NODE_EXTRA_CA_CERTS`, then rebuild, push under a new tag, and redeploy Streaming responses drop mid-stream after a quiet period| A gateway older than v2.1.229 on a Bedrock or Claude Platform on AWS upstream sends nothing while the upstream is quiet, for example during extended thinking with no streamed output. The ALB closes a connection after 60 seconds with no data by default, so it cuts the stream at that gap. Gateways v2.1.229 and later keep a quiet stream under that timeout: on those upstreams the gateway emits an SSE `ping` event once about 15 seconds pass with no stream data, and on an Anthropic API upstream it relays the API’s own pings| Update the gateway to v2.1.229 or later, or set the `idle_timeout.timeout_seconds` attribute to `3600`, via `modify-load-balancer-attributes` or the `load-balancer-attributes` Ingress annotation on EKS -## - -​ - -Telemetry +## Telemetry The gateway gives you per-developer usage metrics without any per-machine OTEL configuration. Claude Code emits OpenTelemetry (OTLP) metrics, logs, and opt-in traces; [Monitoring usage](</docs/en/monitoring-usage>) covers everything the CLI reports. In sessions signed in through `/login`, the CLI [stamps each export](</docs/en/monitoring-usage#standard-attributes>) with the authenticated IdP identity attributes `user.id`, `user.email`, and `user.groups`, so usage rolls up per developer. The gateway itself is an authenticated OTLP relay. Set [`telemetry.forward_to`](</docs/en/claude-apps-gateway-config#telemetry>) together with `listen.public_url`, and it pushes the OTEL exporter settings to every connected client and forwards their OTLP traffic verbatim to each destination you list. Each destination opts into metrics, logs, and traces independently, and the default is metrics only; see the [`telemetry` reference](</docs/en/claude-apps-gateway-config#telemetry>) for the per-signal fields and their sensitivity tradeoffs. The gateway doesn’t buffer, aggregate, or store telemetry, so where the data lands is entirely the collector’s exporter configuration. Client telemetry is off by default; configuring `telemetry.forward_to` is what turns it on for connected developers, and each interactive client shows a security approval dialog for the pushed settings, as described in the [configuration reference](</docs/en/claude-apps-gateway-config#telemetry>). On AWS, each signal maps to a destination as follows. -### - -​ - -Client metrics, logs, and traces +### Client metrics, logs, and traces Point `telemetry.forward_to` at an OpenTelemetry collector, such as the [AWS Distro for OpenTelemetry (ADOT) collector](<https://aws-otel.github.io/>), and export from there to Amazon CloudWatch, Amazon Managed Service for Prometheus, or any OTLP backend. Run the collector as its own internal service reachable over `https://`; the [`telemetry` reference](</docs/en/claude-apps-gateway-config#telemetry>) covers the loopback exception and `CLAUDE_GATEWAY_ALLOW_LOOPBACK`. -### - -​ - -Gateway logs +### Gateway logs On ECS Fargate, no extra setup: the `awslogs` driver delivers the gateway’s stderr, which carries its audit events and operational logs, to the `/ecs/claude-gateway` log group created above. On EKS, pod logs don’t reach CloudWatch by default, so the audit trail is lost until you install log collection: the Amazon CloudWatch Observability add-on with container log capture enabled, or a Fluent Bit DaemonSet. On either track, query the logs with CloudWatch Logs Insights and drive alarms from metric filters. -### - -​ - -Container metrics +### Container metrics Enable Container Insights on the cluster with `aws ecs update-cluster-settings --cluster claude-gateway --settings name=containerInsights,value=enabled` for per-task CPU, memory, and network. On EKS, install the Amazon CloudWatch Observability add-on. -### - -​ - -Spend +### Spend Telemetry shows usage after the fact; [spend limits](</docs/en/claude-apps-gateway-spend-limits>) are the gateway’s live per-developer view and enforcement. -## - -​ - -Cost attribution +## Cost attribution The gateway signs every Bedrock request with its own principal, the ECS task role or EKS IRSA role, so by default AWS sees all of that spend under one IAM principal. There are two ways to split it in AWS’s own billing data, and they combine. -### - -​ - -Per developer with `assume_role` +### Per developer with `assume_role` Create a second IAM role that holds the Bedrock permissions and trusts the gateway’s principal, grant that principal `sts:AssumeRole` on it, and set [`assume_role`](</docs/en/claude-apps-gateway-config#per-developer-aws-cost-attribution>) with `session_name: email` on the Bedrock upstream. The gateway then assumes that role once per developer per hour with the session name set to their email and signs their requests with the result. Requires a gateway running Claude Code v2.1.281 or later. The role can also be in another AWS account: see [Bedrock in another AWS account](</docs/en/claude-apps-gateway-config#bedrock-in-another-aws-account>). In Terraform, next to the task role in the Terraform bundle: @@ -523,11 +471,7 @@ With `assume_role` set the gateway signs every Bedrock call, the free `CountTokens` call for spend metering included, with the assumed role’s credentials, so the gateway’s principal needs a Bedrock policy of its own only for an upstream without `assume_role`. Because the gateway calls STS at request time, the private subnets need a path to `sts.<region>.amazonaws.com`. The NAT gateway from the prerequisites provides one, and so does an STS interface VPC endpoint that answers for that hostname. Each active developer costs one STS call per hour per gateway replica. Each developer’s requests reach AWS as the principal `arn:aws:sts::<account>:assumed-role/<role>/<email>`. To see spend per principal, use a billing export that includes IAM principal data; AWS’s [IAM principal cost allocation](<https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/iam-principal-cost-allocation.html>) page covers how to enable it and which billing tools show it. -### - -​ - -Per team with application inference profiles +### Per team with application inference profiles This route uses only the [`models`](</docs/en/claude-apps-gateway-config#models>) and [`managed`](</docs/en/claude-apps-gateway-config#managed>) sections. Create one Bedrock [application inference profile](<https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-create.html>) per team and model, tag each profile with the team, and activate that tag as a cost allocation tag. Then give each team its own model id in `gateway.yaml` and pin each IdP group to its team’s ids: @@ -555,11 +499,7 @@ See [How requests are priced](</docs/en/claude-apps-gateway-spend-limits#how-requests-are-priced>) for how the gateway’s own spend meter prices these ids. -#### - -​ - -Let a developer choose which team to bill +#### Let a developer choose which team to bill To let a developer who works for two teams choose which team each session bills, give that pair of teams an IdP group and a policy of its own. @@ -594,11 +534,7 @@ By default, the gateway applies the [first policy that matches](</docs/en/claude-apps-gateway-config#managed>), so a developer in only the two team groups gets the `team-platform` policy. Their sessions on the data team’s id fail with `is not in your role's availableModels allowlist`, naming Claude Code’s default model and not the id they typed. If you list both team groups in one policy’s `groups` instead, everyone in either team can bill either team’s profile. In the gateway’s own [spend limits](</docs/en/claude-apps-gateway-spend-limits#set-a-cap>), the developer has one total and one cap per period, by default the lowest of their groups’ caps, whichever id a session uses. To keep one team’s lower cap from stopping work for the other, set a per-user cap for the developer. -## - -​ - -Next steps +## Next steps * [Configuration reference](</docs/en/claude-apps-gateway-config>): every `gateway.yaml` option, including `managed.policies` and `telemetry` * [Deployment and operations](</docs/en/claude-apps-gateway-deploy>): IdP setup, health checks, JWT secret rotation, upgrades, and the security model
modified Deploy Claude apps gateway on Google Cloud View current →
--- a/claude-apps-gateway-on-gcp.md +++ b/claude-apps-gateway-on-gcp.md @@ -2,11 +2,7 @@ This example provisions Claude apps gateway on Google Cloud with Google Cloud’s Agent Platform as the model upstream, using either Cloud Run or GKE for compute. Google Workspace is the example identity provider (IdP), but any OpenID Connect (OIDC) compliant IdP works; only the `oidc` block changes. See [Identity provider setup](</docs/en/claude-apps-gateway-deploy#identity-provider-setup>) for per-IdP details. -## - -​ - -What you’ll build +## What you’ll build The deployment consists of: @@ -17,11 +13,7 @@ * **Service account** with `roles/aiplatform.user`, attached directly on Cloud Run or bound via Workload Identity on GKE * **HTTPS front end** that you provide: an internal Application Load Balancer in front of Cloud Run, which this walkthrough configures the gateway for but doesn’t create, or an internal **GKE Ingress** of class `gce-internal` on GKE -## - -​ - -Prerequisites +## Prerequisites * A GCP project with billing enabled, and permission to create the resources above * The `gcloud` CLI, authenticated with `gcloud auth login`, and Docker installed locally @@ -36,11 +28,7 @@ export REGION=us-east5 # a region where the Claude models you need are published in Model Garden gcloud config set project "$PROJECT_ID" -## - -​ - -Deploy the gateway +## Deploy the gateway The steps below provision the full deployment with `gcloud` commands. @@ -271,11 +259,7 @@ 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. -## - -​ - -Terraform reference +## Terraform reference The [reference deployment assets](<https://github.com/anthropics/claude-code/tree/main/examples/gateway/gcp>) automate the Cloud Run track on this page; the config and image assets apply to both tracks: @@ -285,11 +269,7 @@ The artifacts default Cloud Run ingress to `internal`, matching the deploy command on this page; that setting works with or without an internal Application Load Balancer in front of the service, and the artifacts don’t create the load balancer either. The artifacts also default the invoker layer to an `allUsers` `run.invoker` grant rather than `--no-invoker-iam-check`, the inverse of this page’s walkthrough; either works, and the choice depends on your organization’s policy constraints. The assets are provided as working examples, not as a supported production artifact; review and adapt them to your environment. -## - -​ - -Troubleshooting +## Troubleshooting For gateway boot and login errors, see the platform-agnostic [troubleshooting table](</docs/en/claude-apps-gateway-deploy#troubleshooting>). The entries below are specific to Google Cloud. @@ -302,11 +282,7 @@ Google Cloud’s Agent Platform requests return `403 PERMISSION_DENIED`| Runtime isn’t using the `claude-gateway` service account, or the model isn’t enabled in Model Garden for the project| Set `--service-account` on Cloud Run or bind Workload Identity on GKE, and enable each Claude model in Model Garden for the target region Streaming responses cut off after a fixed duration| Front-end request timeout: the load balancer backend service behind GKE Ingress defaults to 30 seconds and Cloud Run to 300 seconds| Attach a BackendConfig with a raised `timeoutSec` on GKE, or deploy with `--timeout=3600` on Cloud Run -## - -​ - -Next steps +## Next steps * [Configuration reference](</docs/en/claude-apps-gateway-config>): every `gateway.yaml` option, including `managed.policies` and `telemetry` * [Deployment and operations](</docs/en/claude-apps-gateway-deploy>): IdP setup, health checks, JWT secret rotation, upgrades, and the security model
modified Claude apps gateway spend limits View current →
Show diff (153 lines)
--- a/claude-apps-gateway-spend-limits.md +++ b/claude-apps-gateway-spend-limits.md @@ -1,10 +1,6 @@ Spend limits cap how much each developer can spend through your [Claude apps gateway](</docs/en/claude-apps-gateway>) in a given day, week, or month. When a developer passes their cap, the gateway returns `429` on their following requests until an admin raises the cap, or until the cap resets if it’s above $0. Use spend limits to give each developer, group, or the whole organization a ceiling on a credential everyone shares. By default, a Claude apps gateway forwards all inference through one shared upstream credential, so your provider’s bill attributes everything to that credential, not to individual developers. On Amazon Bedrock, [per-developer AWS cost attribution](</docs/en/claude-apps-gateway-config#per-developer-aws-cost-attribution>) changes this. Without per-developer limits, one runaway agent fleet can spend the organization’s entire commitment. Spend limits are the gateway’s per-developer view and circuit breaker on top of that shared bill. -## - -​ - -Set a cap +## Set a cap With the [`admin:`](</docs/en/claude-apps-gateway-config#admin>) block configured in `gateway.yaml`, the gateway serves an admin API at `/v1/organizations/spend_limits` and enforces caps live on every inference request. Caps themselves are set through that API, not in `gateway.yaml`; each `POST /v1/organizations/spend_limits` request creates or replaces one cap from `{scope, amount, period}`. The API mirrors the wire shapes of Anthropic’s public [Admin API](<https://platform.claude.com/docs/en/manage-claude/admin-api>) spend-limits endpoints, so an HTTP client written against that contract can target the gateway by changing its base URL. This request sets an org-wide default of $500 per month for every developer: @@ -28,22 +24,14 @@ A group or organization cap is a per-seat default that each member inherits, not a shared pool. Per period, a developer’s effective cap resolves in this order: a per-user override, then the most restrictive of their group caps, then the org default, then unlimited. [`admin.group_limit_mode: max`](</docs/en/claude-apps-gateway-config#admin>) flips the multi-group tie-break to least-restrictive instead. -### - -​ - -Authenticate to the admin API +### Authenticate to the admin API Send one of: * An `x-api-key` header matching a key in [`admin.write_keys`](</docs/en/claude-apps-gateway-config#admin>) for full access, or `admin.read_keys` for `GET`-only access. Each key carries an `id` that appears in the audit log as `admin-key:<id>`, so give Terraform, CI, and each automation its own. * A gateway bearer token whose `groups` claim includes one of [`admin.admin_groups`](</docs/en/claude-apps-gateway-config#admin>). This is full access and audits as `oidc:<sub>`, so prefer it for human admins. -## - -​ - -How enforcement works +## How enforcement works On each `/v1/messages` request, the gateway looks up the developer’s caps and period-to-date spend in one Postgres query. A developer over any cap gets a `429` with `error.type: billing_error` and header `x-should-retry: false`. For a cap above `"0"`, the message gives the UTC date that cap resets. If you set [`admin.blocked_message`](</docs/en/claude-apps-gateway-config#admin>), the gateway appends it, as in this example: @@ -51,11 +39,7 @@ For a `"0"` cap, which a reset doesn’t lift, the message has no date. When a developer exceeds several caps at once, the message describes the cap that resets last. The response also carries a `retry-after` header with the seconds until that cap’s period ends. Before v2.1.319 on the gateway server, the message named the period and reset time, such as `spend limit reached (daily; resets 2026-08-08 00:00 UTC)`. Before v2.1.225, the message was `spend limit reached` with no period, reset time, or `retry-after` header. On v2.1.227 or later, the protocol reference at `<public_url>/protocol` also lists the exact usage-limit response headers and `429` body. Caps reset on UTC calendar boundaries: daily at 00:00 UTC, weekly on Monday, and monthly on the first. The gateway never blocks `/v1/messages/count_tokens`, because token counting is free. -### - -​ - -How requests are priced +### How requests are priced After each response, a usage meter reads the token counts and adds the cost to the daily, weekly, and monthly counters. It never touches the bytes sent to the client, so a metering failure can’t break a response. The amounts are USD estimates, a circuit breaker rather than an invoice; for billing, reconcile against your provider’s usage reporting. The meter picks each request’s rates in this order: @@ -66,27 +50,15 @@ Whichever rate applies, the meter then multiplies the amount by [`pricing.multiplier`](</docs/en/claude-apps-gateway-config#pricing>), default `1`. Requires a gateway server running Claude Code v2.1.227 or later. Client aborts are billed too. When a stream ends without the upstream’s final usage frame, the meter bills a floor estimate of about four characters per output token for the text already sent to the client, so aborting requests early doesn’t evade a cap. -#### - -​ - -Long-prompt rates +#### Long-prompt rates The list price for [Claude Haiku 5.5](<https://platform.claude.com/docs/en/models/haiku-5-5/overview>) has a [higher rate for prompts over a token threshold](</docs/en/model-config#haiku-5-5-context-window-and-pricing>). When Haiku 5.5 serves a request whose prompt exceeds the threshold, a gateway server running Claude Code v2.1.293 or later prices the whole request at that rate. The meter counts input tokens, cache reads, and cache writes toward that threshold. If one of your `pricing.overrides` rows matches the request, that row’s rates apply at any prompt length. -### - -​ - -Postgres availability +### Postgres availability The pre-check queries Postgres with a two-second timeout. If the store is unreachable or times out, enforcement fails open by default: the request proceeds, the gateway logs a warning, and the response carries no `anthropic-ratelimit-unified-*` headers. Set [`enforcement.fail_closed_on_error: true`](</docs/en/claude-apps-gateway-config#enforcement>) to fail closed instead, which returns the same `429 billing_error` but with the message `spend limit unavailable` and no period, reset time, or `retry-after` header. Fail-open keeps a store outage from becoming an inference outage; fail-closed guarantees no unmetered spend. Fail-open only helps while your load balancer or orchestrator still routes traffic to the gateway. See [Outage behavior](</docs/en/claude-apps-gateway-deploy#outage-behavior>) for `store.readiness_grace_seconds`, which keeps replicas passing their readiness check through a short outage. -### - -​ - -Usage warnings in Claude Code +### Usage warnings in Claude Code Claude Code warns a developer as they approach their cap: once utilization passes 75%, and again past 95% of their most-consumed cap. When the gateway blocks a request, Claude Code shows the gateway’s `429` message as is, including your `admin.blocked_message`. It also shows the cap in `/usage` and passes it to the developer’s [status line](</docs/en/statusline#spend-limit-fields>) script. Each display needs a minimum Claude Code version on the developer’s machine and on the gateway server: @@ -99,11 +71,7 @@ The warnings and the percentage come from the `anthropic-ratelimit-unified-*` headers, which the gateway adds to each successful `/v1/messages` response for a developer who has a cap. The headers always describe the developer’s own cap: the gateway strips the upstream provider’s rate-limit headers, which describe your shared quota, and never forwards them. The spend a developer sees is the gateway’s own estimate, the same figure it enforces the cap with. It isn’t an amount from your provider’s bill. Claude Code reads the dollar amounts with a separate request to the gateway, which it sends even if you set `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` on developers’ machines. Before v2.1.295, Claude Code skipped that request when the variable was set, and `/usage` and the status line showed the percentage and the reset date, with no dollar amounts. -## - -​ - -Admin API reference +## Admin API reference The endpoints below are served under `/v1/organizations/spend_limits`. @@ -126,11 +94,7 @@ Every mutation writes a before/after row to `admin_audit` in the same transaction, attributed to `admin-key:<id>` or `oidc:<sub>`. The gateway serves the spend-limits endpoints only. Other Admin API surfaces, such as the `spend_limit_increase_requests` queue, aren’t part of the gateway’s admin API. -### - -​ - -`/effective` +### `/effective` `GET /v1/organizations/spend_limits/effective` returns Anthropic’s `SpendSummary` schema: each row is a principal for a period, with the resolved cap, period-to-date spend, and an `actor` object. Gateway-specific differences: @@ -151,27 +115,15 @@ `q=` and `user_ids[]=` ride GET query strings, so any fronting proxy or load balancer captures them in its access logs. If your PII log policy is strict, scrub these parameters there. -### - -​ - -`/audit` +### `/audit` Returns the spend-limit mutation trail: who changed which cap, with before/after snapshots, newest-first. `has_more` is exact. This endpoint follows the local Admin API conventions rather than a first-party wire shape. -### - -​ - -Pagination +### Pagination The raw list pages by `after_id` and `before_id`, which are mutually exclusive `spl_…` IDs; results are ordered by creation and `has_more` reflects the traversal direction. `/effective` pages by the opaque `next_page` token passed back as `?page=`, with principals ordered ascending so pages stay stable while spend is being recorded. `limit` is 1–1000, default 20, on both. `/audit` pages by `after_id`, the numeric `id` of the last event on the previous page, and its `limit` defaults to 100. -## - -​ - -Data lifecycle +## Data lifecycle The gateway holds four spend-related tables; an hourly sweep enforces the retention windows: @@ -184,11 +136,7 @@ When a developer leaves, delete any per-user cap via `DELETE /v1/organizations/spend_limits/{id}`; their spend and identity rows age out on the retention windows above. To erase one person immediately, for offboarding or a data subject access request (DSAR), run `DELETE FROM principal_emails WHERE principal = '<sub>'` directly against the gateway database. That removes the only table holding their email, name, and groups. The `spend` and `admin_audit` rows reference the pseudonymous OIDC `sub` only and age out on their own windows. -## - -​ - -Related +## Related * [`admin` and `enforcement` configuration](</docs/en/claude-apps-gateway-config#admin>): enabling the admin API and tuning retention * [Deployment guide](</docs/en/claude-apps-gateway-deploy#postgres>): Postgres schema and backup guidance
modified Use Claude Code features in the SDK View current →
Show diff (114 lines)
--- a/claude-code-features.md +++ b/claude-code-features.md @@ -1,10 +1,6 @@ The Agent SDK is built on the same foundation as Claude Code, which means your SDK agents have access to the same filesystem-based features: project instructions (`CLAUDE.md` and rules), skills, hooks, and more. When you omit `settingSources`, `query()` reads the same filesystem settings as the Claude Code CLI: user, project, and local settings, CLAUDE.md files, and `.claude/` skills, agents, and commands. To run without these, pass `settingSources: []`, which limits the agent to what you configure programmatically. Managed policy settings and the global `~/.claude.json` config are read regardless of this option. For more information, see What settingSources does not control. -## - -​ - -Control filesystem settings with settingSources +## Control filesystem settings with settingSources The setting sources option ([`setting_sources`](</docs/en/agent-sdk/python#claudeagentoptions>) in Python, [`settingSources`](</docs/en/agent-sdk/typescript#settingsource>) in TypeScript) controls which filesystem-based settings the SDK loads. Pass an explicit list to opt in to specific sources, or pass an empty array to disable user, project, and local settings. This example loads both user-level and project-level settings by setting `settingSources` to `["user", "project"]`: @@ -67,11 +63,7 @@ Omitting `settingSources` is equivalent to `["user", "project", "local"]`. The `cwd` option determines where the SDK looks for project-level inputs. Project `settings.json` loads from `<cwd>/.claude/` with no parent-directory fallback. -### - -​ - -What settingSources does not control +### What settingSources does not control `settingSources` covers user, project, and local settings. A few inputs are read regardless of its value: @@ -85,19 +77,11 @@ Do not rely on default `query()` options for multi-tenant isolation. Because the inputs above are read regardless of `settingSources`, an SDK process can pick up host-level configuration and per-directory memory. For multi-tenant deployments, run each tenant in its own filesystem and set `settingSources: []` plus `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1` in `env`. [Server-managed settings](</docs/en/server-managed-settings>) are fetched when the process authenticates with an organization credential; filesystem isolation does not remove them. See [Secure deployment](</docs/en/agent-sdk/secure-deployment>). -## - -​ - -Project instructions (CLAUDE.md and rules) +## Project instructions (CLAUDE.md and rules) `CLAUDE.md` files and `.claude/rules/*.md` files give your agent persistent context about your project: coding conventions, build commands, architecture decisions, and instructions. When `settingSources` includes `"project"`, as in the `settingSources` example, the SDK loads these files into context at session start. The agent then follows your project conventions without you repeating them in every prompt. -### - -​ - -CLAUDE.md load locations +### CLAUDE.md load locations Level| Location| When loaded ---|---|--- @@ -115,11 +99,7 @@ For how to structure and organize CLAUDE.md content, see [Manage Claude’s memory](</docs/en/memory>). -## - -​ - -Skills +## Skills Skills are markdown files that give your agent specialized knowledge and invocable workflows. Unlike `CLAUDE.md` (which loads every session), skills load on demand. The agent receives skill descriptions at startup and loads the full content when relevant. Skills are discovered from the filesystem through `settingSources`. When the `skills` option on `query()` is omitted, discovered user and project skills are enabled and the Skill tool is available, matching CLI behavior. To control which skills are enabled, pass `skills` as `"all"`, a list of skill names, or `[]` to disable all. When `skills` is set, the SDK adds the Skill tool to `allowedTools` automatically. If you also pass an explicit `tools` list, include `"Skill"` in that list so Claude can invoke skills. @@ -165,11 +145,7 @@ Skills must be created as filesystem artifacts (`.claude/skills/<name>/SKILL.md`). The SDK does not have a programmatic API for registering skills. See [Agent Skills in the SDK](</docs/en/agent-sdk/skills>) for full details. -## - -​ - -Hooks +## Hooks The SDK supports two ways to define hooks, and they run side by side: @@ -256,11 +232,7 @@ } } -### - -​ - -When to use which hook type +### When to use which hook type Hook type| Best for ---|--- @@ -271,11 +243,7 @@ For full details on programmatic hooks, see [Control execution with hooks](</docs/en/agent-sdk/hooks>). For filesystem hook syntax, see [Hooks](</docs/en/hooks>). -## - -​ - -Choose the right feature +## Choose the right feature The Agent SDK gives you access to several ways to extend your agent’s behavior. If you’re unsure which to use, this table maps common goals to the right approach. @@ -291,11 +259,7 @@ Every feature you enable adds to your agent’s context window. For per-feature costs and how these features layer together, see [Extend Claude Code](</docs/en/features-overview#understand-context-costs>). -## - -​ - -Related resources +## Related resources * [Extend Claude Code](</docs/en/features-overview>): Conceptual overview of all extension features, with comparison tables and context cost analysis * [Skills in the SDK](</docs/en/agent-sdk/skills>): Full guide to using skills programmatically
modified Use Claude Code in the cloud View current →
Show diff (491 lines)
--- a/claude-code-on-the-web.md +++ b/claude-code-on-the-web.md @@ -16,11 +16,7 @@ * **Many cloud sessions for one body of work** : a [project](</docs/en/claude-projects>) has Claude start and keep track of them for you * **Steering a local session from another device** : sessions in your terminal, IDE, or the Desktop app with **Local** selected run on your machine, and [Remote Control](</docs/en/remote-control>) lets you reach them from your phone or browser -## - -​ - -Cloud environments +## Cloud environments Every cloud session runs in a [cloud environment](</docs/en/cloud-environments>), the saved configuration that controls network access, environment variables, and setup scripts. @@ -29,11 +25,7 @@ * **Change what sessions can reach or run at startup** : see [Configure cloud environments](</docs/en/cloud-environments>) * **What’s installed without any configuration** : see [Installed tools](</docs/en/cloud-environments#installed-tools>) -## - -​ - -GitHub authentication options +## GitHub authentication options Cloud sessions need access to your GitHub repositories to clone code and push branches. You can grant access in two ways: @@ -51,11 +43,7 @@ Organizations with [Zero Data Retention](</docs/en/zero-data-retention>) enabled, or with the [HIPAA configuration](</docs/en/hipaa-setup>) applied, can’t use `/web-setup` or other cloud session features. Organizations that use [customer-managed encryption keys](<https://platform.claude.com/docs/en/manage-claude/cmek>) (CMEK) can’t start cloud sessions either. -### - -​ - -Quick setup for Team and Enterprise +### Quick setup for Team and Enterprise Quick setup is an organization setting that removes steps from members’ GitHub and environment setup. On Team and Enterprise plans it’s off by default. Here’s what changes for members when it’s on: @@ -65,21 +53,13 @@ An [Owner](</docs/en/server-managed-settings#access-control>) turns it on with the **Quick setup** toggle at [**Organization settings > Claude Code**](<https://claude.ai/admin-settings/claude-code>). -## - -​ - -Move tasks between terminal and cloud +## Move tasks between terminal and cloud These workflows require the [Claude Code CLI](</docs/en/quickstart>) signed in to the same claude.ai account. You can start new cloud sessions from your terminal, or pull cloud sessions into your terminal to continue locally. Cloud sessions persist even if you close your laptop, and you can monitor them from anywhere including the Claude mobile app. From the CLI, session handoff is one-way: you can pull cloud sessions into your terminal with `--teleport`, but you can’t push an existing terminal session to the cloud. The `--cloud` flag with a task description creates a new cloud session for your current repository; with `-p` and a session ID or claude.ai/code URL it instead [queues a message into that existing session](</docs/en/claude-code-on-the-web#send-follow-ups-from-the-cli>). The [Desktop app](</docs/en/desktop#continue-in-another-surface>) can send a local session in its Code tab to the cloud from its **Open in** menu. -### - -​ - -Start a cloud session from your terminal +### Start a cloud session from your terminal Start a cloud session from the command line with the `--cloud` flag: @@ -91,11 +71,7 @@ Open the session on claude.ai or the Claude mobile app to check progress or interact directly. From there you can steer Claude, provide feedback, or answer questions as in any other conversation. If Claude asks a question and the session sits idle, you can still answer when you come back, up to environment expiry, and the session continues from your answer. -#### - -​ - -Tips for cloud tasks +#### Tips for cloud tasks **Plan locally, execute in the cloud** : for complex tasks, start Claude in plan mode to collaborate on the approach, then send work to the cloud: @@ -113,11 +89,7 @@ When a session completes, you can create a PR from claude.ai/code or teleport the session to your terminal to continue working. -#### - -​ - -Send local repositories without GitHub +#### Send local repositories without GitHub When you run `claude --cloud` from a repository that has no git remote, or from a github.com repository that the Claude GitHub App isn’t installed on, Claude Code bundles your local repository and uploads it directly to the cloud session. This applies even if you connected GitHub with `/web-setup`. For a full clone, the bundle includes your repository history across all branches, plus uncommitted changes to tracked files. What happens to uncommitted changes in sensitive files depends on your platform: @@ -145,11 +117,7 @@ On macOS, Linux, and WSL, a partial clone made with `git clone --filter` uploads as a snapshot of its working tree without history, as long as the clone holds every tracked file locally. For `claude --cloud`, if the repository is on GitHub, you can avoid the upload and its requirements: push your branch, install the Claude GitHub App on the repository, and start the session again so that it clones from GitHub. -### - -​ - -Send follow-ups from the CLI +### Send follow-ups from the CLI Once a cloud session is running, wherever it executes, send it a follow-up message from the `claude` CLI on any machine where you’re logged in with `claude auth login`. The CLI authenticates with your Anthropic account credentials and sends no local session state, so the command doesn’t need to run from the machine that started the session. The command posts one message and exits: @@ -159,11 +127,7 @@ `--cloud` requires an Anthropic account. It’s not available when Claude Code is configured for Amazon Bedrock, Google Cloud’s Agent Platform, or another third-party provider. An [LLM gateway](</docs/en/llm-gateway>) configured only through `ANTHROPIC_BASE_URL` doesn’t count as a third-party provider for this check, but you still need to sign in with `claude auth login`. Your organization’s `allow_remote_sessions` policy must also be enabled. An Owner can turn it on in the Claude Code admin settings at claude.ai/admin-settings/claude-code. -#### - -​ - -Output +#### Output On success, the command prints the session ID and a link to view the session: @@ -173,11 +137,7 @@ Pass `--output-format json` for a machine-readable result: `{ok, session_id, url}` on success, or `{ok: false, session_id, error}` when the send fails, for example when the session is missing or archived. Configuration errors, such as an unsupported provider or a disabled organization policy, print to stderr without JSON. `--output-format stream-json` isn’t supported with `--cloud <session-id>`. If the send fails, see Errors when sending to a cloud session. -### - -​ - -Continue a cloud session in your terminal +### Continue a cloud session in your terminal Pull a cloud session into your terminal using any of these: @@ -193,11 +153,7 @@ The terminal gets its own copy of the session: new work there stays local and doesn’t appear in the cloud session on claude.ai or the Claude mobile app. To keep steering from your phone after teleporting, start [`/remote-control`](</docs/en/remote-control>) in the local session. -#### - -​ - -Teleport requirements +#### Teleport requirements Teleport checks these requirements before resuming a session. If any requirement isn’t met, you’ll see an error or be prompted to resolve the issue. @@ -210,11 +166,7 @@ When teleport fetches the session’s branch, the fetch never waits for input in your terminal. If git or ssh would ask for a password, a key passphrase, or confirmation of a new SSH host, the fetch fails, and the checkout then works only if your local clone already has the branch. For the two SSH cases, load your key into `ssh-agent` and run `git fetch` once by hand first to record the host. -#### - -​ - -`--teleport` is unavailable +#### `--teleport` is unavailable Teleport requires claude.ai subscription authentication. Find the case that matches yours: @@ -222,30 +174,18 @@ * **The error names your provider** : cloud sessions aren’t available through third-party providers. See the error table * **You’re already signed in via claude.ai** : your organization may have disabled cloud sessions -## - -​ - -Work with sessions +## Work with sessions Sessions appear in the sidebar at claude.ai/code. From there you can review changes, share with teammates, archive finished work, or delete sessions permanently. -### - -​ - -Permission modes in cloud sessions +### Permission modes in cloud sessions You pick a cloud session’s [permission mode](</docs/en/permission-modes>) from the [mode dropdown](</docs/en/permission-modes#switch-permission-modes>), both when you create the task and while the session runs. Claude Code resumes a session in the permission mode it was in when you do either of these: * Reopen a session whose Anthropic-hosted environment expired * Send a message to a session that a self-hosted runner [released while it was idle](</docs/en/self-hosted-environments-reference#runner-cli-flags>) -### - -​ - -Review changes +### Review changes After Claude pushes its changes to a branch, the **Changes** card in the panel beside the chat shows the lines added and removed, such as `+42 -18`. Click the line counts on the **Changes** card to open the diff view. @@ -262,11 +202,7 @@ * **The full walkthrough, including PR creation** : see [Review and iterate](</docs/en/web-quickstart#review-and-iterate>) * **Having Claude monitor the PR for CI failures and review comments automatically** : see Auto-fix pull requests -#### - -​ - -Troubleshoot a missing file in the diff view +#### Troubleshoot a missing file in the diff view A file you expected can be missing from the diff view’s file list when it compares against the base branch, whether or not the session has pushed changes: @@ -275,11 +211,7 @@ To add a missing change to the list, ask Claude to commit and push. -### - -​ - -Manage context +### Manage context Cloud sessions support [built-in commands](</docs/en/commands>) that produce text output. Commands that only run in the terminal interface, such as `/plugin` or `/resume`, aren’t available. Commands that open a picker or panel in the terminal behave differently in cloud sessions: @@ -297,27 +229,15 @@ Auto-compaction runs automatically when the context window approaches capacity. Cloud sessions set [`CLAUDE_AUTOCOMPACT_PCT_OVERRIDE`](</docs/en/env-vars>) themselves, so compaction triggers partway through the [auto-compact window](</docs/en/model-config#set-the-auto-compact-window>) rather than when the window fills. That value overrides one you add in your [environment variables](</docs/en/cloud-environments#set-environment-variables>), so adding the variable there doesn’t change when compaction triggers. To change the auto-compact window instead, set [`CLAUDE_CODE_AUTO_COMPACT_WINDOW`](</docs/en/env-vars>) in your environment variables, or run [`/autocompact`](</docs/en/commands#all-commands>) with a token count in a session where the variable isn’t set. [Subagents](</docs/en/sub-agents>) work the same way they do locally. Claude can spawn them with the Agent tool to offload research or parallel work into a separate context window, keeping the main conversation lighter. Outside a [project](</docs/en/claude-projects#what-threads-pick-up-from-your-repositories>)’s threads, subagents defined in your repo’s `.claude/agents/` load automatically. [Agent teams](</docs/en/agent-teams>) are off by default but can be enabled by adding `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` to your [environment variables](</docs/en/cloud-environments#set-environment-variables>). -### - -​ - -Plugin suggestions in the conversation +### Plugin suggestions in the conversation A card in the conversation that lists one or more [plugins](</docs/en/plugins/overview>), with an **Add** button, means Claude is suggesting plugins for your task. Claude can make these suggestions without you asking. You don’t have to respond, and Claude carries on with the task either way. -#### - -​ - -Add or remove a suggested plugin +#### Add or remove a suggested plugin Select **Add** on a plugin to turn it on for your claude.ai account, where it stays on after the session ends. To undo, open the added plugin from the card, select **Manage** to reach the plugin’s page on claude.ai, and remove the plugin from that page. -#### - -​ - -Turn off plugin suggestions +#### Turn off plugin suggestions To stop Claude from suggesting plugins, deny the `SearchPlugins` and `SuggestPluginInstall` tools with [permission rules](</docs/en/permissions#manage-permissions>). In a session with one repository outside a [project](</docs/en/claude-projects>), commit the rules to that repository’s `.claude/settings.json`, listing both tool names under `permissions.deny`: @@ -329,27 +249,15 @@ Claude Code ignores permission rules in the repository’s `.claude/settings.json`, including these deny rules, when the [managed settings](</docs/en/managed-settings>) that apply to the session set [`allowManagedPermissionRulesOnly`](</docs/en/settings-reference#allowmanagedpermissionrulesonly>). In that case, put the rules in those managed settings instead. For other setups, such as a session with several repositories or a cloud thread in a project, see which [settings reach a cloud session](</docs/en/settings#settings-in-cloud-sessions>). -### - -​ - -Take back a queued message +### Take back a queued message If you send a message while Claude is working, the message queues until Claude reads it. To take a queued message back, click the ✕ on it. The text returns to the message box so you can edit it or send something else. If Claude has already read the message, it stays in the conversation. -### - -​ - -Share sessions +### Share sessions To share a session, toggle its visibility according to the account types below. After that, share the session link as-is. Recipients see the latest state when they open the link, but their view doesn’t update in real time. -#### - -​ - -Share from an Enterprise or Team account +#### Share from an Enterprise or Team account Sharing works as follows for Enterprise and Team accounts: @@ -358,11 +266,7 @@ * **Your name** : your account’s display name is visible to all recipients with access * **Slack sessions** : [Claude in Slack](</docs/en/slack>) sessions are automatically shared with Team visibility -#### - -​ - -Share from a Max, Ultra, or Pro account +#### Share from a Max, Ultra, or Pro account * **Visibility options** : **Private** and **Public**. Public visibility makes the session visible to any user logged into claude.ai * **Repository access** : verification isn’t enabled by default @@ -373,27 +277,15 @@ * **If the Settings menu shows Code instead of Claude Code** : go to [**Privacy**](<https://claude.ai/settings/data-privacy-controls>), which has these settings * **Otherwise** : go to [**Claude Code > Sharing settings**](<https://claude.ai/settings/claude-code>) -### - -​ - -Archive sessions +### Archive sessions Archive a session to remove it from the sidebar’s session list. To archive one, hover over it in the sidebar, open its **⋯** menu, and select **Archive**. -#### - -​ - -Find an archived session +#### Find an archived session To see your archived sessions, go to [claude.ai/code/sessions](<https://claude.ai/code/sessions>) and open the **Archived** tab. To put one back in the sidebar’s session list, hover over it on that tab, open its **⋮** menu, and select **Unarchive**. -### - -​ - -Delete sessions +### Delete sessions Deleting a session permanently removes the session and its data. This action can’t be undone. Delete a session from the sidebar, from the session menu, or from the **Archived** tab if you’ve already archived it: @@ -403,11 +295,7 @@ You will be asked to confirm before a session is deleted. -## - -​ - -Auto-fix pull requests +## Auto-fix pull requests Claude can watch a pull request and automatically respond to CI failures and review comments. Claude subscribes to GitHub activity on the PR, and when a check fails or a reviewer leaves a comment, Claude investigates and pushes a fix if one is clear. @@ -422,11 +310,7 @@ To stop monitoring, turn off **Auto-fix** in the pull request’s **⋮** menu in the session’s **Changes** card, or tell Claude to stop watching the PR. -### - -​ - -How Claude responds to PR activity +### How Claude responds to PR activity When auto-fix is active, Claude receives GitHub events for the PR including new review comments and CI check failures. For each event, Claude investigates and decides how to proceed: @@ -438,11 +322,7 @@ If your repository uses comment-triggered automation such as Atlantis, Terraform Cloud, or custom GitHub Actions that run on `issue_comment` events, be aware that Claude can reply on your behalf, which can trigger those workflows. Review your repository’s automation before enabling auto-fix, and consider disabling auto-fix for repositories where a PR comment can deploy infrastructure or run privileged operations. -## - -​ - -Security and isolation +## Security and isolation Each cloud session is separated from your machine and from other sessions through several layers: @@ -452,19 +332,11 @@ * **Network secrets** : in Anthropic-hosted environments, keys you [add to a cloud environment](</docs/en/cloud-environments#add-network-secrets>) stay outside the sandbox the same way, attached to matching requests after they leave the session. A self-hosted environment doesn’t have network secrets * **Secure analysis** : code is analyzed and modified within the session’s isolated environment before creating PRs -## - -​ - -Troubleshooting +## Troubleshooting For runtime API errors that appear in the conversation such as `API Error: 500`, `529 Overloaded`, `429`, or `Prompt is too long`, see the [Error reference](</docs/en/errors>). Those errors and their fixes are shared with the CLI and Desktop app. The sections below cover issues specific to cloud sessions. -### - -​ - -Session creation failed +### Session creation failed If a new session fails to start with `Session creation failed` or stalls at provisioning, Claude Code could not allocate a VM for the session. @@ -472,30 +344,18 @@ * Retry after a minute, as capacity is provisioned on demand * Confirm your GitHub connection can reach the repository by following [No repositories appear after connecting GitHub](</docs/en/web-quickstart#no-repositories-appear-after-connecting-github>) -### - -​ - -Your new session couldn’t start +### Your new session couldn’t start Your prompt is back in the box you sent it from. * **Connection lost** : check your internet connection and any VPN or proxy you use, then send your prompt again * **Server error** : wait a moment, then send your prompt again. If the notice reappears, check [status.claude.com](<https://status.claude.com>) -### - -​ - -Can’t rewind to this message +### Can’t rewind to this message **Rewind to here** fails with this error on any message except the newest when your session runs on a [self-hosted runner](</docs/en/self-hosted-environments>) with Claude Code before v2.1.246. Ask whoever runs your organization’s runners to [upgrade them](</docs/en/self-hosted-environments-deploy#pin-the-version>). -### - -​ - -Unable to get organization UUID +### Unable to get organization UUID `claude --cloud` and `claude --teleport` require sign-in with a claude.ai account. If you authenticate with an API key or a Console sign-in instead, or your stored account details are stale, you see a message such as: @@ -506,19 +366,11 @@ Run [`claude auth login`](</docs/en/cli-reference#cli-commands>) in your shell to sign in with your claude.ai account, then retry the command. Inside a running session, `/login` does the same. If the error names your provider instead, see the error table: cloud sessions aren’t available through third-party providers. From v2.1.274 through v2.1.289, the sign-in message read `Claude Code cloud sessions require authentication with a Claude.ai account. API key authentication is not sufficient. Please run /login to authenticate, or check your authentication status with /status.` -### - -​ - -Branch is not on GitHub +### Branch is not on GitHub When `claude --cloud` prints a line starting with `Branch <name> is not on GitHub`, the cloud session still starts, but not from your branch. The line names where the session starts instead: a pushed commit from your branch’s history, or the repository’s default branch. Commits that exist only on your machine and uncommitted changes aren’t in the session. You see this line when, for example, you never pushed the branch, or GitHub deleted it after its pull request merged. If the starting point the line names has what your task needs, use the session as it is. Otherwise, push the branch and start a new session so that it clones your branch. -### - -​ - -Remote Control session expired or access denied +### Remote Control session expired or access denied `--teleport` connects through the same Remote Control session infrastructure that cloud sessions use, so authentication and session-expiry errors surface with Remote Control wording. You may see `Remote Control session expired` or `Access denied`. The connection token is short-lived and scoped to your account. @@ -526,11 +378,7 @@ * Confirm you are signed in to the same account that owns the session * If you see `Remote Control may not be available for this organization`, an Owner has not enabled cloud sessions for your organization -### - -​ - -Errors when sending to a cloud session +### Errors when sending to a cloud session These errors come from running `claude` with `--cloud <session-id>`, with or without `-p`. The CLI prefixes errors with `Error: `. A failed delivery is wrapped as `failed to send message to cloud session <id>: <reason>`. @@ -544,11 +392,7 @@ `Session not found: <id>`| The ID or URL doesn’t match a session you can access. Check it against the session’s claude.ai/code URL. `cloud session <id> is archived and cannot accept new messages`| The session has been archived. Start a new session instead. -### - -​ - -Environment expired +### Environment expired 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: @@ -558,11 +402,7 @@ * **Subagents** : Claude Code tells Claude which subagents stopped, and which of those can be [resumed](</docs/en/sub-agents#resume-subagents>) instead of started over. Ask Claude to continue their work. * **Session-scoped scheduled tasks** : tasks you [scheduled in the session](</docs/en/scheduled-tasks>) and a `/loop` waiting for its next iteration don’t carry over to the reopened session. Ask Claude to schedule the tasks again, or run `/loop` again to restart the loop. -## - -​ - -Limitations +## Limitations Before relying on cloud sessions for a workflow, account for these constraints: @@ -572,11 +412,7 @@ * **Platform restrictions** : repository cloning in Anthropic-hosted environments and pull request creation require GitHub. Self-hosted [GitHub Enterprise Server](</docs/en/github-enterprise-server>) instances are supported for Team and Enterprise plans. You can send a GitLab, Bitbucket, or other non-GitHub repository to a cloud session as a local bundle by setting `CCR_FORCE_BUNDLE=1`, but the session can’t push results back to that remote * **Self-hosted environments** : for a repository on another git host, see the [requirements for starting a session with `--environment`](</docs/en/self-hosted-environments-deploy#start-a-session-on-a-repository-outside-github>). -## - -​ - -Related resources +## Related resources * [Cloud environments](</docs/en/cloud-environments>): configure network access, environment variables, and setup scripts for cloud sessions * [Projects](</docs/en/claude-projects>): one conversation where Claude coordinates parallel cloud sessions on your repositories and reports back
modified Explore the .claude directory View current →
Show diff (175 lines)
--- a/claude-directory.md +++ b/claude-directory.md @@ -1,18 +1,10 @@ Claude Code reads instructions, settings, skills, subagents, and memory from your project directory and from `~/.claude` in your home directory. Commit project files to git to share them with your team; files in `~/.claude` are personal configuration that applies across all your projects. On Windows, `~/.claude` resolves to `%USERPROFILE%\.claude`. If you set [`CLAUDE_CONFIG_DIR`](</docs/en/env-vars>), every `~/.claude` path on this page lives under that directory instead. The same applies to `.claude.json`, which otherwise sits at `~/.claude.json`. Most users only edit `CLAUDE.md` and `settings.json`. If your repository already has an `AGENTS.md` for other coding agents, Claude Code [can read that](</docs/en/memory#agents-md>) in place of a `CLAUDE.md`. The rest of the directory is optional: add skills, rules, or subagents as you need them. -## - -​ - -Explore the directory +## Explore the directory Click files in the tree to see what each one does, when it loads, and an example. -## - -​ - -What’s not shown +## What’s not shown The explorer covers files you author and edit. A few related files live elsewhere: @@ -25,11 +17,7 @@ `~/.claude` also holds data Claude Code writes as you work: transcripts, prompt history, file snapshots, caches, and logs. See application data below. -## - -​ - -Choose the right file +## Choose the right file Different kinds of customization live in different files. Use this table to find where a change belongs. @@ -46,11 +34,7 @@ Connect external tools over MCP| `.mcp.json`| project only| [MCP](</docs/en/mcp>) Change how Claude formats responses| `output-styles/*.md`| project or global| [Output styles](</docs/en/output-styles>) -## - -​ - -File reference +## File reference This table lists every file the explorer covers. Project-scope files live in your repo under `.claude/` (or at the root for `CLAUDE.md`, `.mcp.json`, and `.worktreeinclude`). Global-scope files live in `~/.claude/` and apply across all projects. @@ -83,11 +67,7 @@ `keybindings.json`| Global only| | Custom keyboard shortcuts| [Keybindings](</docs/en/keybindings>) `themes/*.json`| Global only| | Custom color themes| [Custom themes](</docs/en/terminal-config#create-a-custom-theme>) -## - -​ - -Frontmatter fields by file +## Frontmatter fields by file Skills, command files, subagents, output styles, and rules read their configuration from YAML [frontmatter](</docs/en/glossary#frontmatter>) at the top of the file, and each accepts its own set of fields. This table lists the field names for each file and links to the reference that describes them. @@ -101,19 +81,11 @@ Agents shipped in a [plugin](</docs/en/plugins/components#agents>) honor a subset of the subagent fields. -## - -​ - -Troubleshoot configuration +## Troubleshoot configuration If a setting, hook, or file isn’t taking effect, see [Debug your configuration](</docs/en/debug-your-config>) for the inspection commands and a symptom-first lookup table. -## - -​ - -Application data +## Application data Beyond the config you author, `~/.claude` holds data Claude Code writes during sessions. These files are plaintext. Anything that passes through a tool is written to a transcript on disk: file contents, command output, pasted text. The transcript can also hold what Claude Code sends the model with your messages: @@ -122,11 +94,7 @@ * Request parameters * The instruction files it loaded, such as CLAUDE.md -### - -​ - -Cleaned up automatically +### Cleaned up automatically Claude Code deletes the files in the paths below once they’re older than [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>), as long as it can safely determine the retention period. The default is 30 days and the minimum is 1; setting `0` fails with a validation error. The same age cutoff applies to automatic removal of [orphaned worktrees](</docs/en/worktrees#clean-up-subagent-and-background-session-worktrees>). @@ -171,11 +139,7 @@ When [managed settings](</docs/en/managed-settings>) provide `cleanupPeriodDays`, Claude Code runs the sweep at the managed value even when a lower-priority settings file has errors. To check that the machines in your organization run the sweep with the retention period you set, see [Check the retention sweep](</docs/en/monitoring-usage#check-the-retention-sweep>). -### - -​ - -Session scratchpad directory +### Session scratchpad directory The scratchpad is a per-session directory that Claude Code gives Claude for temporary files: intermediate results, helper scripts, and drafts that don’t belong in your project. When Claude says it saved something “to the scratchpad”, the file is there. Claude uses it instead of `/tmp`, and can create, edit, and read files in it without a permission prompt. The scratchpad lives under Claude Code’s temp directory rather than `~/.claude`. Find the current session’s path for your platform: @@ -189,11 +153,7 @@ * The session uses the Anthropic API, not Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry * [`enableArtifact`](</docs/en/settings-reference#enableartifact>) isn’t set to `false` -### - -​ - -Kept until you delete them +### Kept until you delete them Apart from the rows that say otherwise, the retention cleanup sweep doesn’t remove the paths below, and Claude Code keeps them until you delete them. @@ -205,11 +165,7 @@ `cache/changelog.md`| Cached copy of the Claude Code changelog, shown by `/release-notes`. Refreshed in the background. `policy-limits.json`| Cached feature policy settings for your organization. Only present for some account types. Refreshed automatically. A `policy-limits.json.stamp.json` sidecar records which account or API key the cache belongs to. Claude Code deletes both files when you log out. -#### - -​ - -State files to keep +#### State files to keep Depending on which features you use, `~/.claude/` also holds files that the tables under Application data don’t list. Of those, caches and lock files are safe to delete. Keep these state files: @@ -217,11 +173,7 @@ * `agent-memory/`: [subagent memory](</docs/en/sub-agents#enable-persistent-memory>) * `jobs/` and `daemon/`: [background session](</docs/en/agent-view#where-state-is-stored>) state -### - -​ - -Plaintext storage +### Plaintext storage Transcripts and history are not encrypted at rest. OS file permissions are the only protection. If a tool reads a `.env` file or a command prints a credential, that value is written to `projects/<project>/<session>.jsonl`. To reduce exposure: @@ -230,11 +182,7 @@ * Set the [`CLAUDE_CODE_SKIP_PROMPT_HISTORY`](</docs/en/env-vars>) environment variable to skip writing transcripts and prompt history in any mode. In non-interactive mode, you can instead pass `--no-session-persistence` alongside `-p`, or set `persistSession: false` in the TypeScript Agent SDK; the Python SDK has no equivalent option. * Use [permission rules](</docs/en/permissions>) to deny reads of credential files -### - -​ - -Clear local data +### Clear local data Run `claude purge` to delete the state Claude Code holds for one project. It deletes: @@ -300,11 +248,7 @@ Don’t delete `~/.claude.json`, `~/.claude/settings.json`, or `~/.claude/plugins/`: those hold your account details, preferences, and installed plugins. -## - -​ - -Related resources +## Related resources * [Manage Claude’s memory](</docs/en/memory>): write and organize CLAUDE.md, rules, and auto memory * [Configure settings](</docs/en/settings>): set permissions, hooks, environment variables, and model defaults
modified Claude Code on Claude Platform on AWS View current →
Show diff (174 lines)
--- a/claude-platform-on-aws.md +++ b/claude-platform-on-aws.md @@ -4,11 +4,7 @@ Some Claude Code features are unavailable or work differently on Claude Platform on AWS. See the [feature availability matrix](</docs/en/feature-availability#summary-by-provider>) and the [features that need feature-flag fetching](</docs/en/env-vars#features-that-need-feature-flag-fetching>). -## - -​ - -Prerequisites +## Prerequisites Before configuring Claude Code, you need: @@ -17,28 +13,16 @@ * An IAM principal with permission to invoke the Anthropic service, or an API key scoped to the workspace * AWS credentials in your environment, in `~/.aws/credentials`, or from an attached IAM role if you want SigV4 authentication. The AWS CLI is required only for the SSO login flow. -## +## Setup -​ - -Setup - -### - -​ - -1\. Configure AWS credentials +### 1\. Configure AWS credentials Claude Code supports two authentication methods for Claude Platform on AWS. Choose the method that fits how your team manages access: * AWS credentials with SigV4: authenticate as an IAM principal, with credentials from the standard AWS credential chain * Workspace API key: authenticate with a long-lived key you generate in the AWS Console -#### - -​ - -Use AWS credentials with SigV4 +#### Use AWS credentials with SigV4 Claude Code signs requests with SigV4 using the standard AWS credential chain: environment variables, shared credentials in `~/.aws/credentials`, IAM roles, AWS SSO sessions, and any other sources the AWS SDK supports. For local use, log in with the AWS CLI before starting Claude Code. The example below uses an SSO profile, but any method that produces credentials in the standard locations works. @@ -53,11 +37,7 @@ Claude Code also runs this command at startup when it can’t validate your existing AWS credentials, and shows the command’s output in an `Authentication` panel until the login completes. With `awsAuthRefresh` configured, run `/login`, select **3rd-party platform** , then select **Claude Platform on AWS · refresh credentials** under **Using 3rd-party platforms**. Claude Code runs the configured command and re-reads your AWS credentials without a restart. -#### - -​ - -Use a workspace API key +#### Use a workspace API key A workspace API key is a long-lived secret, useful when you don’t want to manage federated AWS credentials. Generate one in the AWS Console under **Claude Platform on AWS → API keys** and set it as `ANTHROPIC_AWS_API_KEY`: @@ -67,11 +47,7 @@ The `/login` and `/logout` commands don’t sign you into a claude.ai subscription for Claude Platform on AWS. Authentication runs through your AWS credentials or workspace API key. -### - -​ - -2\. Configure Claude Code +### 2\. Configure Claude Code Set the environment variables that route Claude Code through Claude Platform on AWS instead of the default Anthropic API. @@ -81,11 +57,7 @@ `ANTHROPIC_AWS_WORKSPACE_ID` is required. Claude Code sends it on every request as the `anthropic-workspace-id` header. Replace the example `wrkspc_01ABCDEFGHIJKLMN` value with your own workspace ID from your Claude Platform on AWS setup. Claude Code computes the base URL as `https://aws-external-anthropic.{region}.api.aws` from the AWS region, which it resolves with the [same precedence as Amazon Bedrock](</docs/en/amazon-bedrock#3-configure-claude-code>). To override the URL directly, set `ANTHROPIC_AWS_BASE_URL`. Claude Platform on AWS is opt-in even when AWS credentials are present in your environment. Amazon Bedrock and Microsoft Foundry take precedence in provider routing, so unset `CLAUDE_CODE_USE_BEDROCK` and `CLAUDE_CODE_USE_FOUNDRY` if they’re set. -### - -​ - -3\. Pin model versions +### 3\. Pin model versions Claude Platform on AWS uses the same model IDs as the direct Claude API. The default aliases `fable`, `opus`, `sonnet`, and `haiku` resolve to Claude Code’s built-in defaults for Claude Platform on AWS, which can lag the newest release. Without `ANTHROPIC_DEFAULT_OPUS_MODEL`, the `opus` alias resolves to Opus 5.5. Before v2.1.280, it resolved to Opus 5 from v2.1.219. If you deploy Claude Code to a team, pin the model IDs explicitly so a new release doesn’t move everyone at once: @@ -96,11 +68,7 @@ For the full list of model IDs and aliases, see [Models overview](<https://platform.claude.com/docs/en/about-claude/models/overview>). For other model-related variables, see [Model configuration](</docs/en/model-config>). [Prompt caching](</docs/en/prompt-caching>) is enabled automatically. To request a 1-hour cache TTL instead of the 5-minute default, set `ENABLE_PROMPT_CACHING_1H=1`. The API bills 1-hour cache writes at a higher rate. See [prompt caching pricing](<https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pricing>) for the rates. To set different TTLs for your main conversation and for the requests Claude Code makes outside it, [choose the TTL yourself](</docs/en/prompt-caching#choose-the-ttl-yourself>). -### - -​ - -4\. Launch and verify +### 4\. Launch and verify Start Claude Code and confirm the routing: @@ -108,11 +76,7 @@ The startup banner shows `Claude Platform on AWS` when the provider is active. Run `/status` to check the details: the `API provider` line reads `Claude Platform on AWS`, and the output includes your `Workspace ID`, the `AWS region`, and the `Claude Platform on AWS base URL` if you set an override. -## - -​ - -Use the Agent SDK +## Use the Agent SDK The [Agent SDK](</docs/en/agent-sdk/overview>) reads the same environment variables as the CLI, so any program that spawns the Claude Code subprocess can target Claude Platform on AWS by exporting `CLAUDE_CODE_USE_ANTHROPIC_AWS`, `ANTHROPIC_AWS_WORKSPACE_ID`, and either `ANTHROPIC_AWS_API_KEY` or AWS credentials before the call. @@ -128,11 +92,7 @@ This example relies on the ambient AWS credential chain for SigV4. To authenticate with a workspace API key instead, set `ANTHROPIC_AWS_API_KEY` the same way. For the broader Agent SDK surface, see [Agent SDK overview](</docs/en/agent-sdk/overview>). -## - -​ - -Route through a corporate proxy +## Route through a corporate proxy To route traffic through a proxy or [LLM gateway](</docs/en/llm-gateway>), set `ANTHROPIC_AWS_BASE_URL` to the proxy’s address. Claude Code sends requests to that URL with the same workspace and authentication headers, so any gateway that forwards them unchanged works. @@ -147,43 +107,23 @@ export ANTHROPIC_AWS_WORKSPACE_ID=wrkspc_01ABCDEFGHIJKLMN export ANTHROPIC_AWS_BASE_URL=https://anthropic-proxy.example.com -## - -​ - -Troubleshooting +## Troubleshooting Run `/status` to see the resolved provider and any explicitly configured workspace ID, region, base URL override, and auth-skip setting. This is the fastest way to confirm Claude Code is targeting Claude Platform on AWS at all. -### - -​ - -`403 Forbidden` or `AccessDenied` on every request +### `403 Forbidden` or `AccessDenied` on every request The IAM principal Claude Code resolved likely lacks permission to invoke the Anthropic service in your workspace. Check the role attached to your AWS profile or the runner that started Claude Code, and verify it has the `aws-external-anthropic` actions documented in the [IAM action reference](<https://platform.claude.com/docs/en/api/claude-platform-on-aws-iam-actions>). If you set `ANTHROPIC_AWS_API_KEY`, the key takes precedence over SigV4 and a stale key produces the same error. Regenerate the key in the AWS Console under **Claude Platform on AWS → API keys** or unset the variable to fall back to your AWS credentials. -### - -​ - -Requests fail with a missing-workspace error +### Requests fail with a missing-workspace error `ANTHROPIC_AWS_WORKSPACE_ID` is likely unset or empty. Every Claude Platform on AWS request must include the workspace ID. It is not implied by your AWS credentials. Find the ID in your Claude Platform on AWS setup and export it before starting Claude Code. -### - -​ - -Requests still go to `api.anthropic.com` +### Requests still go to `api.anthropic.com` `CLAUDE_CODE_USE_ANTHROPIC_AWS` is likely unset or set to a value that doesn’t parse as truthy. Set it to `1` and run `/status` to confirm the resolved provider. If `CLAUDE_CODE_USE_BEDROCK` or `CLAUDE_CODE_USE_FOUNDRY` is also set, those take precedence over Claude Platform on AWS. -## - -​ - -Additional resources +## Additional resources The Claude Platform on AWS subscription, workspace, and IAM setup that comes before configuring Claude Code is covered in the platform documentation:
modified Let Claude coordinate ongoing work with Projects View current →
Show diff (519 lines)
--- a/claude-projects.md +++ b/claude-projects.md @@ -8,11 +8,7 @@ If you already know the work you want a project to run, go straight to Create a project. -## - -​ - -When to use a project +## When to use a project A project is worth creating when the work has a goal that outlasts one session and keeps producing tasks. These kinds of work suit a project well: @@ -23,11 +19,7 @@ In any of them you can send a batch of tasks, tell Claude to start without asking you to confirm, and walk away. When you’re back, you can find the threads that need you under **Waiting on you**. You can also ask Claude to put part of the work on a schedule as a [cloud scheduled task](</docs/en/routines>). If one of these is your situation, create a project. -### - -​ - -When something else fits better +### When something else fits better A project still fits when only some tasks need your machine. Cloud threads work on GitHub repositories and on the files, folders, and Google Drive folders you upload to the project, and for the occasional task that needs a local database or a tool on your computer, you can ask Claude to run that task’s thread on your computer. Something other than a project fits better in these cases: @@ -38,11 +30,7 @@ A project draws on the same plan limits as your other Claude Code sessions and uses them faster. Usage and cost covers what draws on your plan and how to keep it down. -## - -​ - -How a project is organized +## How a project is organized A project is one coordinating conversation with Claude plus the threads it starts to do the work. These are its parts: @@ -57,11 +45,7 @@ Cloud threads don’t pick up anything from the Claude Code setup on your own machine. Get skills, plugins, connectors, and tools into threads covers how to give them what they’d otherwise be missing. Here is how those parts connect, from you through the conversation to the threads doing the work, with Overview tracking their state: -## - -​ - -Create a project +## Create a project You create and use projects at [claude.ai/code](<https://claude.ai/code>), in the Code tab of the desktop app, or in the Claude mobile app for [iOS](<https://apps.apple.com/us/app/claude-by-anthropic/id6473753684>) and [Android](<https://play.google.com/store/apps/details?id=com.anthropic.claude>). In the browser and the desktop app there are two ways to start a project: @@ -70,11 +54,7 @@ Either way, check the prerequisites first. -### - -​ - -Check the prerequisites +### Check the prerequisites Before you create a project, check your plan, your GitHub setup, and what the work needs to reach: @@ -82,11 +62,7 @@ * **GitHub, if the project will work on code** : your code is on github.com rather than GitHub Enterprise Server, GitLab, or Bitbucket, your connected GitHub account has push access to it, and the Claude GitHub App is installed on it. If you connected GitHub with [`/web-setup`](</docs/en/web-quickstart#connect-from-your-terminal>), that token lets your other cloud sessions reach a repository but isn’t enough for a project’s cloud threads, which need the Claude GitHub App. Set up GitHub access has the steps. * **Network access, secrets, and tools** : for cloud threads, these come from the project’s cloud environment. The default environment already reaches [common package registries](</docs/en/cloud-environments#default-allowed-domains>), so check this only if the work needs other domains, a secret, or a tool that isn’t preinstalled. If the work needs an MCP server, check that it shows as connected in your [claude.ai connectors](<https://claude.ai/customize/connectors>). -### - -​ - -Start a new project from scratch +### Start a new project from scratch Starting a project from scratch means opening the **New project** dialog, naming the stream of work, and optionally giving it a goal and the repositories and files it works on. Only the name is required, so you can create the project first and fill in the rest as the work takes shape. @@ -119,11 +95,7 @@ The project is now in the sidebar, and its conversation is open. Your first batch covers what to set up before you send it work. -### - -​ - -Start from an existing session +### Start from an existing session If a cloud session you started yourself is doing work that belongs in a project, open its sidebar menu and choose **Continue in project** , then pick from the submenu: @@ -137,11 +109,7 @@ If **Require trusted devices** is on, or you don’t use Remote Control, describe the work in the project conversation yourself. Or push the session’s branch, add its repository to the project, and tell Claude the branch name. -### - -​ - -Set up GitHub access +### Set up GitHub access Most GitHub setup happens once, not per project. You connect your GitHub account to Claude once, and the Claude GitHub App is installed once per repository, or once for a whole GitHub organization if you give it all repositories. You come back to these steps when you add a repository the Claude GitHub App doesn’t cover yet or one in a GitHub organization that enforces SSO. @@ -165,19 +133,11 @@ When one of these steps is incomplete, the **New project** dialog and the project page name the missing step and link to where you finish it. Finish the step there, then click **Check again** if the dialog offers it. If a repository is still missing from the list afterward, open the Claude GitHub App’s installation on GitHub, at [github.com/settings/installations](<https://github.com/settings/installations>) for a personal account, and confirm the repository is listed under **Repository access**. For the error messages a thread or the project reports when access is still wrong, see Repository access errors. -## - -​ - -Work in a project +## Work in a project Give Claude work through the project conversation: tasks one at a time or several at once, plus updates and loose thoughts as they come up. Claude routes each message, and threads do the work and report back. -### - -​ - -Your first batch +### Your first batch Before you send a new project a batch of work, set it up so the first threads come back the way you want: @@ -186,11 +146,7 @@ 3. Check **Thread model** and **Thread effort** in **Project settings > General**. A new project runs every thread on Opus at high effort, which draws on your plan fastest; Choose models and let Claude manage context covers the alternatives. 4. Ask Claude to propose threads before starting them and to run a few at a time, and drop those limits once a few threads come back the way you want. -### - -​ - -Send work and read results +### Send work and read results Claude decides where each message you send in the conversation goes: @@ -200,11 +156,7 @@ If Claude routes something differently than you wanted, say so. Tune how Claude runs a project lists things you can tell it, such as reusing an existing thread for follow-ups or answering in place instead of starting a thread. A thread’s full results stay in the thread, and you open its card in the conversation to read them. Files a thread produced are also in the project’s **Library**. Sometimes Claude proposes threads instead of starting them, in a **Suggested threads** list. Click the arrow on a suggestion to start that thread. When several are listed, a button under the list starts all of them. -### - -​ - -Review a thread’s pull request +### Review a thread’s pull request When a cloud thread changes code, this is what it does unless you tell it otherwise: @@ -220,11 +172,7 @@ To change when threads open pull requests, for example only when you ask, or which branch they start from, say so in the task or in project instructions. -### - -​ - -See what needs you in Overview +### See what needs you in Overview The Overview pane beside the conversation tracks the project’s threads. It’s already open the first time you open a new project. To reopen it after you close it, click the **Threads** button in the project header. The button shows a dot when a thread is waiting on you. In the desktop app, a notification appears by default when Claude posts in the conversation, a thread hits an error, or a thread needs your input. None appears while you’re viewing the project. To also get one each time a thread finishes a turn, or to turn them off for a project, choose **Notifications** in the project’s sidebar menu. In a browser, check the dot on the **Threads** button. The pane’s **Threads** view groups threads by state: @@ -242,11 +190,7 @@ * **Library** : the files and folders you added and the files that threads produced. Click the **Library** button beside **Threads**. * **Scheduled tasks** : the [cloud scheduled tasks](</docs/en/routines>) Claude set up from this project. Select it in the header’s **⋯** menu. -### - -​ - -Open a thread when you need control +### Open a thread when you need control Click a thread’s card in the conversation or its row in Overview to open its transcript in the Overview pane. From there you can: @@ -255,11 +199,7 @@ * Answer a permission prompt the thread is waiting on. * Interrupt the thread with **Stop** , which replaces the send button while the thread is working, or by pressing Esc. -### - -​ - -Choose models and let Claude manage context +### Choose models and let Claude manage context Set models and effort in **Project settings > General**. A new project runs Opus everywhere, with high [effort](</docs/en/model-config#adjust-effort-level>) for threads and low effort for the conversation: @@ -268,11 +208,7 @@ You don’t manage context windows in a project. Threads compact automatically, and the conversation works from recent messages, recent threads, and project memory rather than its full history, so it keeps going for as long as the project runs. Put anything that must never be dropped in project memory. If one thread outgrows its context, it shows Claude ran out of context on this turn. -### - -​ - -Tune how Claude runs a project +### Tune how Claude runs a project Tell Claude in the conversation how many threads to run at once, when to post updates, and when to open pull requests. If Claude is coordinating in a way you don’t want, say so. For example, you can say: @@ -287,19 +223,11 @@ Claude saves preferences like these to project memory on its own and follows them in later cloud threads. They’re instructions Claude keeps to, not enforced settings, so a thread limit you give this way isn’t a hard cap. Add one to project instructions when you want it worded exactly and applied to every thread from the start. -### - -​ - -Unblock a thread waiting on approval +### 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. Cloud threads don’t read [permission rules](</docs/en/permissions>) from a repository’s `.claude/settings.json`, so you rely on auto mode and on the approvals you give inside each thread. -### - -​ - -Run a thread on your own computer +### Run a thread on your own computer When a task needs something only your computer has, such as a local database, a device emulator, or an API behind your VPN, ask Claude to run the thread for that task on your computer instead of in the cloud. When you ask in the project conversation, the thread is a Claude Code session in a folder on your machine, connected through [Remote Control](</docs/en/remote-control>). The project’s other threads keep running in the cloud. Compared with a cloud thread, a thread on your computer: @@ -328,18 +256,14 @@ Claude answers with an **Allow Claude to work in a folder on your device** card. Pick the folder if you connected several. Two threads working in one folder at the same time can overwrite each other’s changes, so if the folder is a git repository, you can turn on **Worktree** in the folder’s options to give this thread its own worktree instead. Then click **Allow once**. -The thread runs in [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>), so Claude runs commands and edits files in that folder without asking you each time. If auto mode is unavailable or turned off in that computer’s Claude Code, the thread runs without it, and any permission prompt it raises waits for your answer in the thread, as Unblock a thread waiting on approval describes. While the thread runs, a laptop icon in its header shows whether your computer is connected. Click it to see which folder the thread is using or to turn the connection off. The thread pauses while that computer is asleep, and stops if the desktop app or `claude remote-control` quits. +The thread runs in [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>), so Claude runs commands and edits files in that folder without asking you each time. If auto mode is unavailable or turned off in that computer’s Claude Code, the thread runs without it, and any permission prompt it raises waits for your answer in the thread, as Unblock a thread waiting on approval describes. To run the thread in another mode, start `claude remote-control` with [`--settings`](</docs/en/remote-control#start-a-remote-control-session>). Then [`permissions.defaultMode`](</docs/en/permission-modes#start-in-a-different-mode>), in that file or in that computer’s settings, can pick another mode. While the thread runs, a laptop icon in its header shows whether your computer is connected. Click it to see which folder the thread is using or to turn the connection off. The thread pauses while that computer is asleep, and stops if the desktop app or `claude remote-control` quits. * **To get the thread going again** : see Lost contact with your folder * **To keep the computer from sleeping on its own** : in the desktop app, turn on **Keep this computer awake for Remote Control** in **Settings > Code** or **Settings > Claude Code** A project can’t run a thread on your computer while [**Require trusted devices**](</docs/en/remote-control#trusted-devices>) is on for your account. -## - -​ - -Give a project standing context +## Give a project standing context Project memory, project instructions, and the project’s repositories, files, and environment carry context across threads. You set each one once. @@ -351,11 +275,7 @@ **Project settings > Memory** lists these files under **Auto memory** , because Claude writes them itself as it works in the project. They’re separate from the [auto memory](</docs/en/memory>) Claude Code keeps on your machine, even though both use a `MEMORY.md` index. Project memory is also separate from the `CLAUDE.md` files in the project’s repositories. Each cloud thread still reads those `CLAUDE.md` files from its clone when it starts, so put instructions about a repository in its `CLAUDE.md` and notes about the project in project memory. -### - -​ - -Write project instructions +### Write project instructions Project instructions are the brief every new thread starts from. Select **Settings** in the **⋯** menu in the project header to open **Project settings** , then go to **Memory > Project instructions**. A useful brief covers: @@ -376,11 +296,7 @@ Rules about one repository, such as its build commands, belong in that repository’s `CLAUDE.md`, which every cloud thread reads when the repository is part of the project. Once work is underway, when you correct a thread, also tell Claude to remember the correction: it goes into project memory and later cloud threads start with it. -### - -​ - -Decide which repositories to add +### Decide which repositories to add The repositories you add to a project come with their code and `CLAUDE.md` in every cloud thread, but not their skills, `.claude/settings.json`, or `.mcp.json`. Repositories you don’t add are still within reach: a cloud thread can add one to itself when its task needs it. Most projects use both: @@ -389,11 +305,7 @@ A project doesn’t need a repository at all. Its cloud threads can still research, write documents, and write and run code in their own sandbox. They deliver files to the project’s **Library**. Any of its cloud threads can still add a repository to itself when a task calls for one. Once the project has repositories, Claude can only add repositories from a GitHub owner the project already uses, whether it adds one to the project or a thread adds one to itself. To bring in a repository from a different owner, add it to the project yourself in **Project settings > Environment**. For a project that spans many repositories, such as one feature with server, web, mobile, and desktop code, add the one or two repositories nearly every task touches and name the others in project instructions so Claude knows where the rest of the code lives. Cloud threads then start small and pull in the other repositories only for the tasks that need them. -### - -​ - -Add files and folders +### Add files and folders Add the files and folders you want threads to read in the **New project** dialog’s **Context** field, or afterward with **Add** in the project’s **Library**. These limits apply to what you add: @@ -401,11 +313,7 @@ * **Folders you upload** : hidden files and `node_modules` aren’t added. A project holds up to 10 folders and Google Drive folders combined, and single files don’t count toward that limit. * **Changes after upload** : uploads are copies, so a change you make on your computer afterward doesn’t reach the project until you upload the file again and choose **Replace** when asked about the existing name. -### - -​ - -What threads pick up from your repositories +### What threads pick up from your repositories Cloud threads load each repository’s `CLAUDE.md` instructions but not its skills, `.mcp.json` servers, or `.claude/settings.json`, whether the project has one repository or several. @@ -420,19 +328,11 @@ Hooks in `.claude/settings.json`| Not run. To use your hooks, run the thread on your own computer `env` in `.claude/settings.json`| Not applied. Set environment variables in the cloud environment -### - -​ - -Choose an environment for threads +### Choose an environment for threads Every new cloud thread starts in the project’s [cloud environment](</docs/en/cloud-environments>). The environment sets which domains threads can reach, which environment variables they have, which network secrets are added to their requests, and what the setup script installs before Claude starts. Cloud threads use a default Anthropic-hosted environment until you pick one in **Project settings > Environment**. If cloud threads need to reach an internal API or a private package registry, or need a token your machine normally holds, change the environment rather than the project: see [Network access](</docs/en/cloud-environments#network-access>), [Add network secrets](</docs/en/cloud-environments#add-network-secrets>), and [Setup scripts](</docs/en/cloud-environments#setup-scripts>). -### - -​ - -Get skills, plugins, connectors, and tools into threads +### Get skills, plugins, connectors, and tools into threads 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: @@ -443,11 +343,7 @@ To see which connectors a running cloud thread has at claude.ai/code, open the thread and select **Connectors** from the **+** menu beside its message box. Turning a connector off there removes it from that thread and saves that as your account default, so new threads and claude.ai chats start without it until you turn it back on. A cloud thread picks up a connector you add or reconnect after the next message you send it. -## - -​ - -Project settings reference +## Project settings reference You change project settings at claude.ai/code or in the desktop app, not in `settings.json`. Open **Project settings** from **Settings** in the project’s sidebar menu or in the project header’s **⋯** menu. Settings save as you change them; a text field you’re editing, such as the goal or instructions, shows **Save changes** and **Discard** until you leave it. Changes to instructions, repositories, plugins, and environment in **Project settings** reach new threads, not threads already running. @@ -466,11 +362,7 @@ Restart Claude| General| Restarts the project conversation when Claude stops responding there Pause, Archive, Delete| General| Stops, hides, or removes the project; see Pause, archive, or delete a project -### - -​ - -Pause, archive, or delete a project +### Pause, archive, or delete a project All three controls are at the bottom of **Project settings > General**: @@ -478,19 +370,11 @@ * **Archive** : hides the project from the sidebar and archives its threads, which stops any thread that was running or watching a pull request. Scheduled tasks in the project don’t run while it’s archived. To bring the project back, open it from the Projects page and click **Unarchive**. Its threads stay archived until you unarchive them individually from the session list. * **Delete** : permanently removes the project along with its threads, its memory, and its files, and turns off the project’s scheduled tasks. This can’t be undone. Branches and pull requests the threads pushed to GitHub aren’t affected. -## - -​ - -Usage and cost +## Usage and cost Project usage counts against the same [plan limits](</docs/en/errors#youve-hit-your-session-limit>) as your other Claude Code sessions, and a project can’t spend past those limits on its own. A thread that stops at your plan’s limit waits and by default continues on its own when the limit resets. Its work then counts against your next usage window. To keep threads from continuing, see A thread hit the usage limit. Work goes past your plan’s limits only if you have turned on [usage credits](</docs/en/costs#add-usage-credits-to-your-subscription>) for your account. A thread can’t turn them on for you. -### - -​ - -What draws on your plan +### What draws on your plan A project uses your limits faster than a single session does, and on a Pro plan in particular you should expect to reach your limit sooner on days you run one. These are the parts of a project that use your plan: @@ -500,11 +384,7 @@ A project with no running threads, no watched pull requests, and no new messages doesn’t use your plan while it sits idle, and neither does an archived project. -### - -​ - -See and reduce a project’s usage +### See and reduce a project’s usage Open **Usage** in **Project settings** to see token use by thread and by model, and how much went to the project conversation. To bring it down: @@ -512,11 +392,7 @@ * For work that doesn’t need the largest model, choose a smaller model or a lower effort level for threads, the conversation, or both. * Ask Claude in the project conversation to run fewer threads at a time, or to answer small questions itself instead of starting a thread. -## - -​ - -How projects relate to other Claude Code features +## How projects relate to other Claude Code features Several Claude Code features let more than one session work at the same time, so running work in parallel is not by itself what a project is for. In a project, Claude starts and tracks the sessions instead of you, and each one starts from the same instructions. This is how each neighboring feature connects to a project: @@ -532,11 +408,7 @@ [Run agents in parallel](</docs/en/agents>) compares these options side by side. -## - -​ - -Limitations +## Limitations * Projects are available at claude.ai/code, in the desktop app, and in the Claude mobile app, not in the terminal CLI, the VS Code extension, or the JetBrains plugin, and not through Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry. * Project threads are [cloud sessions](</docs/en/claude-code-on-the-web>), or sessions on your own machine through [Remote Control](</docs/en/remote-control>), with Anthropic as the model provider in both cases. [Security](</docs/en/security>) and [Data usage](</docs/en/data-usage>) cover how cloud sessions are isolated and what’s retained, and [Connection and security](</docs/en/remote-control#connection-and-security>) covers how a thread on your machine connects and what’s stored. @@ -545,27 +417,15 @@ * A project belongs to one user. You can’t share a project or its threads with another user, and thread transcripts don’t have the share option other cloud sessions have. There are no organization-level controls for projects during the beta. * A thread belongs to the one project that started it. You can’t move or copy a thread to another project, or move it out to stand alone. **Continue in project** goes the other way only: it brings a cloud session’s work into a project. You can’t merge two projects into one. -## - -​ - -Troubleshooting +## Troubleshooting For the GitHub setup prompts in the **New project** dialog, see Set up GitHub access. -### - -​ - -A thread looks stuck +### A thread looks stuck Claude doesn’t post each step a thread takes, so a thread that shows as running with no new messages in the project conversation is usually still working. A new cloud thread also provisions its [cloud environment](</docs/en/cloud-environments>) before Claude begins, so its first update takes a moment. Open the thread to read its transcript. If the thread is waiting on a permission prompt, answer it there. -### - -​ - -Threads guessed or stalled instead of asking +### Threads guessed or stalled instead of asking When several threads come back having assumed something wrong, worked around missing access, or stopped with “blocked”, the cause is usually the same gap in the project’s setup rather than a problem with each task. Sort out which threads are sound before you fix anything: @@ -573,19 +433,11 @@ 2. For threads that started from a wrong assumption, open the thread from Overview and mark it resolved from its menu, or tell it what to do instead. Its branch and any pull request stay on GitHub until you delete them. 3. Fix the gap once, in project instructions or the environment, then send one thread before sending the rest of the work again as new threads. -### - -​ - -Claude hasn’t responded +### Claude hasn’t responded The project conversation shows a “Claude hasn’t responded” banner when Claude is running but its replies aren’t reaching the project. Click **Restart Claude** on the banner, or go to **Project settings > General** and click **Restart** in the **Restart Claude** row. Claude reconnects to the conversation; any reply it was in the middle of writing is lost, and threads aren’t affected. -### - -​ - -Repository access errors +### Repository access errors Three messages mean a thread or the project can’t reach one of its repositories. A project’s cloud threads need the GitHub prerequisites even when your other cloud sessions clone the same repository without trouble. @@ -595,38 +447,22 @@ To fix GitHub access for “Couldn’t start the session” or “Unable to access your repository”, click the button the message offers, such as **Install on GitHub** or **Select repositories**. If there’s no button, follow Set up GitHub access. After the fix, ask Claude in the project conversation to start a new thread for the same work. -### - -​ - -A thread hit the usage limit +### A thread hit the usage limit When a thread or the project conversation stops at your plan’s five-hour or weekly limit, it waits and by default continues on its own when the limit resets. To keep a thread or conversation from continuing at the reset time its message shows, turn off **Auto-continue when usage limits reset** in **Project settings > General** before then. The setting is for the whole project, not only the thread you’re looking at. To continue with the setting off, send the thread or conversation a message after the reset. [Usage limit errors](</docs/en/errors#youve-hit-your-session-limit>) explain the limits and when they reset. -### - -​ - -Additional usage credits are required +### Additional usage credits are required A thread or the project conversation made a request your plan covers only with usage credits, such as one to a model or context size your plan doesn’t include, and usage credits aren’t turned on for your account. [Add usage credits to your subscription](</docs/en/costs#add-usage-credits-to-your-subscription>) covers who can turn them on or buy them on each plan. Once credits are available, send another message to retry. -### - -​ - -Lost contact with your folder +### Lost contact with your folder A thread running on your computer shows this when the Claude Code session there stopped responding, usually because the computer went to sleep or the desktop app or `claude remote-control` quit. Wake the computer. If the desktop app or `claude remote-control` is no longer running there, start it again: * **Desktop app** : reopen the app and confirm **Use this computer from your phone and claude.ai** is still on under **Settings > Code** or **Settings > Claude Code** * **Terminal** : run `claude remote-control` again in the same folder -### - -​ - -Other messages +### Other messages These messages name their own cause. The table gives the next step for each. @@ -642,11 +478,7 @@ ”Claude is out of date on your device”| The computer you picked to run a thread has a Claude Code version older than v2.1.280. Update Claude Code there, or update the desktop app if that’s what connects the folder, then ask Claude to run the task again ”Reached the turn limit”| The thread reached the cap on agentic turns that [`CLAUDE_CODE_MAX_TURNS`](</docs/en/env-vars>) sets. Send another message to continue, or raise or remove that variable where it’s set -## - -​ - -Related resources +## Related resources * [Use Claude Code in the cloud](</docs/en/claude-code-on-the-web>): how the cloud sessions behind each cloud thread work, including GitHub access options and auto-fix on pull requests * [Configure cloud environments](</docs/en/cloud-environments>): change what cloud threads can reach on the network, give them environment variables and network secrets, and install tools with a setup script
modified Scan your codebase for vulnerabilities View current →
Show diff (172 lines)
--- a/claude-security.md +++ b/claude-security.md @@ -1,10 +1,6 @@ The Claude Security plugin runs a multi-agent vulnerability scan of your codebase inside a Claude Code session. By default, when you scan a whole repository, Claude agents map your architecture, build a threat model, hunt for vulnerabilities, and independently review every finding before writing the report. Use the plugin to scan a whole repository or only a set of changes, such as a branch’s diff, a pull request’s diff, or a single commit, then turn the findings you choose into patches that you review and apply yourself. The plugin runs locally in your session, uses whichever models you have access to in Claude Code, and each scan counts toward your [usage](</docs/en/costs>). If you want a managed service that monitors your repositories, or want to run scans on [Claude Mythos](<https://platform.claude.com/docs/en/about-claude/models/introducing-claude-fable-5-and-claude-mythos-5>), see the [Claude Security](<https://claude.com/product/claude-security>) product, available on the Enterprise plan. The plugin is also distinct from the review tools already in Claude Code: the [security guidance plugin](</docs/en/security-guidance>) reviews code as Claude writes it, [`/security-review`](</docs/en/commands#all-commands>) runs a single pass over your branch, and [Code Review](</docs/en/code-review>) reviews pull requests. For how the layers stack, see How the plugin fits with other security tools. -## - -​ - -Prerequisites +## Prerequisites To run the plugin, you need: @@ -13,11 +9,7 @@ * Linux, macOS, or Windows. * Git, for change scans and for turning findings into patches; those jobs don’t support other version control systems. A full scan works in any directory, with or without version control. -## - -​ - -Models and providers +## Models and providers A scan runs inside your Claude Code session. The plugin makes no model calls of its own, so there’s no separate API key or provider setting to configure. @@ -26,11 +18,7 @@ On a third-party provider, the `sonnet` alias can resolve to a different version than it does on the Anthropic API. If your account can’t use that version, [pin your model versions](</docs/en/model-config#pin-models-for-third-party-deployments>), including `ANTHROPIC_DEFAULT_SONNET_MODEL`. [Automatic model fallback](</docs/en/model-config#automatic-model-fallback>) re-runs a request that a model’s safeguards flag. On Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry, the request can end with a refusal message instead, depending on [how your deployment is set up](</docs/en/model-config#enable-fallback-on-bedrock-agent-platform-and-foundry>). -## - -​ - -Install the plugin +## Install the plugin In the VS Code extension or the desktop app, install it by following [Install a plugin](</docs/en/plugins/install#install-a-plugin>). In a terminal, start Claude Code by running `claude`, then enter this at its prompt to install from the [official Anthropic marketplace](</docs/en/plugins/anthropic-marketplaces>): @@ -43,27 +31,15 @@ Check the install summary. If it reports `Run /reload-plugins to apply.`, see [Apply plugin changes without restarting](</docs/en/plugins/cli-reference#reload-plugins>) to activate the plugin in your current session. Once the plugin is active, you’re ready to scan and fix your codebase. -### - -​ - -Update the plugin +### Update the plugin To update the plugin yourself, see [Update plugins now](</docs/en/plugins/install#update-plugins-now>). Claude Code also [updates the plugin automatically](</docs/en/plugins/install#keep-plugins-updated>) unless auto-update is turned off. -### - -​ - -Uninstall the plugin +### Uninstall the plugin To remove the plugin, uninstall it from the `/plugin` menu, or run `claude plugin uninstall claude-security` in your terminal. -## - -​ - -Scan and fix your codebase +## Scan and fix your codebase The plugin adds one command, `/claude-security`, which opens a menu of its three jobs: scanning the codebase, scanning a set of changes, and suggesting patches. The happy path runs a full scan, then turns its findings into patches: @@ -105,27 +81,15 @@ You don’t have to start from the menu: ask for a job directly, as arguments to the command, such as `/claude-security scan my branch`, or in plain language, such as “scan commit abc1234”. The plugin works best in [auto mode](</docs/en/permission-modes>), which lets the scan’s agents proceed without a permission prompt at each step. -### - -​ - -Scan only your changes +### Scan only your changes When your branch has commits its base doesn’t, the `/claude-security` menu offers to scan only that diff, so you can check a branch before merging. You can also scan one of your open pull requests, or a single commit by asking for it, such as “scan commit abc1234”. Only committed changes are scanned: commit or stash in-progress edits first, or run a full scan, which reads the working tree. Change scans need a git repository; full scans of an unversioned directory still work. Finding your open pull requests is offered only when your session already has permission to run the GitHub CLI and `gh` is signed in. -### - -​ - -Scope large repositories +### Scope large repositories On a large repository, scan one area at a time instead of the whole tree. Pick one of the focused scopes the plugin offers, such as your API layer or your authentication code, and the run sizes itself to what you pick. The report’s coverage section states what was and wasn’t examined. Run another scan on a different area anytime. -### - -​ - -Choose a scan effort +### Choose a scan effort Scan effort sets how deep a scan goes. Your findings go through the same independent verification at `low`, `medium`, and `high`. @@ -135,11 +99,7 @@ Name the scan effort in your request at the Claude Code prompt, such as `/claude-security scan my public API code at high` or `/claude-security scan my branch at high`. If a scan of a large repository finds less than you expect, choose `high` scan effort, scan a second time, or do both. Each can report findings that one `medium` scan doesn’t. -### - -​ - -Read the scan results +### Read the scan results Every scan writes its results into a timestamped `CLAUDE-SECURITY-<timestamp>/` directory in your repository: @@ -150,19 +110,11 @@ That directory is the only change a scan makes to your checkout, and it carries its own `.gitignore`, so a stray `git add` never sweeps a report into a commit. To keep a report in history for an audit trail, delete that one `.gitignore` file and commit the directory like any other. Findings only appear in the report after independent verifier agents analyze them, which keeps reports short and worth reading. Scans are nondeterministic: two scans of the same code can surface different findings. Run scans regularly. -## - -​ - -Fix findings +## Fix findings Start the fix flow by picking **Suggest patches** from the `/claude-security` menu, or ask in plain language, such as “fix finding F3”, then pick which findings from the report to address. Patches are built against committed code, and the report has to still describe the code you have: findings whose code has since changed are skipped with a note, and the plugin offers a fresh scan instead of patching from a stale report. Each patch is drafted in a scratch copy of your repository, so your source files stay untouched until you apply a patch yourself. Before delivery, each patch is reviewed by an agent independent of the one that wrote it, which runs your project’s tests against the change when the code has them and reads the diff on its own terms for anything new it might introduce. A patch is written only when that review can vouch that the change addresses the one finding, introduces no new vulnerability, and leaves behavior otherwise unchanged. When it can’t vouch for all three, you get a short note explaining why instead of a patch. -### - -​ - -Patches are never applied automatically +### Patches are never applied automatically Applying a patch is always your decision. Patches are written to the report’s `patches/` folder, one `F<n>.patch` per finding with a note beside it explaining the change. Apply one from your shell, or ask Claude to apply it and open a pull request: @@ -170,11 +122,7 @@ When the patched code has no tests, the patch’s note says so, so you know its review ran without a test pass. Apply each patch in its own pull request so it can be reviewed and tested on its own. -## - -​ - -How the plugin fits with other security tools +## How the plugin fits with other security tools The Claude Security plugin is the on-demand deep-scan layer in a defense-in-depth stack, alongside the [security guidance plugin](</docs/en/security-guidance>), [`/security-review`](</docs/en/commands#all-commands>), [Code Review](</docs/en/code-review>), the managed [Claude Security](<https://claude.com/product/claude-security>) product, and your existing scanners: @@ -189,19 +137,11 @@ The plugin doesn’t replace your existing source-code security tools. Run it alongside static analysis, dependency scanning, and code review: it reasons about your code the way a human security researcher would, which complements the deterministic checks those tools provide. -## - -​ - -Troubleshooting +## Troubleshooting **The`/claude-security` menu opens with a Python warning.** The plugin needs `python3` 3.9 or later on your `PATH`. When it can’t find `python3` at all, the menu warns that Claude Security won’t work until one is installed; when the first `python3` on your `PATH` is older, the warning names the version it found. Install Python 3, or put a newer `python3` first on your `PATH`, then start a new session. **You may see a “safeguards flagged this message” notice when scanning on a Fable model.** The message names the model you’re running. Fable’s cybersecurity safety classifiers flag certain requests, and Claude Code re-runs a flagged request on an Opus model through [automatic model fallback](</docs/en/model-config#automatic-model-fallback>). This is expected. When the request re-runs, the scan should still complete successfully. -## - -​ - -Related resources +## Related resources To go deeper on the pieces this page touches:
modified Claude Tag View current →
--- a/claude-tag.md +++ b/claude-tag.md @@ -26,19 +26,11 @@ Done: Pulled p99 latency from DatadogDone: Diffed deploy 4f2c1 against mainDone: Reproduced the slow query locallyIn progress: Opening a pull request with the fix… -## - -​ - -Plans that include Claude Tag +## Plans that include Claude Tag Claude Tag is available on Team and Enterprise plans, on Anthropic’s first-party service. It isn’t available on individual plans (Free, Pro, Max, or Ultra), or for third-party deployments. To use it, your organization pairs its Slack workspace with its Claude organization; see [the setup overview](</docs/claude-tag/admins/setup-overview>) for the full prerequisites. If you’re choosing between Claude products for Slack-shaped work, [how Claude Tag differs from Cowork and Claude Code](</docs/claude-tag/concepts/how-it-works#how-claude-tag-differs-from-cowork-and-claude-code>) compares them directly: team work in shared channels is Claude Tag; personal work on your own files is Cowork or Claude Code. -### - -​ - -Who needs a Claude seat +### Who needs a Claude seat Slack users don’t each need a Claude seat to work with Claude in channels. @@ -46,11 +38,7 @@ * **In group DMs** : the same restriction on who can use Claude applies, and the work bills to your organization’s usage balance. See [Group DMs](</docs/claude-tag/admins/restrict-access#group-dms>). * **In one-to-one DMs** : a DM from a member who has connected a Claude account runs on that account and bills to that person’s seat. For the DM to work, that person needs either a seat that includes Claude Code or, on the Enterprise plan, Cowork access on a **Standard** seat or a usage-based **Chat** seat. A [DM from a member who hasn’t connected a Claude account](</docs/claude-tag/admins/restrict-access#direct-messages-from-members-without-a-claude-account>) can bill to your organization for a limited time. -## - -​ - -Where Claude Tag runs +## Where Claude Tag runs Claude Tag works in Slack. You interact with it by writing in a Slack channel, thread, or direct message, and it replies there. Mention `@Claude` in a channel to guarantee it picks the message up. When Claude works on a task, it runs in an ephemeral sandbox, not on your computer. The sandbox is created when a conversation starts, holds any code or files Claude is working with, and is discarded when the conversation goes idle. See [how Claude Tag works](</docs/claude-tag/concepts/how-it-works>) for the full lifecycle. You extend what Claude can reach, like your repositories, ticketing systems, data warehouses, and custom tools, through [Claude Tag connectors](</docs/claude-tag/admins/add-connections>), [plugins, and skills](</docs/claude-tag/admins/customize>). An Owner or a [Claude Tag admin](</docs/claude-tag/admins/restrict-access#delegate-claude-tag-administration>) configures these for all of Slack, for one workspace, or for one channel. Members’ own claude.ai connectors are separate from that configuration; Claude can use them in a channel for the member’s own requests, as [personal connectors in channels](</docs/claude-tag/concepts/personal-connectors>) describes. @@ -62,29 +50,17 @@ [How do I hand Claude Tag a task?Mention Claude in any channel it’s in, with nothing to install](</docs/claude-tag/users/getting-started>)[What is Claude Tag good at?Use cases for coding, data, incidents, and go-to-market](</docs/claude-tag/users/use-cases>)[How do I get good results?Good habits for scoping and reviewing work](</docs/claude-tag/users/good-habits>)[What does Claude Tag remember?Channel memory, what’s shared across the workspace, and who can see what](</docs/claude-tag/users/memory>)[Can Claude Tag run tasks on a schedule?Scheduled jobs, channel watching, and triggers](</docs/claude-tag/users/proactivity>) -## - -​ - -Billing and spend limits +## Billing and spend limits Adding Claude to Slack doesn’t add a per-seat charge. Channel, thread, and group DM work is billed by usage instead: it draws from a **usage balance** , an amount in your organization’s billing currency that an Owner funds. A [spend limit](</docs/claude-tag/admins/set-spend-limit>) caps how much of that balance Claude Tag can use each billing period. One-to-one direct messages from members who have connected a Claude account don’t draw from this balance. Such a DM runs on the sender’s own claude.ai account and follows that seat’s usual usage limits, so the organization spend limit doesn’t apply to it. A [DM from a member who hasn’t connected a Claude account](</docs/claude-tag/admins/restrict-access#direct-messages-from-members-without-a-claude-account>) can draw from this balance. To learn what your team’s usage costs, run a pilot with a spend limit set and watch the per-channel breakdown on the [usage page in your admin settings](<https://claude.ai/admin-settings/usage/claude-tag>). [Set a spend limit](</docs/claude-tag/admins/set-spend-limit>) covers how to fund the balance on each plan, set the limit, and what happens when usage reaches it. For end users -## - -​ - -Put Claude Tag to work +## Put Claude Tag to work If Claude Tag is in your channel, you can use it now. (If it isn’t there yet, an Owner in your Claude organization runs setup: see [Set up Claude Tag](</docs/claude-tag/admins/setup-overview>).) Anyone in the channel can hand it work, and channel work bills to the organization, not to you. What it can reach starts with the channel you’re in. The fastest way to find out is to ask it: `@Claude what can you access from this channel?` Or, if you’re signed in to your Claude organization, click **Configure** in the footer of a Claude reply in the channel to see its [connections](</docs/claude-tag/concepts/glossary#connection>), the external services an admin has connected for that channel. Replies in org-shared channels have no Configure link. For your own requests, Claude can also [use the connectors on your claude.ai account](</docs/claude-tag/concepts/personal-connectors>), after you allow it. In a one-to-one DM, Claude runs on your own claude.ai account instead of a channel’s setup. An Owner can turn off DMs for the whole organization; see [Allow or disable direct messages](</docs/claude-tag/admins/restrict-access#allow-or-disable-direct-messages>). -### - -​ - -Common uses +### Common uses Each link opens a guide with the prompts to paste and the connections the task needs. @@ -101,11 +77,7 @@ For administrators -## - -​ - -Set Claude Tag up once for everyone +## Set Claude Tag up once for everyone You set up Claude Tag once, at [`claude.ai/admin-settings/claude-tag`](<https://claude.ai/admin-settings/claude-tag>), and you must be an Owner in your Claude organization to do it. The setup page at that URL walks you through it: @@ -120,11 +92,7 @@ The security model, what admins can and can’t restrict, audit trails, and network requirements. -## - -​ - -Where to start with Claude Tag +## Where to start with Claude Tag ## Set up Claude Tag
modified Recommend your plugin from your CLI View current →
--- a/cli-hints.md +++ b/cli-hints.md @@ -2,11 +2,7 @@ To publish a plugin, see [Publish and distribute a plugin](</docs/en/plugins/publish>). -## - -​ - -Emit the hint +## Emit the hint Emit the tag only when `CLAUDECODE` or `CLAUDE_CODE_CHILD_SESSION` is set, so it doesn’t appear when a person runs your CLI directly. Claude Code sets `CLAUDECODE=1` in the commands it runs through the Bash and PowerShell tools and in hook commands. On v2.1.172 and later it also sets `CLAUDE_CODE_CHILD_SESSION=1` there. The variables differ in which processes carry them: @@ -48,11 +44,7 @@ Replace `example-cli` with your plugin’s name in the official marketplace. You can emit the hint on every invocation, because Claude Code prompts for each plugin once. To check the emitter, run `CLAUDECODE=1 example-cli` in a terminal and confirm the tag line appears on stderr, then run `example-cli` without the variable and confirm nothing extra prints. -## - -​ - -Hint format +## Hint format The tag must occupy its own line; Claude Code ignores a tag embedded mid-line. The tag takes three attributes, all required: @@ -64,11 +56,7 @@ Values may be double-quoted or unquoted; an unquoted value can’t contain whitespace. Claude Code removes the line from the output even when `v` or `type` is unrecognized. -## - -​ - -Check when the prompt appears +## Check when the prompt appears The prompt appears only in interactive terminal sessions. In `claude -p` runs, in subagent runs, and in hook command output, the tag is stripped and no prompt is shown. All of these checks must also pass: @@ -78,11 +66,7 @@ * **Not turned off** : the user hasn’t chosen **No, and don’t show plugin installation hints again** * **Local, attended session** : the session’s workspace is local rather than on a cloud or remote machine, and the session isn’t running unattended. For example, a session started with `--cloud`, one serving Remote Control, or an agent-team teammate never prompts -## - -​ - -Preview what the user sees +## Preview what the user sees When the checks in Check when the prompt appears pass, Claude Code shows a **Plugin recommendation** dialog like the following: @@ -108,11 +92,7 @@ * **No, and don’t show plugin installation hints again** : turns off future hint prompts for that user * **No answer for 30 seconds** : counts as **No** -## - -​ - -Next steps +## Next steps * [Publish and distribute a plugin](</docs/en/plugins/publish>): the routes for distributing a plugin, including the official marketplace, which the hint requires * [Plugin commands reference](</docs/en/plugins/cli-reference#plugin-install>): the shell command that installs the same plugin outside a session
modified CLI reference View current →
--- a/cli-reference.md +++ b/cli-reference.md @@ -1,8 +1,4 @@ -## - -​ - -CLI commands +## CLI commands You can start sessions, pipe content, resume conversations, and manage updates with these commands: @@ -47,11 +43,7 @@ If you mistype a subcommand, Claude Code suggests the closest match and exits without starting a session. For example, `claude udpate` prints `Did you mean claude update?`. `claude --dangerously-skip-permissions daemon <subcommand>` runs the `daemon` subcommand, so the subcommand works when `claude` is aliased to include the flag. Only a leading `--dangerously-skip-permissions` or `--allow-dangerously-skip-permissions` routes to `daemon` this way; with any other flag ahead of `daemon`, the subcommand doesn’t run. -## - -​ - -CLI flags +## CLI flags Customize Claude Code’s behavior with these command-line flags. `claude --help` does not list every flag, so a flag’s absence from `--help` does not mean it is unavailable. @@ -142,11 +134,7 @@ `--version`, `-v`| Output the version number| `claude -v` `--worktree`, `-w`| Start Claude in an isolated [git worktree](</docs/en/worktrees>) at `<repo>/.claude/worktrees/<name>`. If you don’t give a name, Claude Code generates one. Pass `#<number>`, a GitHub pull request URL, or a GitLab merge request URL to [fetch that PR or MR from `origin` and branch the worktree from it](</docs/en/worktrees#branch-from-a-pull-request>). Branching from a GitLab merge request requires Claude Code v2.1.233 or later| `claude -w feature-auth` -### - -​ - -System prompt flags +### System prompt flags Claude Code provides five flags for customizing the system prompt. Four set its text, and with `--system-prompt-snapshot` you control whether a conversation keeps the text it started with. All five work in both interactive and non-interactive modes. @@ -164,19 +152,11 @@ Claude receives the default system prompt followed by the contents of `style.md`, a blank line, and then `Always reply in French`. The file’s contents come first even if you pass `--append-system-prompt` before `--append-system-prompt-file`. When the replacement text combines instructions that are the same on every run with context that changes per run, add a line containing only `__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__` between the instructions and the context. Claude Code splits the prompt at the first such line and removes that line, so the part above it stays cached while the part below changes. Requires Claude Code v2.1.275 or later. [Cache the static part of a custom prompt](</docs/en/agent-sdk/modifying-system-prompts#cache-the-static-part-of-a-custom-prompt>) lists the configurations where the split applies. Choose based on whether Claude Code’s default identity still fits your task. Use an append flag when Claude should remain a coding assistant that also follows your extra rules: per-invocation instructions, output formatting, or domain context for a `-p` script. Appending preserves the default tool guidance, safety instructions, and coding conventions, so you only supply what differs. Use a replacement flag when the surface, identity, or permission model differs from Claude Code’s, like a non-coding agent in a pipeline that no human watches. Replacing drops all of the default prompt, including tool guidance and safety instructions, so you take responsibility for whatever your task still needs. For persistent personas you can switch between and share across a project, use [output styles](</docs/en/output-styles>). For project conventions Claude should always follow, use [CLAUDE.md](</docs/en/memory>). The [Agent SDK guide on system prompts](</docs/en/agent-sdk/modifying-system-prompts#decide-on-a-starting-point>) covers the same decision in more depth. -#### - -​ - -System prompt flags in resumed conversations +#### System prompt flags in resumed conversations By default, Claude Code builds the system prompt once, on a conversation’s first request, with the text from any system prompt flags applied, and records it in the session. Until the conversation is compacted, every later request uses that recorded prompt, including after you return to the conversation with `--resume` or `--continue`. If you pass different system prompt flag text, or none, on that later launch, it takes effect once the conversation is compacted or when you start a new conversation. Outside of [cloud sessions](</docs/en/cloud-environments>), if you start Claude Code in [bare mode](</docs/en/headless#start-faster-with-bare-mode>) by passing `--bare` or setting `CLAUDE_CODE_SIMPLE=1`, recording stays off unless you pass `--system-prompt-snapshot on`. Before v2.1.268, sessions that don’t [fetch feature flags](</docs/en/env-vars#features-that-need-feature-flag-fetching>), including sessions on Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry, rebuilt the prompt on every request and `--system-prompt-snapshot` had no effect. To rebuild the prompt on every request instead, for example while you iterate on its wording across `--continue` runs, pass `--system-prompt-snapshot off`. Before v2.1.265, passing any of the system prompt flags also turned recording off unless you passed `--system-prompt-snapshot on`. -## - -​ - -See also +## See also * [Chrome extension](</docs/en/chrome>) \- Browser automation and web testing * [Interactive mode](</docs/en/interactive-mode>) \- Shortcuts, input modes, and interactive features
modified Configure cloud environments View current →
Show diff (467 lines)
--- a/cloud-environments.md +++ b/cloud-environments.md @@ -13,11 +13,7 @@ [Remote Control](</docs/en/remote-control>) sessions connect the web and mobile interfaces to a session on your own machine, which uses your machine’s network and files, not a cloud environment. To choose the environment a Claude Tag channel uses, see Set the environment a Claude Tag channel uses. -## - -​ - -The Default environment +## The Default environment If you don’t have an environment yet, onboarding sets up the **Default** environment. How depends on where you onboard: @@ -37,11 +33,7 @@ Configure an environment when the default isn’t enough: when Claude needs to reach domains outside the default allowlist, needs environment variables set for its sessions, or needs dependencies installed before it starts working. -## - -​ - -Configure your environment +## Configure your environment Add, edit, and archive environments from the environment selector under the message box on the screen where you start a new session at [claude.ai/code](<https://claude.ai/code>). To reach that screen, complete [web onboarding](</docs/en/web-quickstart>). For the Desktop app, see [Cloud sessions](</docs/en/desktop#cloud-sessions>). Environments you create are personal to your account; shared environments created by an Owner appear in the selector alongside them. See Installed tools for what’s available without any configuration. The selector appears only until you send a new session’s first message. To edit the environment of a running cloud session of your own, select the caret after the session title at the top, then select **Edit cloud environment**. @@ -60,11 +52,7 @@ When you add an environment or edit one of your own, select the dialog’s **Network access**, **Setup script**, or **Environment variables** row to open that setting. After your last change, save with **Add environment** for a new environment or **Save changes** for an existing one. To store a key that sessions use without seeing it, see Add network secrets. -### - -​ - -Set environment variables +### Set environment variables Environment variables use `.env` format, one `KEY=value` pair per line. Plain values don’t need quotes, and if you quote a value with a matching pair, the quotes don’t become part of the value. Quote a value that spans multiple lines or contains a `#`: in an unquoted value, `#` starts a comment and the rest of the line is dropped. The following example defines three variables. @@ -79,19 +67,11 @@ After you edit, add, or remove a variable, an existing session in an Anthropic-hosted environment keeps the values it last read until its VM is next restored or rebuilt, and uses your change from then on. Its VM pauses on its own once the session is idle, and you can’t pause it yourself. To use a new value right away, ask Claude to set it on the command it runs, for example `LOG_LEVEL=trace npm test`, or start a new session. A cloud session also sets some variables itself when it starts. For [`CLAUDE_AUTOCOMPACT_PCT_OVERRIDE`](</docs/en/claude-code-on-the-web#manage-context>), the value the session sets overrides one you add here, so adding that key here has no effect. Anyone who uses the environment can read the values. In an Anthropic-hosted environment, use a network secret instead for a key the agent proxy can attach to a request. The requests that never get a secret are listed there. -### - -​ - -Add network secrets +### Add network secrets A network secret is an API key or token you store on a cloud environment so Claude can call that API from any session in the environment without seeing the key. Anthropic’s agent proxy adds the key to requests for the hosts you list, after each request leaves the session’s VM, so the key itself stays outside the VM. Network secrets are available on Pro, Max, Ultra, Team, and Enterprise plans. To check whether you can add one yourself, see Requirements. -#### - -​ - -Requirements +#### Requirements These requirements decide whether you can add a secret and whether the agent proxy can use it once added: @@ -102,11 +82,7 @@ * **API reachability** : the API accepts connections from the internet, because requests leave from Anthropic’s network * **Encryption keys** : if your organization uses customer-managed encryption keys, you can’t save network secrets -#### - -​ - -Add a secret +#### Add a secret You add secrets one at a time. To change a secret’s hosts or value, delete it and add it again. To add a secret to a shared environment, open it for editing from the **Cloud environments** page in [admin settings](<https://claude.ai/admin-settings>), then continue from step 2 in its **Network secrets** section. If you’re on a Team or Enterprise plan and don’t hold an organization admin role, follow step 1 on your own environment, then fill in the shorter form. @@ -135,30 +111,18 @@ To confirm the secret works, start a session in the environment and ask Claude to call the API, for example with `curl`. The API answers as if the key were in the request, and the key doesn’t appear in the session’s environment variables or in any file. If the list marks a secret **Not sent** instead, the note under it says why and what to do. Two secrets whose hosts overlap without matching exactly get no marker, and the agent proxy sends only one of them. -#### - -​ - -Add a secret without an organization admin role +#### Add a secret without an organization admin role If you’re on a Team or Enterprise plan and don’t hold an organization admin role, the **Add secret** form takes one secret for one host. Select your environment’s **Network secrets** row and then **Add secret**. Fill in these fields and select the form’s **Add secret** button: * **Host** : the one host that gets the secret, such as `api.example.com`. The form doesn’t accept a `*.` wildcard * **Secret type** : **Token** for a key that travels in a request header, or **Username and password**. For a token, paste the key in the **Token** field. For a header other than `Authorization`, such as `X-Api-Key`, change **Header** to its name -#### - -​ - -Which requests get the secret +#### Which requests get the secret The agent proxy attaches a secret to a request when the request’s host matches one you listed on that secret. Sessions can reach those hosts even when the environment’s network access level wouldn’t otherwise allow them, except the hosts that never get the secret. The secret applies in every session that runs in the environment, whoever started it, until you delete it. -#### - -​ - -Requests that never get the secret +#### Requests that never get the secret The agent proxy never attaches a secret you add to these requests: @@ -167,19 +131,11 @@ * **Setup script requests** : Claude Code connects to the agent proxy when it launches, after the setup script has run * **Claude Code’s telemetry export** : Claude Code sends its [telemetry export](</docs/en/monitoring-usage#telemetry-from-cloud-sessions-and-claude-tag>) itself rather than through a command it runs, and that request doesn’t go through the agent proxy -### - -​ - -Select an environment from the CLI +### Select an environment from the CLI Run `/remote-env` in your terminal to choose the default environment for cloud sessions you create from the CLI, such as [`claude --cloud`](</docs/en/claude-code-on-the-web#from-terminal-to-cloud>). The command opens a picker of your existing environments and saves your choice to the `remote.defaultEnvironmentId` key in your [user settings](</docs/en/settings#where-settings-live>), so it applies in every project on your machine until you change it, unless the same key is set at a higher-precedence [settings layer](</docs/en/settings#settings-precedence>), such as a repo’s project settings. A [self-hosted environment](</docs/en/self-hosted-environments>) ID, which has the form `ccpool_...`, follows a stricter source rule. See [`remote.defaultEnvironmentId`](</docs/en/settings-reference#remote-defaultenvironmentid>) for the settings layers Claude Code honors it from. `/remote-env` only sets the default: it doesn’t start a session, and it can’t add or edit environments. Manage them from the environment selector. -### - -​ - -Archive an environment +### Archive an environment To archive one of your own environments, open it for editing, then select **Archive environment** and confirm. If the environment is shared with your organization, an Owner archives it from the **Cloud environments** page in [admin settings](<https://claude.ai/admin-settings>) instead, so ask an Owner unless you are one. Archiving affects new sessions, not running ones: @@ -192,11 +148,7 @@ When you no longer need an Anthropic-hosted environment, archive it. Neither the environment dialog nor the **Cloud environments** admin page has an option to delete an Anthropic-hosted environment. If the environment is [self-hosted](</docs/en/self-hosted-environments>), an Owner can delete it from the **Cloud environments** page in admin settings. If you aren’t an Owner, ask one to delete it. -### - -​ - -Organization-shared environments +### Organization-shared environments On Team and Enterprise plans, an Owner can create cloud environments that are shared with every member of the organization. The same role manages everything else on the **Cloud environments** admin page, including [self-hosted environments](</docs/en/self-hosted-environments>); the Admin role can’t open the page. The full list of roles that can open it is the one for [managing server-managed settings](</docs/en/server-managed-settings#access-control>). Shared environments appear in each member’s environment selector under an **Organization** heading, after the member’s own environments under **Personal** , so a team can standardize on one configuration instead of each member recreating it. Selecting a shared environment’s settings icon there opens a read-only summary of its configuration for every member, Owners included. An Owner makes an environment available to the organization in one of two ways: @@ -205,32 +157,20 @@ Owners choose the organization’s default environment separately, at [claude.ai/admin-settings/claude-code](<https://claude.ai/admin-settings/claude-code>). To give a shared environment’s sessions a key they can’t read, add a network secret when you edit the environment on the **Cloud environments** page. Don’t include secrets in its variables, because every member’s sessions read them. -### - -​ - -Set the environment a Claude Tag channel uses +### Set the environment a Claude Tag channel uses In [Claude Tag](<https://claude.com/docs/claude-tag/overview>) channels, Claude works as your organization’s shared identity, not as any member, so channel sessions use organization-level environments only, either shared environments or [self-hosted environments](</docs/en/self-hosted-environments>). To give a channel a toolchain that isn’t pre-installed, such as .NET, an Owner can create a shared environment from the **Cloud environments** admin page with a setup script that installs it. Point the channel at an environment in one of two ways: * Set a shared or self-hosted environment as the organization’s default environment at [claude.ai/admin-settings/claude-code](<https://claude.ai/admin-settings/claude-code>). * [Pin one to a channel](<https://claude.com/docs/claude-tag/admins/troubleshooting#channel-sessions-use-the-wrong-environment-or-can%E2%80%99t-find-one>) in the Claude Tag admin settings. -## - -​ - -Network access +## Network access Each environment sets one network access level, which controls the outbound connections its sessions can make. A new environment starts at **Limited** with **Allow package managers** checked, so its sessions reach package registries and other allowlisted domains. To change an environment’s network access, open it for editing and use the **Network access** selector in the dialog. A shared environment opens read-only there, so an Owner changes its network access from the **Cloud environments** page in [admin settings](<https://claude.ai/admin-settings>) instead. The control that opens the selector appears on the app surfaces listed under The Default environment and in the [cloud scheduled task editor](</docs/en/routines#environments-and-network-access>). Personal environments don’t have a separate page in your claude.ai account settings. When you change an Anthropic-hosted environment’s network access, its existing sessions follow the new setting within about a minute, for requests that go through the session’s network allowlist. You don’t need to start a new session. MCP connectors you enable on a session or scheduled task work without adding their hosts to **Allowed domains** , because connector traffic travels through Anthropic’s servers rather than the session’s network. This relies on the same Anthropic-bound channel noted under [Security and isolation](</docs/en/claude-code-on-the-web#security-and-isolation>). Turn off any connector you don’t need to limit which tools Claude can reach. -### - -​ - -Access levels +### Access levels The **Network access** field in the environment dialog takes one of three levels: @@ -252,11 +192,7 @@ * **Saved as Trusted** : opens as **Limited** with **Allow package managers** checked * **Saved as Custom** : opens as **Limited** with its **Allowed domains** list and **Allow package managers** as you set them, or as **Full** if the list contained a bare `*` -### - -​ - -Allow specific domains +### Allow specific domains To allow domains that aren’t in the default allowlist, select **Limited** in the environment’s **Network access** selector, then list one domain per line in the **Allowed domains** field. A leading `*.` matches every subdomain. This example allows three hosts an internal project might need. @@ -271,11 +207,7 @@ Each environment has its own allowed-domains list; there’s no organization-level allowlist that admins can push to every member’s environments. No [server-managed setting](</docs/en/server-managed-settings>) adds domains to an environment’s network allowlist either. To give a team one standard list, an Owner can create an organization-shared environment with **Limited** network access and that list. -### - -​ - -GitHub proxy +### GitHub proxy In Anthropic-hosted environments, all GitHub operations go through a dedicated proxy that keeps your real GitHub credentials outside the session’s VM, independent of the environment’s access level. Sessions in a self-hosted environment authenticate git operations with credentials your deployment provides; [Configure git](</docs/en/self-hosted-environments-deploy#configure-git>) covers the options, including per-session minted credentials and an opt-in to this same proxy. The proxy provides: @@ -287,32 +219,20 @@ Committed files from public repositories arrive through `raw.githubusercontent.com`, which the security proxy handles instead. That domain is on the default allowlist, so those files stay reachable as long as the environment’s network access allows that list. -### - -​ - -Security proxy +### Security proxy Cloud sessions in Anthropic-hosted environments run behind an HTTP/HTTPS network proxy for security and abuse prevention purposes; in a [self-hosted environment](</docs/en/self-hosted-environments-deploy#default-deny-egress>), outbound traffic leaves through your own network boundary instead. All outbound internet traffic from an Anthropic-hosted session passes through this proxy, which provides: * Protection against malicious requests * Rate limiting and abuse prevention -## - -​ - -What’s available in cloud sessions +## What’s available in cloud sessions In Anthropic-hosted environments, each session gets a fresh virtual machine (VM) running Ubuntu 24.04 on x86_64, regardless of your own operating system and CPU architecture, with your repository cloned and common toolchains pre-installed. When a dependency provides precompiled binaries, such as Ruby gems with native extensions or prebuilt Python wheels, use its x86_64 Linux build to match the VM. This section covers the Anthropic-hosted defaults, the built-in GitHub tools, how to run tests and services, the resource limits each VM gets, and the time limits on long-running work. Sessions your organization routes to a [self-hosted environment](</docs/en/self-hosted-environments>) run on your own runners instead, with the tools your runner image provides. -### - -​ - -What carries over from your setup +### What carries over from your setup Of the repository configuration in this table, a cloud thread in a [project](</docs/en/claude-projects>) loads only the repository root’s `CLAUDE.md`, `.claude/CLAUDE.md`, and `.claude/rules/` files that aren’t [path-specific](</docs/en/memory#path-specific-rules>). See [What threads pick up from your repositories](</docs/en/claude-projects#what-threads-pick-up-from-your-repositories>). @@ -337,11 +257,7 @@ To make your own configuration available in cloud sessions, commit it to the repo. Anyone who uses the environment can read its environment variables and setup script. The dialog’s note under **Environment variables** says so and warns against putting secrets there. In an Anthropic-hosted environment, store a key the agent proxy can attach as a network secret instead. -#### - -​ - -Add personal preferences without committing to the repo +#### Add personal preferences without committing to the repo In an Anthropic-hosted environment, add a setup script that writes `~/.claude/CLAUDE.md` for preferences you’d rather not put in a shared repository. Claude Code loads that file as [user instructions](</docs/en/memory#choose-where-to-put-claude-md-files>) in the session. This example sets a commit-message preference: @@ -353,11 +269,7 @@ Put the script on one of your own environments rather than a shared one. Run `/context` in your next cloud session and confirm `/root/.claude/CLAUDE.md` appears under **Memory files**. -### - -​ - -Installed tools +### Installed tools Cloud sessions come with common language runtimes, build tools, and databases pre-installed. The table below summarizes what’s included by category. @@ -378,11 +290,7 @@ ¹ Bun is installed but has known proxy compatibility issues for package fetching. To get the versions of most of the tools in this table, ask Claude to run `check-tools` in a cloud session. It’s a shell command installed on the session VM, not a command you type with `/`; you ask Claude because Claude runs all VM commands for you. For a tool it doesn’t report, such as Ruby, PHP, bun, PostgreSQL, or Redis, ask Claude to run the tool’s own version command, for example `psql --version`. Node.js versions are installed at `/opt/node20`, `/opt/node21`, and `/opt/node22`, with 22 on `PATH` by default. To work with a different version, ask Claude to prepend that version’s `bin` directory, such as `/opt/node20/bin`, to `PATH`. Toolchains outside this list, such as the .NET SDK, aren’t pre-installed even when their package registries are on the default allowlist. Install them with a setup script. -### - -​ - -Work with GitHub issues and pull requests +### Work with GitHub issues and pull requests Cloud sessions include built-in GitHub tools that let Claude read issues, list pull requests, fetch diffs, and post comments without any setup. These tools authenticate through the GitHub proxy using whichever method you configured under [GitHub authentication options](</docs/en/claude-code-on-the-web#github-authentication-options>), so your token never enters the container. You can set `GH_TOKEN` or `GITHUB_TOKEN` yourself in environment settings, or leave both unset and let the GitHub proxy authenticate for you: @@ -391,37 +299,21 @@ A token you set is an ordinary environment variable, so anyone who uses the environment can read it; the proxy path keeps the credential out of the environment configuration and the session VM. To check which case applies to your session, ask Claude to run `echo $GH_TOKEN`. GitHub’s [`gh` CLI](<https://cli.github.com>) is pre-installed. If you need a GitHub operation the built-in tools don’t cover, ask Claude to call the REST API with `gh api`. `gh` subcommands that use the REST API, such as `gh workflow list`, work too. The proxy rejects subcommands that use GraphQL, such as `gh pr` and `gh issue`. `gh` reads `GH_TOKEN` automatically, so you don’t need to run `gh auth login`. -### - -​ - -Link output back to the session +### Link output back to the session Each cloud session has a transcript URL on claude.ai, and the session can read its own ID from the `CLAUDE_CODE_REMOTE_SESSION_ID` environment variable. Use this to put a traceable link in PR bodies, commit messages, Slack posts, or generated reports so a reviewer can open the run that produced them. Commits that Claude creates in a cloud session include a `Claude-Session: <url>` git trailer, and PR bodies include the session URL on its own line. To omit the trailer and the PR-body link, set [`attribution.sessionUrl`](</docs/en/settings-reference#attribution-sessionurl>) to `false`. To include the session link in something other than a commit or PR, such as a Slack message Claude posts or a report file it writes, have Claude run the following command and use its output. The command converts the `cse_` prefix in the environment variable’s value to the `session_` prefix that the transcript URL expects: echo "https://claude.ai/code/${CLAUDE_CODE_REMOTE_SESSION_ID/#cse_/session_}" -### - -​ - -Run tests, start services, and add packages +### Run tests, start services, and add packages You don’t get a shell into the session VM. Claude runs every command for you, so phrase the tasks in this section as requests in your prompt. -#### - -​ - -Run tests +#### Run tests Claude runs tests as part of working on a task. Ask for it in your prompt, like “fix the failing tests in `tests/`” or “run pytest after each change.” Test runners that come with the pre-installed toolchains, like pytest and cargo test, work without additional setup. A runner your project declares as a dependency, like jest, installs with your dependencies. -#### - -​ - -Start services +#### Start services PostgreSQL and Redis are pre-installed but not running by default. Ask Claude to start whichever you need; the commands it runs are: @@ -431,19 +323,11 @@ Docker is available for running containerized services. Ask Claude to run `docker compose up` to start your project’s services. Network access to pull images follows your environment’s access level, and the default allowlist includes Docker Hub and other common registries. If your images are large or slow to pull, add `docker compose pull` or `docker compose build` to your setup script. The environment cache keeps the pulled images, so each new session has them on disk. The cache stores files only, not running processes, so Claude still starts the containers each session. -#### - -​ - -Add packages +#### Add packages To add packages that aren’t pre-installed, use a setup script. The environment cache keeps what the script installs, so packages you install there are available at the start of every session without reinstalling each time. You can also ask Claude to install packages mid-session, but those installs don’t carry over to other sessions. -### - -​ - -Resource limits +### Resource limits Cloud sessions in Anthropic-hosted environments run with approximate resource ceilings that may change over time: @@ -453,11 +337,7 @@ The VM may stop tasks that need significantly more memory, such as large build jobs or memory-intensive tests. For workloads beyond these limits, use [Remote Control](</docs/en/remote-control>) to run Claude Code on your own hardware, or run cloud sessions in a [self-hosted environment](</docs/en/self-hosted-environments>) on compute your organization operates. -### - -​ - -Time limits +### Time limits In Anthropic-hosted environments, these time limits apply to long-running work in a cloud session, such as a build, an install, or a test run. Each entry links to the section that defines the limit. @@ -468,30 +348,18 @@ To raise the command timeouts for an environment’s sessions, add [`BASH_DEFAULT_TIMEOUT_MS` and `BASH_MAX_TIMEOUT_MS`](</docs/en/env-vars#variables>) to its environment variables. Both take milliseconds. For example, `BASH_DEFAULT_TIMEOUT_MS=600000` makes 10 minutes the default. -## - -​ - -Setup scripts +## Setup scripts A setup script is a Bash script that runs when a new cloud session starts, before Claude Code launches. Use setup scripts to install dependencies, configure tools, or fetch anything the session needs that isn’t pre-installed. Scripts run as root on Ubuntu 24.04, so `apt install` and most language package managers work. -### - -​ - -Add a setup script +### Add a setup script To add a setup script to your own environment, you can type or paste it, or load a text file such as `setup.sh`. Add or edit the environment and select the **Setup script** row. Enter the script in the box that opens, or select **Choose file** to replace the box’s contents with the text of a file up to 64 KB. Then select **Add environment** or **Save changes**. This example installs [ShellCheck](<https://www.shellcheck.net/>), which isn’t pre-installed. #!/bin/bash apt update && apt install -y shellcheck -### - -​ - -Script requirements +### Script requirements A setup script has four constraints to write around: @@ -500,19 +368,11 @@ * **Network access for installs** : package installs need to reach registries. The default **Limited** level with **Allow package managers** checked covers common package registries including npm, PyPI, RubyGems, and crates.io. With **None** network access, installs fail. * **The environment’s variables aren’t set yet** : the script runs before the session sets the environment’s environment variables. Set any value the script needs in the script itself. -### - -​ - -Environment caching +### Environment caching The setup script runs the first time you start a session in an environment. When setup completes within roughly five minutes, Anthropic snapshots the filesystem and reuses that snapshot as the starting point for later sessions. New sessions start with your dependencies, tools, and Docker images already on disk, and skip the setup script step. This keeps startup fast even when the script installs large toolchains or pulls container images. If setup takes longer than roughly five minutes, the environment isn’t cached. The cache is a filesystem snapshot, so it keeps what the setup script writes to disk and loses anything that was only running. Packages you install, Docker images you pull, and files you write all carry over. A database the script started, a `docker compose up` stack, or any other background process doesn’t; start those per session by asking Claude or with a SessionStart hook. The setup script runs again to rebuild the cache when you change the environment’s setup script or allowed network hosts, and when the cache reaches its expiry after roughly seven days. In an Anthropic-hosted environment, the setup script doesn’t run when a session’s VM is restored after being idle, so a change to the script reaches an existing session only when its VM was [reclaimed](</docs/en/claude-code-on-the-web#environment-expired>) and is rebuilt. To apply a change right away, run the commands in the session or start a new session. You don’t need to enable caching or manage snapshots yourself. -### - -​ - -Setup scripts vs. SessionStart hooks +### Setup scripts vs. SessionStart hooks Use a setup script to provision the VM itself: toolchains and CLI tools that aren’t pre-installed. Use a [SessionStart hook](</docs/en/hooks#sessionstart>) for project setup that should run everywhere, cloud and local, like `npm install`. Setup scripts and SessionStart hooks run in a fixed order when a cloud session starts. The table compares where you configure them, when they run, and where they run. @@ -527,11 +387,7 @@ * **Anthropic-hosted environment** : Claude Code runs hooks from your organization’s [server-managed settings](</docs/en/server-managed-settings>) and, outside a [project](</docs/en/claude-projects#what-threads-pick-up-from-your-repositories>) thread, from the repository. [Claude Tag](<https://claude.com/docs/claude-tag/overview>) sessions don’t receive server-managed settings, so hooks from server-managed settings don’t run there. * **[Self-hosted environment](</docs/en/self-hosted-environments-configuration#permissions-and-tool-approval>)** : Claude Code also runs the hooks the operator seeded from the runner host’s `~/.claude/`, and the hooks in the runner image’s managed settings file when that file is one of the [managed sources Claude Code applies](</docs/en/managed-settings#how-claude-code-combines-managed-sources>). -### - -​ - -Install dependencies with a SessionStart hook +### Install dependencies with a SessionStart hook To install dependencies only in cloud sessions outside a [project](</docs/en/claude-projects#what-threads-pick-up-from-your-repositories>)’s threads, pair a SessionStart hook with a script that checks where it’s running. First, add a SessionStart hook to your repo’s `.claude/settings.json`. This configuration tells Claude Code to run `scripts/install_pkgs.sh` from your repository whenever a session starts or resumes: @@ -578,11 +434,7 @@ If `npm install` reads other files, such as a workspace’s `package.json`, an `.npmrc`, or your `postinstall` script’s inputs, add them to the `sha256sum` command that saves the hashes. Otherwise, you keep the old packages after one of those files changes. -#### - -​ - -Limitations in cloud sessions +#### Limitations in cloud sessions SessionStart hooks behave the same in the cloud as locally, with these caveats: @@ -595,11 +447,7 @@ To customize the base image, use a setup script to install what you need on top of the provided image, or run your own image as a container alongside Claude with `docker compose`. Replacing the base image entirely isn’t supported yet. -## - -​ - -Default allowed domains +## Default allowed domains When **Allow package managers** is checked under **Limited** network access, as it is in a new environment, sessions can reach the following domains. Domains marked with `*` indicate wildcard subdomain matching, so `*.gcr.io` allows any subdomain of `gcr.io`. @@ -858,11 +706,7 @@ * *.modelcontextprotocol.io -## - -​ - -Related resources +## Related resources * [Cloud sessions reference](</docs/en/claude-code-on-the-web>): start, manage, and share cloud sessions * [Cloud sessions quickstart](</docs/en/web-quickstart>): connect GitHub and start your first cloud session
modified Code intelligence plugins View current →
Show diff (122 lines)
--- a/code-intelligence.md +++ b/code-intelligence.md @@ -4,11 +4,7 @@ To get started, find your language in the table under Install a code intelligence plugin. The plugins in that table come from Anthropic’s [official plugin marketplace](</docs/en/plugins/anthropic-marketplaces>). If you already saw an **LSP plugin recommendation** dialog, see Accept or dismiss the recommendation dialog for what each choice does. -## - -​ - -Install a code intelligence plugin +## Install a code intelligence plugin A code intelligence plugin tells Claude Code which command starts the language server and which file extensions it handles. It doesn’t include the language server. Install the language server binary first, then the plugin, then confirm the server starts. @@ -57,38 +53,22 @@ After you install a missing binary, Claude Code tries again the next time Claude edits a matching file. If you installed the binary into a directory that isn’t on the `PATH` of the shell you started `claude` from, start a new session from a shell where it is. -## - -​ - -See what Claude gains +## See what Claude gains With a language server running, Claude gains diagnostics and code navigation: * **Diagnostics after edits** : each time Claude edits or writes a file the server handles, Claude gets the errors and warnings the server reports. It sees a type error, missing import, or syntax error it introduced without running a compiler. * **Code navigation** : Claude gets an `LSP` tool that looks up symbols through the server instead of searching text for them. The tool is read-only. For what Claude can look up with the tool and how permissions apply to it, see [LSP tool behavior](</docs/en/tools-reference#lsp-tool-behavior>). -### - -​ - -Read the diagnostics yourself +### Read the diagnostics yourself After Claude edits a file the server handles, the conversation shows only the `Found N new diagnostic issues` summary. To read the issues themselves, press **Ctrl+O**. -## - -​ - -Accept or dismiss the recommendation dialog +## Accept or dismiss the recommendation dialog If a language server binary is already on your `PATH` and the plugin that uses it isn’t installed, Claude Code offers to install the plugin for you in a dialog titled **LSP plugin recommendation**. -### - -​ - -When the recommendation dialog appears +### When the recommendation dialog appears The **LSP plugin recommendation** dialog can appear after Claude edits a file. These conditions decide whether it appears and which plugin it offers: @@ -97,11 +77,7 @@ * **Once per session** : the dialog appears at most once in a session, for the first matching file Claude edits. * **Not for cloud sessions** : the dialog never appears when your terminal is attached to a cloud session, such as one you started with [`claude --cloud`](</docs/en/claude-code-on-the-web#from-terminal-to-cloud>). -### - -​ - -Respond to the recommendation dialog +### Respond to the recommendation dialog The **LSP plugin recommendation** dialog names the plugin and offers these choices: @@ -112,22 +88,14 @@ If you don’t choose an option, Claude Code closes it after 30 seconds and counts that as ignored. The count is kept across sessions. After five ignored dialogs, Claude Code stops recommending plugins, the same as if you’d chosen **Disable all LSP recommendations**. -### - -​ - -Turn recommendations back on +### Turn recommendations back on The **LSP plugin recommendation** dialog stops appearing after you choose **Disable all LSP recommendations** or ignore it five times. * **Disabled or ignored five times** : to turn it back on in either case, remove the `lspRecommendationDisabled` and `lspRecommendationIgnoredCount` keys from `~/.claude.json`, Claude Code’s own configuration file. * **Never for this plugin** : if you chose **Never for this plugin** and want that plugin offered again, remove its `name@marketplace` id from the `lspRecommendationNeverPlugins` list in the same file. -## - -​ - -Troubleshoot code intelligence +## Troubleshoot code intelligence The plugins troubleshooting page covers the symptoms specific to code intelligence plugins under [Language server doesn’t start, uses too much memory, or reports wrong diagnostics](</docs/en/plugins/troubleshooting#language-server-doesnt-start>): @@ -135,11 +103,7 @@ * **High memory use** : memory use increases while the server indexes the project. * **False positive diagnostics in a monorepo** : diagnostics report imports as unresolved when they aren’t. -## - -​ - -Add a language without an official plugin +## Add a language without an official plugin If your language isn’t in the table of official plugins, you can still connect a language server. @@ -148,11 +112,7 @@ For the file’s fields and a worked example, see [LSP servers in plugin components](</docs/en/plugins/components#lsp-servers>). -## - -​ - -Next steps +## Next steps * [LSP servers in plugin components](</docs/en/plugins/components#lsp-servers>): write the `.lsp.json` for a language server that has no official plugin * [Install and manage plugins](</docs/en/plugins/install>): scopes, updates, and uninstalling
modified Code Review View current →
Show diff (103 lines)
--- a/code-review.md +++ b/code-review.md @@ -4,11 +4,7 @@ To turn on Code Review, an Owner of your Claude organization follows [Set up Code Review](</docs/en/code-review-setup>). Claude can also review code without this service. Run [`/code-review`](</docs/en/code-review-local>) in your Claude Code session on any plan, or compare all the options. -## - -​ - -Availability +## Availability Check that your organization qualifies before you set up Code Review: @@ -18,11 +14,7 @@ * **Encryption keys** : Code Review isn’t yet available for organizations that use customer-managed encryption keys (CMEK). * **Cloud providers** : you need a Claude organization on one of these plans even if your developers use Claude Code through Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry -## - -​ - -Set up and use Code Review +## Set up and use Code Review Pick the page for what you need to do: @@ -46,11 +38,7 @@ See how reviews are billed, estimate spend, set the monthly spend limit, and track review activity -## - -​ - -How reviews work +## How reviews work By default, Code Review focuses on correctness: bugs that would break production, not formatting preferences or missing test coverage. To change what it flags, [add guidance files](</docs/en/code-review-customize>) to your repository. A review runs on Anthropic infrastructure in four stages: @@ -67,11 +55,7 @@ Code Review chooses the Claude models that reviews run on, and its admin settings don’t offer a model choice. To make reviews more or less thorough, change the review level. After an Owner turns on Code Review, each repository has a setting for [when reviews run](</docs/en/code-review-setup#set-when-reviews-run>): once when a pull request opens, after every push, or only on request. Whichever it is, someone with write access to the repository can comment `@claude review` on a pull request to [start a review](</docs/en/code-review-pull-requests#comment-commands>). -### - -​ - -Review levels +### Review levels The review level sets how thorough each review is, and a more thorough review costs more: @@ -81,11 +65,7 @@ An Owner [chooses one level for the organization](</docs/en/code-review-setup#set-the-default-review-level>) and can give an individual repository its own, such as Quick for a routine codebase and Deep for a critical one. For what else drives the cost of each review, see [Code Review costs and usage](</docs/en/code-review-costs>). -### - -​ - -What a review can access +### What a review can access A review reaches your repository through the Claude GitHub App that an Owner [installs during setup](</docs/en/code-review-setup#turn-on-code-review>): @@ -93,20 +73,12 @@ * **What it reads and writes** : inside a review, access to your repository is read-only, and a review doesn’t push commits. On the pull request, it posts comments and the [check run](</docs/en/code-review-pull-requests#check-run-output>), resolves its own earlier comment threads, and can react to a comment command with 👀. The app itself holds a [broader permission set](</docs/en/github-actions#github-app-permissions>) that other Claude features share. * **How it examines your code** : a review works from reading the diff and the surrounding code, without building or running your code. -### - -​ - -Who controls a review +### Who controls a review * **Who can start one** : where reviews run automatically, opening or pushing to a pull request starts a review, [except on drafts and forks](</docs/en/code-review-pull-requests#review-drafts-and-pull-requests-from-forks>). After some pushes, Code Review [keeps the earlier result](</docs/en/code-review-pull-requests#when-a-push-keeps-the-earlier-result>) instead. A [comment command](</docs/en/code-review-pull-requests#comment-commands>) starts one only when it comes from a person with write access to the repository. * **Which instructions it follows** : `REVIEW.md` from the base or default branch and [never from the pull request’s own changes](</docs/en/code-review-customize#which-branch-review-md-is-read-from>). -## - -​ - -Compare ways to get a review +## Compare ways to get a review To find the options open to you, check the **Who can use it** column against your plan and code host: @@ -118,11 +90,7 @@ Claude in your own CI, with [GitHub Actions](</docs/en/github-actions>) or [GitLab CI/CD](</docs/en/gitlab-ci-cd>)| Your pipeline’s events, such as every pull request or merge request| Your own CI runners| Anyone with a Claude API key or cloud provider credentials, on GitHub or GitLab Your own reviewer, as a [subagent](</docs/en/sub-agents>) or [skill](</docs/en/skills>)| You or Claude invoke it during a session| Wherever you run Claude Code| Anyone who writes one -## - -​ - -Related resources +## Related resources * [GitHub Enterprise Server](</docs/en/github-enterprise-server>): use Code Review with a self-hosted GitHub instance * [GitHub App permissions](</docs/en/github-actions#github-app-permissions>): the full permission set the Claude GitHub App requests
modified Code Review costs and usage View current →
--- a/code-review-costs.md +++ b/code-review-costs.md @@ -3,19 +3,11 @@ * **Cost of each review** : scales with the [review level](</docs/en/code-review-setup#set-the-default-review-level>), the size of the change, the complexity of the surrounding code, and how many candidate issues need verification * **Number of reviews** : set by how often reviews run in each repository -## - -​ - -Pricing +## Pricing Code Review is billed on token usage through [usage credits](<https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans>), separately from your plan’s included usage. Reviews are billed to your organization, not to the developer who opened the PR or requested the review. Costs appear on your Anthropic bill regardless of whether your organization uses Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry for other Claude Code features. -### - -​ - -How often reviews run +### How often reviews run A repository you add from the admin page starts at **After every push** , which runs the most reviews. Each repository’s [**Review runs** setting](</docs/en/code-review-setup#set-when-reviews-run>) decides how many reviews a pull request gets: @@ -30,11 +22,7 @@ * **`@claude review`** : runs a single review without subscribing to future pushes * **Drafts and pull requests from forks** : [automatic reviews skip both](</docs/en/code-review-pull-requests#review-drafts-and-pull-requests-from-forks>), so pushes to them don’t add reviews -## - -​ - -Estimate your spend +## Estimate your spend Before a wide rollout, run a small pilot to estimate monthly spend from your own pull requests. @@ -45,11 +33,7 @@ A repository’s average moves with the size of its pull requests and with the review level you choose. -## - -​ - -Limit your spend +## Limit your spend To set a monthly spend limit for Code Review, go to [claude.ai/admin-settings/usage](<https://claude.ai/admin-settings/usage>) and configure the limit for the Claude Code Review service. The limit applies to the whole organization. Code Review skips reviews when any of these runs out: @@ -59,11 +43,7 @@ Code Review also skips reviews once what’s left is less than the expected cost of one review. When a review is skipped, developers see a [comment on the PR](</docs/en/code-review-troubleshooting#review-didn%E2%80%99t-run-and-the-pr-shows-a-budget-message>) that names the cause and links to the usage settings. To monitor spend, use the analytics dashboard. -## - -​ - -View usage +## View usage Go to [claude.ai/analytics/code-review](<https://claude.ai/analytics/code-review>) to see Code Review activity across your organization. @@ -77,11 +57,7 @@ The Code Review cost card shows an amount only when the current month is selected. Cost figures in analytics can differ from your invoice. Repository breakdown costs are estimated at list price, before any discounts or credits, and cover only reviews that Claude posted on a pull request. For invoice-accurate spend, refer to your Anthropic bill. -## - -​ - -Related resources +## Related resources * [Set up Code Review](</docs/en/code-review-setup>): where to choose the review level and when reviews run in each repository * [Read and request reviews on a pull request](</docs/en/code-review-pull-requests>): the comment commands, pull requests from forks, and the budget message developers see when a review is skipped
modified Customize Code Review View current →
Show diff (180 lines)
--- a/code-review-customize.md +++ b/code-review-customize.md @@ -7,19 +7,11 @@ To change how thorough reviews are or when they run, ask an Owner to change the [review level](</docs/en/code-review-setup#set-the-default-review-level>) or the [**Review runs** setting](</docs/en/code-review-setup#set-when-reviews-run>). -## - -​ - -Use CLAUDE.md for project-wide rules +## Use CLAUDE.md for project-wide rules Code Review reads your repository’s `CLAUDE.md` files as project context. A change that violates one of their rules becomes a finding at whichever [severity level](</docs/en/code-review-pull-requests#severity-levels>) fits the issue. A review reads the `CLAUDE.md` at your repository root and the `CLAUDE.md` files in the parent directories of each changed file. A subdirectory’s `CLAUDE.md` is read when the pull request changes a file under that path. -## - -​ - -Use REVIEW.md for review-only rules +## Use REVIEW.md for review-only rules `REVIEW.md` is a file at your repository root that tailors Code Review to your repository. On a protected branch, you can also add a `REVIEW.md` in most subdirectories to add checks for changes under that subdirectory, on top of the root file. The agents that find issues and the agents that verify them receive its contents as your repository’s review instructions, alongside Code Review’s default review guidance. The step that writes the final review consults it before settling severity and writing the summary. This example layout has a root file and one subdirectory file: @@ -34,11 +26,7 @@ The Code Review service and the local [`/code-review` command](</docs/en/code-review-local>) are two separate tools, and they read different files. The service reads both `CLAUDE.md` and `REVIEW.md`. The `/code-review` command, which you run inside a Claude Code session on your own machine, reads your `CLAUDE.md` files and not `REVIEW.md`. Put guidance you want applied in both places in `CLAUDE.md`, and keep `REVIEW.md` for rules specific to pull request review. -### - -​ - -When a subdirectory REVIEW.md doesn’t apply +### When a subdirectory REVIEW.md doesn’t apply Code Review doesn’t apply a `REVIEW.md` in or below a subdirectory with one of these names, whatever the subdirectory holds. A subdirectory name matches only as a whole, in any letter case and at any depth, so `Tests` matches and `integration-tests` doesn’t: @@ -49,11 +37,7 @@ Put checks for those subdirectories in the root `REVIEW.md`, or in a parent subdirectory’s `REVIEW.md` when neither that parent nor anything above it is on the list. The remaining subdirectory `REVIEW.md` files on the paths a pull request changes share a limit of 150,000 bytes, not counting the root file. If the [check run](</docs/en/code-review-pull-requests#check-run-output>) reports that some of them didn’t fit, shorten the files to fit that limit. -### - -​ - -Example REVIEW.md +### Example REVIEW.md This `REVIEW.md` recalibrates severity for a backend service, caps nits, skips generated files, and adds repo-specific checks. @@ -83,11 +67,7 @@ - Log lines don't include email addresses, user IDs, or request bodies - Database queries are scoped to the caller's tenant -### - -​ - -Choose what to write in REVIEW.md +### Choose what to write in REVIEW.md `REVIEW.md` is freeform Markdown that changes what a review finds and reports. It doesn’t change the format of the review. Find the problem you’re seeing, then add an instruction like the one shown. The example uses the first four. @@ -99,11 +79,7 @@ Some of these instructions need the root file on a protected default branch. Keep `REVIEW.md` to instructions that change review behavior, and leave general project context in `CLAUDE.md`. -### - -​ - -Include other files in REVIEW.md +### Include other files in REVIEW.md You can split review instructions across several files and pull them into your root `REVIEW.md`. Use this when `REVIEW.md` grows long or when you already keep review rules in another file. To include a file, add a line to the root `REVIEW.md` with only `@` and the file name on it. Code Review puts the file’s contents in place of that line, so they apply as part of `REVIEW.md`. In this example, the root file gives one instruction of its own and then includes two rule files: @@ -135,11 +111,7 @@ * **Links** : keep Markdown links at 64 or fewer across `REVIEW.md` and the files it includes. Links to `http`, `https`, or `mailto` addresses and to `#` anchors don’t count, and neither do links in a skill file. Past that limit, the review skips your whole root `REVIEW.md`, not only the included files. The check run then [says the instructions weren’t applied](</docs/en/code-review-troubleshooting#the-check-run-mentions-review-md>). * **Merged copy** : merge the included file into the branch `REVIEW.md` is read from. The review reads both from the same commit, never from the pull request’s own changes. -### - -​ - -Include a skill file +### Include a skill file To have reviews follow guidance you keep in a [skill](</docs/en/skills>), include the skill’s `SKILL.md` in your root `REVIEW.md`. Code Review doesn’t run skills. Add `@` and the path to `SKILL.md`, in the form `.claude/skills/<folder>/SKILL.md`, on a line of its own: @@ -153,11 +125,7 @@ Protect the branch that `REVIEW.md` is read from, because Code Review includes a skill file only when it reads `REVIEW.md` from a protected branch. The skill file counts toward the limits of eight files and 150,000 bytes, and has its own limit of 30,000 bytes. -#### - -​ - -Write a skill line that Code Review includes +#### Write a skill line that Code Review includes Use a folder name without spaces. A line with a space in its path stays in `REVIEW.md` as plain text, and the check run doesn’t report it as a skipped include. If the `@` line for a skill breaks one of the rules below, Code Review doesn’t include the skill from that line: @@ -170,11 +138,7 @@ When Code Review skips a skill line for breaking the File, Size, Count, or Blocks rule, the check run’s [message about skipped include lines](</docs/en/code-review-troubleshooting#the-check-run-mentions-review-md>) counts it. The message appears only when the review applies `REVIEW.md` from a protected branch. -#### - -​ - -Check what a review gets from a skill +#### Check what a review gets from a skill When the skill is included, a review gets the body of `SKILL.md` and nothing else from the skill, so check the skill against the list below. @@ -187,11 +151,7 @@ If you edit the skill’s `!` commands, `$ARGUMENTS`, or links, you also change how it works in Claude Code. If your team relies on those, copy the guidance into a file beside `REVIEW.md` and include that file in place of the skill. -#### - -​ - -Characters that Code Review changes in skill text +#### Characters that Code Review changes in skill text Code Review changes some characters in the skill’s text, so your code samples reach a review in the form below. @@ -203,11 +163,7 @@ Where a rule depends on one of those characters, state it in words too. -### - -​ - -Which branch REVIEW.md is read from +### Which branch REVIEW.md is read from Code Review reads `REVIEW.md` from the pull request’s base branch or from the default branch, never from the pull request’s own changes. To change review behavior, merge the `REVIEW.md` change first. Keep `REVIEW.md` on your default branch and protect that branch. When a review reads the copy on a protected default branch, the first row of the table below, it honors these instructions from the root file: @@ -217,11 +173,7 @@ Write exclusions and Nit caps in `REVIEW.md` or a file beside it, not in an included skill. -#### - -​ - -What counts as branch protection +#### What counts as branch protection Code Review counts these settings as protection: @@ -230,11 +182,7 @@ A ruleset counts when it restricts updates or requires pull requests with at least one approval. If it requires pull requests, it must also dismiss that approval on a new push or require the approval to come after the last push. -#### - -​ - -What a review reads for each branch setup +#### What a review reads for each branch setup Find your repository’s situation in the first column of the table below. @@ -247,11 +195,7 @@ If the check run mentions `REVIEW.md`, see [The check run mentions REVIEW.md](</docs/en/code-review-troubleshooting#the-check-run-mentions-review-md>). -## - -​ - -Related resources +## Related resources * [Code Review](</docs/en/code-review>): what the service is and how a review runs * [Read and request reviews on a pull request](</docs/en/code-review-pull-requests#severity-levels>): what each severity level means and how findings appear
modified Review locally with /code-review View current →
Show diff (140 lines)
--- a/code-review-local.md +++ b/code-review-local.md @@ -29,11 +29,7 @@ Ask Claude to fix what the review found. With `--fix` or `--comment`, Claude applies or posts the findings as part of the review, and you may be asked to approve its edits. -## - -​ - -Choose what to review +## Choose what to review To review something other than your current branch, type a target after the effort level and any flags. Claude receives that text as the review target. A target can be a pull request number, a branch name, a file path, or a Git revision range. Find what you want reviewed in the first column and type what the second column shows: @@ -48,11 +44,7 @@ With no target, `/code-review` reviews your branch’s commits ahead of its upstream branch plus your uncommitted changes. If the branch has no upstream, Claude compares against `main`, or against the previous commit. With `ultra`, Claude Code reads the target differently, as Text after the effort level and flags describes. -## - -​ - -What the review reads and edits +## What the review reads and edits Check these before you run a review, especially with `--fix`: @@ -60,11 +52,7 @@ * **Rewinding** : a background review applies its `--fix` edits outside your session’s [checkpoints](</docs/en/checkpointing#subagent-edits-not-restored>). After one, `/rewind` restores only the files Claude had already edited in your conversation. The review’s edits to other files stay, so use git to revert them. When the review runs in the foreground, it edits your working tree during your own turn, so `/rewind` restores its edits as usual. * **Instructions** : the review follows your `CLAUDE.md`, including in a non-interactive `-p` run. It doesn’t read `REVIEW.md`. That file configures the managed [Code Review service](</docs/en/code-review-customize#use-review-md-for-review-only-rules>) on GitHub pull requests. -## - -​ - -How findings are reported +## How findings are reported Claude reports the findings as text in the reply in both of these runs: @@ -73,11 +61,7 @@ In a host application that requests the findings list, such as the [desktop app](</docs/en/desktop#review-your-code>), Claude reports the review’s findings through the [`ReportFindings` tool](</docs/en/tools-reference>) instead. The report appears as a findings list, and each entry shows the file location, a one-sentence summary, and a category tag such as `correctness` when the finding carries one. A host request applies at every effort level. When Claude fixes reported findings later in the session, it reports them again. Claude Code then marks each finding in the updated findings list as fixed, skipped, or no change needed. -## - -​ - -Tune effort and arguments +## Tune effort and arguments Beyond `--fix` and `--comment`, the command takes these flags: @@ -91,30 +75,18 @@ * **`ultra`** : the review neither uses nor updates the remembered level * **No level ever typed** : the review uses the session’s current effort -### - -​ - -Post findings to a GitLab merge request +### Post findings to a GitLab merge request When you pass `--comment` for a GitLab merge request, Claude Code posts the findings through GitLab’s `glab` CLI. Requires Claude Code v2.1.257 or later. When `glab` isn’t installed, Claude prints the findings in the terminal instead. Pass the merge request as its URL or a `!123` reference. Claude Code treats a bare number or branch name as a merge request only when the checkout’s origin is on `gitlab.com`. On a self-managed GitLab instance, pass the URL or `!123` form. -### - -​ - -Text after the effort level and flags +### Text after the effort level and flags After the effort level and flags, Claude Code reads the rest of the line as the review target. The `ultra` argument changes that reading: * **With`ultra`**: Claude Code reads a single word as a base branch or PR number. Longer text that doesn’t name a branch or PR becomes [a note attached to the review](</docs/en/ultrareview#pass-a-request-in-plain-words>). `/code-review ultra check my auth changes` reviews your current branch, and Claude relates the findings to your note. * **Without`ultra`**: everything left is the review target, even when it starts with another command name. `/code-review /fix-issue 123` reviews with `/fix-issue 123` as target text instead of loading `/fix-issue` as a second [stacked skill](</docs/en/skills#stack-several-skills-in-one-message>). -## - -​ - -Run in the foreground +## Run in the foreground To make the review run in the foreground, do one of these: @@ -122,11 +94,7 @@ * Set [`CLAUDE_CODE_DISABLE_BACKGROUND_TASKS`](</docs/en/env-vars>) to `1`, which also turns off other background task features * Run `/code-review` again while an earlier review is still in progress -## - -​ - -Let Claude start the review +## Let Claude start the review Claude can start `/code-review` on its own, without you typing the command: @@ -143,11 +111,7 @@ Before v2.1.246, Claude started `/code-review` on its own only where a feature flag fetched from Anthropic turned it on. In [sessions that don’t fetch feature flags](</docs/en/env-vars#features-that-need-feature-flag-fetching>), `/code-review` ran only when you typed it, and a scheduled `/code-review` reached Claude as plain text. -## - -​ - -Escalate to ultrareview +## Escalate to ultrareview `/code-review ultra --fix` runs the deeper [ultrareview](</docs/en/ultrareview>) in the cloud, then asks Claude to apply its findings to your working tree when they arrive back in your session. Ultrareview uses its own scope: @@ -161,11 +125,7 @@ To run a cloud review from a script or CI job, use the [`claude ultrareview` subcommand](</docs/en/ultrareview#run-ultrareview-non-interactively>), which waits for the findings and prints them to stdout. -## - -​ - -Change or build on the review +## Change or build on the review `/code-review` is a [bundled skill](</docs/en/skills#bundled-skills>): its instructions are built into Claude Code, so there is no `SKILL.md` file on disk to open or edit. To give every review project rules to follow, add them to your `CLAUDE.md`. To go further, start from one of these pages: @@ -175,11 +135,7 @@ The command was named `/simplify` before v2.1.147, when it applied fixes by default. If you scripted `/simplify` for bug-finding, switch to `/code-review --fix`. -## - -​ - -Related resources +## Related resources * [Code Review](</docs/en/code-review>): the managed service that reviews every pull request on GitHub for your organization * [Ultrareview](</docs/en/ultrareview>): setup, limits, and cost of the deeper cloud review
modified Read and request reviews on a pull request View current →
Show diff (141 lines)
--- a/code-review-pull-requests.md +++ b/code-review-pull-requests.md @@ -2,11 +2,7 @@ If your plan doesn’t include Code Review, you can still have Claude review your branch from a Claude Code session: see [Review locally with `/code-review`](</docs/en/code-review-local>). -## - -​ - -Severity levels +## Severity levels Claude posts each finding as an inline comment on the lines concerned and marks it with one of three severity levels: @@ -18,11 +14,7 @@ When the review recorded its reasoning, the finding has a collapsed **Why this was flagged** section. Expand it to read why Claude flagged the issue and how it verified the problem. To change what Claude flags in your repository or how it ranks severity, see [Customize Code Review](</docs/en/code-review-customize>). -## - -​ - -Respond to findings +## Respond to findings You can merge without responding to a finding, unless your repository’s own rules require it. If its branch protection [requires conversation resolution](<https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/about-protected-branches#require-conversation-resolution-before-merging>), resolve each finding’s thread before you merge. To clear a finding, resolve its thread or push a fix. @@ -32,11 +24,7 @@ To get that next review without pushing, comment `@claude review` as a top-level pull request comment. -## - -​ - -Check run output +## Check run output The **Details** link on the **Claude Code Review** check run opens the findings in one table sorted by severity, including any finding whose inline comment GitHub didn’t accept: @@ -47,11 +35,7 @@ A finding that has a line but wasn’t posted as an inline comment appears as an annotation in the **Files changed** tab, on the lines concerned. Important findings show in red, nits in yellow, and pre-existing bugs in gray. The check run concludes as neutral, or as skipped after some pushes that change no files and keep the earlier result. It never concludes as a failure, so a finished review doesn’t fail a required check. If you don’t see findings, or a review didn’t run, see [Troubleshoot Code Review](</docs/en/code-review-troubleshooting>). -### - -​ - -When a push keeps the earlier result +### When a push keeps the earlier result If the check run has one of these titles after you push, Code Review kept the result of an earlier review instead of starting a new one: @@ -65,11 +49,7 @@ To get a review without a code change, comment `@claude review` or click **Re-run** on the check run. -### - -​ - -Read the result from a script +### Read the result from a script To gate a merge or post a summary from your own CI, parse the last line of the Details text with `gh` and jq. That line is an HTML comment that holds the severity counts as JSON: @@ -111,11 +91,7 @@ * **`normal` is above zero**: fail the job if you want to gate the merge. The `normal` key holds the count of Important findings, so Claude found at least one bug worth fixing before merge. To print only that count, add `| .normal` before the closing single quote. * **The line is missing** : the command prints an error that contains `no severity line` instead of counts, and exits with a non-zero status. Treat that as no verdict rather than as zero findings. A check run for a review that failed, timed out, was canceled, or was superseded by a newer one has no such line, and some completed reviews have none either. -## - -​ - -Request a review +## Request a review If your pull request is a draft or comes from a fork, automatic reviews skip it, so request the review with a comment command. To get a review on your pull request, do one of these: @@ -125,11 +101,7 @@ * **Click Re-run** : after a review fails or times out on a pull request that isn’t from a fork, [run it again](</docs/en/code-review-troubleshooting#retrigger-a-failed-or-timed-out-review>) from the check run. On a pull request that isn’t from a fork, you can also click **Re-run** after a push that kept the earlier result. * **Wait for the automatic retry** : a review whose session was interrupted is retried once automatically. The [check run’s summary](</docs/en/code-review-troubleshooting#retrigger-a-failed-or-timed-out-review>) says when that’s happening. -### - -​ - -Comment commands +### Comment commands Post one of these commands as a comment on the pull request: @@ -152,11 +124,7 @@ Before a July 2026 update, `@claude review` subscribed the PR to push-triggered reviews. If you relied on that behavior, comment `@claude review always` instead. -### - -​ - -What a later review covers +### What a later review covers A later review that starts on its own, such as after a push, focuses on what changed since the last review and posts fewer nits and pre-existing findings. To see whether it left findings out as a result, look in the review body for a sentence that counts them: @@ -165,11 +133,7 @@ To get a review that leaves none of these out, comment `@claude review`. It covers the whole pull request again. -### - -​ - -Review drafts and pull requests from forks +### Review drafts and pull requests from forks Automatic reviews skip both of these, so request the review with a comment command: @@ -178,19 +142,11 @@ On a pull request from a fork, `@claude review always` works too, but doesn’t subscribe the pull request to reviews on later pushes. Clicking **Re-run** on the check run doesn’t start a review there. -### - -​ - -Use Code Review alongside the Claude Code GitHub Action +### Use Code Review alongside the Claude Code GitHub Action If the repository also runs the [Claude Code GitHub Action](</docs/en/github-actions>) in interactive mode with its default `@claude` trigger phrase, an `@claude review` comment starts the Action as well. To keep the two apart, set the Action’s `trigger_phrase` input to a different phrase. -## - -​ - -Related resources +## Related resources * [Troubleshoot Code Review](</docs/en/code-review-troubleshooting>): a review that didn’t start, failed, or was skipped for budget * [Code Review](</docs/en/code-review>): what the service is and how a review runs
modified Set up Code Review View current →
Show diff (148 lines)
--- a/code-review-setup.md +++ b/code-review-setup.md @@ -1,10 +1,6 @@ As an Owner of your Claude organization, you turn on Code Review in [**Admin settings > Claude Code**](<https://claude.ai/admin-settings/claude-code#code-review>) on claude.ai. Reviews run on Anthropic infrastructure, so you don’t add workflow files to your repositories. After setup, you choose how thorough reviews are and when they run in each repository. You spend more at a higher review level and when reviews run more often. See [Code Review costs](</docs/en/code-review-costs#pricing>). -## - -​ - -What you need to turn on Code Review +## What you need to turn on Code Review First check that your organization [qualifies for Code Review](</docs/en/code-review#availability>). Then make sure you have this access, or someone who does: @@ -14,11 +10,7 @@ Owner of the GitHub organization| Installing the Claude GitHub App and [linking it to your Claude organization](</docs/en/admin-setup#connected-github-accounts>). If you aren’t an owner, have one install and link the app before you start Write access to each repository you add, from the GitHub account you connect to Claude| Adding the repository -## - -​ - -Turn on Code Review +## Turn on Code Review 1 @@ -63,19 +55,11 @@ Open a test pull request in one of the repositories you added, and don’t mark it as a draft. A check run named **Claude Code Review** appears within a few minutes. If you already set the repository to **Manual (@claude review)** , comment `@claude review` on the pull request to start the first review.If no check run appears, see [No check run appears on the test pull request](</docs/en/code-review-troubleshooting#no-check-run-appears-on-the-test-pull-request>).Once the review arrives, send your developers [Read and request reviews on a pull request](</docs/en/code-review-pull-requests>), which covers the severity levels, the comment commands, and how to respond to findings. -## - -​ - -Set defaults for your organization +## Set defaults for your organization As an Owner, you decide how thorough reviews are and how often they run. Both are in the **Code review** section of [**Admin settings > Claude Code**](<https://claude.ai/admin-settings/claude-code#code-review>). -### - -​ - -Set the default review level +### Set the default review level The review level sets how thorough each review is, and a more thorough review costs more. You set one default for the organization and can override it for individual repositories. @@ -90,11 +74,7 @@ A new level applies to reviews that start after the change. For what else drives the cost of each review, see [Code Review costs and usage](</docs/en/code-review-costs>). -### - -​ - -Set when reviews run +### Set when reviews run Each repository has its own **Review runs** setting, which decides when its pull requests get reviewed. @@ -107,11 +87,7 @@ * **Drafts and pull requests from forks** : whichever option you choose, [automatic reviews skip both](</docs/en/code-review-pull-requests#review-drafts-and-pull-requests-from-forks>) * **New repositories** : a repository you add from the **Add a repository** dialog starts at **After every push**. If its GitHub organization is covered as a whole, it takes that organization row’s setting instead. -### - -​ - -Turn tip comments on or off +### Turn tip comments on or off A tip comment is a short comment Claude posts on a pull request when no review starts, saying why and what to do next. **Show tips on pull requests** is on by default. With it on, Claude posts a tip in each of these cases, explaining: @@ -122,11 +98,7 @@ Turn the setting off to stop these comments. -### - -​ - -What developers can change +### What developers can change Developers come to you to change the review level, the **Review runs** setting, or which repositories get reviews. From GitHub, without the Owner role, they can do these: @@ -136,30 +108,18 @@ Reviews that developers request are [billed to your organization](</docs/en/code-review-costs#pricing>). To limit what Code Review spends in a month, see [Limit your spend](</docs/en/code-review-costs#limit-your-spend>). -## - -​ - -Manage repositories +## Manage repositories You can add repositories one at a time or cover a whole GitHub organization at once, and stop reviews wherever you don’t want them. -### - -​ - -Add more repositories +### Add more repositories To add repositories after setup, click **Add** above the **Repositories** table in the **Code review** section. The **Add a repository** dialog opens. Select repositories and click **Continue**. * **A repository isn’t listed** : see [A repository isn’t listed in Add a repository](</docs/en/code-review-troubleshooting#a-repository-isn%E2%80%99t-listed-in-add-a-repository>). * **You want every repository in a GitHub organization** : cover the organization instead of selecting repositories one at a time -### - -​ - -Cover a whole GitHub organization +### Cover a whole GitHub organization To turn on Code Review for every repository in a GitHub organization, set **Review runs** on the organization’s row in the **Repositories** table. That covers every repository there that the Claude GitHub App can access, including repositories added later. This can raise spend significantly. It requires all of these: @@ -174,11 +134,7 @@ * **Individual changes afterward** : a repository you later set differently from its organization is marked **Custom** in the table. * **Review level** : an organization row has no review level of its own. -### - -​ - -Turn off Code Review or remove a repository +### Turn off Code Review or remove a repository In the **Code review** section of [**Admin settings > Claude Code**](<https://claude.ai/admin-settings/claude-code#code-review>), pick the control that matches what you want to stop: @@ -187,11 +143,7 @@ * **A whole GitHub organization** : click **Edit** on the organization’s row and select **Off**. This also turns off repositories in that organization that you added one at a time. * **Everything** : turn off **Allow code review**. No new reviews start in any repository, and your repository list stays so you can turn it back on later. -## - -​ - -Related resources +## Related resources * [Code Review costs and usage](</docs/en/code-review-costs>): how the review level and when reviews run affect spend, how to set a spend limit, and where to see usage * [Read and request reviews on a pull request](</docs/en/code-review-pull-requests>): what developers see on a pull request and the comment commands
modified Troubleshoot Code Review View current →
Show diff (127 lines)
--- a/code-review-troubleshooting.md +++ b/code-review-troubleshooting.md @@ -1,10 +1,6 @@ When [Code Review](</docs/en/code-review>) doesn’t do what you expect on a pull request, start with the **Claude Code Review** check run. Its title says how far the review got. -## - -​ - -Check how far the review got +## Check how far the review got Find the **Claude Code Review** check run on your pull request, then match its title to one of these common ones: @@ -19,19 +15,11 @@ **Code review declined**| The review didn’t run| Read the check run’s summary. If it names a budget or a spend limit, see Review didn’t run and the PR shows a budget message No check run| No review started| Comment `@claude review`. If no check run appears after that, see A comment command didn’t start a review -## - -​ - -A review didn’t start +## A review didn’t start Check these cases when no **Claude Code Review** check run appears, or when Claude posts a comment saying the review was skipped. -### - -​ - -A comment command didn’t start a review +### A comment command didn’t start a review After you comment `@claude review`, look for a **Claude Code Review** check run titled **Code review queued…** or **Code review in progress…** on the pull request. An 👀 reaction on your comment doesn’t confirm a review is coming. If no check run appears, check for each of these causes: @@ -40,11 +28,7 @@ * **You don’t have write access** : you need write, maintain, or admin permission on the repository. On a pull request from a fork, the permission that counts is on the base repository. Unless the pull request is yours, Claude can reply with a [tip](</docs/en/code-review-setup#turn-tip-comments-on-or-off>): “No review was started: manual reviews can only be requested by someone with write access to this repository.” Ask someone with write access to comment instead. * **The budget ran out** : Claude posts a comment that begins with “⚠️ Code review skipped”. See Review didn’t run and the PR shows a budget message. -### - -​ - -Review didn’t run and the PR shows a budget message +### Review didn’t run and the PR shows a budget message When your organization’s budget can’t cover a review, Code Review skips the review and Claude posts a comment on the pull request that begins with “⚠️ Code review skipped”. In some of these cases a check run titled **Code review declined** also appears. The comment links [claude.ai/admin-settings/usage](<https://claude.ai/admin-settings/usage>), where an admin restores the budget. Its wording tells you which limit was reached: @@ -54,22 +38,14 @@ After the budget is restored, comment `@claude review` on the pull request to get the review that was skipped. The [conditions for comment commands](</docs/en/code-review-pull-requests#comment-commands>) apply, so the commenter needs write access. -## - -​ - -Retrigger a failed or timed-out review +## Retrigger a failed or timed-out review If the check run’s summary says “The review session was interrupted before it could finish. A new review of this commit has been queued automatically.”, you don’t need to do anything. That review is retried once automatically. Otherwise, when the check run’s title is **Code review failed** or **Code review timed out** , run the review again with a comment or a re-run: * **Comment`@claude review`**: post it as a top-level comment on the pull request. This starts a fresh review without subscribing the pull request to future pushes. * **Click Re-run** : if the pull request isn’t [from a fork](</docs/en/code-review-pull-requests#review-drafts-and-pull-requests-from-forks>), click **Re-run** on the **Claude Code Review** check in GitHub’s **Checks** tab. The re-run covers the pull request’s current head commit and doesn’t subscribe the pull request either. -## - -​ - -Find issues that aren’t showing as inline comments +## Find issues that aren’t showing as inline comments If the check run title says issues were found but you don’t see inline review comments on the diff, look in these other locations where findings are surfaced: @@ -77,11 +53,7 @@ * **Files changed annotations** : open the **Files changed** tab on the PR. A finding that has a line but wasn’t posted as an inline comment appears there as an annotation on the lines concerned. * **Review body** : findings that have no inline location, or that fall outside the current diff, appear under an **Additional findings** heading in the review body. -## - -​ - -The check run mentions REVIEW.md +## The check run mentions REVIEW.md These are four of the messages a check run can carry about `REVIEW.md`: @@ -93,35 +65,19 @@ * **A link to a changed file** : it links to a file or folder this pull request changes, and the review couldn’t leave out only the lines with that link. Write the rule in `REVIEW.md` itself. * **“include line(s) in the root REVIEW.md were skipped on this review”** : your root `REVIEW.md` applied, but the files those lines name didn’t. Check the lists under [Include other files in REVIEW.md](</docs/en/code-review-customize#include-other-files-in-review-md>) and, for a skill, under [Include a skill file](</docs/en/code-review-customize#include-a-skill-file>). -## - -​ - -Setup problems +## Setup problems These cases come up for an Owner while [setting up Code Review](</docs/en/code-review-setup>). -### - -​ - -A repository isn’t listed in Add a repository +### A repository isn’t listed in Add a repository Search for the repository by name first, because the dialog doesn’t load a long list in full. The dialog lists a repository only if the Claude GitHub App can access it. Click **Install GitHub App** and give the app access to the repository. When no repositories are listed, **Install GitHub App** is a button in the dialog. Otherwise, it’s at the bottom of the dialog’s GitHub organization filter menu. -### - -​ - -No check run appears on the test pull request +### No check run appears on the test pull request Confirm that **Allow code review** is on, that the repository is listed under **Repositories** in the **Code review** section, and that the Claude GitHub App has access to it. Automatic reviews skip draft pull requests, and a repository set to **Manual (@claude review)** needs an `@claude review` comment to start the first review. -## - -​ - -Related resources +## Related resources * [Read and request reviews on a pull request](</docs/en/code-review-pull-requests>): what the findings and the check run mean, and the comment commands * [Set up Code Review](</docs/en/code-review-setup>): for Owners, turn on Code Review and manage repositories
modified Commands View current →
--- a/commands.md +++ b/commands.md @@ -1,25 +1,15 @@ Commands control Claude Code from inside a session. They provide a quick way to switch models, manage permissions, clear context, run a workflow, and more. Type `/` to see the commands available to you, or type `/` followed by letters to filter. How the command menu matches what you type covers highlighting, typos, and the few commands Claude Code hides from the menu until you type their full name. A command is only recognized at the start of your message. Text that follows the command name becomes its arguments. At the terminal prompt, you can start one message with several [skills](</docs/en/skills#stack-several-skills-in-one-message>): typing `/skill-a /skill-b do XYZ` loads both skills and passes the trailing text to each as arguments. Up to six skills can be chained. If you send a command while Claude is responding, Claude Code queues it and runs it after the current turn finishes. Claude Code runs some commands immediately without interrupting the response, such as `/status`, `/tasks`, and `/usage`. In [fullscreen rendering](</docs/en/fullscreen>), Claude Code also opens dialog commands such as `/theme` and `/help` immediately. Before v2.1.234, Claude Code queued those dialogs until the turn finished. -## - -​ - -Commands across a typical workflow +## Commands across a typical workflow Most commands are useful at a specific point in a session, from setting up a project to shipping a change. **First session in a repo.** Run `/init` to generate a starter `CLAUDE.md`, then `/memory` to refine it. Use `/mcp` to set up any servers the project needs, ask Claude to create any [subagents](</docs/en/sub-agents>) you want, and run `/permissions` to set your approval rules. **During a task.** `/plan` switches into plan mode before a large change. `/model` and `/effort` adjust which model you’re using and how much reasoning it applies. When the conversation gets long, `/context` shows what’s filling the window and `/compact` summarizes it to free space. Use `/btw` for a side question that shouldn’t add to the conversation history. **Run work in parallel.** Claude delegates side tasks to [subagents](</docs/en/sub-agents>), and `/tasks` lists the current session’s background work, including subagents that have finished. `/background` detaches the whole session to keep running as a [background agent](</docs/en/agent-view>) and frees your terminal. For a large change that spans the codebase, `/batch` decomposes it into independent units and runs each in its own [worktree](</docs/en/worktrees>). See [Run agents in parallel](</docs/en/agents>) for how these approaches relate. **Before you ship.** `/diff` shows what changed. `/code-review` checks the current diff for correctness bugs and can apply the findings with `--fix`; pass a PR number, such as `/code-review high 1234`, to review a pull request instead. `/review` is an alias. `/code-review ultra` runs a multi-agent review in the cloud. `/security-review` checks the diff for security vulnerabilities. **Between sessions.** `/clear` starts fresh on a new task while keeping project memory. `/resume` returns to an earlier conversation, `/branch` branches the current one to try a different direction, and `/fork` copies it into a new [background session](</docs/en/agent-view>). `/teleport` pulls a cloud session into this terminal, and `/remote-control` lets you continue this local session from another device. **When something is wrong.** `/rewind` rolls code and conversation back to a checkpoint, or summarizes part of the conversation. `/doctor` runs a setup checkup that diagnoses installation and configuration issues and can fix them, `/debug` diagnoses runtime issues, and `/feedback` reports a bug with session context attached. -## - -​ - -All commands +## All commands The table below lists all the commands included in Claude Code. Most are built-in commands whose behavior is coded into the CLI. Two kinds of entries are marked: * **[Skill](</docs/en/skills#bundled-skills>)** : a bundled skill. It works like skills you write yourself: a prompt handed to Claude. - * `/verify` runs only when you invoke it. * **[Workflow](</docs/en/workflows#bundled-workflows>)** : a bundled [dynamic workflow](</docs/en/workflows>) that fans work out across many subagents and runs in the background. - * `/deep-research` runs only when you invoke it. To add your own commands, see [skills](</docs/en/skills>). In the table below, `<arg>` indicates a required argument and `[arg]` indicates an optional one. @@ -149,11 +139,7 @@ `/workflow-authoring`| **[Skill](</docs/en/skills#bundled-skills>).** Load the reference for writing [dynamic workflow](</docs/en/workflows>) scripts: the script API, resume behavior, quality patterns, and worked examples. Claude normally loads it on its own before writing a script; run it yourself before [editing a saved script by hand](</docs/en/workflows#edit-a-saved-script>). Available when dynamic workflows are enabled, and requires Claude Code v2.1.248 or later `/workflows`| Open the [workflow](</docs/en/workflows#watch-the-run>) progress view to watch, pause, resume, or save running and completed workflows -## - -​ - -How the command menu matches what you type +## How the command menu matches what you type Claude Code filters the `/` menu as you type. Each bullet below covers one thing you might notice while filtering: @@ -162,19 +148,11 @@ * **Commands that aren’t available to you** : Claude Code leaves them out of the menu. When nothing matches, Claude Code shows `No commands match "/name"`. Most unavailable commands return [Unknown command](</docs/en/errors#unknown-command>) when you submit them; a few, such as [`/schedule` on a Console API key](</docs/en/routines#schedule-returns-unknown-command>), answer with their own availability message instead. Some commands also answer with a message of their own when your organization’s policy disables them. * **Hidden commands** : Claude Code keeps a few available commands, such as `/heapdump`, out of the menu by design. A partial name never brings a hidden command into the menu: if the partial matches nothing visible, Claude Code shows the same no-match message. Claude Code lists the command only once you’ve typed its full name, and submitting the full name runs it. -## - -​ - -MCP prompts +## MCP prompts MCP servers can expose prompts that appear as commands. See [MCP prompts](</docs/en/mcp#use-mcp-prompts-as-commands>) for details. -## - -​ - -See also +## See also * [Skills](</docs/en/skills>): create your own commands * [Interactive mode](</docs/en/interactive-mode>): keyboard shortcuts, Vim mode, and command history
modified Common workflows View current →
Show diff (261 lines)
--- a/common-workflows.md +++ b/common-workflows.md @@ -7,27 +7,15 @@ * Delegate research to subagents to keep your main context clean * Pipe Claude into scripts for CI and batch processing -## - -​ - -Prompt recipes +## Prompt recipes These are prompt patterns for everyday tasks like exploring unfamiliar code, debugging, refactoring, writing tests, and creating PRs. Each works in any Claude Code surface; adapt the wording to your project. -### - -​ - -Understand new codebases +### Understand new codebases For configuring Claude Code in a monorepo or large codebase, see [Monorepos and large repos](</docs/en/large-codebases>). -#### - -​ - -Get a quick codebase overview +#### Get a quick codebase overview Suppose you’ve just joined a new project and need to understand its structure quickly. @@ -67,11 +55,7 @@ * Ask about coding conventions and patterns used in the project * Request a glossary of project-specific terms -#### - -​ - -Find relevant code +#### Find relevant code Suppose you need to locate code related to a specific feature or functionality. @@ -101,11 +85,7 @@ * * * -### - -​ - -Fix bugs efficiently +### Fix bugs efficiently Suppose you’ve encountered an error message and need to find and fix its source. @@ -135,11 +115,7 @@ * * * -### - -​ - -Refactor code +### Refactor code Suppose you need to update old code to use modern patterns and practices. For porting an entire codebase to a new language, see [how Anthropic runs large-scale code migrations with Claude Code](<https://claude.com/blog/ai-code-migration>) on the blog. @@ -175,11 +151,7 @@ * * * -### - -​ - -Work with tests +### Work with tests Suppose you need to add tests for uncovered code. @@ -211,11 +183,7 @@ * * * -### - -​ - -Create pull requests +### Create pull requests You can create pull requests by asking Claude directly (“create a pr for my changes”), or guide Claude through it step-by-step: @@ -241,11 +209,7 @@ Review Claude’s generated PR before submitting and ask Claude to highlight potential risks or considerations. -### - -​ - -Handle documentation +### Handle documentation Suppose you need to add or update documentation for your code. @@ -281,21 +245,13 @@ * * * -### - -​ - -Work in notes and non-code folders +### Work in notes and non-code folders Claude Code works in any directory. Run it inside a notes vault, a documentation folder, or any collection of markdown files to search, edit, and reorganize content the same way you would code. The `.claude/` directory and `CLAUDE.md` sit alongside other tools’ config directories without conflict. Claude reads files fresh on each tool call, so it sees edits you make in another application the next time it reads that file. * * * -### - -​ - -Work with images +### Work with images Suppose you need to work with images in your codebase, and you want Claude’s help analyzing image content. @@ -345,11 +301,7 @@ * * * -### - -​ - -Reference files and directories +### Reference files and directories Use @ to quickly include files or directories without waiting for Claude to read them. @@ -390,11 +342,7 @@ * * * -### - -​ - -Run Claude on a schedule +### Run Claude on a schedule Suppose you want Claude to handle a task automatically on a recurring basis, like reviewing open PRs every morning, auditing dependencies weekly, or checking for CI failures overnight. Pick a scheduling option based on where you want the task to run: @@ -409,19 +357,11 @@ * * * -### - -​ - -Ask Claude about its capabilities +### Ask Claude about its capabilities Claude can answer questions about its own features and limitations. It looks up the answers in the current Claude Code documentation, so they aren’t limited to the version you’re running. -#### - -​ - -Example questions +#### Example questions can Claude Code create pull requests? @@ -444,11 +384,7 @@ * * * -## - -​ - -Resume previous conversations +## Resume previous conversations When a task spans multiple sittings, pick up where you left off instead of re-explaining context. Claude Code saves every conversation locally. @@ -456,11 +392,7 @@ This resumes the most recent session in the current directory; if there isn’t one yet, it prints `No conversation found to continue` and exits. Use `claude --resume` to choose from a list, or `/resume` from inside a running session. See [Manage sessions](</docs/en/sessions>) for naming, branching, and the full picker reference. -## - -​ - -Run parallel sessions with worktrees +## Run parallel sessions with worktrees Work on a feature in one terminal while Claude fixes a bug in another, without the edits colliding. Each [git worktree](<https://git-scm.com/docs/git-worktree>) is a separate checkout on its own branch, created from an existing commit, so the repository needs at least one commit first. @@ -468,11 +400,7 @@ Run the same command with a different name in a second terminal to start an isolated parallel session. See [Worktrees](</docs/en/worktrees>) for cleanup, `.worktreeinclude`, and non-git VCS support. To monitor parallel sessions from one screen instead of separate terminals, see [background agents](</docs/en/agent-view>). -## - -​ - -Plan before editing +## Plan before editing For changes you want to review before they touch disk, switch to plan mode. Claude reads files and proposes a plan but makes no edits until you approve. The status bar shows `⏸ plan mode on` while plan mode is active. @@ -480,11 +408,7 @@ You can also press `Shift+Tab` mid-session until the status bar shows `⏸ plan mode on`. See [Plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>) for the approval flow and editing the plan in your text editor. -## - -​ - -Delegate research to subagents +## Delegate research to subagents Exploring a large codebase fills your context with file reads. Delegate the exploration so only the findings come back. @@ -492,11 +416,7 @@ The subagent reads files in its own context window and reports a summary. See [Subagents](</docs/en/sub-agents>) for defining custom agents with their own tools and prompts. -## - -​ - -Pipe Claude into scripts +## Pipe Claude into scripts Run Claude non-interactively for CI, pre-commit hooks, or batch processing. Stdin and stdout work like any Unix tool. @@ -504,11 +424,7 @@ See [Non-interactive mode](</docs/en/headless>) for output formats, permission flags, and fan-out patterns. -## - -​ - -Next steps +## Next steps ## Best practices
modified Communications kit View current →
Show diff (223 lines)
--- a/communications-kit.md +++ b/communications-kit.md @@ -2,19 +2,11 @@ Treat everything here as draft copy, not finished copy. Rewrite each message in your organization’s voice, swap the example tasks for real bugs and modules from your own codebase, and replace the `[bracketed placeholders]` before sending. The announcements that drive adoption are the ones that read like someone at your company wrote them. -## - -​ - -Launch communications +## Launch communications One announcement in two formats, plus two optional variants. Pick whichever fits your rollout and rewrite it from there. -### - -​ - -Before you send +### Before you send Work through this checklist before the announcement goes out. Each item closes a gap that otherwise turns into a launch-day support thread. @@ -27,11 +19,7 @@ A named owner for the channel for the first 48 hours| Unanswered launch-day questions kill momentum A C-suite sponsor lined up to send or co-sign the announcement| Exec-sent launches consistently see higher first-week adoption than admin-sent ones -### - -​ - -The announcement +### The announcement Use this as your standard org-wide rollout message. It covers what Claude Code is, gives a two-minute install path, hands readers one concrete task to try, and answers “where does my code go?” before anyone has to ask. @@ -98,11 +86,7 @@ Questions → this thread. [Owner] is on point. -### - -​ - -Executive sponsor variant +### Executive sponsor variant Send this from your sponsoring executive, such as the CTO, CIO, or SVP Engineering, under their name and from their account. Launches that go out under an exec’s name consistently see higher open rates and faster first-week activation than the same message from an admin or tooling team. It signals a company priority rather than an optional experiment. This version is deliberately stripped to one ask: install it and run it on one real task. The exec’s job is to make the ask land; the standard announcement and `#claude-code` handle the how. @@ -145,11 +129,7 @@ That's it. Questions → #claude-code. -### - -​ - -Pilot group variant +### Pilot group variant Use for a phased rollout. Send to the pilot cohort only. @@ -171,11 +151,7 @@ without editing your source. It is the fastest way to calibrate how much to trust it. -### - -​ - -Champion recruitment DM +### Champion recruitment DM After launch, DM the two or three people who are most active in `#claude-code`. @@ -187,19 +163,11 @@ are posting, plus first crack at new features and a direct line to the Anthropic team. I can share a short playbook if you're in. -## - -​ - -Tips and tricks campaign +## Tips and tricks campaign Ready-to-paste Slack or Teams messages designed to drive feature activation after launch. Each follows the same pattern: a hook, the payoff, a “try it now” prompt, and a docs link. Drip them one or two a week in `#claude-code`, or pick the handful that match your team’s gaps. They stand alone with no required order. -### - -​ - -Get started +### Get started **Choosing the right model** @@ -253,11 +221,7 @@ 📖 Quickstart → https://code.claude.com/docs/en/quickstart -### - -​ - -Project memory +### Project memory **`/init` and CLAUDE.md** @@ -293,11 +257,7 @@ 📖 Referencing files → https://code.claude.com/docs/en/common-workflows -### - -​ - -Control and safety +### Control and safety **Permission modes** @@ -334,11 +294,7 @@ 📖 Checkpointing → https://code.claude.com/docs/en/checkpointing -### - -​ - -Connect your tools +### Connect your tools **MCP connectors** @@ -357,11 +313,7 @@ 📖 MCP connectors → https://code.claude.com/docs/en/mcp -### - -​ - -Automate your workflows +### Automate your workflows **Skills** @@ -395,11 +347,7 @@ 📖 Hooks guide → https://code.claude.com/docs/en/hooks-guide -### - -​ - -Day-to-day development +### Day-to-day development **Screenshots and images** @@ -434,11 +382,7 @@ 📖 Creating pull requests → https://code.claude.com/docs/en/common-workflows -### - -​ - -Share and scale +### Share and scale **Plugins** @@ -456,11 +400,7 @@ 📖 Plugins → https://code.claude.com/docs/en/plugins -### - -​ - -Security and admin +### Security and admin **Security architecture** @@ -498,17 +438,9 @@ 📖 Best practices → https://code.claude.com/docs/en/best-practices -## - -​ - -Quick reference - -### - -​ - -FAQ responses +## Quick reference + +### FAQ responses One-line replies for the questions you will be asked most. @@ -521,11 +453,7 @@ “How is this different from Copilot?”| Copilot autocompletes lines. Claude Code is an agent that reads files, runs commands, and makes multi-file edits. [Overview →](</docs/en/overview>) “What should I try first?”| A bug you’ve been putting off because it’s tedious. “The test in [file] is flaky, figure out why.” [Quickstart →](</docs/en/quickstart>) -### - -​ - -Prompt templates +### Prompt templates Share these starter prompts with engineers who have installed but aren’t sure what to ask. Each one is phrased the way it would be typed into a real session; replace the bracketed pieces with files from your own repo.
modified Add components to a plugin View current →
Show diff (345 lines)
--- a/components.md +++ b/components.md @@ -6,13 +6,9 @@ * **Installing someone else’s plugin** : see [Install plugins](</docs/en/plugins/install>) * **Your plugin’s users are on claude.ai or in Cowork** : a different set of components loads there. See [Plugin structure and testing](<https://claude.com/docs/plugins/build>) and the [component support table](<https://claude.com/docs/plugins/platform-support#compare-component-support-by-app>) -## - -​ - -Explore the plugin directory - -The explorer shows an example plugin, `my-plugin`, that has one of every kind of component in its default location: +## Explore the plugin directory + +The explorer shows an example plugin, `my-plugin`, that has these components in their default locations: * A review skill and an `about` command * A security-review subagent @@ -21,24 +17,15 @@ * An output style and a color theme * A route-audit workflow * A `hello-plugin` executable - * Default settings * A local MCP server and a Go language server Each file is the smallest valid example of its format, there to show the shape rather than to be useful: a real skill or agent carries full instructions and often supporting files, and a real hook or monitor does real work. The sections after the explorer use the same files as their examples and link to fuller ones. Select a file or folder to read what it’s for, see what goes in it, and find the section that covers it. -## - -​ - -Add each kind of component +## Add each kind of component Each section below covers one kind of component: where its files go in the plugin, an example that validates, what the user sees once the plugin loads, and the manifest key that changes the default location. Add the ones your plugin needs; none is required. -### - -​ - -Skills +### Skills A [skill](</docs/en/skills>) is a `SKILL.md` file that Claude can load when its description matches the task. The user can also run it as a command. Save each skill in its own directory under `skills/`: @@ -71,11 +58,7 @@ To include instructions in a plugin, write them as a skill. Claude Code doesn’t load a `CLAUDE.md` at the plugin root, and `claude plugin validate` warns `CLAUDE.md at the plugin root is not loaded as project context`. If a rule must hold every time, such as [blocking edits to protected files](</docs/en/hooks-guide#block-edits-to-protected-files>), add it to the plugin as a hook rather than a skill. To choose between the two, see the Hook vs Skill tab under [Compare similar features](</docs/en/features-overview#compare-similar-features>). For frontmatter fields and supporting files, see [Skills](</docs/en/skills>). -### - -​ - -Commands +### Commands A command is a single Markdown file the user runs by name, such as `/my-plugin:about`. @@ -83,11 +66,7 @@ Save a command at `commands/<file>.md` and it becomes `/<plugin>:<file>`. A subdirectory adds a segment, so `commands/db/migrate.md` is `/my-plugin:db:migrate`. Command files take the same frontmatter as skills. -#### - -​ - -Define commands in the manifest +#### Define commands in the manifest You only need this if you want to keep command files somewhere other than `commands/`, or to define a short command inside `plugin.json` without a separate Markdown file. Set the `commands` manifest key, and Claude Code reads it instead of scanning `commands/`. The key takes a path, an array of paths, or an object that maps each command name to either a `source` file or inline `content`. This manifest defines `/my-plugin:about` inline, with no Markdown file: @@ -105,11 +84,7 @@ Load the plugin and run `/my-plugin:about` in the session to confirm it loaded. For the full key syntax, see [`commands`](</docs/en/plugins/manifest-reference#commands>). -### - -​ - -Agents +### Agents A [subagent](</docs/en/sub-agents>) is a separate assistant, with its own instructions and context window, that Claude can delegate a task to. Each Markdown file under `agents/` defines one: @@ -125,22 +100,14 @@ This agent is named `my-plugin:security-reviewer`, and the user can [invoke it explicitly](</docs/en/sub-agents#invoke-subagents-explicitly>) with `@agent-my-plugin:security-reviewer`. The name form is `<plugin>:<name>`, where `<name>` comes from the frontmatter `name` field, or from the file name when that field is missing. The `agents` manifest key replaces the `agents/` scan. -#### - -​ - -Organize agents in subfolders +#### Organize agents in subfolders You can put plugin agent files in subfolders of `agents/`. Claude Code [loads them recursively](</docs/en/sub-agents#choose-the-subagent-scope>) and joins the plugin name, each subfolder name, and the file name with colons to form the agent’s scoped name. For example, `agents/review/security.md` in a plugin named `my-plugin` loads as `my-plugin:review:security`. Two settings change that name: * Frontmatter `name`: it replaces only the file name, so `name: audit` in `agents/review/security.md` loads as `my-plugin:review:audit` * Manifest [`agents`](</docs/en/plugins/manifest-reference#fields>) field: a file you list there loads without subfolder names, so `"agents": "./custom/review/security.md"` loads as `my-plugin:security` -#### - -​ - -Frontmatter fields in plugin agents +#### Frontmatter fields in plugin agents A plugin agent’s frontmatter follows these rules: @@ -151,11 +118,7 @@ For what each field does and the precedence rules, see [Subagents](</docs/en/sub-agents#supported-frontmatter-fields>). -### - -​ - -Hooks +### Hooks A [hook](</docs/en/hooks-guide>) runs something automatically at a point in Claude Code’s lifecycle, such as after every file edit: a shell command, an HTTP request, an MCP tool call, a prompt to a model, or a subagent. Save the plugin’s hooks in `hooks/hooks.json` at the plugin root, under a top-level `"hooks"` key, in the same shape as the `hooks` object in `settings.json`. That lets you copy an existing settings hook in unchanged. This hook runs a bundled script after every `Write` or `Edit`: @@ -179,19 +142,11 @@ Save the script at `scripts/format.sh` and make it executable. Load the plugin and ask Claude to edit a file. A `PostToolUse` hook that exits 0 shows nothing in the transcript, so confirm it ran with [debug logging](</docs/en/hooks#debug-hooks>) or by what the script itself changes. Hooks in `hooks/hooks.json` and in the `hooks` manifest key both load. For every event and its payload, see [Hook events](</docs/en/hooks#hook-events>). When another enabled plugin has the same name, one of the two registers its `hooks/hooks.json` hooks and the other’s are left out. See [Hooks when two enabled plugins share a name](</docs/en/plugins/loading#hooks-when-two-enabled-plugins-share-a-name>) for which one, and for the note in `/plugin` that tells you. To write hooks as JavaScript functions that run inside Claude Code and can draw in its interface, list a module file under a `modules` key in the same `hooks/hooks.json`. A plugin with one is a mod. See [Create a mod](</docs/en/plugins/mods/create>). -#### - -​ - -When plugin hooks fire +#### When plugin hooks fire A plugin’s hooks don’t wait for one of the plugin’s skills or commands to be used. Claude Code registers them when a session loads the plugin, and they fire on their events from then on. To limit when a hook runs, narrow its `matcher`. If a hook never fires, see [hooks that don’t fire](</docs/en/plugins/troubleshooting#failed-to-load-hooks-from-and-hooks-that-dont-fire>). -#### - -​ - -Environment, quoting, and matching MCP tools +#### Environment, quoting, and matching MCP tools The hook’s environment, the quoting of `${CLAUDE_PLUGIN_ROOT}`, and matchers for the plugin’s own MCP tools work as follows: @@ -199,11 +154,7 @@ * **Quoting** : when `command` has no `args`, it runs through a shell, so wrap the `${CLAUDE_PLUGIN_ROOT}` path in double quotes, as the `hooks/hooks.json` example under Hooks does, to keep the expanded path one shell word. When you pass `args` instead, each element is passed as one argument with no shell and needs no quoting. See [exec form and shell form](</docs/en/hooks#exec-form-and-shell-form>) * **Matching the plugin’s own MCP tools** : a tool from an MCP server this plugin declares is named `mcp__plugin_<plugin>_<server>__<tool>`, so write that full name in the matcher. A matcher on the server name alone never fires. See [Match MCP tools](</docs/en/hooks#match-mcp-tools>) -### - -​ - -MCP servers +### MCP servers An MCP server gives Claude tools from an external system. Declare it in `.mcp.json` at the plugin root, in the same shape as a [project `.mcp.json`](</docs/en/mcp#project-scope>). This `.mcp.json` declares one server named `db`: @@ -220,19 +171,11 @@ You can also omit the `mcpServers` wrapper and put `db` at the top level of the file. Load the plugin and run `/mcp` to confirm the server appears as `plugin:my-plugin:db`. `claude plugin validate` checks `.mcp.json` and reports a server entry that Claude Code would drop at load time as an error. Requires Claude Code v2.1.281 or later. For where a bad entry shows up at load time, see [MCP servers that don’t start](</docs/en/plugins/troubleshooting#invalid-mcp-server-config-for-and-mcp-servers-that-dont-start>). The `mcpServers` manifest key takes an inline server map, a path to a JSON file, or an array of those. When a manifest server has the same name as one in `.mcp.json`, the manifest server replaces it. -#### - -​ - -Reach users on claude.ai and Cowork +#### Reach users on claude.ai and Cowork A local stdio server, such as the `db` server under MCP servers, runs in Claude Code and in a Cowork session that runs on your machine in the Claude Desktop app, but not on claude.ai. To reach users there too, reference a remote server by its `https://` URL, which claude.ai and Cowork offer to the user as a connector, as [Bundle an MCP connector with its skill](<https://claude.com/docs/plugins/build#bundle-an-mcp-connector-with-its-skill>) shows. -#### - -​ - -Server names, tool names, and reloads +#### Server names, tool names, and reloads The server’s names, variable substitution, and reload behavior follow these rules: @@ -241,11 +184,7 @@ * **Substitution** : `${CLAUDE_PLUGIN_ROOT}` and the other path variables are substituted in `command`, `args`, and `env`. No quoting is needed in `args`, because each element is passed as one argument * **Reload** : when the user runs `/reload-plugins` and [the reload applies](</docs/en/plugins/cli-reference#reloads-that-change-mcp-tools>), a server whose configuration is unchanged keeps its connection. A server whose configuration changed reconnects, and one you removed disconnects -#### - -​ - -Include a packaged MCPB server +#### Include a packaged MCPB server The `mcpServers` key also accepts a packaged server as an [MCPB file](<https://github.com/modelcontextprotocol/mcpb>), whose extension is `.mcpb` or the older `.dxt`. Point the key at the file, as a path inside the plugin or an `https://` URL: @@ -263,11 +202,7 @@ For transports and authentication, see [MCP](</docs/en/mcp#plugin-provided-mcp-servers>). -### - -​ - -LSP servers +### LSP servers An LSP server gives Claude diagnostics and code navigation for a language. If an [official code intelligence plugin](</docs/en/plugins/code-intelligence>) already covers your language, install that instead of writing one. Otherwise declare the server in `.lsp.json` at the plugin root: @@ -290,11 +225,7 @@ The `lspServers` manifest key takes the same map inline, a path to a JSON file, or an array of those, and its servers add to the ones in `.lsp.json`. When a manifest server has the same name as one in `.lsp.json`, the manifest server replaces it. For `transport`, timeouts, restarts, and the other fields, see [`lspServers`](</docs/en/plugins/manifest-reference#lspservers>). Send log output to stderr, not stdout. Claude Code reads a server’s stdout as protocol messages only, and accepts message headers up to 64 KiB and a message body up to 32 MiB. Claude Code disconnects a server that exceeds either limit or writes non-protocol output to stdout, and counts the disconnect as a crash for `restartOnCrash` and `maxRestarts`. When you run with `--debug`, Claude Code writes an error naming the cause to the debug log. -### - -​ - -Executables +### Executables Files in `bin/` at the plugin root are on the `PATH` of the Bash tool’s shell while the plugin is enabled, so Claude can run them as bare commands. A command that Claude runs with the [PowerShell tool](</docs/en/tools-reference#powershell-tool>) outside the [sandbox](</docs/en/sandboxing>) finds them on its `PATH` too, and a sandboxed PowerShell command doesn’t. Add an executable script: @@ -305,33 +236,7 @@ Make it executable with `chmod +x bin/hello-plugin` and load the plugin. When you ask Claude to run `hello-plugin`, the Bash tool result shows the script’s output. Plugin `bin/` directories come after the user’s own `PATH` entries, so a plugin can’t shadow `git`, `ls`, or another system command. claude.ai and Cowork don’t install a plugin that has a top-level `bin/` directory, including one you [distribute through claude.ai organization settings](<https://claude.com/docs/plugins/org-sync#keep-executables-out-of-the-top-level-bin-directory>). -### - -​ - -Default settings - -To set defaults that apply while the plugin is enabled, add a `settings.json` at the plugin root, or put the same object inline in the `settings` manifest key. Two keys take effect, `agent` and `subagentStatusLine`, and every other key is dropped. Set `agent` to run one of the plugin’s own agents as the main thread: - -settings.json - - { - "agent": "security-reviewer" - } - -Load the plugin and start a session. Claude then answers in the main conversation with the `security-reviewer` agent’s system prompt and model. For everything the key controls, see the [`agent` setting](</docs/en/settings-reference#agent>). When the same key is set in more than one place, these rules decide which value applies: - - * **File over manifest** : when both exist and `settings.json` sets at least one supported key, `settings.json` applies and the manifest’s `settings` is ignored - * **User settings over plugin defaults** : across settings sources, plugin defaults are the lowest layer, so a user’s own `agent` in `~/.claude/settings.json` overrides yours - * **Two plugins set the same key** : the value from the plugin loaded last applies, and `claude --debug` logs `overrides setting` - -For the `subagentStatusLine` shape, see [subagent status lines](</docs/en/statusline#subagent-status-lines>). - -### - -​ - -Themes and output styles +### Themes and output styles A plugin can include color themes and output styles. Both appear in the same pickers as the user’s own. For either one, setting the manifest key replaces the folder scan. @@ -353,11 +258,7 @@ } } -### - -​ - -Channels +### Channels A [channel](</docs/en/channels>) lets an outside system such as a chat app send messages into a session. In a plugin, a channel is one of the MCP servers plus a `channels` entry that binds to it and can prompt for its own configuration. This manifest binds a channel to a `telegram` server and asks for a bot token: @@ -389,11 +290,7 @@ `server` must match a key in `mcpServers`. The per-channel `userConfig` takes the same shape as the top-level `userConfig` key. For what the server must implement and how users enable a channel plugin, see [Package as a plugin](</docs/en/channels-reference#package-as-a-plugin>) in the channels reference. For the field table, see [`channels`](</docs/en/plugins/manifest-reference#channels>). -### - -​ - -Monitors +### Monitors A monitor is a shell command that runs in the background for the whole session. What it prints reaches Claude as notifications, so Claude can react to a log or a status change without being asked to watch it. Save the entries in `monitors/monitors.json`: @@ -416,11 +313,7 @@ The `experimental.monitors` manifest key takes the same array inline or a path to a JSON file, and is read instead of `monitors/monitors.json`. For the `when` trigger and the other fields, see [`monitors`](</docs/en/plugins/manifest-reference#monitors>). -## - -​ - -Ask the user for configuration values +## Ask the user for configuration values Declare the values your plugin needs from the user in the `userConfig` manifest key, so users don’t edit `settings.json` themselves. Each option appears in a dialog with its `title` as the label and its `description` beneath it. Set `"sensitive": true` for a token or password. The dialog then masks the input, and the value is stored in secure storage rather than `settings.json`. This manifest asks for an endpoint and a token: @@ -443,11 +336,7 @@ } } -### - -​ - -When the configuration dialog appears +### When the configuration dialog appears The dialog is part of the interactive `/plugin` interface. When the user does any of the following, it opens for any option that isn’t set yet: @@ -457,11 +346,7 @@ To open the same dialog at any time, the user runs `/plugin configure <plugin>@<marketplace>`. The VS Code extension’s [Manage plugins dialog](</docs/en/vs-code#install-plugins>) asks for unset options as a form after an install, and a gear icon on the plugin’s row opens the form again with every option. The `claude plugin install` shell command never prompts for `userConfig` values. To set values from the shell, pass each one as `--config KEY=VALUE` when you install, or pipe a JSON object to [`claude plugin configure --values-stdin`](</docs/en/plugins/cli-reference#plugin-configure>) afterward. When options remain unset, `claude plugin install` prints a `userConfig options not yet set` line. For the line’s exact text, see [The `userConfig` dialog never appears](</docs/en/plugins/troubleshooting#the-userconfig-dialog-never-appears>). For the option fields, where each value is stored, how a component references a saved value, and which fields reject `${user_config.*}`, see [User configuration](</docs/en/plugins/manifest-reference#user-configuration>). -## - -​ - -Reference plugin paths and store data +## Reference plugin paths and store data You don’t know where your plugin will be installed, so refer to its files and data through these variables rather than fixed paths. They’re substituted in skill, command, and agent content, in hook and monitor commands, and in MCP and LSP server configurations. They’re also exported to hook, MCP, and LSP processes: @@ -471,11 +356,7 @@ In the data directory path, `<id>` is the plugin identifier with every character other than letters, digits, `_`, and `-` replaced by `-`, so `my-plugin@my-marketplace` becomes `my-plugin-my-marketplace`. On Windows, most substituted paths use forward slashes, as in `C:/Users/you/...`. They keep their native backslashes in an [exec-form hook](</docs/en/hooks#exec-form-and-shell-form>) and in a hook that runs through PowerShell, which is the default shell on Windows when Git Bash isn’t installed. -### - -​ - -Install dependencies into the data directory +### Install dependencies into the data directory For a marketplace-installed plugin, Claude Code installs eligible [Node.js package dependencies](</docs/en/plugins/loading#node-js-package-dependencies>) automatically when it caches the plugin, so you may not need to install them yourself. When you do, this `SessionStart` hook installs `node_modules` into `${CLAUDE_PLUGIN_DATA}` on first run and again after an update changes `package.json`: @@ -498,11 +379,7 @@ After the first session, `~/.claude/plugins/data/<id>/node_modules` exists. An MCP server can then set `NODE_PATH` to `${CLAUDE_PLUGIN_DATA}/node_modules` in its `env`. For which fields substitute which variable, see [Environment variables](</docs/en/plugins/manifest-reference#environment-variables>). -## - -​ - -Next steps +## Next steps * [Plugin manifest reference](</docs/en/plugins/manifest-reference>): `plugin.json` fields, path rules, and the standard layout * [Test plugins with evals](</docs/en/plugin-evals>): check that the components you added change Claude’s behavior the way you intend
modified Let Claude use your computer from the CLI View current →
Show diff (224 lines)
--- a/computer-use.md +++ b/computer-use.md @@ -2,11 +2,7 @@ Computer use lets Claude open apps, control your screen, and work on your machine the way you would. From the CLI, Claude can compile a Swift app, launch it, click through every button, and screenshot the result, all in the same conversation where it wrote the code. This page covers how computer use works in the CLI. For the Desktop app on macOS or Windows, see [computer use in Desktop](</docs/en/desktop#let-claude-use-your-computer>). -## - -​ - -What you can do with computer use +## What you can do with computer use Computer use handles tasks that require a GUI: anything you’d normally have to leave the terminal and do by hand. @@ -15,11 +11,7 @@ * **Debug visual and layout issues** : tell Claude “the modal is clipping on small windows.” Claude resizes the window, reproduces the bug, screenshots it, patches the CSS, and verifies the fix. Claude sees what you see. * **Drive GUI-only tools** : interact with design tools, hardware control panels, the iOS Simulator, or proprietary apps that have no CLI or API. -## - -​ - -When computer use applies +## When computer use applies Claude has several ways to interact with an app or service. Computer use is the broadest and slowest, so Claude tries the most precise tool first: @@ -30,11 +22,7 @@ Screen control is reserved for things nothing else can reach: native apps, simulators such as the iOS Simulator, and tools without an API. -## - -​ - -Enable computer use +## Enable computer use Computer use is available as a built-in MCP server called `computer-use`. It’s off by default until you enable it. @@ -70,11 +58,7 @@ Build the app target, launch it, and click through each tab to make sure nothing crashes. Screenshot any error states you find. -## - -​ - -Approve apps per session +## Approve apps per session Enabling the `computer-use` server doesn’t grant Claude access to every app on your machine. The first time Claude needs a specific app in a session, a prompt appears in your terminal showing: @@ -92,51 +76,27 @@ These apps aren’t blocked. The warning lets you decide whether the task warrants that level of access. Approve Finder to let Claude click the desktop, the Dock, or a Finder window. Claude’s level of control also varies by app category: browsers and trading platforms are view-only, terminals and IDEs are click-only, and everything else gets full control. See [app permissions in Desktop](</docs/en/desktop#app-permissions>) for the complete tier breakdown. -## - -​ - -How Claude works on your screen +## How Claude works on your screen Understanding the flow helps you anticipate what Claude will do and how to intervene. -### - -​ - -One session at a time +### One session at a time Only one session at a time can use your computer. A session takes a lock at its first computer use action and releases it when the session exits, not when the task finishes. A second session’s computer use fails with an error naming the session that holds the lock. Exit that session first. -### - -​ - -Apps are hidden while Claude works +### Apps are hidden while Claude works When Claude starts controlling your screen, other visible apps are hidden so Claude interacts with only the approved apps. Your terminal window stays visible and is excluded from screenshots, so you can watch the session and Claude never sees its own output. When Claude finishes the turn, hidden apps are restored automatically. -### - -​ - -Screenshots are downscaled automatically +### Screenshots are downscaled automatically Claude Code downscales every screenshot before sending it to the model. You don’t need to lower your display resolution or resize windows on Retina or other high-resolution displays. A 16-inch MacBook Pro at native Retina resolution captures at 3456×2234 and downscales to roughly 1372×887, preserving aspect ratio. There is no setting to change the target size. If on-screen text or controls are too small for Claude to read after downscaling, increase their size in the app rather than changing your display resolution. -### - -​ - -Stop at any time +### Stop at any time The first time Claude uses your computer in each turn, a macOS notification appears: “Claude is using your computer · press Esc to stop.” Press `Esc` anywhere to abort the current action immediately, or press `Ctrl+C` in the terminal. Either way, Claude stops, unhides your apps, and returns control to you. The session keeps the computer use lock until it exits. A second notification appears when Claude is done. -## - -​ - -Safety and the trust boundary +## Safety and the trust boundary Unlike the [sandboxed Bash tool](</docs/en/sandboxing>), computer use runs on your actual desktop with access to the apps you approve. Claude checks each action and flags potential prompt injection from on-screen content, but the trust boundary is different. See the [computer use safety guide](<https://support.claude.com/en/articles/14128542>) for best practices. @@ -148,19 +108,11 @@ * **Global escape** : the `Esc` key aborts computer use from anywhere, and the key press is consumed so prompt injection can’t use it to dismiss dialogs. * **Lock file** : only one session can control your machine at a time. -## - -​ - -Example workflows +## Example workflows These examples show common ways to combine computer use with coding tasks. -### - -​ - -Validate a native build +### Validate a native build After making changes to a macOS or iOS app, have Claude compile and verify in one pass: @@ -170,11 +122,7 @@ Claude runs `xcodebuild`, launches the app, interacts with the UI, and reports what it finds. -### - -​ - -Reproduce a layout bug +### Reproduce a layout bug When a visual bug only appears at certain window sizes, let Claude find it: @@ -184,11 +132,7 @@ Claude resizes the window, captures the broken state, and reads the relevant stylesheets. -### - -​ - -Test a simulator flow +### Test a simulator flow Drive the iOS Simulator without writing XCTest: @@ -197,11 +141,7 @@ Claude controls the simulator the same way you would with a mouse. This flow applies to the CLI; in the Desktop app, the same request opens the [iOS Simulator pane](</docs/en/desktop-ios-simulator>) instead of screen control. -## - -​ - -Differences from the Desktop app +## Differences from the Desktop app The CLI and Desktop surfaces share the same computer use engine, with a few differences: @@ -213,33 +153,17 @@ Auto-unhide toggle| Optional| Always on Dispatch integration| Dispatch-spawned sessions can use computer use| Not applicable -## +## Troubleshooting -​ - -Troubleshooting - -### - -​ - -”Computer use is in use by another Claude session” +### ”Computer use is in use by another Claude session” Another Claude Code session holds the lock, which it keeps until it exits. Exit that session. If the other session crashed, the lock is released automatically when Claude detects the process is no longer running. -### - -​ - -macOS permissions prompt keeps reappearing +### macOS permissions prompt keeps reappearing macOS sometimes requires a restart of the requesting process after you grant Screen Recording. Quit Claude Code completely and start a new session. If the prompt persists, open **System Settings > Privacy & Security > Screen Recording** and confirm your terminal app is listed and enabled. -### - -​ - -`computer-use` doesn’t appear in `/mcp` +### `computer-use` doesn’t appear in `/mcp` The server only appears on eligible setups. Check that: @@ -248,11 +172,7 @@ * You’re authenticated through claude.ai. Computer use is not available with third-party providers like Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry. If you access Claude exclusively through a third-party provider, you need a separate claude.ai account to use this feature. * You’re in an interactive session. Computer use is not available in non-interactive mode with the `-p` flag. -## - -​ - -See also +## See also * [Computer use in Desktop](</docs/en/desktop#let-claude-use-your-computer>): the same capability with a graphical settings page * [Claude in Chrome](</docs/en/chrome>): browser automation for web-based tasks
modified Configure your agent View current →
Show diff (118 lines)
--- a/configuration.md +++ b/configuration.md @@ -1,10 +1,6 @@ An Agent SDK session reads configuration from settings files, environment variables, and the `options` object you pass when you start it. This page shows how to compose the `options` object and what settings files and environment variables control. For every option’s type and default, see the [`Options`](</docs/en/agent-sdk/typescript#options>) (TypeScript) and [`ClaudeAgentOptions`](</docs/en/agent-sdk/python#claudeagentoptions>) (Python) references. -## - -​ - -Pass options to a session +## Pass options to a session Every `query()` call accepts an options object: `Options` in TypeScript, `ClaudeAgentOptions` in Python. Each field is optional, and a session started with no options runs with the SDK’s defaults. The example below configures a read-only session that summarizes a project’s open TODOs. Pairs read as TypeScript / Python where the spellings differ: @@ -56,11 +52,7 @@ Point `cwd` at one of your own projects and run the example. The summary of that project’s open TODOs prints when the result message arrives. `allowedTools` (TypeScript) or `allowed_tools` (Python) pre-approves the listed tools, so calls to them run without stopping for approval. Tools outside the list stay available. When Claude calls an unlisted tool, the permission mode decides whether the call runs. For more information, see [Allow and deny rules](</docs/en/agent-sdk/permissions#allow-and-deny-rules>). -## - -​ - -Load settings files +## Load settings files Settings files supply configuration beyond the options object. Two options control how they load: @@ -69,11 +61,7 @@ Pass `[]` to disable user, project, and local settings. For more information, see [Use Claude Code features in the SDK](</docs/en/agent-sdk/claude-code-features>). -## - -​ - -Choose a model +## Choose a model Unless the `model` option, your settings, or your environment selects a model, a new session starts on [Claude Code’s default model](</docs/en/model-config#default-model-setting>). For the order of those sources, see [Setting your model](</docs/en/model-config#setting-your-model>). Set `model` to pin a specific model, or to pick a smaller one for faster, cheaper agents. The value takes a model alias or a full model name; aliases and the versions they resolve to are listed under [Model aliases](</docs/en/model-config#model-aliases>). Set `fallbackModel` (TypeScript) or `fallback_model` (Python) to name a backup model. When the primary is overloaded or unavailable, the session switches to the backup. The primary is retried at the start of each user turn, so the session returns to it once the outage passes. In either language, the option accepts a single model or a comma-separated list of backups. For the order and the chain cap, see [Fallback model chains](</docs/en/model-config#fallback-model-chains>). In TypeScript, a fallback equal to `model` throws an error at startup. The examples below show a fallback list in TypeScript and a single fallback in Python: @@ -93,11 +81,7 @@ The [Messages API](<https://platform.claude.com/docs/en/api/messages>) request parameters `temperature`, `top_p`, and `max_tokens` have no fields on the options object in either language. Set the [effort level](</docs/en/agent-sdk/agent-loop#effort-level>) or a spend cap instead, or call the Messages API when you need those parameters directly. -## - -​ - -Set environment variables +## Set environment variables The `env` option sets environment variables for the Claude Code process that runs your session. Whether your values replace the inherited environment or merge over it differs by language: @@ -120,11 +104,7 @@ The variables you pass can also configure Claude Code itself. For the variables the Claude Code process reads, see [Environment variables](</docs/en/env-vars>). To tune API timeouts and stall detection this way, follow the Handle slow or stalled API responses section in the [TypeScript reference](</docs/en/agent-sdk/typescript#handle-slow-or-stalled-api-responses>) or the [Python reference](</docs/en/agent-sdk/python#handle-slow-or-stalled-api-responses>). -## - -​ - -Set the working directory +## Set the working directory Set `cwd` to run the session in a specific directory. When you leave `cwd` unset, the session runs in your process’s working directory. Neither SDK has a setter for `cwd`. To run in a different directory, start another session with that `cwd`. Claude Code reads the working directory to determine: @@ -134,11 +114,7 @@ To let tools reach files outside the working directory, add paths with `additionalDirectories` (TypeScript) or `add_dirs` (Python). For the scope of that grant, see [Additional directories grant file access, not configuration](</docs/en/permissions#additional-directories-grant-file-access-not-configuration>). -## - -​ - -Limit turns and spend +## Limit turns and spend Cap turns and spend with `maxTurns` / `max_turns` and `maxBudgetUsd` / `max_budget_usd`. Both caps are off when unset. When a session hits a cap, the run ends with a result message whose subtype names the cap, `error_max_turns` or `error_max_budget_usd`. What happens next differs by input mode: @@ -152,11 +128,7 @@ For more information about both caps, including subagent spend, see [Turns and budget](</docs/en/agent-sdk/agent-loop#turns-and-budget>). -## - -​ - -Change configuration mid-session +## Change configuration mid-session When you start a session with [streaming input](</docs/en/agent-sdk/streaming-vs-single-mode>), you can switch its model and permission mode while it runs. Where you call the setters differs by language: @@ -258,11 +230,7 @@ Each model has its own prompt cache, so after a mid-session switch the next request recomputes the full conversation uncached at the new model’s rates. For more information, see [Switching models](</docs/en/prompt-caching#switching-models>). -## - -​ - -Configure specific features +## Configure specific features The table below maps each option to the feature it configures. For options this page doesn’t cover, see the [TypeScript](</docs/en/agent-sdk/typescript#options>) and [Python](</docs/en/agent-sdk/python#claudeagentoptions>) references. If you know your goal but not which option serves it, start from [Choose the right feature](</docs/en/agent-sdk/claude-code-features#choose-the-right-feature>). @@ -286,11 +254,7 @@ `effort`| `effort`| How much work Claude puts into responses| [Effort level](</docs/en/agent-sdk/agent-loop#effort-level>) `sandbox`| `sandbox`| Sandbox behavior for tool execution| [TypeScript](</docs/en/agent-sdk/typescript#sandbox-configuration>) and [Python](</docs/en/agent-sdk/python#sandbox-configuration>) references, with deployment context in [Secure deployment](</docs/en/agent-sdk/secure-deployment>) -## - -​ - -Next steps +## Next steps To see configuration composed into working agents:
modified Explore the context window View current →
--- a/context-window.md +++ b/context-window.md @@ -1,10 +1,6 @@ Claude Code’s context window holds everything Claude knows about your session: your instructions, the files it reads, its own responses, and content that never appears in your terminal. The timeline below plays a full session from startup to compaction: what loads before you type, what each file read, rule, and hook adds as Claude works, and how a subagent keeps large reads out of your context. See the written breakdown for the same content as a list. -## - -​ - -What the timeline shows +## What the timeline shows The session walks through a realistic flow with representative token counts: @@ -13,11 +9,7 @@ * **The follow-up prompt** : a [subagent](</docs/en/sub-agents>) handles the research in its own separate context window, so the large file reads stay out of yours. Only the summary and a small metadata trailer come back. * **At the end of the walkthrough** : you run `/compact`, which replaces the conversation with a structured summary. Most startup content reloads automatically; the table below shows what happens to each mechanism. -## - -​ - -What survives compaction +## What survives compaction When a long session compacts, Claude Code summarizes the conversation history to fit the context window. @@ -39,11 +31,7 @@ Right after compaction, Claude Code re-reads up to five of the files Claude has read or edited in the session, choosing the ones modified most recently. A file over 5,000 tokens comes back as a path reference without its content, shown as `Referenced file` instead of `Read`. Path-scoped rules and nested CLAUDE.md files load into message history when Claude reads, writes, or edits their trigger file, so compaction summarizes them away with everything else. If a rule must persist across compaction, drop the `paths:` frontmatter or move it to the project-root CLAUDE.md. Skill bodies are re-injected after compaction, but large skills are truncated to fit the per-skill cap, and the oldest invoked skills are dropped once the total budget is exceeded. Truncation keeps the start of the file, so put the most important instructions near the top of `SKILL.md`. -## - -​ - -When your context fills up +## When your context fills up Claude Code compacts automatically as you approach the limit, so a full context window doesn’t end your session. The automatic pass works the same way as the `/compact` step in the timeline. See [When context fills up](</docs/en/how-claude-code-works#when-context-fills-up>) for what it preserves. For when Claude Code also compacts a conversation you leave idle, see [idle compaction](</docs/en/settings-reference#idlecompaction>). You can also act before the automatic pass runs: @@ -55,19 +43,11 @@ If you need a larger window rather than a smaller conversation, Fable models, Sonnet 5 and later, Haiku 5.5, Opus 4.6 and later, and Sonnet 4.6 support a 1 million token context window. See [Extended context](</docs/en/model-config#extended-context>) for availability by plan and how to select a `[1m]` model variant. Compaction works the same way at the larger limit. The point where automatic compaction runs depends on your model and configuration. See [Default auto-compact thresholds](</docs/en/model-config#default-auto-compact-thresholds>) for the boundaries per model, and [Correct the window for a gateway or custom model ID](</docs/en/model-config#correct-the-window-for-a-gateway-or-custom-model-id>) if Claude Code assumes the wrong window for your model ID, such as an [LLM gateway](</docs/en/llm-gateway>) alias. -## - -​ - -Check your own session +## Check your own session The visualization uses representative numbers. To see your actual context usage at any point, run `/context` for a live breakdown by category with optimization suggestions, including which CLAUDE.md and auto memory files loaded. Run `/memory` to open and edit those files. -## - -​ - -Related resources +## Related resources For deeper coverage of the features shown in the timeline, see these pages:
modified Run Claude Code behind a corporate launcher View current →
Show diff (111 lines)
--- a/corporate-launcher.md +++ b/corporate-launcher.md @@ -2,11 +2,7 @@ `CLAUDE_CODE_PROCESS_WRAPPER` requires Claude Code v2.1.208 or later. Earlier versions ignore the variable and start every process unwrapped. The equivalent [`processWrapper` setting](</docs/en/settings-reference#processwrapper>) requires v2.1.210 or later. Earlier versions ignore it as an unknown key, apply no launcher, and report no error.After deploying either form, use the Verify step to confirm the running version applies it. -## - -​ - -What the launcher covers +## What the launcher covers With `CLAUDE_CODE_PROCESS_WRAPPER` set, Claude Code starts each of the following processes through your launcher: @@ -19,11 +15,7 @@ On Windows, the variable is ignored: the launcher contract depends on `exec`, which Windows doesn’t support. A Windows machine with the variable set runs every process unwrapped and keeps working, and the only signal is a warning in the [debug log](</docs/en/troubleshooting>). If your launcher policy covers Windows, the variable doesn’t satisfy it there: count Windows machines as unwrapped when you plan the rollout. -### - -​ - -Processes that start outside the launcher +### Processes that start outside the launcher The following processes don’t start through the launcher: @@ -32,19 +24,11 @@ * The relaunch that `--worktree` combined with `--tmux` performs: the terminal multiplexer starts that pane, not Claude Code’s binary. * The native-messaging host that [Claude in Chrome](</docs/en/chrome>) registers: the browser starts it, not Claude Code’s binary. -### - -​ - -Helper process names in process monitors +### Helper process names in process monitors With a launcher configured, `ps` and Activity Monitor no longer show Claude Code’s `claude bg-pty-host` and `claude bg-spare` labels for the background helper processes, because the launcher’s `exec` rebuilds the argument list. Losing the labels is a side effect, not concealment: the processes are otherwise unchanged, and Claude Code identifies its own processes by binary path, never by display name. -## - -​ - -Set up the launcher +## Set up the launcher 1 @@ -93,11 +77,7 @@ Run `/status` in a session: the Self-exec entry shows the resolved launch command and warns when the running background service doesn’t match it. `claude daemon status` prints the same information from the shell, including after you unset the variable, when `/status` no longer shows the entry. -## - -​ - -The launcher contract +## The launcher contract When the launcher can’t run, Claude Code refuses to start the process instead of starting it unwrapped. On Windows, the variable is ignored and processes start unwrapped. Claude Code holds the script to these rules: @@ -114,11 +94,7 @@ * **Don’t read standard input.** A command that reads it before the `exec`, such as one that asks for a password, can wait for input that doesn’t come and leave the session stuck. It can also take input meant for Claude Code, and the session can then run without that input and report no error. Redirect such a command’s input from `/dev/null`. * **Call other programs by absolute path.** The launcher can start with a `PATH` that lacks the directories your shell profile adds. -### - -​ - -Format of the launcher value +### Format of the launcher value `CLAUDE_CODE_PROCESS_WRAPPER` and the `processWrapper` setting take the same format. For most launchers, the value is the script’s absolute path, like `/opt/corp/launcher`. To pass your launcher arguments of its own, write them after the path. Claude Code parses the value as an argument list, not a shell command: @@ -128,11 +104,7 @@ When the value can’t be used, Claude Code refuses to start the affected process and [reports the reason](</docs/en/errors#claude_code_process_wrapper-launcher-errors>). In a settings file, write the array form inside a JSON string and escape its quotes: `"[\"/opt/corp/launcher\", \"--profile\", \"cc\"]"`. -### - -​ - -Pass arguments to the launcher +### Pass arguments to the launcher Write the launcher’s own arguments after its path in the value, and remove them in the script before the `exec` call. They reach the script first, ahead of the Claude Code command. The following script, written for the value `/opt/corp/launcher --profile cc`, saves the profile name and then removes both arguments with `shift`: @@ -146,19 +118,11 @@ Use the Verify step to see the launch command Claude Code resolved from the value. -## - -​ - -Relationship to `CLAUDE_CODE_SHELL_PREFIX` +## Relationship to `CLAUDE_CODE_SHELL_PREFIX` `CLAUDE_CODE_PROCESS_WRAPPER` wraps Claude Code’s own processes and passes the command through as separate argv tokens for the launcher to `exec`. [`CLAUDE_CODE_SHELL_PREFIX`](</docs/en/env-vars>) wraps the shell commands Claude runs on your behalf, such as Bash tool calls, hooks, and the commands that start stdio MCP servers, and passes each one as a single shell-quoted string in `$1` for the wrapper to re-evaluate. A launcher written for one doesn’t work as the other. -## - -​ - -Related resources +## Related resources * [Agent view](</docs/en/agent-view>): the background sessions and supervisor process the launcher covers * [Environment variables](</docs/en/env-vars>): the `CLAUDE_CODE_PROCESS_WRAPPER` reference entry
modified Track cost and usage View current →
Show diff (172 lines)
--- a/cost-tracking.md +++ b/cost-tracking.md @@ -8,11 +8,7 @@ One billing rule the SDK does model is [data residency pricing](<https://platform.claude.com/docs/en/about-claude/pricing#data-residency-pricing>). When a response’s `usage` reports `inference_geo: "us"`, the SDK multiplies the list price of that response’s tokens by 1.1. Per-request fees such as web search aren’t multiplied. Requires TypeScript Agent SDK v0.3.239 or later, or Python Agent SDK v0.2.144 or later.Use these fields for development insight and approximate budgeting. For authoritative billing, see [Manage costs for your organization](</docs/en/costs#manage-costs-for-your-organization>). Don’t bill end users or trigger financial decisions from these fields. -## - -​ - -Understand token usage +## Understand token usage The TypeScript and Python SDKs expose the same usage data with different field names: @@ -39,11 +35,7 @@ When the `query()` call completes, the SDK emits a result message with `total_cost_usd` and cumulative `usage`, typed as [`SDKResultMessage`](</docs/en/agent-sdk/typescript#sdkresultmessage>) in TypeScript and [`ResultMessage`](</docs/en/agent-sdk/python#resultmessage>) in Python. If you only need the estimated total, you can ignore the per-step usage and read this single value.If you make multiple independent `query()` calls, each result reflects only the cost of that individual call. A call that resumes a session also counts the session’s earlier spend.In streaming input mode, each turn emits its own result message. See Track costs in streaming input mode for how to read call totals in that mode. -## - -​ - -Track costs in streaming input mode +## Track costs in streaming input mode In [streaming input mode](</docs/en/agent-sdk/streaming-vs-single-mode>), one `query()` call carries multiple user turns and each turn emits its own result message. The result fields differ in scope: @@ -58,11 +50,7 @@ To total the whole call, add the last result from before each `/clear` to the call’s final result. Every other result, including the `/clear` turn’s own, is superseded by a later one. In TypeScript, the SDK also emits an [`SDKConversationResetMessage`](</docs/en/agent-sdk/typescript#sdkconversationresetmessage>) at each reset, so you can detect resets from the stream. In Python, the SDK likewise emits a `ConversationResetMessage`. Before Python SDK v0.2.137, the Python iterator dropped that message, so on those versions count the resets yourself from the `/clear` turns your app sends. `maxBudgetUsd` (TypeScript) or `max_budget_usd` (Python) counts only the call’s own spend: totals restored from a resumed session don’t count against it, and a `/clear` starts the budget over. -## - -​ - -Get the total cost of a query +## Get the total cost of a query The result message, typed as [`SDKResultMessage`](</docs/en/agent-sdk/typescript#sdkresultmessage>) in TypeScript and [`ResultMessage`](</docs/en/agent-sdk/python#resultmessage>) in Python, marks the end of the agent loop for a `query()` call. It includes `total_cost_usd`, the cumulative estimated cost across all steps in that call. A call that resumes a session also counts the session’s earlier spend. Two caveats apply when you read the value: @@ -117,19 +105,11 @@ To bound how much subagents can add to `total_cost_usd`, set the [depth, concurrency, and spend limits](</docs/en/agent-sdk/subagents#cap-subagent-depth-concurrency-and-spend>) on the query. -## - -​ - -Track per-step and per-model usage +## Track per-step and per-model usage The examples in this section use TypeScript field names. In Python, the equivalent fields are [`AssistantMessage.usage`](</docs/en/agent-sdk/python#assistantmessage>) and `AssistantMessage.message_id` for per-step usage, and [`ResultMessage.model_usage`](</docs/en/agent-sdk/python#resultmessage>) for per-model breakdowns. -### - -​ - -Track per-step usage +### Track per-step usage Each assistant message contains a nested `BetaMessage` (accessed via `message.message`) with an `id` and `usage` object with token counts. When Claude uses tools in parallel, multiple messages share the same `id` with identical usage data. Track which IDs you’ve already counted and skip duplicates to avoid inflated totals. @@ -170,11 +150,7 @@ console.log(`Input tokens: ${totalInputTokens}`); console.log(`Output tokens: ${resultOutputTokens}`); -### - -​ - -Break down usage per model +### Break down usage per model The result message includes [`modelUsage`](</docs/en/agent-sdk/typescript#modelusage>), a map of model name to per-model token counts and cost. This is useful when you run multiple models (for example, Haiku for subagents and Opus for the main agent) and want to see where tokens are going. Each entry’s `costBasis` says which price table priced that model’s latest request: `list` for list price, `managed` for a [`modelPricing`](</docs/en/settings-reference#modelpricing>) table, or `unknown` when neither matched the model ID. The field requires Claude Code v2.1.246 or later. The following example runs a query and prints the cost and token breakdown for each model used: @@ -199,11 +175,7 @@ console.error(`Session ended with an error: ${error}`); } -## - -​ - -Accumulate costs across multiple calls +## Accumulate costs across multiple calls Each `query()` call returns `total_cost_usd` on its results. How you combine the values depends on whether the calls share a session: @@ -275,27 +247,15 @@ asyncio.run(main()) -## - -​ - -Handle errors, caching, and output token counts +## Handle errors, caching, and output token counts For accurate cost tracking, account for the placeholder output count on assistant messages, the tokens a failed conversation consumed, and cache token pricing. -### - -​ - -Read output tokens from the result message +### Read output tokens from the result message Claude Code builds each assistant message from the usage the API reported when the response began, so the message’s `output_tokens` is only the count the API had reported at `message_start`, before the response was generated. One API response can produce several assistant messages, and every one of them carries that same placeholder. The API reports the real output count at the end of the response, and Claude Code adds it to the result message. Read output tokens from the result’s `usage`, or from `modelUsage` for a per-model breakdown. -### - -​ - -Track costs on failed conversations +### Track costs on failed conversations Both success and error result messages include `usage` and `total_cost_usd`; in Python both fields are typed as optional, so check that they aren’t `None` before you read them. If a conversation fails midway, you still consumed tokens up to the point of failure. Read cost data from every result message, whether its `subtype` is `success` or one of the error subtypes. On some error results, `usage` reports less than the call spent: @@ -304,11 +264,7 @@ Where you have the choice, account from `total_cost_usd` or `modelUsage` rather than `usage`. -### - -​ - -Recover totals after a session crash +### Recover totals after a session crash When the Claude Code process crashes, it emits a final `error_during_execution` result and exits, in single-shot and streaming input mode alike. That result may carry zeroed `usage`, `total_cost_usd`, and `modelUsage`, so recover the call’s totals from what arrived before it. Step 1 recovers the full totals whenever an earlier result exists; the fallback in step 2 recovers only the main loop’s input and cache tokens. @@ -318,11 +274,7 @@ * The turn before the crash was the `/clear` itself, so its result covers only the reset. 2. Sum the `usage` on the assistant messages instead, counting each API response once, as the Track per-step usage example does. In single-shot mode, sum all of them; in streaming input mode, sum the ones that arrived after the last result. This gives you the main loop’s input and cache tokens. Subagent usage isn’t recoverable this way, and neither are output tokens or USD cost, because per-step `output_tokens` is a placeholder. -### - -​ - -Track cache tokens +### Track cache tokens The Agent SDK automatically uses [prompt caching](<https://platform.claude.com/docs/en/build-with-claude/prompt-caching>) to reduce costs on repeated content. You do not need to configure caching yourself. The usage object includes two additional fields for cache tracking: @@ -331,11 +283,7 @@ Track these separately from `input_tokens` to understand caching savings. In TypeScript, these fields are typed on the [`Usage`](</docs/en/agent-sdk/typescript#usage>) object. In Python, they appear as keys in the [`ResultMessage.usage`](</docs/en/agent-sdk/python#resultmessage>) dict (for example, `message.usage.get("cache_read_input_tokens", 0)`). -### - -​ - -Extend the prompt cache TTL to one hour +### Extend the prompt cache TTL to one hour Your own turns fall in the [main conversation TTL bucket](</docs/en/prompt-caching#which-ttl-each-request-gets>), together with the helpers Claude Code runs inline with them. The requests Claude Code makes outside that conversation, such as [subagents](</docs/en/agent-sdk/subagents>), have a [separate TTL control](</docs/en/prompt-caching#choose-the-ttl-yourself>). Cache entries for your own turns use a 5-minute TTL by default when you authenticate with an API key or run on Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, or [Claude Platform on AWS](</docs/en/claude-platform-on-aws>). If your workload runs many short sessions against the same system prompt and context with gaps longer than 5 minutes between them, the cache expires between sessions and each new session pays full input price. To request a 1-hour TTL on cache writes, set the [`ENABLE_PROMPT_CACHING_1H`](</docs/en/env-vars>) environment variable. You can export it in your shell or container environment, or pass it through `options.env`. The following example enables 1-hour TTL for an agent running on Amazon Bedrock. Because it sets `CLAUDE_CODE_USE_BEDROCK`, it requires working AWS credentials for [Amazon Bedrock](</docs/en/amazon-bedrock>); without them the query fails. @@ -380,11 +328,7 @@ Setting `promptCacheTtl` to `1h` keeps the 1-hour cache on the main conversation while you’re drawing on usage credits. For the full precedence order, see [choose the TTL yourself](</docs/en/prompt-caching#choose-the-ttl-yourself>). -## - -​ - -Related documentation +## Related documentation * [TypeScript SDK Reference](</docs/en/agent-sdk/typescript>) \- Complete API documentation * [SDK Overview](</docs/en/agent-sdk/overview>) \- Getting started with the SDK
modified Manage costs effectively View current →
Show diff (380 lines)
--- a/costs.md +++ b/costs.md @@ -1,16 +1,8 @@ Claude Code charges by API token consumption. For subscription plan pricing (Pro, Max, Ultra, Team, Enterprise), see [claude.com/pricing](<https://claude.com/pricing>). Per-developer costs vary widely based on model selection, codebase size, and usage patterns such as running multiple instances or automation. Across enterprise deployments, the average cost is around $13 per developer per active day and $150-250 per developer per month, with costs remaining below $30 per active day for 90% of users. To estimate spend for your own team, start with a small pilot group and use the tracking tools below to establish a baseline before wider rollout. This page covers Claude Code usage only: how to track your costs, manage costs for your organization, and reduce token usage. For usage limits in other Claude products, see the [Claude Help Center](<https://support.claude.com>). -## - -​ - -Track your costs - -### - -​ - -Using the `/usage` command +## Track your costs + +### Using the `/usage` command The Session block in `/usage` shows API token usage and is intended for API users. Claude Pro, Max, and Ultra subscribers have usage included in their subscription, so the session cost figure isn’t relevant for billing purposes. Subscribers see plan usage bars, activity stats, and a usage breakdown on the same screen. @@ -25,11 +17,7 @@ These totals reset when `/clear` starts a new session, so the next session’s total cost starts at $0. Before v2.1.211, they kept accumulating across `/clear` for the lifetime of the Claude Code process. For a response from the Claude API billed at the 1.1× [data residency rate](<https://platform.claude.com/docs/en/about-claude/pricing#data-residency-pricing>), Claude Code multiplies the list price of that response’s tokens by 1.1 in the session cost figure. The same total appears in the [status line’s cost field](</docs/en/statusline#cost-and-duration-tracking>), and the multiplied figure also counts toward [`--max-budget-usd`](</docs/en/cli-reference#cli-flags>). -#### - -​ - -Prompt cache statistics +#### Prompt cache statistics After the main conversation’s first API response, Claude Code also adds a `Prompt cache (main)` line to the Session block, summarizing the session’s [prompt cache](</docs/en/prompt-caching>) use: the request count, the share of input tokens served from cache, cache misses, and whether the cache is warm right now. Requires Claude Code v2.1.251 or later. @@ -43,11 +31,7 @@ The counts come from the cache token fields in the API’s responses, so the line works on every provider and gateway. It covers the main conversation only, not subagents. `/clear` resets it with the rest of the Session block. Status line scripts can read the same numbers from the [`prompt_cache` object](</docs/en/statusline#prompt-cache-fields>). -#### - -​ - -Plan usage breakdown +#### Plan usage breakdown On a Pro, Max, Ultra, Team, or Enterprise plan, `/usage` also shows a breakdown of what counts against your plan limits, with recommendations: @@ -61,11 +45,7 @@ Press `d` or `w` to switch between the last 24 hours and the last 7 days. The figures are approximate and computed from local session history on this machine, so usage from other devices or claude.ai is not included. In the [VS Code extension](</docs/en/vs-code#check-account-and-usage>), the attribution shares and recommendations appear in the Account & usage dialog with a Day and Week toggle, without the Loops rows. -#### - -​ - -Apply recommendations with the fix shortcut +#### Apply recommendations with the fix shortcut When the `/usage` footer shows a hint such as `f to fix 2 of 3`, press `f` to have Claude Code act on the recommendations it can. The `f` shortcut requires Claude Code v2.1.305 or later. @@ -82,11 +62,7 @@ In `f to fix 2 of 3`, the first number counts the rows Claude Code acts on when you press `f`, and the second counts the rows shown. A hint with no `of` in it, such as `f to fix both`, means Claude Code acts on every row shown. While [Remote Control](</docs/en/remote-control>) is connected, the footer shows no `f` hint. If pressing `f` closes `/usage` with `Nothing was sent. Turn off Remote Control to use fixes.`, Remote Control connected while `/usage` was open. To use `f` again, [disconnect Remote Control](</docs/en/remote-control#check-connection-status>), then run `/usage` at the Claude Code prompt and press `f` again. -#### - -​ - -Check your usage-credits spend +#### Check your usage-credits spend `/usage` also shows a usage-credits row while usage credits are on. What the row shows depends on your plan: @@ -95,19 +71,11 @@ When you have a spend limit, the row appears as soon as usage credits are on and shows 0% until you first spend usage credits. Before v2.1.236, `/usage` showed the row only on Pro, Max, and Ultra plans, and a row with a spend limit stayed hidden until you had spent something. -#### - -​ - -When the usage request fails +#### When the usage request fails When the request for your plan limits fails, most often because the usage endpoint is rate limited, `/usage` shows the last usage bars it loaded on this machine within the past 60 minutes, along with a `Showing last-known usage` note stating how long ago that data was fetched. Press `r` to retry; a successful retry replaces the last-known bars with fresh data. Without a snapshot from the past 60 minutes, `/usage` reports that the usage endpoint is rate limited and offers the same retry shortcut. Before v2.1.208, a rate-limited request in a session that hadn’t loaded usage yet always showed the error with no bars. A message such as `rate limited until 3:14am` in `/usage` means Claude Code can’t fetch your plan limits again until then, not that your work with Claude is limited. If you press `r` earlier, expect the same message. Press `r` after that time for fresh data. -### - -​ - -Read the token count beside the spinner +### Read the token count beside the spinner While Claude works in the main conversation, the line beside the spinner can end with an elapsed time and a token count, as in `Deciphering… (10m 27s · ↓ 5.5k tokens)`. It is a live, approximate count of the output the current turn has produced so far. The arrow beside the count points down while output arrives or tools run. @@ -118,19 +86,11 @@ It won’t match the `Usage by model` output figures in the `/usage` Session block, which add up the whole session rather than one turn. It also differs from the token count [verbose mode adds](</docs/en/statusline#notifications-share-the-status-line-row>), because that count measures the size of your context rather than one turn’s output. -### - -​ - -Analyze your usage patterns +### Analyze your usage patterns Run [`/insights`](</docs/en/commands#all-commands>) for a report on how you work rather than how many tokens you’ve used. It analyzes your recent sessions on this machine and writes an HTML report covering what you work on, friction points such as misunderstood requests or buggy code, and suggestions for using Claude Code more effectively. A single run analyzes up to 200 sessions it hasn’t seen before and skips very short ones. When sessions are left out, the report header shows the analyzed count with the total in parentheses, for example `200 sessions (412 total)`. When [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) is available to the session and your recent sessions mostly ran without it, the report can also include an estimate of how many permission prompts auto mode could have handled across those sessions. Claude Code writes the latest report to `~/.claude/usage-data/report.html` and saves a timestamped copy of each run in the same directory, so earlier reports aren’t overwritten. Claude Code deletes reports on the same schedule as the rest of your session data: at startup, it removes files older than [`cleanupPeriodDays`](</docs/en/claude-directory#cleaned-up-automatically>), 30 days by default. You can run `/insights` on any plan and with any provider. The analysis runs through the same provider and account as your regular sessions, and the tokens count against your plan or API usage. Sessions from other devices and claude.ai aren’t included. -### - -​ - -Add usage credits to your subscription +### Add usage credits to your subscription [Usage credits](<https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans>) let you keep working past your plan’s usage limit. To manage them, run `/usage-credits` after signing in with your claude.ai subscription through `/login`; the command isn’t available with API key authentication. In self-serve Enterprise organizations, Enterprise trials, and Enterprise organizations billed through AWS Marketplace, the command requires Claude Code v2.1.248 or later; earlier versions reject it with [`Unknown command: /usage-credits`](</docs/en/errors#unknown-command>). What it opens depends on your role: @@ -142,11 +102,7 @@ For Team and Enterprise members without billing access, the confirmation appears only in interactive sessions: in non-interactive mode with the `-p` flag and from [Remote Control](</docs/en/remote-control>), the command sends no request and tells you to run it in an interactive session instead. If you run `/usage-credits` again while your earlier request is waiting on an admin, Claude Code tells you a request has already been sent rather than sending a duplicate. After an admin dismisses your request, running the command again sends a new one. Before v2.1.222, a dismissed request also blocked new requests. On Pro, Max, and Ultra plans, when you reach your spend limit with usage credits left, Claude Code prompts you to raise or remove the limit without leaving the CLI. If the server rejects the change, see [Could not update your spend limit](</docs/en/errors#could-not-update-your-spend-limit>). -## - -​ - -Manage costs for your organization +## Manage costs for your organization Which controls you have depends on how your organization accesses Claude Code: a Claude for Teams or Enterprise plan, the Claude Console, or a cloud provider. On Teams and Enterprise plans, usage draws from each member’s seat allowance. On the Console and on cloud providers, usage is billed per token to your organization. If your organization mixes sign-in methods, each developer is metered according to the one they authenticated with. The table maps each setup to where you see spend, where you cap it, and how you pull per-user numbers. On an individual Pro, Max, or Ultra plan you have no organization to manage, so track your own usage-credit spend, including [fast mode](</docs/en/fast-mode#see-where-fast-mode-spend-appears>), under Add usage credits to your subscription. @@ -158,11 +114,7 @@ [OpenTelemetry export](</docs/en/monitoring-usage>) works on every setup and is the only option that streams per-user token and cost metrics into your own observability stack in near real time. -### - -​ - -Report spend at your contracted rates +### Report spend at your contracted rates By default, Claude Code computes every cost figure it shows developers at list price, so if your organization pays contracted rates, the figures in `/usage`, the status line, and OpenTelemetry don’t match your bill. To make them match, set the [`modelPricing`](</docs/en/settings-reference#modelpricing>) managed setting to your rates. The setting changes what Claude Code reports, not what Anthropic charges. Requires Claude Code v2.1.242 or later. @@ -186,11 +138,7 @@ To confirm the rates are in effect, run `/usage` in a session that has [received the managed settings](</docs/en/managed-settings#read-the-source-in-%2Fstatus>): the Session block’s `Total cost` line carries the note `at your organization's configured rates`. The figures are still estimates, not an invoice. The per-million-token prices in the `/model` picker stay at list price. -### - -​ - -Claude for Teams and Enterprise +### Claude for Teams and Enterprise On Claude for Teams and Enterprise plans, each member’s Claude Code usage draws from a per-seat allowance that resets on a rolling five-hour window and a weekly window. The allowance is shared with Claude chat and Cowork, and its size depends on the member’s [seat tier](<https://support.claude.com/en/articles/11845131-use-claude-code-with-your-team-or-enterprise-plan>) (Standard or Premium). Your controls live in the claude.ai admin console, not the Claude Console. @@ -201,11 +149,7 @@ The [Claude Enterprise consumption guide](<https://support.claude.com/en/articles/14782391-claude-enterprise-consumption-guide>) is the planning reference for admins. It explains how consumption differs across Claude chat, Claude Code, and Cowork, and gives per-user dollar starting points for budgeting. Budget more for a coding seat than a chat seat: each Claude Code turn carries file contents, tool calls, and multi-step reasoning, so one debugging session can consume more than a day of chat. -### - -​ - -Claude Console +### Claude Console API organizations manage Claude Code spend through [workspaces](<https://platform.claude.com/docs/en/build-with-claude/workspaces>). You can [set workspace spend limits](<https://platform.claude.com/docs/en/build-with-claude/workspaces#workspace-limits>) on total Claude Code spend and [view cost and usage reporting](<https://platform.claude.com/docs/en/build-with-claude/workspaces#usage-and-cost-tracking>) in the Console. @@ -213,11 +157,7 @@ For per-user reporting, the [Console dashboard](<https://platform.claude.com/claude-code>) shows spend and lines accepted per member, and the [Claude Code Analytics API](<https://platform.claude.com/docs/en/build-with-claude/claude-code-analytics-api>) returns daily per-user metrics programmatically with an [Admin API key](<https://platform.claude.com/settings/admin-keys>). See [analytics for API customers](</docs/en/analytics#access-analytics-for-api-customers>). -#### - -​ - -Rate limit recommendations +#### Rate limit recommendations When setting up Claude Code for teams, consider these Token Per Minute (TPM) and Request Per Minute (RPM) per-user recommendations based on your organization size: @@ -234,11 +174,7 @@ If you anticipate scenarios with unusually high concurrent usage (such as live training sessions with large groups), you may need higher TPM allocations per user. -### - -​ - -Cloud providers +### Cloud providers On Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry, Claude Code is billed per token to your cloud account, and spend controls live in your cloud provider’s billing console. Claude Code does not send metrics from your cloud back to Anthropic, so the [analytics dashboards](</docs/en/analytics>) and the Claude Code Analytics API do not cover this usage. For per-user cost attribution, you have three options: @@ -246,11 +182,7 @@ * **A Claude apps gateway** : a self-hosted [Claude apps gateway](</docs/en/claude-apps-gateway>) provides per-user usage attribution, OTLP metrics with token counts, and [per-user spend limits](</docs/en/claude-apps-gateway-spend-limits>) on these providers. * **An LLM gateway** : route all Claude Code traffic through a proxy that tracks spend per key. Several large enterprises reported using [LiteLLM](</docs/en/llm-gateway>), an open-source tool that [tracks spend by key](<https://docs.litellm.ai/docs/proxy/virtual_keys#tracking-spend>). This project is unaffiliated with Anthropic and has not been audited for security. -### - -​ - -When a developer asks about a limit +### When a developer asks about a limit Developers usually bring limit questions to their admin, so it helps to know which ceiling they hit. These situations mean different things: @@ -262,11 +194,7 @@ * **A context or auto-compact warning** : not a usage limit. The conversation has grown close to the session’s [auto-compact window](</docs/en/model-config#set-the-auto-compact-window>), the threshold where Claude Code summarizes older history to free space. Point the developer at reduce token usage. * **Unexpectedly high spend on an API or cloud-provider plan** : usually traces back to long sessions that were never cleared or to Opus left as the default model. The highest-impact habits to share are clearing between unrelated tasks and matching the model to the job, both covered in reduce token usage. -### - -​ - -Agent team token costs +### Agent team token costs [Agent teams](</docs/en/agent-teams>) spawn multiple Claude Code instances, each with its own context window. Token usage scales with the number of active teammates and how long each one runs. To keep agent team costs manageable: @@ -276,19 +204,11 @@ * Shut down teammates when their work is done. Each active teammate continues consuming tokens until it exits or the session ends. * Agent teams are disabled by default. Set `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` in your [settings.json](</docs/en/settings>) or environment to enable them. See [enable agent teams](</docs/en/agent-teams#enable-agent-teams>). -## - -​ - -Reduce token usage +## Reduce token usage Token costs scale with context size: the more context Claude processes, the more tokens you use. Claude Code automatically optimizes costs through [prompt caching](</docs/en/prompt-caching>), which reduces costs for repeated content like system prompts, and auto-compaction, which summarizes conversation history when approaching context limits. The following strategies help you keep context small and reduce per-message costs. -### - -​ - -Manage context proactively +### Manage context proactively Use `/usage` to check your current token usage, or [configure your status line](</docs/en/statusline#context-window-usage>) to display it continuously. @@ -301,38 +221,22 @@ When you are using compact, please focus on test output and code changes -### - -​ - -Choose the right model +### Choose the right model Sonnet handles most coding tasks well and costs less than Opus. Reserve Opus for complex architectural decisions or multi-step reasoning. Use `/model` to switch models mid-session, or set a default in `/config`. A switch to Opus also applies to the [subagents that inherit your session’s model](</docs/en/model-config#setting-your-model>). For simple subagent tasks, specify `model: haiku` in your [subagent configuration](</docs/en/sub-agents#choose-a-model>). -### - -​ - -Reduce MCP server overhead +### Reduce MCP server overhead MCP tool definitions are [deferred by default](</docs/en/mcp#scale-with-mcp-tool-search>), so only tool names and server instructions enter context until Claude uses a specific tool. Run `/context` to see what’s consuming space. * **Prefer CLI tools when available** : Tools like `gh`, `aws`, `gcloud`, and `sentry-cli` are still more context-efficient than MCP servers because they don’t add any per-tool listing. Claude can run CLI commands directly. * **Disable unused servers** : Run `/mcp` to see configured servers and disable any you’re not actively using. -### - -​ - -Install code intelligence plugins for typed languages +### Install code intelligence plugins for typed languages [Code intelligence plugins](</docs/en/plugins/code-intelligence>) give Claude precise symbol navigation instead of text-based search, reducing unnecessary file reads when exploring unfamiliar code. A single “go to definition” call replaces what might otherwise be a grep followed by reading multiple candidate files. Installed language servers also report type errors automatically after edits, so Claude catches mistakes without running a compiler. -### - -​ - -Offload processing to hooks and skills +### Offload processing to hooks and skills Custom [hooks](</docs/en/hooks>) can preprocess data before Claude sees it. Instead of Claude reading a 10,000-line log file to find errors, a hook can grep for `ERROR` and return only matching lines, reducing context from tens of thousands of tokens to hundreds. This PreToolUse hook trims test output to its last 100 lines: @@ -376,51 +280,27 @@ To verify the setup, run `/hooks` and check that the hook appears under PreToolUse. You can also start Claude Code with `claude --debug-file ./claude-debug.txt` and ask Claude to run `npm test`. When the hook rewrites the command, that log file contains a `modified tool input keys` line listing `command` and the other Bash input fields. A [skill](</docs/en/skills>) can give Claude domain knowledge so it doesn’t have to explore. For example, a “codebase-overview” skill could describe your project’s architecture, key directories, and naming conventions. When Claude invokes the skill, it gets this context immediately instead of spending tokens reading multiple files to understand the structure. -### - -​ - -Move instructions from CLAUDE.md to skills +### Move instructions from CLAUDE.md to skills Your [CLAUDE.md](</docs/en/memory>) file is loaded into context at session start. If it contains detailed instructions for specific workflows (like PR reviews or database migrations), those tokens are present even when you’re doing unrelated work. [Skills](</docs/en/skills>) load on-demand only when invoked, so moving specialized instructions into skills keeps your base context smaller. Aim to keep CLAUDE.md under 200 lines by including only essentials. -### - -​ - -Adjust extended thinking +### Adjust extended thinking Extended thinking is enabled by default because it significantly improves performance on complex planning and reasoning tasks. Thinking tokens are billed as output tokens, and the default budget can be tens of thousands of tokens per request depending on the model. For simpler tasks where deep reasoning isn’t needed, you can reduce costs by lowering the [effort level](</docs/en/model-config#adjust-effort-level>) with `/effort` or in `/model`, or by disabling thinking in `/config`. You can’t turn off thinking on Opus 5.5, Sonnet 5.5, Haiku 5.5, or the Fable models, which always use extended thinking. On models with a [fixed thinking budget](</docs/en/model-config#adaptive-reasoning-and-fixed-thinking-budgets>), you can also lower the budget by setting the `MAX_THINKING_TOKENS` [environment variable](</docs/en/env-vars>), for example `MAX_THINKING_TOKENS=8000`. Adaptive-reasoning models ignore nonzero budgets, so use effort levels there instead. -### - -​ - -Delegate verbose operations to subagents +### Delegate verbose operations to subagents Running tests, fetching documentation, or processing log files can consume significant context. Delegate these to [subagents](</docs/en/sub-agents#isolate-high-volume-operations>) so the verbose output stays in the subagent’s context while only a summary returns to your main conversation. The subagent’s own requests still draw on your usage. To spend less on them, [choose a smaller model for a subagent](</docs/en/sub-agents#choose-a-model>) or [run every subagent on one model](</docs/en/sub-agents#run-every-subagent-on-one-model>). -### - -​ - -Manage agent team costs +### Manage agent team costs Agent teams use approximately 7x more tokens than standard sessions when teammates run in plan mode, because each teammate maintains its own context window and runs as a separate Claude instance. Keep team tasks small and self-contained to limit per-teammate token usage. See [agent teams](</docs/en/agent-teams>) for details. -### - -​ - -Write specific prompts +### Write specific prompts Vague requests like “improve this codebase” trigger broad scanning. Specific requests like “add input validation to the login function in auth.ts” let Claude work efficiently with minimal file reads. -### - -​ - -Work efficiently on complex tasks +### Work efficiently on complex tasks For longer or more complex work, these habits help avoid wasted tokens from going down the wrong path: @@ -429,19 +309,11 @@ * **Give verification targets** : Include test cases, paste screenshots, or define expected output in your prompt. When Claude can verify its own work, it catches issues before you need to request fixes. * **Test incrementally** : Write one file, test it, then continue. This catches issues early. -## - -​ - -Background token usage +## Background token usage Session recap and idle compaction can use tokens while you’re idle. See [session recap](</docs/en/interactive-mode#session-recap>) and [idle compaction](</docs/en/settings-reference#idlecompaction>) for when each runs and how to turn it off. When prompt suggestions are on, Claude Code also sends a short request to the model your session is using after Claude responds, to [suggest your next prompt](</docs/en/interactive-mode#prompt-suggestions>). That request reuses the conversation’s prompt cache, so it is mostly cache reads plus a few output tokens. Claude Code [skips it while your account is close to or at its usage limit](</docs/en/interactive-mode#when-claude-code-skips-suggestions>). To stop these requests, [turn prompt suggestions off](</docs/en/interactive-mode#turn-prompt-suggestions-off>). -## - -​ - -Why usage climbs in a long session +## Why usage climbs in a long session A session that has been open for hours can use far more of your plan limits than your activity suggests, usually for one of these reasons: @@ -456,11 +328,7 @@ To see what to change on a Pro, Max, Ultra, Team, or Enterprise plan, run `/usage` at the Claude Code prompt. Its breakdown recommends a change for behaviors behind 10% or more of your recent usage. Those behaviors include long context and cache misses. -## - -​ - -Understanding changes in Claude Code behavior +## Understanding changes in Claude Code behavior Claude Code regularly receives updates that may change how features work, including cost reporting. Run `claude --version` to check your current version. For billing questions about your specific account, contact Anthropic support through the in-product messenger:
modified Create a Claude Code plugin View current →
Show diff (277 lines)
--- a/create.md +++ b/create.md @@ -11,11 +11,7 @@ * **Nothing yet** : follow Create your first plugin, then Develop without a marketplace and Test and debug. * **Files under`.claude/` already**: do the first-plugin walkthrough once to learn the layout, then follow Convert an existing `.claude/` setup. -## - -​ - -Decide when to use a plugin +## Decide when to use a plugin Skills, agents, hooks, and MCP servers all work standalone in your project or home directory. Keep that standalone setup while it serves one project or only you. Make a plugin when you want to share the setup with teammates, install it in several projects, or publish versioned releases. When you move standalone skills, agents, hooks, and MCP config into a plugin, their location and names change: @@ -24,11 +20,7 @@ To move an existing setup into a plugin, see Convert an existing `.claude/` setup. -## - -​ - -Create your first plugin +## Create your first plugin In this walkthrough, you create a plugin whose only component is one skill, a greeting, and run it with `--plugin-dir`, which loads a plugin for one session without installing it. A plugin can hold any mix of [components](</docs/en/plugins/components>), such as skills, agents, hooks, and MCP servers, and none is required; one skill is the smallest example that shows the layout. You need Claude Code [installed and signed in](</docs/en/quickstart#step-1-install-claude-code>). Open a terminal in the directory where you want to keep the plugin, such as `~/projects`, and run the commands in these steps from it. You can keep a plugin anywhere, because you pass its path to Claude Code when you start a session. @@ -64,7 +56,7 @@ * **`version`** : optional. Setting it keeps users on that version until you change it; [Release a new version](</docs/en/plugins/host-marketplace#release-a-new-version>) says when to set or omit it. * **`author`** : who to credit. `name` is required inside it; `email` and `url` are optional. -Every other field is on the [manifest reference](</docs/en/plugins/manifest-reference#fields>).Only `plugin.json` goes inside `.claude-plugin/`. The skill you add next goes directly under `my-first-plugin/`, next to that folder. +Other fields are on the [manifest reference](</docs/en/plugins/manifest-reference#fields>).Only `plugin.json` goes inside `.claude-plugin/`. The skill you add next goes directly under `my-first-plugin/`, next to that folder. 3 @@ -114,11 +106,7 @@ The plugin loads only in sessions you start with `--plugin-dir`. To keep working on it without the flag, or to test a `.zip` build, see Develop without a marketplace. To have Claude scaffold and check a larger plugin with you, [install](</docs/en/plugins/install#install-a-plugin>) Anthropic’s `plugin-dev` plugin from the `claude-plugins-official` marketplace, which adds skills and agents for writing components such as skills, hooks, and MCP servers and for validating the finished plugin. Once it’s installed, run `/plugin-dev:create-plugin` followed by a description of the plugin you want, and Claude walks you through designing, creating, and validating it. -### - -​ - -Share your plugin +### Share your plugin A plugin you built with Create your first plugin exists only on your machine. When it’s ready for other people, there are three ways to get it to them: @@ -126,11 +114,7 @@ * **List it in your own marketplace** : teammates add your marketplace once and install the plugin by name, and they receive your updates. See [Publish through your own marketplace](</docs/en/plugins/publish#publish-through-your-own-marketplace>). * **Submit it to Anthropic’s directory** : after it passes review, people can add it on claude.ai and in Cowork, and it reaches Claude Code through their account. See [Submit to Anthropic’s directory](</docs/en/plugins/publish#submit-to-anthropics-directory>). -### - -​ - -Plugin layout +### Plugin layout Each kind of [component](</docs/en/plugins/components>), such as skills, agents, hooks, and MCP servers, goes in a fixed directory under the plugin root, which is the directory you pass to `--plugin-dir`. Add only the directories you use. To click through a complete plugin directory and read what each file does, open the [plugin explorer](</docs/en/plugins/components#explore-the-plugin-directory>). The table lists the directories most plugins start with, and the [full layout](</docs/en/plugins/manifest-reference#standard-layout>) lists the rest. @@ -145,11 +129,7 @@ Only `plugin.json` goes inside `.claude-plugin/`. Components saved there don’t load.The plugin root is the plugin’s own directory, not `~/.claude/` itself. A `.mcp.json` saved at `~/.claude/.mcp.json` doesn’t load. -## - -​ - -Develop without a marketplace +## Develop without a marketplace You don’t need a [marketplace](</docs/en/plugins/overview#get-plugins-from-a-marketplace>) to run a plugin you’re writing. Load it directly from disk or a URL instead: @@ -159,11 +139,7 @@ If two plugins loaded in different ways share a name, see [Name conflicts](</docs/en/plugins/loading#name-conflicts>) for which one Claude Code keeps. -### - -​ - -Load a plugin for one session +### Load a plugin for one session You can load a plugin for a single session in three ways: @@ -173,21 +149,13 @@ When you edit the plugin’s files during the session, run `/reload-plugins` to load the changes. -#### - -​ - -Load a plugin 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: claude --plugin-dir ./my-first-plugin --plugin-dir ./other-plugin.zip -#### - -​ - -Load 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: @@ -196,11 +164,7 @@ A message appears in the session for each of these changes. If loading or unloading a plugin mid-conversation would [invalidate the prompt cache](</docs/en/prompt-caching#enabling-or-disabling-a-plugin>), the change is held instead, and the message tells you to run `/reload-plugins` to apply it. -#### - -​ - -Load a plugin 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: @@ -208,27 +172,15 @@ Claude Code downloads the archive at startup. To load several, repeat the flag or pass the URLs space-separated in one quoted argument. Point the flag only at archives you control or trust. If Claude Code can’t fetch the archive, or the archive is invalid, it starts without the plugin and records a plugin load error that you can review in the `/plugin` manager’s **Errors** tab. -#### - -​ - -Load plugins 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>). -### - -​ - -Make a plugin load in every session +### Make a plugin load in every session Your personal skills directory is `~/.claude/skills/`, and a folder there that contains a `.claude-plugin/plugin.json` is a skills-directory plugin. Unless your administrator has [blocked skills-directory plugins](</docs/en/plugins/loading#skills-directory-plugins-blocked-by-managed-settings>), Claude Code loads each one when a session starts, with no flag and no install step. `claude plugin init` scaffolds one for you. -#### - -​ - -Scaffold the plugin with `claude plugin init` +#### Scaffold the plugin with `claude plugin init` `claude plugin init` writes a starter plugin under `~/.claude/skills/`. Scaffold one from your shell: @@ -236,35 +188,19 @@ The command creates `~/.claude/skills/my-tool/` with a `.claude-plugin/plugin.json` and a root `SKILL.md`. It prints `✔ Created plugin "my-tool" at ~/.claude/skills/my-tool` followed by `It will auto-load next session as my-tool@skills-dir. Run /reload-plugins to load it now.` Pass `--with skills` to have `claude plugin init` scaffold a skill under `skills/` for you. The other `--with` values are on the [plugin commands reference](</docs/en/plugins/cli-reference#plugin-init>). -#### - -​ - -Name the plugin’s skills +#### Name the plugin’s skills The root skill at `~/.claude/skills/my-tool/SKILL.md` is also a personal skill, so you invoke it as `/my-tool`, not `/my-tool:my-tool`. Skills you add under `skills/` inside the plugin get the plugin-name prefix, such as `/my-tool:example`. -#### - -​ - -Stop loading the plugin +#### Stop loading the plugin To stop loading a scaffolded plugin, delete its directory, or run `claude plugin disable my-tool@skills-dir` in your shell with the `my-tool@skills-dir` name that `claude plugin init` printed. In the ID `my-tool@skills-dir`, `skills-dir` stands where a marketplace name would, because the plugin loads from your skills directory rather than from a marketplace. -#### - -​ - -Share the plugin through a repository +#### Share the plugin through a repository `claude plugin init` writes the plugin to your personal skills directory at `~/.claude/skills/`, which all your projects on this machine share. To make a plugin load for everyone in one repository, create the same layout yourself at `<project>/.claude/skills/<name>/`, including its `.claude-plugin/plugin.json`. See [Plugins shared through a repository](</docs/en/plugins/loading#plugins-shared-through-a-repository>) for the conditions under which Claude Code loads it. -## - -​ - -Test and debug +## Test and debug When a change to your plugin doesn’t show up, work through these checks in order. Each one tells you what Claude Code did with the plugin: @@ -276,51 +212,27 @@ To check an MCP server, run `/mcp` in the session to see the server’s status. When the server is healthy, `/mcp` lists it as connected. If it isn’t, see [MCP servers that don’t start](</docs/en/plugins/troubleshooting#invalid-mcp-server-config-for-and-mcp-servers-that-dont-start>). To check a hook, trigger the event it matches. For example, ask Claude to edit a file to trigger a `PostToolUse` hook. Then read the [debug log](</docs/en/hooks#debug-hooks>), which shows which hooks matched, their exit codes, and their output. The next sections cover the failures you’re most likely to hit while developing, and the [troubleshooting page](</docs/en/plugins/troubleshooting#build-a-plugin>) has the full entry for each. -### - -​ - -A component path isn’t found +### A component path isn’t found The **Errors** tab of `/plugin` shows `<component> path not found: <path>`, for example `commands path not found`. A component path in your manifest, such as `commands`, `skills`, `agents`, or `hooks`, points at nothing. Fix the path or create the directory, then run `/reload-plugins` in the session. See [`commands path not found`](</docs/en/plugins/troubleshooting#commands-path-not-found>). -### - -​ - -`--plugin-dir` at a marketplace root doesn’t load the plugins under `plugins/` +### `--plugin-dir` at a marketplace root doesn’t load the plugins under `plugins/` `--plugin-dir` takes the plugin’s root directory, the one that contains `.claude-plugin/plugin.json` and the component directories such as `skills/`. If you point it at a marketplace root instead, Claude Code doesn’t read `marketplace.json`, so a plugin under `plugins/` doesn’t load, and you see no error. Point the flag at one plugin’s folder, or add the marketplace. See [the troubleshooting entry](</docs/en/plugins/troubleshooting#plugin-dir-loads-a-plugin-with-no-components>). -### - -​ - -The plugin loads but its skills are missing +### The plugin loads but its skills are missing The `skills/` directory is inside `.claude-plugin/`, or a `skills` entry in the manifest points at a file. Move `skills/` to the plugin root, point each `skills` entry at a directory that contains `SKILL.md`, and run `/reload-plugins` in the session. See [Plugin loads but its skills are missing](</docs/en/plugins/troubleshooting#plugin-loads-but-its-skills-are-missing>). -### - -​ - -The `userConfig` dialog never appears +### The `userConfig` dialog never appears The dialog for your plugin’s [`userConfig`](</docs/en/plugins/components#user-configuration>) options is part of installing through `/plugin` in a session. Loading with `--plugin-dir` doesn’t show it, and neither does `claude plugin install` in the shell. With the plugin loaded, run `/plugin configure <plugin-name>` in the session to open it. See [The `userConfig` dialog never appears](</docs/en/plugins/troubleshooting#the-userconfig-dialog-never-appears>). -### - -​ - -Check that the plugin changes Claude’s behavior +### Check that the plugin changes Claude’s behavior A plugin that loads without errors can still fail to steer Claude the way you intend. `claude plugin eval`, which you run in your shell, runs your test cases with and without the plugin and scores the difference. See [Test plugins with evals](</docs/en/plugin-evals>), starting with [Create your first eval suite](</docs/en/plugin-evals#create-your-first-eval-suite>). -## - -​ - -Convert an existing `.claude/` setup +## Convert an existing `.claude/` setup If you already have skills, agents, or hooks under a project’s `.claude/` directory, you can move them into a plugin without rewriting them. Run the commands in these steps from the project root, which is the directory that contains `.claude/`, because the `cp` paths are relative to it. @@ -373,7 +285,7 @@ "PostToolUse": [ { "matcher": "Write|Edit", - "hooks": [{ "type": "command", "command": "jq -r '.tool_input.file_path' | xargs npm run lint:fix" }] + "hooks": [{ "type": "command", "command": "f=$(jq -r '.tool_input.file_path') && npm run lint:fix -- \"$f\"" }] } ] } @@ -402,11 +314,7 @@ After you’ve confirmed the plugin works, delete the originals from `.claude/` and remove the `hooks` object from your settings file. -## - -​ - -Next steps +## Next steps * [Plugin components](</docs/en/plugins/components>): add agents, hooks, MCP servers, LSP servers, and user configuration to your plugin * [Test plugins with evals](</docs/en/plugin-evals>): write eval cases and run them with `claude plugin eval` to check how reliably the plugin guides Claude’s behavior
modified Create a marketplace View current →
Show diff (163 lines)
--- a/create-marketplace.md +++ b/create-marketplace.md @@ -8,11 +8,7 @@ Start with Create a marketplace to build one on your own machine and install a plugin from it, then add more plugin entries. -## - -​ - -Create a marketplace +## Create a marketplace The following steps create a marketplace on your machine, add a plugin to it, register it in Claude Code, and install the plugin from it. That is the whole loop, and it’s the same loop your users go through once you host the marketplace somewhere they can reach. Run every command in your shell, from the directory where you want `my-marketplace/` created. You need a plugin to list. The example uses `my-first-plugin` from [Create your first plugin](</docs/en/plugins/create#create-your-first-plugin>), a plugin with one skill that you run as `/my-first-plugin:hello`; build it first if you don’t have a plugin yet. To use a plugin of your own instead, substitute its directory and its `name` wherever the steps say `my-first-plugin`. For what a plugin directory can contain, see the [plugin directory explorer](</docs/en/plugins/components#explore-the-plugin-directory>). @@ -92,11 +88,7 @@ The `Component inventory` section reads `Skills (1) hello`.To run the skill, start a session and enter `/my-first-plugin:hello`. Claude greets you. The command has the plugin’s name as a prefix, as every plugin skill’s name does. -## - -​ - -Add plugin entries +## Add plugin entries Every plugin you distribute is one object in the `plugins` array of `marketplace.json`. To add a second plugin, add a second object. These fields cover most entries: @@ -106,30 +98,18 @@ For the full field list, see [Plugin entries](</docs/en/plugins/marketplace-reference#plugin-entries>), which also covers the [`plugin.json`](</docs/en/plugins/manifest-reference>) fields an entry can set and when they apply. -## - -​ - -Rules for plugin entries +## Rules for plugin entries Most failed installs from a new marketplace come from a relative path written from the wrong directory, or from an entry name that differs from the `name` in the plugin’s `plugin.json`. -### - -​ - -Write relative paths from the marketplace root +### Write relative paths from the marketplace root The marketplace root is the directory that contains `.claude-plugin/`. In the walkthrough, that’s `my-marketplace/`, so the entry’s `source` is `"./plugins/my-first-plugin"`. The path doesn’t start inside `.claude-plugin/`, so don’t use `..` to leave it. A path with `..` and a path to a missing directory fail at different commands: * **A path with`..`**: `claude plugin validate` reports the entry as invalid. The message begins `Path contains "..": ./../plugins/my-first-plugin`. * **A path to a directory that doesn’t exist** : `claude plugin validate` passes. `claude plugin install` fails with `Source path does not exist: <path>`, and `<path>` is the absolute location Claude Code checked. -### - -​ - -Keep the entry name and the manifest name the same +### Keep the entry name and the manifest name the same A marketplace plugin has an entry `name` in `marketplace.json` and a `name` in its own `plugin.json`, called the manifest name. Each name appears in different places: @@ -138,11 +118,7 @@ When the two names differ and someone installs by the manifest name, Claude Code reports `Plugin "<manifest-name>" not found in marketplace "<marketplace>"`. Keep the two names the same. For more on how Claude Code uses the two names, see [Plugin loading reference](</docs/en/plugins/loading#find-where-a-plugin-came-from>). -### - -​ - -Keep unused submodules out of the clone +### Keep unused submodules out of the clone When someone adds your marketplace, Claude Code clones the repository and fetches only the git submodules that hold plugin files. Requires Claude Code v2.1.295 or later. You decide which submodules Claude Code fetches by where you put each plugin: @@ -151,11 +127,7 @@ If a plugin at the root runs a file from a submodule, write the file’s path out in the plugin’s hook or server configuration, such as `${CLAUDE_PLUGIN_ROOT}/vendor/tool/run.sh`. Claude Code reads those paths to find out whether the plugin needs the submodules. It can’t see a path that a script builds while it runs. For the full rule, see [Git submodules in the marketplace repository](</docs/en/plugins/marketplace-reference#git-submodules-in-the-marketplace-repository>). -## - -​ - -Choose a plugin source +## Choose a plugin source Each plugin entry in `marketplace.json` has a `source` that tells Claude Code where to fetch that one plugin. Pick the source by where the plugin’s files are stored. The table lists the sources most marketplace owners use. @@ -174,19 +146,11 @@ For the fields of every source type, and for pinning a git-based source to a `ref` or `sha`, see [Plugin sources](</docs/en/plugins/marketplace-reference#plugin-sources>). -## - -​ - -Validate and test +## Validate and test As you add plugins, run `claude plugin validate ./my-marketplace` in your shell after every edit, and install from the marketplace on your own machine before you share it. Validation and installation catch different problems. -### - -​ - -Problems that validation reports +### Problems that validation reports `claude plugin validate` reads only files inside the marketplace directory. It reports: @@ -199,11 +163,7 @@ For every message `validate` can print, see [Validation messages](</docs/en/plugins/marketplace-reference#validation-messages>). For its flags and exit codes, see [`plugin validate`](</docs/en/plugins/cli-reference#plugin-validate>). -### - -​ - -Problems that surface when you add or install +### Problems that surface when you add or install Problems that `claude plugin validate` doesn’t report appear when you add the marketplace or install from it: @@ -212,35 +172,19 @@ * Claude Code first fetches a `github`, `git-subdir`, or other remote source when you install the plugin, so a wrong `repo` or `path` appears then. * A relative `source` whose directory doesn’t exist also fails at install, with `Source path does not exist: <path>`. -### - -​ - -Test an edit to a plugin +### Test an edit to a plugin In the walkthrough, you added `my-marketplace` from a local directory with a relative-path `source`. With that setup, Claude Code reads the plugin’s files directly from `my-marketplace/plugins/`. Your edits take effect at the next session start or when you run `/reload-plugins` in a session, with no change to the plugin’s `version`. People who install from your hosted marketplace get a copy in the plugin cache instead. For how they receive a new version, see [Keep users up to date](</docs/en/plugins/host-marketplace#keep-users-up-to-date>). -### - -​ - -Remove the marketplace to start over +### Remove the marketplace to start over To remove everything and start over, run `claude plugin marketplace remove my-marketplace` in your shell. The command removes the marketplace and uninstalls its plugins. -## - -​ - -Host your marketplace +## Host your marketplace Once you can install a plugin from the marketplace on your own machine, as in Create a marketplace, push the marketplace directory to a git host. Before you push, give the marketplace a top-level `name` that other authors are unlikely to pick, because a user [can’t have two marketplaces with the same name](</docs/en/plugins/marketplace-reference#marketplace-file>). Your teammates then run `claude plugin marketplace add <owner>/<repo>` in their shell for a GitHub repository, or the same command with the repository URL. They then install a plugin by name as in the walkthrough. For private-repository access, updates, versioning, and renaming or removing entries, see [Host and maintain a marketplace](</docs/en/plugins/host-marketplace>). -## - -​ - -Next steps +## Next steps * [Host and maintain a marketplace](</docs/en/plugins/host-marketplace>): pick a host, keep users up to date, and rename or remove plugins safely * [Marketplace reference](</docs/en/plugins/marketplace-reference>): `marketplace.json` fields and source types
modified Message your other Claude Code sessions View current →
Show diff (259 lines)
--- a/cross-session-messaging.md +++ b/cross-session-messaging.md @@ -2,11 +2,7 @@ Cross-session messaging lets Claude deliver a message from one of your Claude Code sessions to another. When a change in one session breaks what another is building on, Claude can warn that session before you notice. When one session settles a question another is blocked on, Claude can send the answer across. A message is a piece of text one Claude writes to another, never the sender’s conversation history or files. To move a whole conversation or its context, [resume the session](</docs/en/sessions#resume-a-session>) instead. -## - -​ - -When to use cross-session messaging +## When to use cross-session messaging Use messaging when one of your sessions has something another session needs mid-task. Claude can send a message on its own when it sees the need, for example after making a change that affects work another session is doing, or you can ask it to send one. The common cases: @@ -15,11 +11,7 @@ * **Get status from long-running work** : have a migration or test run report back to the session you’re watching, or ask it yourself from there. If that session is on this machine, Claude can also ask it for one notice when it next goes idle or exits. * **Message across machines** : reach one of your sessions on another machine or in the cloud. -## - -​ - -Message another session +## Message another session When one of your sessions learns something another session needs, such as a finding, a status, or a decision, Claude passes it along instead of you copy-pasting between terminals. Claude discovers the target with `ListAgents` and sends with `SendMessage`, so you never call either tool yourself. Claude can decide to send a message without being asked, and you can also prompt for one. To prompt one yourself, tell Claude what you want the other session to know or do. This example is a prompt you type, not a message Claude sends: @@ -40,11 +32,7 @@ You can also type the mention without the picker. When more than one live session answers to the mentioned name, Claude asks you which one you mean before sending. For what the message Claude writes looks like when it arrives, including an example of one, see what a message looks like. -### - -​ - -Message delivery +### Message delivery The receiving Claude reads the message between tool calls during an active turn. When the receiving session is idle, Claude Code starts a new turn with the message. A message from another session arrives as plain text. If it mentions a file or an [MCP resource](</docs/en/mcp#use-mcp-resources>) with `@`, Claude sees the mention as written and Claude Code attaches nothing, whether the message starts a new turn or arrives during one. Claude can still open a mentioned path on the receiving machine with its own tools, subject to that session’s permissions. Claude Code refuses a message in the following cases: @@ -61,19 +49,11 @@ Once delivered, the message counts toward [usage](</docs/en/costs>) like a prompt you type. The receiving Claude can reply to the sender with `SendMessage`, except in the cases under Replies from other machines and cloud sessions and Turn off cross-session messaging. Permission boundaries stay per-session. Claude is instructed never to ask another session for an action that was denied or blocked in its own session, or that its own permission settings would block, and to route that work back to you instead. On the receiving side, the receiving session’s own permission prompts and rules still apply to anything the message asks for. -### - -​ - -Get a notice when another session goes idle +### Get a notice when another session goes idle Claude can ask one of your sessions on this machine to send back one notice when that session next goes idle or exits. Idle here means the session finished a turn with nothing queued. Use it when you’re waiting on a long task in another session and want to hear when it’s done instead of checking. Requires Claude Code v2.1.236 or later in both sessions. -#### - -​ - -Ask for a notice +#### Ask for a notice Tell Claude what you’re waiting on. This prompt asks for a notice from the migration session: @@ -81,19 +61,11 @@ Claude subscribes with the `SendMessage` tool’s `notify_when_idle` input, either attached to a message it’s sending anyway or on its own. On its own, Claude Code subscribes without starting a turn or spending tokens in the watched session, and sends the notice right away if that session is already idle. Attached to a message, Claude Code delivers the message first and sends the notice later. -#### - -​ - -What each session shows +#### What each session shows The watched session shows a line saying another process asked to be told when the session is next idle. The asking session shows the notice as a line naming the watched session. The line can include the time that session’s turn finished and a one-line status from that turn. If the asking session is idle, Claude Code starts a new turn with the notice. -#### - -​ - -Limits +#### Limits If no notice arrives within 12 hours, Claude Code drops the subscription and tells Claude, so it doesn’t keep waiting. Each side’s inbound controls apply to a notice like a message: @@ -102,11 +74,7 @@ Only the Claude in your main conversation can subscribe, and only to your sessions on this machine. When Claude asks for a notice from any other target, such as a teammate, a subagent, or a session beyond this machine, Claude Code refuses the whole call, including any message attached to it. -### - -​ - -See which sessions Claude can reach +### See which sessions Claude can reach Claude finds a message’s target on its own, so you don’t need to run anything before asking it to send. To see for yourself which sessions Claude can reach, run the `/list-agents` command. The first line, when present, is this session’s own name, the one your other sessions use to message it. The rows below it are the sessions Claude can reach: @@ -127,11 +95,7 @@ * **One session answers to the name** : Claude Code delivers the message on the name alone. * **Several sessions share the name, or Claude Code couldn’t check everywhere your sessions run** : Claude adds a short identifier to each row of its listing and uses the identifier in the address. -### - -​ - -Message sessions on other machines +### Message sessions on other machines How a message travels, and whether it passes through Anthropic servers, depends on where the target session runs: @@ -148,19 +112,11 @@ A session inside a container and a session on the host can’t reach each other. Two sessions inside the same container can still message each other, including on a [self-hosted runner](</docs/en/self-hosted-environments>). A session inside WSL 2 and a native Windows session on the same computer can’t reach each other either. To require your approval before any message goes beyond this machine, set `isolatePeerMachines`. -#### - -​ - -Replies from other machines and cloud sessions +#### Replies from other machines and cloud sessions A [cloud session](</docs/en/claude-code-on-the-web>), including one on a [self-hosted runner](</docs/en/self-hosted-environments>), can’t use `SendMessage` to answer a message from another machine, even when the message carries a reply address. The message still arrives. Read the cloud session’s response in its transcript at [claude.ai/code](<https://claude.ai/code>). If this session isn’t connected to Remote Control when Claude sends to a session beyond this machine, the message still goes through, but without a reply address. The receiving Claude can’t answer it. -## - -​ - -How a session treats an incoming message +## How a session treats an incoming message When session A messages session B, Claude Code tells B’s Claude that the message came from another session, not from you, and limits what the message can do: @@ -169,11 +125,7 @@ * **Commands don’t run** : a command in the message’s text, such as `/compact`, arrives as plain text. Claude Code never executes it. * **Permission prompts still fire** : if acting on the message requires a permission the receiving session doesn’t have, you see the same prompt you’d see for any other work. -### - -​ - -What a message looks like +### What a message looks like When a message arrives, Claude Code shows it in the conversation as a dim one-line preview, and the preview line stays in the conversation afterward. The preview carries the sender’s name and the first line of the message, cut with `…` when it’s long, such as `› Message from @api-worker: Schema migration finished (ctrl+o to expand)`. Any of these shows you the full text: @@ -186,11 +138,7 @@ Schema migration finished The new column is tenant_id, and rebasing on main is safe now. -### - -​ - -Control inbound messages +### Control inbound messages Set [`crossSessionInbound`](</docs/en/settings-reference#crosssessioninbound>) to choose what a session does with messages arriving from your other sessions: @@ -215,11 +163,7 @@ A session in the VS Code extension or the Desktop app can’t show the dialog. Claude Code keeps a held message there until the same deadline, as Non-interactive sessions describes. Claude Code holds at most 100 messages, and past that drops the oldest. -### - -​ - -Non-interactive sessions +### Non-interactive sessions Claude Code binds an inbox socket for a [`claude -p`](</docs/en/headless>) session like an interactive one, so a long-running `-p` worker can receive messages and appears in the listing. When you start a session in [bare mode](</docs/en/headless#start-faster-with-bare-mode>), Claude Code doesn’t bind the socket, so that session can’t receive messages and doesn’t appear in the agent list. A `-p` session can’t show the approval dialog. When the inbound default holds a message there, Claude Code keeps it for the same [`dialogExpiry`](</docs/en/settings-reference#dialogexpiry>) deadline the dialog uses, five minutes by default: @@ -228,11 +172,7 @@ Set `dialogExpiry` to `"never"` to keep default-held messages until the session ends. A message held by an explicit `hold` setting doesn’t expire; Claude Code delivers it when an `accept` later applies. To let a `-p` worker take messages unattended, start it with `crossSessionInbound` set to `accept` in its `--settings` value. An `accept` in your user settings also works but applies to every session you run. -### - -​ - -The session’s inbox socket +### The session’s inbox socket Read this section when a session you expect isn’t in the agent list, when you want a script or hook to post into a session, or when a sandboxed command can’t reach the socket. Claude Code binds an inbox socket for each session with cross-session messaging enabled, where other sessions on the machine deliver messages. The socket is a Unix domain socket on macOS and Linux, including Linux inside WSL 2, and a named pipe on native Windows. For which session kinds bind one, see Non-interactive sessions. You can find the socket’s path in two places: @@ -253,19 +193,11 @@ * When Claude Code can verify neither way, it treats the message like any other that asserts no permission class, so a session that bypasses permission prompts holds it for your approval. * **Sandboxed sessions** : control whether a Bash command can reach the socket from inside the [sandbox](</docs/en/sandboxing>) with the sandbox’s Unix-socket settings, [`sandbox.network.allowAllUnixSockets` and `sandbox.network.allowUnixSockets`](</docs/en/settings-reference#sandbox-settings>). -## - -​ - -Restrict cross-session messaging +## Restrict cross-session messaging Beyond the per-message defaults, you can narrow messaging in two ways. Require your approval before any message leaves the machine, or turn messaging off for a session or an organization. -### - -​ - -Require approval for cross-machine messages +### Require approval for cross-machine messages Set [`isolatePeerMachines`](</docs/en/settings-reference#isolatepeermachines>) to `true` to require your explicit approval before any `SendMessage` reaches a session beyond this machine: @@ -275,11 +207,7 @@ With this set, Claude Code asks for your approval before Claude’s message to a session beyond this machine leaves, even in `bypassPermissions` mode, which skips ordinary permission prompts. A `true` from any settings scope applies, so a checked-in project file can turn the requirement on but not off. Claude Code doesn’t prompt for messages between sessions on the same machine. -### - -​ - -Turn off cross-session messaging +### Turn off cross-session messaging Receiving and sending are separate controls, so turn off whichever direction you need, or both. Use `crossSessionInbound` for messages that arrive, and permission rules for what Claude here can send or list: @@ -297,11 +225,7 @@ With this in place, Claude Code still binds each session’s inbox socket, but drops every message that arrives on it without delivering anything to Claude. Denying `SendMessage` also removes messaging to subagents and agent-team teammates, since the same tool serves both. A refusing session shows no visible change, in its own `/status` or in the listings of other sessions on the same machine, so to confirm it, check the settings files that apply to that session rather than its status. -## - -​ - -Availability +## Availability Cross-session messaging requires Claude Code v2.1.224 or later on macOS, Linux, and WSL 2, and v2.1.234 or later on native Windows. Availability, and which sessions Claude can message, also depend on your operating system, provider, and configuration: @@ -323,11 +247,7 @@ In a session with messaging, `/status` also shows a `Peer address` row with the session’s own inbox address, or `unavailable` and the reason when Claude Code couldn’t set up an inbox. -## - -​ - -Limitations +## Limitations The limits here are properties of the messaging channel itself and apply wherever the feature runs. For platform and provider gaps, see Availability instead. @@ -336,11 +256,7 @@ * **Rapid bursts to one session are refused at the sender** : once a rapid burst of messages to a session on this machine reaches what that session’s inbox accepts, Claude Code refuses further sends in the sending session. The [refusal names the burst](</docs/en/errors#too-many-messages-to-this-session-just-now>) and tells Claude to batch the rest into one message or wait. * **Message loops are throttled** : in the receiving session, Claude Code rate-limits repeated messages per sender, drops identical repeats arriving within a short window, and queues at most 50 accepted messages for Claude to read. A message loop between two sessions therefore stops on its own. -## - -​ - -Related resources +## Related resources * [Subagents](</docs/en/sub-agents#resume-subagents>) and [agent teams](</docs/en/agent-teams#messages-between-agents>): messaging within a single session or team * [Background agents](</docs/en/agent-view>): dispatch and monitor the parallel sessions you might message
modified Give Claude custom tools View current →
Show diff (214 lines)
--- a/custom-tools.md +++ b/custom-tools.md @@ -1,10 +1,6 @@ Custom tools extend the Agent SDK by letting you define your own functions that Claude can call during a conversation. Using the SDK’s in-process MCP server, you can give Claude access to databases, external APIs, domain-specific logic, or any other capability your application needs. -## - -​ - -Quick reference +## Quick reference What you want to do| Do this ---|--- @@ -20,11 +16,7 @@ Return a machine-readable JSON result| Set `structuredContent` on the result. See Return structured data. Scale to many tools| Use [tool search](</docs/en/agent-sdk/tool-search>) to load tools on demand. -## - -​ - -Create a custom tool +## Create a custom tool A tool is defined by four parts, passed as arguments to the [`tool()`](</docs/en/agent-sdk/typescript#tool>) helper in TypeScript or the [`@tool`](</docs/en/agent-sdk/python#tool>) decorator in Python: @@ -48,11 +40,7 @@ pip install httpx -### - -​ - -Weather tool example +### Weather tool example This example defines a `get_temperature` tool and wraps it in an MCP server, without passing the server to `query`. To run the tool, see Call a custom tool. @@ -137,11 +125,7 @@ See the [`tool()`](</docs/en/agent-sdk/typescript#tool>) TypeScript reference or the [`@tool`](</docs/en/agent-sdk/python#tool>) Python reference for full parameter details, including JSON Schema input formats and return value structure. -### - -​ - -Make a parameter optional +### Make a parameter optional To make a parameter optional, declare it optional in the schema and apply the default in the handler: @@ -150,11 +134,7 @@ The `get_precipitation_chance` tool shows both patterns. -### - -​ - -Call a custom tool +### Call a custom tool To call a custom tool, follow these steps: @@ -219,11 +199,7 @@ Claude calls `get_temperature` and the script prints a one-line answer with the current temperature in San Francisco. -### - -​ - -Add more tools +### Add more tools A server holds as many tools as you list in its `tools` array. With more than one tool on a server, you can list each one in `allowedTools` individually or use the wildcard `mcp__weather__*` to cover every tool the server exposes. The example below defines a second tool, `get_precipitation_chance`, and replaces the `weatherServer` definition from the weather tool example with one that lists both tools in the array. @@ -321,11 +297,7 @@ [Tool search](</docs/en/agent-sdk/tool-search>) is on by default and defers SDK MCP tools: Claude sees each tool’s name in a compact list and loads its full schema on demand. With tool search disabled, every tool in this array consumes context window space on every turn. In TypeScript, pass `alwaysLoad: true` in the `extras` argument of [`tool()`](</docs/en/agent-sdk/typescript#tool>) or in the options of [`createSdkMcpServer()`](</docs/en/agent-sdk/typescript#createsdkmcpserver>) to keep a tool’s full schema in the initial prompt. -### - -​ - -Add tool annotations +### Add tool annotations [Tool annotations](<https://modelcontextprotocol.io/docs/concepts/tools#tool-annotations>) are optional metadata describing how a tool behaves. Pass them as the fifth argument to `tool()` helper in TypeScript or via the `annotations` keyword argument for the `@tool` decorator in Python. All hint fields are Booleans. @@ -368,19 +340,11 @@ See `ToolAnnotations` in the [TypeScript](</docs/en/agent-sdk/typescript#toolannotations>) or [Python](</docs/en/agent-sdk/python#toolannotations>) reference. -## - -​ - -Control tool access +## Control tool access The weather tool example registered a server and listed tools in `allowedTools`. This section covers how to scope access when you have multiple tools or want to restrict built-ins. For how tool names are constructed, see Call a custom tool. -### - -​ - -Configure allowed tools +### Configure allowed tools You control two layers with the `tools`, `allowedTools`, and `disallowedTools` options: @@ -396,11 +360,7 @@ To remove a built-in from Claude’s context, omit it from `tools` or list its bare name in `disallowedTools` (TypeScript) or `disallowed_tools` (Python). For the full evaluation order, see [Configure permissions](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>). -### - -​ - -Require approval for specific tools +### Require approval for specific tools Set a tool’s `permission_policy` to `always_ask`, and `allowedTools` stops approving that tool’s calls, so they can reach your [`canUseTool`](</docs/en/agent-sdk/user-input>) callback even though the tool is listed. Set `always_deny` instead, and [a call to the tool is denied](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>), but a [mod](</docs/en/plugins/mods/overview>) in a plugin you load [can still approve it](</docs/en/permissions#precedence-among-rules-hooks-and-mods>). The field is TypeScript-only and requires Agent SDK v0.3.301 or later. Put the policy entry in a `tools` array on the config object `createSdkMcpServer()` returns, not in the `tools` option you pass into that function. This example spreads `weatherServer` from the weather tool example and adds a `tools` array giving `get_temperature` the `always_ask` policy: @@ -423,11 +383,7 @@ To try the policy, replace the `options` in the Call a custom tool script with this example’s `options`, then run that script from your terminal. The script prints `Approval requested for mcp__weather__get_temperature`, followed by Claude’s answer about the temperature. For a complete script, see the [TypeScript reference](</docs/en/agent-sdk/typescript#mcpsdkserverconfigwithinstance>). If you use `auto` or `plan` [permission mode](</docs/en/agent-sdk/permissions#permission-modes>), set `destructiveHint: true` in the tool’s annotations so calls to the tool still reach your callback. Otherwise the [auto mode classifier](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) can approve some `always_ask` calls, under [conditions listed in the TypeScript reference](</docs/en/agent-sdk/typescript#permission-modes-that-can-approve-an-always_ask-call>), and a call it approves doesn’t reach your callback. Set the hint explicitly, because an unset `destructiveHint` counts as `false` for `always_ask` calls rather than defaulting to `true`. -## - -​ - -Handle errors +## Handle errors A handler error doesn’t stop the agent loop. The SDK’s in-process MCP server catches uncaught exceptions and returns them as error results, so how you report an error determines what Claude reads, not whether the query fails: @@ -531,19 +487,11 @@ } ); -## - -​ - -Return images and resources +## Return images and resources The `content` array in a tool result accepts `text`, `image`, `audio`, `resource`, and `resource_link` blocks. You can mix them in the same response. In TypeScript, the SDK saves audio blocks to disk and Claude receives a text block with the saved file path; in Python, the SDK drops audio blocks from the tool result and logs a warning. Claude receives each resource link block as a text block containing the link’s name, URI, and description. In TypeScript, your application also receives the links themselves as [`resourceLinks`](</docs/en/agent-sdk/typescript#sdkmcpresourcelink>) on the user message’s `tool_use_result`; in Python, the SDK flattens them to text before the CLI sees the result, so the Python [`resourceLinks` key](</docs/en/agent-sdk/python#usermessage>) is never produced for in-process tools. -### - -​ - -Images +### Images An image block carries the image bytes inline, encoded as base64. There is no URL field. To return an image that lives at a URL, fetch it in the handler, read the response bytes, and base64-encode them before returning. A PNG, JPEG, GIF, or WebP image reaches Claude as visual input; an image of any other type is saved to disk and Claude receives its file path as text instead. @@ -607,11 +555,7 @@ } ); -### - -​ - -Resources +### Resources A resource block embeds a piece of content identified by a URI. The actual content rides in the block’s `text` or `blob` field. Use this when your tool produces a generated file or a record from an external system. @@ -657,11 +601,7 @@ These block shapes come from the MCP `CallToolResult` type. See the [MCP specification](<https://modelcontextprotocol.io/specification/2025-06-18/server/tools#tool-result>) for the full definition. -## - -​ - -Return structured data +## Return structured data `structuredContent` is an optional JSON object on the result, separate from the `content` array. Use it to return raw values that Claude can read as exact fields instead of parsing them out of a text string or image. For Python handlers, see Structured content in Python. When a TypeScript `tool()` handler sets `structuredContent`, Claude receives the JSON plus the image and resource blocks in `content`, and the text blocks in `content` don’t reach Claude. The example below renders a chart as an image block and returns the data points behind it in `structuredContent` from the same handler. In the snippet, `chartPngBuffer` is a `Buffer` holding the rendered PNG bytes. @@ -684,11 +624,7 @@ The Python `@tool` decorator forwards only `content` and `is_error` from the handler’s return dict. To return `structuredContent` from Python, run a [standalone MCP server](</docs/en/agent-sdk/mcp>) instead of an in-process SDK server. -## - -​ - -Example: unit converter +## Example: unit converter This tool converts values between units of length, temperature, and weight. A user can ask “convert 100 kilometers to miles” or “what is 72°F in Celsius,” and Claude picks the right unit type and units from the request. It demonstrates two patterns: @@ -927,11 +863,7 @@ } } -## - -​ - -Next steps +## Next steps You can mix the patterns on this page in the same server: a single server can hold a database tool, an API gateway tool, and an image renderer alongside each other. From here:
modified Data usage View current →
Show diff (132 lines)
--- a/data-usage.md +++ b/data-usage.md @@ -1,38 +1,18 @@ -## +## Data policies -​ - -Data policies - -### - -​ - -Data training policy +### Data training policy **Consumer users (Free, Pro, Max, and Ultra plans)** : We give you the choice to allow your data to be used to improve future Claude models. We will train new models using data from Free, Pro, Max, and Ultra accounts when this setting is on (including when you use Claude Code from these accounts). **Commercial users** : (Team and Enterprise plans, API, 3rd-party platforms, and Claude Gov) maintain existing policies: Anthropic does not train generative models using code or prompts sent to Claude Code under commercial terms, unless the customer has chosen to provide their data to us for model improvement (for example, the [Developer Partner Program](<https://support.claude.com/en/articles/11174108-about-the-development-partner-program>)). -### - -​ - -Development Partner Program +### Development Partner Program If you explicitly opt in to methods to provide us with materials to train on, such as via the [Development Partner Program](<https://support.claude.com/en/articles/11174108-about-the-development-partner-program>), we may use those materials provided to train our models. An organization admin can expressly opt-in to the Development Partner Program for their organization. Note that this program is available only for Anthropic first-party API, and not for Amazon Bedrock or Google Cloud’s Agent Platform users. -### - -​ - -Feedback using the `/feedback` command +### Feedback using the `/feedback` command If you choose to send us feedback about Claude Code using the `/feedback` command, we may use your feedback to improve our products and services. Transcripts shared via `/feedback`, or via `/bug` and `/share`, which report through the same path, are retained for 5 years. With [Claude-drafted feedback](</docs/en/tools-reference#sendfeedback-tool-behavior>), Claude can also draft a feedback report and queue it on your machine for you to review. Claude Code sends nothing until you choose to send the draft, and a sent draft goes through the same submission path and retention as other `/feedback` reports. -### - -​ - -Session quality surveys +### Session quality surveys When you see the “How is Claude doing this session?” prompt in Claude Code, responding to this survey, including selecting “Dismiss”, records only your rating. We do not collect or store any conversation transcripts, inputs, outputs, or other session data as part of the rating prompt itself. Unlike thumbs up/down feedback or `/feedback` reports, this session quality survey is a simple product satisfaction metric. After the rating prompt, you may see a separate follow-up asking “Can Anthropic look at your session transcript to help us improve Claude Code?”. This is an optional second step distinct from the rating: @@ -42,11 +22,7 @@ Nothing is uploaded unless you explicitly select **Yes**. Organizations with [zero data retention](</docs/en/zero-data-retention>), or where product feedback is disabled by organization policy, or where `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` is set, never see this follow-up. Your responses to this survey, including session transcripts submitted after the rating prompt, do not impact your data training preferences and cannot be used to train our AI models. To disable these surveys, set `CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1`. The survey is also disabled when `DISABLE_TELEMETRY`, `DO_NOT_TRACK`, or `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` is set. Organizations that block nonessential traffic but capture survey responses through their own [OpenTelemetry collector](</docs/en/monitoring-usage>) can opt the survey back in by setting `CLAUDE_CODE_ENABLE_FEEDBACK_SURVEY_FOR_OTEL=1`. The survey then logs ratings to the configured collector only. The transcript-share follow-up and all other Anthropic-bound feedback traffic stay disabled. To control frequency instead of disabling, set [`feedbackSurveyRate`](</docs/en/settings-reference#feedbacksurveyrate>) in your settings file to a probability between `0` and `1`. -### - -​ - -Data retention +### Data retention Anthropic retains Claude Code data based on your account type and preferences. **Consumer users (Free, Pro, Max, and Ultra plans)** : @@ -62,19 +38,11 @@ You can delete individual cloud sessions at any time. Deleting a session permanently removes the session’s event data. For instructions on how to delete sessions, see [Delete sessions](</docs/en/claude-code-on-the-web#delete-sessions>). Learn more about data retention practices in our [Privacy Center](<https://privacy.anthropic.com/>). For full details, please review our [Commercial Terms of Service](<https://www.anthropic.com/legal/commercial-terms>) (for Team, Enterprise, and API users) or [Consumer Terms](<https://www.anthropic.com/legal/consumer-terms>) (for Free, Pro, Max, and Ultra users) and [Privacy Policy](<https://www.anthropic.com/legal/privacy>). -## - -​ - -Data access +## Data access For all first party users, you can learn more about what data is logged for local Claude Code and remote Claude Code. [Remote Control](</docs/en/remote-control>) sessions follow the local data flow since all execution happens on your machine; while connected, the session transcript is also stored on Anthropic servers to sync the conversation across devices, as described in [Connection and security](</docs/en/remote-control#connection-and-security>). Note for remote Claude Code, Claude accesses the repository where you initiate your Claude Code session. Claude does not access repositories that you have connected but have not started a session in. -## - -​ - -Local Claude Code: Data flow and dependencies +## Local Claude Code: Data flow and dependencies The diagram below shows how Claude Code connects to external services during installation and normal operation. Solid lines indicate required connections, while dashed lines represent optional or user-initiated data flows. Claude Code runs locally. To interact with the LLM, Claude Code sends data over the network. This data includes all user prompts and model outputs, encrypted in transit via TLS 1.2+. Claude Code is compatible with most popular VPNs and LLM proxies. Encryption at rest depends on your model provider: @@ -87,11 +55,7 @@ Claude Code is built on Anthropic’s APIs. For details on API security controls, including API logging procedures, see the compliance artifacts in the [Anthropic Trust Center](<https://trust.anthropic.com>). -### - -​ - -Cloud execution: Data flow and dependencies +### Cloud execution: Data flow and dependencies [Cloud sessions](</docs/en/claude-code-on-the-web>) run in Anthropic-managed virtual machines by default instead of locally. Sessions your organization routes to a [self-hosted environment](</docs/en/self-hosted-environments>) run on infrastructure you control; for what stays on your machines and what still goes to Anthropic, see [What stays on your infrastructure](</docs/en/self-hosted-environments#what-stays-on-your-infrastructure>). In Anthropic-hosted cloud sessions: @@ -102,11 +66,7 @@ For security details about cloud execution, see [Security](</docs/en/security#cloud-execution-security>). -## - -​ - -Telemetry services +## Telemetry services Claude Code sends two kinds of operational telemetry: usage metrics and error reports. You can turn each off individually with the environment variables below, or disable all non-essential traffic at once by setting `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`. Setting `DISABLE_TELEMETRY` or `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` also disables feature-flag evaluation, which can make [Remote Control](</docs/en/remote-control#requirements>) unavailable; `DISABLE_ERROR_REPORTING` doesn’t. **Metrics** : latency, reliability, and usage patterns, sent to Anthropic and to third-party logging infrastructure over TLS. Metrics never include your code, prompts, or file paths. Set `DISABLE_TELEMETRY=1` to opt out. **Error reports** : error messages and stack traces from Claude Code’s own internals, sent to a third-party error tracking service over TLS. Claude Code redacts known patterns of secrets, file paths, email addresses, and other personal information before anything leaves your machine. Set `DISABLE_ERROR_REPORTING=1` to opt out. Error reporting is on only when all of these apply: @@ -117,11 +77,7 @@ When you run the `/feedback` command, a copy of your conversation history including code is sent to Anthropic. The `/bug` and `/share` commands submit through the same path. Before submitting a report from the feedback dialog, you choose how much history to include: the current session only, which is the default, or also other sessions from the same project over the last 24 hours or 7 days. Claude Code submits [Claude-drafted feedback](</docs/en/tools-reference#sendfeedback-tool-behavior>) through the same path, including the transcript when you chose to include it on the draft’s review screen. The data is encrypted in transit via TLS and stored in Google Cloud Storage, which encrypts stored data at rest by default. Optionally, a GitHub issue is created in the public repository. To opt out, set the `DISABLE_FEEDBACK_COMMAND` environment variable to `1`. When you use a third-party provider such as Amazon Bedrock or Google Cloud’s Agent Platform, or have no Anthropic credentials configured, `/feedback` writes the report to a local archive under `~/.claude/feedback-bundles/` instead of sending it to Anthropic. Known API key and token patterns are redacted before the archive is written. Nothing leaves your machine until you send that file to your Anthropic account representative or attach it to a support request. -## - -​ - -Default behaviors by API provider +## Default behaviors by API provider By default, error reporting, telemetry, and bug reporting are disabled when using Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, or Claude Platform on AWS. Session quality surveys and the WebFetch domain safety check are exceptions and run regardless of provider. On a signed-in [Claude apps gateway](</docs/en/claude-apps-gateway>) session, usage analytics, error reporting, and survey ratings to Anthropic are disabled by the gateway credential itself, with no setting to re-enable them. You can opt out of all non-essential traffic, including surveys, at once by setting `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`. This variable doesn’t affect the WebFetch check or official plugin marketplace auto-install; each has its own opt-out: `skipWebFetchPreflight` in [settings](</docs/en/settings>) for WebFetch, and `CLAUDE_CODE_DISABLE_OFFICIAL_MARKETPLACE_AUTOINSTALL` for the marketplace. Here are the full default behaviors: @@ -160,10 +116,6 @@ All environment variables can be checked into `settings.json` (see [settings reference](</docs/en/settings-reference>)). When a host platform sets `CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST`, metrics default to on for Google Cloud’s Agent Platform, Amazon Bedrock, Microsoft Foundry, and Claude Platform on AWS, and follow the standard `DISABLE_TELEMETRY` opt-out. Error reporting and `/feedback` reports remain off by default on those providers. -### - -​ - -WebFetch domain safety check +### WebFetch domain safety check Before fetching a URL, the WebFetch tool sends the requested hostname to `api.anthropic.com` to check it against a safety blocklist maintained by Anthropic. Only the hostname is sent, not the full URL, path, or page contents. Claude Code caches a hostname that passes the check for five minutes, and re-checks a blocked or failed hostname on the next request. This check runs regardless of which model provider you use and is not affected by `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`. If your network blocks `api.anthropic.com`, WebFetch requests fail until you either allowlist the domain or set `skipWebFetchPreflight: true` in [settings](</docs/en/settings>). Disabling the check means WebFetch attempts to retrieve any URL without consulting the blocklist, so combine it with [`WebFetch` permission rules](</docs/en/permissions#webfetch>) if you need to restrict which domains Claude can reach.
modified Debug your configuration View current →
--- a/debug-your-config.md +++ b/debug-your-config.md @@ -1,10 +1,6 @@ When Claude ignores an instruction or a feature you configured doesn’t appear, the cause is usually that the file didn’t load, it loaded from a different location than you expected, or another file overrode it. This guide shows how to inspect what Claude Code actually loaded so you can narrow down which applies. For installation, authentication, and connectivity problems, see [Troubleshoot installation and login](</docs/en/troubleshoot-install>) instead. -## - -​ - -See what loaded into context +## See what loaded into context The `/context` command shows everything occupying the context window for the current session. It breaks this down by category: system prompt, system tools, MCP tools, custom subagents with the source each loaded from, memory files, skills, and conversation messages. Run it first to confirm whether your `CLAUDE.md`, rules, or skill descriptions are present at all. The skills section in `/context` also includes [bundled skills](</docs/en/skills#bundled-skills>), which `/skills` doesn’t list. In [fullscreen mode](</docs/en/fullscreen>), `/context` collapses the per-item breakdown, so run `/context all` to expand it. For detail on a specific category, follow up with the dedicated command: @@ -23,19 +19,11 @@ CLAUDE.md and permissions solve different problems. CLAUDE.md tells Claude how your project works so it makes good decisions. [Permissions](</docs/en/permissions>) and [hooks](</docs/en/hooks>) enforce limits regardless of what Claude decides. Use CLAUDE.md for “we do it this way here.” Use permissions or hooks for security boundaries and anything that must never happen, where you need a guarantee instead of guidance. -## - -​ - -Check resolved settings +## Check resolved settings Settings merge across managed, user, project, and local scopes. Managed settings apply first when present. Among the rest, the closer scope overrides the broader one in the order local, then project, then user. Some settings can also be set by command-line flags or [environment variables](</docs/en/env-vars>), which act as another override layer. When a setting doesn’t seem to apply, the value you set is usually being overridden by another scope or an environment variable. To find invalid settings files, run `claude doctor` from your terminal. It prints read-only installation and settings diagnostics without starting a session. For a full checkup that also proposes fixes and asks before applying them, run [`/doctor`](</docs/en/commands#all-commands>) inside a session. Run `/status` to see which settings sources are active, including whether managed settings are in effect. To understand which scope Claude Code uses for a given key, see [Settings precedence](</docs/en/settings#settings-precedence>). -## - -​ - -Check MCP servers +## Check MCP servers Run `/mcp` to see every configured server, its connection status, and whether you have approved it for the current project. A server can be defined correctly but still not provide tools for a few common reasons: @@ -45,11 +33,7 @@ For configuration locations and scope rules, see [MCP](</docs/en/mcp>). -## - -​ - -Check hooks +## Check hooks Run `/hooks` to list every hook registered for the current session, grouped by event. If a hook you defined doesn’t appear, Claude Code didn’t load it. Check for these causes: @@ -64,11 +48,7 @@ When you edit `settings.json`, the change takes effect in the running session after a brief file-stability delay, even if you create the file or the project’s `.claude/` folder itself after the session started. You don’t need to restart. Before v2.1.257, Claude Code didn’t detect edits in a `.claude/` folder created after the session started. If `/hooks` still shows the old definition a few seconds after you save, run `/hooks` again to refresh the view. If `/hooks` shows the hook but it still does not fire, the next step is to watch hook evaluation live. Start a session with `claude --debug` and trigger the tool call. The debug log records each event, which matchers were checked, and the hook’s exit code and output. See [Debug hooks](</docs/en/hooks#debug-hooks>) for the log format and [hooks troubleshooting](</docs/en/hooks-guide#limitations-and-troubleshooting>) for common failure patterns. -## - -​ - -Test against a clean configuration +## Test against a clean configuration Start with [`claude --safe-mode`](</docs/en/cli-reference#cli-flags>), which launches a session with your customizations disabled, including: @@ -126,11 +106,7 @@ * **Problem gone** : the cause is in your user or project configuration. Copy `~/.claude.json` and the files in `~/.claude` into `~/claude-clean/config` one at a time. If none brings the problem back, go to your project directory in the same shell and start Claude Code without `--setting-sources user`. In Bash or Zsh, run `CLAUDE_CONFIG_DIR=~/claude-clean/config claude`. In PowerShell, the variable is still set, so run `claude`. * **Problem persists** : the cause is outside your user and project configuration. Run `/status` in the session to check for managed settings, check your shell for [environment variables](</docs/en/env-vars>), then see [Troubleshooting](</docs/en/troubleshooting>). -## - -​ - -Check common causes +## Check common causes Most configuration surprises trace back to a small set of location and syntax rules. Check these before assuming a bug: @@ -154,11 +130,7 @@ MCP server starts without expected environment variables| The server’s config entry doesn’t set them, and they aren’t in the environment Claude Code passes to stdio servers: its own environment, minus the [variables it strips from subprocesses](</docs/en/monitoring-usage#administrator-configuration>)| Set per-server `env` inside the server’s `.mcp.json` entry, which doesn’t depend on the launch environment or workspace trust. `Bash(rm *)` deny rule doesn’t block `/bin/rm` or `find -delete`| Bash rules match the literal command string, not the underlying executable; see [what a Bash rule doesn’t match](</docs/en/permissions#bash-rule-limits>)| Use a [PreToolUse hook](</docs/en/hooks-guide>) or the [sandbox](</docs/en/sandboxing>) for a hard guarantee. -## - -​ - -Related resources +## Related resources For full reference on each configuration surface, see the dedicated page:
modified Launch sessions from links View current →
Show diff (181 lines)
--- a/deep-links.md +++ b/deep-links.md @@ -7,11 +7,7 @@ This page covers how to build a link, embed one in a runbook or trigger it from the shell, and manage or disable handler registration on each platform. -## - -​ - -How deep links work +## How deep links work The `claude-cli://` prefix is a custom URL scheme that Claude Code registers with your operating system, similar to how `mailto:` links open your email client. When you click a deep link: @@ -22,19 +18,11 @@ The link itself can be hosted anywhere, but the session always opens locally on the computer where you clicked. See Registration and supported platforms for which terminal emulator opens on each operating system. The platform that displays the link must allow custom URL schemes. For what GitHub does with them and the workaround, see The link renders as plain text instead of being clickable. -### - -​ - -What a launched session shows +### What a launched session shows A deep link never executes anything on its own. The link only chooses a directory and fills the prompt box. If you click a link from a page you do not trust, the prompt is still inert: nothing reaches the model until you read what was filled in and press Enter. When the session opens, a warning line below the input box reads `Prompt from an external link` and stays visible until you send or clear the prompt. For prompts over 1,000 characters, the warning includes the character count and tells you to scroll and review the full text before pressing Enter, since long prompts can push instructions off screen. Permission rules, `CLAUDE.md`, and trust prompts for the selected directory apply the same way as for any other session. -## - -​ - -Build a link +## Build a link A deep link starts with `claude-cli://open`, followed by optional query parameters. The minimal form opens Claude Code in your home directory with an empty prompt: @@ -59,11 +47,7 @@ You can edit the prompt before pressing Enter to send it. See Choose between `cwd` and `repo` for how the local path is selected when you have multiple clones or worktrees. -### - -​ - -Choose between `cwd` and `repo` +### Choose between `cwd` and `repo` Use `cwd` when everyone who clicks the link has the project at the same absolute path, such as a standardized devcontainer or VM image. Use `repo` when the link is shared and each person clones to a different location. Claude Code resolves the slug to a local path as follows: @@ -72,19 +56,11 @@ The welcome header shows which path it picked so you can confirm the right clone opened. -## - -​ - -Examples +## Examples The sections below show two common ways to use a deep link: as a Markdown link in a document and as a command in a script or shell alias. -### - -​ - -Embed a link in a runbook +### Embed a link in a runbook A deep link in a runbook gives whoever is triaging a one-click way to start investigating in the right repository with a prepared prompt. The platform that renders the runbook must allow custom URL schemes. GitHub-rendered Markdown does not allow `claude-cli://`, so a deep link in a GitHub README, issue, or wiki shows only its label with no clickable link. See the troubleshooting note for a workaround. The prompt is part of the URL and must be URL-encoded. To produce the encoded value, pass your prompt text through `encodeURIComponent` in a browser console or any URL encoder. The example below adds an investigation entry point to an incident runbook for a service called `web-gateway`: @@ -96,11 +72,7 @@ To use this in your own runbook, replace `acme/web-gateway` with your service’s repository slug. Before engineers click step 2, their machine must have the `claude-cli://` handler registered, and they must have run `claude` in their local clone or worktree. -### - -​ - -Open a link from the shell +### Open a link from the shell You can also open a deep link from a shell script, alias, or automation rather than by clicking it. Call your operating system’s URL-opening command with the link as the argument. These commands rely on the handler that Claude Code registers on the machine. @@ -132,11 +104,7 @@ On success, a new terminal window opens with Claude Code running and the prompt pre-filled. -## - -​ - -Registration and supported platforms +## Registration and supported platforms Claude Code registers the `claude-cli://` handler with your operating system on macOS, Linux, and Windows when you do either of these: @@ -153,73 +121,37 @@ The handler launches Claude Code in a detected terminal emulator. On macOS, Claude Code remembers the terminal from your most recent interactive session and reuses it, supporting iTerm2, Ghostty, kitty, Alacritty, WezTerm, and Terminal.app. On Linux it honors the `$TERMINAL` environment variable, then `x-terminal-emulator`, then a list of common emulators. On Windows it prefers Windows Terminal, then PowerShell, then `cmd.exe`. To prevent registration entirely, set [`disableDeepLinkRegistration`](</docs/en/settings-reference#disabledeeplinkregistration>) to `"disable"` in `settings.json`. To enforce this across an organization so users cannot re-enable it, set it in [managed settings](</docs/en/server-managed-settings>) instead. Claude Code’s `disableDeepLinkRegistration` setting covers `claude-cli://` links only. -## - -​ - -Open a VS Code tab instead of a terminal +## Open a VS Code tab instead of a terminal The VS Code extension registers its own handler at `vscode://anthropic.claude-code/open`, which opens a Claude Code editor tab rather than a terminal window. See [Launch a VS Code tab from other tools](</docs/en/vs-code#launch-a-vs-code-tab-from-other-tools>) for that URL’s parameters. -## - -​ - -Open a Claude Desktop session on an SSH connection +## Open a Claude Desktop session on an SSH connection Claude Desktop handles its own `claude://` links. To open a Desktop session on a remote machine over SSH, see [Open an SSH session from a link](</docs/en/desktop#open-an-ssh-session-from-a-link>). -## +## Troubleshooting -​ - -Troubleshooting - -### - -​ - -Clicking the link does nothing +### Clicking the link does nothing The handler likely isn’t registered yet. In an interactive session, registration happens when you send something, not when the session starts. Start an interactive `claude` session on that machine, send any prompt, exit, and try the link again. If you are on Linux without a desktop environment, `xdg-open` may have nothing to dispatch to. -### - -​ - -xdg-open is not found on Linux +### xdg-open is not found on Linux The `xdg-open` command is part of the `xdg-utils` package, which minimal server images, containers, and WSL distributions often leave out. Install `xdg-utils` with your distribution’s package manager, for example `sudo apt install xdg-utils`, then run the command again. If the command then runs but nothing opens, `xdg-open` may have no desktop environment to dispatch to; see Clicking the link does nothing. -### - -​ - -The link renders as plain text instead of being clickable +### The link renders as plain text instead of being clickable Some Markdown renderers only allow `http` and `https` links and strip other URL schemes. GitHub does this in READMEs, issues, pull requests, and wikis: `[label](claude-cli://...)` renders as `label`, with no link and the URL removed. On these platforms, put the deep link in a code block so readers can see the URL and paste it into their browser’s address bar. -### - -​ - -The session opens in my home directory instead of the repo +### The session opens in my home directory instead of the repo The `repo` parameter only resolves to clones Claude Code has already seen. Run `claude` inside the clone once so Claude Code records its path, or switch the link to use `cwd` with an absolute path. -### - -​ - -The link opens the wrong terminal +### The link opens the wrong terminal On macOS, start `claude` in your preferred terminal once and the next deep link will use it. On Linux, set the `$TERMINAL` environment variable to your preferred emulator’s command name. On Windows, the order is fixed: install Windows Terminal if you want links to open there instead of a PowerShell or `cmd.exe` window. -## - -​ - -Learn more +## Learn more These pages cover related ways to launch or extend Claude Code sessions:
modified Plugin dependencies View current →
Show diff (171 lines)
--- a/dependencies.md +++ b/dependencies.md @@ -8,19 +8,11 @@ To add a constraint, start at Declare a dependency with a version constraint. If you maintain a plugin that others depend on, tag your releases so their constraints can resolve. -## - -​ - -Declare dependencies +## Declare dependencies Without a version constraint, a dependency moves to each new release its marketplace publishes the next time users update. If that release renames an MCP tool your plugin calls, your plugin breaks for everyone who updates. With a constraint such as `~2.1.0` on a dependency from a git-backed source, users who have your plugin installed keep receiving `2.1.x` patches of the dependency and never move to `2.2`. To upgrade on your own schedule, test against a newer release and then publish a new version of your plugin with a wider constraint. -### - -​ - -Declare a dependency with a version constraint +### Declare a dependency with a version constraint List dependencies in the `dependencies` array of your plugin’s `.claude-plugin/plugin.json`. The following manifest declares one unversioned dependency and one constrained dependency: @@ -45,11 +37,7 @@ A range doesn’t match pre-release versions such as `2.0.0-beta.1` unless you opt in with a pre-release suffix such as `^2.0.0-0`. -### - -​ - -Bundle plugins for a team +### Bundle plugins for a team To let engineers install a curated set of plugins with one command, publish a plugin whose manifest contains a `name` and a `dependencies` array. A plugin manifest needs only `name`, so this is a valid plugin, and installing it installs every dependency. For example, a platform team can publish role-specific bundles in an internal marketplace so engineers run one `claude plugin install` instead of installing each plugin separately: @@ -74,11 +62,7 @@ For the engineer-side steps, see [Keep plugins updated](</docs/en/plugins/install#keep-plugins-updated>). To deploy a bundle to everyone in an organization, an administrator adds it to `enabledPlugins` in managed settings. See [Pre-install and require plugins](</docs/en/plugins/org#pre-install-and-require-plugins>). -### - -​ - -Depend on a plugin from another marketplace +### Depend on a plugin from another marketplace By default, Claude Code doesn’t install a dependency from a different marketplace than the declaring plugin’s own, unless the user already has that dependency installed and enabled at the same scope. This default prevents one marketplace from silently installing plugins from a source the user hasn’t reviewed. To allow the install, add the target marketplace’s name to `allowCrossMarketplaceDependenciesOn` in the root marketplace’s `marketplace.json`. The root marketplace is the one that hosts the plugin the user is installing. Only the root marketplace’s allowlist applies. The following `marketplace.json` allows `deploy-kit` to depend on a plugin from `your-shared-marketplace`: @@ -101,11 +85,7 @@ If `allowCrossMarketplaceDependenciesOn` is missing or doesn’t include the target marketplace, Claude Code doesn’t install the dependency. When the dependency is declared in the marketplace entry, the install itself is refused with a message that starts `Dependency "audit-logger@your-shared-marketplace" (required by deploy-kit@your-marketplace) is in marketplace "your-shared-marketplace", which is not in the allowlist` and names the field to set. When it’s declared in `plugin.json`, the install completes without the dependency and your plugin then fails to load. The allowlist check doesn’t apply to a dependency that is already enabled. If a user installs `audit-logger` from `your-shared-marketplace` themselves first, at the same scope, `deploy-kit` then installs without any change to the allowlist. -### - -​ - -Test a plugin and its dependency locally +### Test a plugin and its dependency locally If you’re developing a plugin and the plugin it depends on at the same time, start Claude Code from your shell and load both with [`--plugin-dir`](</docs/en/plugins/cli-reference#flags-that-load-a-plugin-for-one-session>): @@ -123,22 +103,14 @@ When both plugins are in one parent folder, you can pass that folder to `--plugin-dir` once. If the folder isn’t itself a plugin, Claude Code loads each child folder that has a `.claude-plugin/plugin.json`. Requires Claude Code v2.1.265 or later. -## - -​ - -Release a plugin that others depend on +## Release a plugin that others depend on If you maintain a plugin that other plugins depend on with a version constraint, tag its releases so those constraints can resolve. A constraint resolves against git tags on the repository that hosts the plugin. Tag the repository that the plugin’s [plugin source](</docs/en/plugins/marketplace-reference#plugin-sources>) in `marketplace.json` points at: * **`github`, `url`, or `git-subdir` source**: the plugin’s own repository, so the plugin’s author creates the tags * **Relative path such as`./plugins/secrets-vault`**: the marketplace repository, so the marketplace maintainer creates the tags -### - -​ - -Create a release tag +### Create a release tag Tag each release as `<plugin-name>--v<version>`, where `<version>` matches the `version` field in that commit’s `plugin.json`. The plugin-name prefix lets one marketplace repository host several plugins with independent version histories. Create the tag from the plugin directory, with an `origin` remote configured to receive the pushed tag, using [`claude plugin tag`](</docs/en/plugins/cli-reference#plugin-tag>): @@ -153,11 +125,7 @@ A successful run prints `Created tag secrets-vault--v2.1.0`. With `--push`, it also prints `Pushed to origin`. Without `--push`, it prints the `git push` command to run yourself. Pass `--dry-run` to see the plan without creating anything. The [`claude plugin tag` reference](</docs/en/plugins/cli-reference#plugin-tag>) lists the remaining flags. You can also run `git tag secrets-vault--v2.1.0` directly, as long as you keep the `version` in `plugin.json` and in the marketplace entry in sync yourself. -### - -​ - -Constrain a dependency that has a non-git source +### Constrain a dependency that has a non-git source Tag-based resolution applies only to git-backed sources. For a dependency with an `npm`, `archive`, or `command` [plugin source](</docs/en/plugins/marketplace-reference#plugin-sources>), the constraint doesn’t control which version is fetched. It’s still checked when the plugin loads, and the dependent plugin is disabled if the installed version doesn’t satisfy it. For `npm`, `archive`, and `command` sources, the version checked is the `version` in the dependency’s `plugin.json`. Set one there before you constrain that dependency, because a `plugin.json` that sets no version satisfies no constraint. Claude Code never installs a dependency with a `command` source itself, so users [install it first](</docs/en/plugins/marketplace-reference#command-plugin-source>). It also never runs a dependency’s [`headersHelper`](</docs/en/plugins/host-marketplace#authenticate-archive-downloads>), so users also install a dependency whose marketplace entry sets one before they install your plugin. Besides `claude plugin install`, these operations also install any missing declared dependency, and the `command` and `headersHelper` limits apply to them too: @@ -166,19 +134,11 @@ * Re-running `claude plugin install` on the dependent plugin * `claude plugin marketplace add` -## - -​ - -How dependencies behave for your users +## How dependencies behave for your users These sections describe how Claude Code resolves, checks, and combines the constraints you declare once your plugin is installed alongside others. -### - -​ - -How a constraint resolves against tags +### How a constraint resolves against tags When a user installs a plugin that declares `{ "name": "secrets-vault", "version": "~2.1.0" }`, the dependency installs from the highest `secrets-vault--v` tag that satisfies `~2.1.0` on the repository that hosts `secrets-vault`. When no tag satisfies the range, the install either fails or uses the marketplace’s current copy: @@ -187,19 +147,11 @@ For a plugin the marketplace references by a relative path, a marketplace you added as a local folder path also resolves constraints against that folder’s git tags, when the folder is a git repository. A local folder that isn’t a git repository has no tags, so Claude Code installs the dependency from the folder’s current contents instead. -### - -​ - -Confirm the resolved version +### Confirm the resolved version To confirm which version a constraint resolved to, run `claude plugin list` in your shell. A tag-resolved dependency shows its version with a 12-character commit suffix, such as `2.1.0-8713c5b11005`. Constraint checks use the tag’s version rather than the `version` in `plugin.json`, even if `plugin.json` at that commit lags behind. If you force-move a tag to a different commit, the next install fetches that commit’s content instead of reusing a stale cached copy. See [Versions and updates](</docs/en/plugins/loading#versions-and-updates>) for how a plugin’s version becomes its cache key. -### - -​ - -Combine constraints from several plugins +### Combine constraints from several plugins When several installed plugins constrain the same dependency, the dependency resolves to the highest version that satisfies all of their ranges. Common combinations resolve like this: @@ -211,11 +163,7 @@ Auto-update fetches a constrained dependency at the highest git tag that satisfies every installed plugin’s range, rather than at the marketplace’s latest version. If the installed plugins’ ranges don’t overlap, auto-update leaves that dependency at its current version, and the `/plugin` **Errors** tab shows an entry naming the constraining plugin. If they overlap but no tag falls in the range, auto-update fetches the marketplace’s current copy and skips the update when that copy’s `version` falls outside any installed plugin’s range. When a user uninstalls the last plugin that constrains a dependency, the dependency is no longer constrained to a version range and resumes tracking its marketplace entry on the next update. -### - -​ - -Dependencies when your plugin loads from claude.ai +### Dependencies when your plugin loads from claude.ai When a user turns your plugin on for their claude.ai account, Claude Code loads it as `<name>@synced`, [with no marketplace](</docs/en/plugins/loading#synced-plugins>). For that copy of your plugin, Claude Code counts a dependency entry that names a marketplace as met when the user has either of these: @@ -224,11 +172,7 @@ If you tell users to turn your plugin on from claude.ai, tell them to turn the dependency on there too, or to install it from its marketplace. A claude.ai plugin meets the entry only when your plugin also loads from claude.ai. -## - -​ - -See also +## See also * [`claude plugin prune`](</docs/en/plugins/cli-reference#plugin-prune>): remove auto-installed dependencies no plugin needs anymore * [Host a marketplace](</docs/en/plugins/host-marketplace>): release channels and recommending other plugins
modified Desktop application View current →
Show diff (1494 lines)
--- a/desktop.md +++ b/desktop.md @@ -26,11 +26,7 @@ For [scheduled recurring work](</docs/en/desktop-scheduled-tasks>), keyboard shortcuts, or sending tasks from your phone, see the linked pages and sections. If you already use the terminal-based CLI, see the CLI comparison for what carries over. -## - -​ - -Start a session +## Start a session Before you send your first message, choose the environment, project folder, permission mode, and model in the row under the prompt box: @@ -44,27 +40,15 @@ Type your task and press **Enter** to start. Each session tracks its own context and changes independently. -## - -​ - -Work with code +## Work with code Give Claude the right context, control how much it does on its own, and review what it changed. -### - -​ - -Use the prompt box +### Use the prompt box Type what you want Claude to do and press **Enter** to send. Claude reads your project files, makes changes, and runs commands based on your permission mode. You can redirect Claude at any point: click the stop button to interrupt immediately, or type a correction and press **Enter** to send it without stopping the running action. Claude reads the correction as soon as the current action completes and adjusts before its next step. Click the **+** button next to the prompt box for file attachments, skills, connectors, and plugins. -### - -​ - -Accept a suggested prompt +### Accept a suggested prompt After Claude replies, the Code tab can show a suggested next prompt as gray text in the empty prompt box. Claude Code [generates each suggestion](</docs/en/interactive-mode#prompt-suggestions>) from your conversation with a short background request that counts toward your plan’s usage limits or your API costs. @@ -73,11 +57,7 @@ Turn off **Prompt suggestions** in **Settings > Code** or **Settings > Claude Code** to stop suggestions. Each session stops showing them the next time it starts or resumes. -### - -​ - -Add files and context to prompts +### Add files and context to prompts To give Claude a file, @mention it or attach it in the prompt box: @@ -86,11 +66,7 @@ * **Attach files** : attach images, PDFs, and other files to your prompt from the **+** button next to the prompt box, or drag and drop files directly into the prompt. This is useful for sharing screenshots of bugs, design mockups, or reference documents. * **In a[WSL session](</docs/en/desktop-wsl>)**: if the **+** menu shows **Add image** instead of **Add files or photos** , you can attach only images. To give Claude any other file from the session’s folder, @mention it. -### - -​ - -Choose a permission mode +### Choose a permission mode Permission modes control how much autonomy Claude has during a session: whether it asks before editing files, running commands, or both. You can switch permission modes at any time using the mode selector in the row under the prompt box. To approve each change yourself, switch to Manual. To set a default permission mode for new local sessions, add `permissions.defaultMode` to your [settings file](</docs/en/settings#where-settings-live>). A mode you pick in a local session is remembered per folder and outranks a `defaultMode` in the project’s `.claude/` settings. A new local session can still start in a `defaultMode` from `~/.claude/settings.json` or managed settings, so check the selector before your first message. If you pick Plan, it applies to this session only. @@ -108,19 +84,11 @@ Cloud sessions support Accept edits, Plan, and Auto. Accept edits corresponds to `default` mode: cloud sessions pre-approve file edits, so the selector shows Accept edits instead of Manual. Bypass permissions isn’t available in cloud sessions, including sessions in a [self-hosted environment](</docs/en/self-hosted-environments>). Enterprise admins can restrict which permission modes are available. See enterprise configuration for details. -#### - -​ - -Auto mode availability +#### Auto mode availability Auto mode is available to all users on the Anthropic API and requires Claude Opus 4.6 or later, Sonnet 4.6 or later, Haiku 5.5, or a [Fable model](</docs/en/model-config#work-with-fable>). Organization administrators can turn auto mode off with the `disableAutoMode` key in managed settings. In Enterprise deployments that route Desktop to Google Cloud’s Agent Platform, auto mode is also available by default; see [Auto mode on Bedrock, Agent Platform, or Foundry](</docs/en/permission-modes#enable-auto-mode-on-bedrock-agent-platform-or-foundry>) for the supported models. -### - -​ - -Preview your app +### Preview your app Claude can start a dev server and open it in the Browser pane to verify its changes. This works for frontend web apps as well as backend servers: Claude can test API endpoints, view server logs, and iterate on issues it finds. In most cases, Claude starts the server automatically after editing project files. You can also ask Claude to preview at any time. By default, Claude auto-verifies changes after every edit. In a local session, click an HTML, PDF, or video path in the chat to open it in the Browser pane. In an SSH or WSL session, you can preview an HTML file. @@ -135,11 +103,7 @@ In an SSH session, you lose the pane’s cookies when you quit Desktop. You can’t change that with **Keep cookies**. Claude creates the initial server configuration based on your project. If your app uses a custom dev command, edit `.claude/launch.json` to match your setup. See Configure preview servers for the full reference. To clear the Browser’s saved data, select **Clear browsing data** in the Browser pane’s **⋮** menu. To turn the Browser off entirely, turn off **Browser tools** in **Settings > Code** or **Settings > Claude Code**. -#### - -​ - -Preview HTML files in SSH and WSL sessions +#### Preview HTML files in SSH and WSL sessions In an SSH or [WSL](</docs/en/desktop-wsl>) session, click an HTML file’s path in the chat to preview the file in the Browser pane. If charts or tables in the preview stay empty, the notice above it tells you why: @@ -148,11 +112,7 @@ If you closed the notice, open the file again to bring it back. -#### - -​ - -Turn off scripts in SSH and WSL previews for your organization +#### Turn off scripts in SSH and WSL previews for your organization To keep HTML previews in SSH and WSL sessions from running scripts, set the `disableRemotePreviewScripts` managed setting to `true`. Users can still browse external sites. Requires Claude Desktop v5.1231.0 or later. @@ -172,46 +132,26 @@ After the restart, open an HTML file from an SSH or WSL session on that computer. If the notice above the preview starts with `This preview doesn't load anything from the web`, scripts still run there. Check Desktop’s version, where you put the key, and that its value is the JSON Boolean `true`. -### - -​ - -Browse external sites +### Browse external sites The Browser pane is a tabbed browser, so you can open documentation, issue trackers, or any other site next to your running app. To open the Browser, press **Cmd+Shift+B** on macOS or **Ctrl+Shift+B** on Windows, or click **Browser** in the session’s title bar. You can sign in to sites in the pane, including popup sign-in flows such as Google OAuth. The first time you click an external link in the chat, a dialog asks whether links open in the Browser pane or in your default browser. To change your choice later, use **Open links in built-in browser** in the Browser pane’s **⋮** menu. **Cmd** -click on macOS or **Ctrl** -click on Windows opens a link in your default browser directly. Claude can read and interact with external pages using the same tools it uses to verify your app, with two additional safety checks: * Safety classifiers review Claude’s write actions on external pages, such as clicking and typing, in every permission mode. These are the same classifiers auto mode uses, and when they flag an action, you get a permission prompt regardless of mode. * In permission modes other than Auto and Bypass permissions, a domain allowlist check also applies before Claude navigates to a new site. -#### - -​ - -Approve Claude’s actions on a site +#### Approve Claude’s actions on a site The first time Claude acts on an external site, a permission card appears and Claude waits for your choice: **Allow once** , **Always allow** , or **Deny**. **Allow once** approves the action without saving anything. **Always allow** saves the approval for that site on your device, and you can revoke it in Settings. Each site needs its own approval, including subdomains. Your local dev servers and project files don’t need approval, so auto-verify keeps working without prompts. Even on an approved site, Claude won’t purchase items, create accounts, or bypass CAPTCHAs without your input. Browsing in the Browser pane uses the same safety model as the [Claude in Chrome extension](</docs/en/chrome>). See [Using Claude in Chrome safely](<https://support.claude.com/en/articles/12902428-using-claude-in-chrome-safely>) for how Claude handles sensitive sites and risky actions. -#### - -​ - -Choose between the Browser and the Chrome extension +#### Choose between the Browser and the Chrome extension The Browser pane uses a clean browser profile, separate from your personal browser, with none of your saved logins or history. Use it for building and testing your app and for sites that don’t need your identity. When you want Claude to act as you in your logged-in sessions, use the [Claude in Chrome extension](</docs/en/chrome>) instead, which shares your browser’s login state. -#### - -​ - -Restrict external browsing for your organization +#### Restrict external browsing for your organization The Browser follows the same [site allowlist and blocklist controls](<https://support.claude.com/en/articles/13065128-claude-in-chrome-admin-controls>) as the Claude in Chrome extension. If your organization already configured those lists for the extension, the Browser respects them automatically. Administrators can also turn off Claude’s tools on external pages with the `browserExternalPageTools` managed setting. With tools disabled, users can still visit external sites; Claude’s tools can’t read or act on them. To turn off external browsing entirely, set the `disableBrowserExternalNavigation` managed setting to `true`. This blocks all external navigation in the Browser, including sites on your organization’s allowlist. Localhost dev servers and file previews keep working, but HTML previews in SSH and WSL sessions don’t run scripts. Use `browserExternalPageTools` to let users keep browsing external sites without Claude’s tools, and `disableBrowserExternalNavigation` to block external sites for both users and Claude. -### - -​ - -Review changes with diff view +### Review changes with diff view After Claude makes changes to your code, the diff view lets you review modifications file by file before creating a pull request. To open the diff view, click the line counts, such as `+12 -1`, in the **Changes** card of the session details panel. You can also click **Changes** in the session’s title bar. A cloud session’s diff against the base branch can [leave out changes that aren’t pushed yet](</docs/en/claude-code-on-the-web#troubleshoot-a-missing-file-in-the-diff-view>). To comment on specific lines, hover over a line and click the **+** that appears beside its line number to open a comment box. Type your feedback and press **Enter** to add the comment. After adding comments to multiple lines, submit all comments at once: @@ -220,11 +160,7 @@ Claude reads your comments and makes the requested changes, which appear as a new diff you can review. -### - -​ - -Review your code +### Review your code To have Claude review your changes before you commit, enter `/code-review` in the prompt box. The findings arrive in the conversation when the review completes. In local, SSH, and [WSL](</docs/en/desktop-wsl>) sessions, the findings appear as a **Code review** card, grouped by file. Use the card to act on them: @@ -233,11 +169,7 @@ In any session, you can also ask Claude in the prompt box to fix what the review found. For what `/code-review` looks for and the arguments it takes, see [Review locally with `/code-review`](</docs/en/code-review-local>). -### - -​ - -Monitor pull request status +### Monitor pull request status To have Claude fix failing checks, or to have GitHub merge the pull request, turn on **Auto-fix** or **Merge when ready**. After you open a pull request, it appears in the **Changes** card of the session details panel with the status of its CI checks. Open the **⋮** menu beside its title: @@ -251,11 +183,7 @@ PR monitoring requires the [GitHub CLI (`gh`)](<https://cli.github.com/>) to be installed and authenticated on your machine. If `gh` is not installed, Desktop prompts you to install it the first time you try to create a PR.In an SSH session, set up `git` and `gh` on the remote machine before you click **Create PR** , because Claude pushes the branch and runs `gh pr create` there. Install `gh` there yourself, because Desktop doesn’t prompt you to in an SSH session. Then check there that `git push` works and that `gh auth status` reports that you are logged in. -## - -​ - -Arrange your workspace +## Arrange your workspace The Code tab is built around panes you can arrange in any layout: chat, diff, browser, terminal, file, plan, tasks, and subagent, along with the [iOS Simulator](</docs/en/desktop-ios-simulator>) on macOS. Drag a pane by its header to reposition it, or drag a pane edge to resize it. Press **Cmd+\** on macOS or **Ctrl+\** on Windows to close the focused pane. To open another pane, click its icon button in the session’s title bar. Hover to see each button’s name, such as **Terminal** , **Changes** for the diff view, **Browser** , and **Files**. If the pane you want has no button in the title bar, select it from the **⋮** menu beside the buttons: @@ -266,27 +194,15 @@ The pane layout, terminal, file editor, and view modes in this section require Claude Desktop v1.2581.0 or later. Open **Claude > Check for Updates…** on macOS or **Help > Check for Updates…** on Windows to update. -### - -​ - -See session details +### See session details The session details panel is a set of cards beside the chat that show where the session runs, what it changed, what it’s running, and its context usage. The panel appears after you start a session, while the chat is wide enough for it. -#### - -​ - -Hide or show the session details panel +#### Hide or show the session details panel To hide or show the panel, click **Hide session rail** or **Show session rail** in the session’s title bar, or in the bar’s **⋮** menu. If you still don’t see the panel, check which Code tab layout you have. -### - -​ - -Minimize a pane +### Minimize a pane To keep the Terminal, Browser, [iOS Simulator](</docs/en/desktop-ios-simulator>), or a side chat in view at a small size, click **Minimize** in the pane’s header. The button requires Claude Desktop v4.0.0 or later and a Claude account rather than a [third-party provider](</docs/en/third-party-integrations>). The Browser pane has it only in local sessions. The minimized pane sits in the session details panel while that panel is on screen, and floats in a corner of the chat otherwise: @@ -295,38 +211,22 @@ To get the full pane back, click **Expand** in the minimized pane’s header. To close the minimized pane instead, click the close button beside **Expand**. -### - -​ - -Run commands in the terminal +### Run commands in the terminal The integrated terminal lets you run commands alongside your session without switching to another app. Click **Terminal** in the session’s title bar or press **Ctrl+`** on macOS or Windows. The terminal opens in your session’s working directory and shares the same environment as Claude, so commands like `npm test` or `git status` see the same files Claude is editing. To open a second terminal tab, click **+** in the terminal pane header or right-click a folder in the chat to choose **Open in terminal**. If a WSL session has no terminal, see [If the terminal or connectors are unavailable](</docs/en/desktop-wsl#check-for-the-terminal-and-connectors>). The terminal is available in local and SSH sessions, with a limit on Windows remote machines. -### - -​ - -Open and edit files +### Open and edit files To open a file Claude mentions, click its path in the chat. To edit a file yourself, use the file pane: * **Local sessions** : you can edit files inside the session’s working directory, except some view-only ones such as `.mcp.json` and `.claude/settings.json`. To change one, open it in another app. * **Cloud, SSH, and WSL sessions** : the file pane is view-only, so ask Claude to make edits. -#### - -​ - -Save edits in the file pane +#### Save edits in the file pane By default, your edits in the file pane save on their own, so the pane shows no **Save** button. To save your edits yourself, uncheck **Auto save** in the pane’s **⋮** menu. With **Auto save** off, click **Save** after you change a file to write your edits, or **Cancel** to revert them. If the pane warns that the file changed on disk, click **Override** to write your edits over the version on disk, or **Discard** to drop your edits. -### - -​ - -Open files in other apps +### Open files in other apps Right-click any file path in the chat, diff viewer, or file pane to open a context menu: @@ -335,11 +235,7 @@ * **Show in Finder** on macOS, **Show in Explorer** on Windows: open the containing folder * **Copy** : a submenu that copies the file’s **Absolute path** , **Relative path** , or **Filename** -### - -​ - -Switch view modes +### Switch view modes View modes control how much detail appears in the chat transcript. To switch view modes, open the session menu from the caret beside the session title and select **Transcript view** , or press **Ctrl+O** on macOS or Windows to cycle through them. The Thinking mode appears in the menu only after Claude has produced thinking in the session you’re viewing. @@ -351,11 +247,7 @@ Use Thinking to follow Claude’s reasoning with tool calls still collapsed. Use Verbose when debugging why Claude took a particular action. Claude Desktop versions before 1.46388.1 also list a Summary mode, and a session still set to Summary opens in Normal once you update. -### - -​ - -Keyboard shortcuts +### Keyboard shortcuts Press **Cmd+/** on macOS or **Ctrl+/** on Windows to see all shortcuts available in the Code tab. The table in this section shows the macOS keys. On Windows and Linux, change these keys: @@ -391,11 +283,7 @@ These shortcuts apply to the Code tab. In Desktop, `Shift+Tab` doesn’t cycle permission modes as it does in the terminal’s [interactive mode](</docs/en/interactive-mode#keyboard-shortcuts>). -### - -​ - -Check usage +### Check usage To see how full this session’s context window is, find your Code tab layout: @@ -404,11 +292,7 @@ In either layout, type `/context` in the prompt box to print a per-category breakdown of this session’s context window in the chat. In both layouts, the usage ring is in the row under the prompt box. Click it to see your plan usage, which is shared across all your Claude Code surfaces. -## - -​ - -Let Claude use your computer +## Let Claude use your computer Computer use lets Claude open your apps, control your screen, and work directly on your machine the way you would. Ask Claude to interact with a desktop tool that has no CLI, or automate something that only works through a GUI. For running and testing iOS apps, Desktop opens the dedicated [iOS Simulator pane](</docs/en/desktop-ios-simulator>) instead of controlling your screen; the pane works without enabling computer use. @@ -418,11 +302,7 @@ Unlike the [sandboxed Bash tool](</docs/en/sandboxing>), computer use runs on your actual desktop with access to whatever you approve. Claude checks each action and flags potential prompt injection from on-screen content, but the trust boundary is different. See the [computer use safety guide](<https://support.claude.com/en/articles/14128542>) for best practices. -### - -​ - -When computer use applies +### When computer use applies Claude has several ways to interact with an app or service, and computer use is the broadest and slowest. It tries the most precise tool first: @@ -434,11 +314,7 @@ The per-app access tiers reinforce this: browsers are capped at view-only, and terminals and IDEs at click-only, steering Claude toward the dedicated tool even when computer use is active. Screen control is reserved for things nothing else can reach, like native apps, hardware control panels, or proprietary tools without an API. -### - -​ - -Enable computer use +### Enable computer use Computer use is off by default. If you ask Claude to do something that needs it while it’s off, Claude tells you it could do the task if you enable computer use in Settings. @@ -475,11 +351,7 @@ The Settings page shows the current status of each permission. If either is denied, click the badge to open the relevant System Settings pane. -### - -​ - -App permissions +### App permissions The first time Claude needs to use an app, a prompt appears in your session. Click **Allow for this session** or **Deny**. Approvals last for the current session, or 30 minutes in Dispatch-spawned sessions. The prompt also shows what level of control Claude gets for that app. These tiers are fixed by app category and can’t be changed: @@ -494,19 +366,11 @@ * **Denied apps** : add apps here to reject them without prompting. Claude may still affect a denied app indirectly through actions in an allowed app, but it can’t interact with the denied app directly. * **Unhide apps when Claude finishes** : when computer use isn’t running in the background, Claude hides your other windows while it works so it interacts with only the approved app. When Claude finishes, hidden windows are restored unless you turn this setting off. -## - -​ - -Manage sessions +## Manage sessions Each session is an independent conversation with its own context and changes. You can run multiple sessions in parallel, branch off side chats, let Claude check on and message your other sessions, send work to the cloud, or let Dispatch start sessions for you from your phone. -### - -​ - -Work in parallel with sessions +### Work in parallel with sessions Click **\+ New** in the sidebar, or press **Cmd+N** on macOS or **Ctrl+N** on Windows, to work on multiple tasks in parallel. Press **Ctrl+Tab** and **Ctrl+Shift+Tab** to switch between sessions. You can also open a second session next to the current session or in a window of its own: @@ -515,11 +379,7 @@ In the split view, the pane you opened or clicked last has focus, and the other pane is dimmed. To change which session a pane shows, click in that pane to give it focus, then click a session in the sidebar. To take the focused session out of the split view, press **Cmd+Ctrl+W** on macOS or **Ctrl+Alt+W** on Windows. -#### - -​ - -Run a session in its own worktree +#### Run a session in its own worktree In a project that’s a Git repository, turn on **Worktree** before you start a session to run it in its own [Git worktree](</docs/en/worktrees>), an isolated copy of the project. By default, **Worktree** is off and Claude works in the project folder itself. On the current layout, turn on **Worktree** in the row under the prompt box. @@ -536,30 +396,18 @@ Session isolation requires [Git](<https://git-scm.com/downloads>). Most Macs include Git by default. Run `git --version` in Terminal to check; if it prints a version number, Git is installed. If you run into Git errors, ask Claude in [Cowork](<https://claude.com/product/cowork>) to help troubleshoot your setup. -### - -​ - -Add folders to a session +### Add folders to a session Add folders before the session starts or while it runs: * **Before a local session starts** : add the folders under **Folders** when you create a saved environment or edit one, then start the session from that saved environment. * **While a local orSSH session runs**: click **+** next to the prompt box and select **Add folder**. Claude works in that folder itself, with no worktree. -### - -​ - -Archive a session +### Archive a session Before you archive a session whose worktree has uncommitted changes, see Keep uncommitted changes when a session is archived. To archive a session, hover over it in the sidebar, open its menu, and select **Archive**. The session moves to your archived sessions. To have sessions archive themselves when their pull request merges or closes, turn on **Auto-archive after PR merge or close** in **Settings > Code** or **Settings > Claude Code**. Cloud sessions and sessions that are still running don’t archive themselves. -#### - -​ - -Keep uncommitted changes when a session is archived +#### Keep uncommitted changes when a session is archived You can lose uncommitted changes in a session’s worktree when the session is archived, so commit what you want to keep first: @@ -567,11 +415,7 @@ * **If the only changes are untracked files** : commit the ones you want to keep before a pull request that Claude opened in the session merges, because Desktop can then delete them without asking * **In any other case** : the worktree stays on disk with its changes. For a local session, Desktop removes both about 30 days after the session is archived or you last open it, whichever is later. To keep the changes, open the session from the **Archived** tab and select **Unarchive** -### - -​ - -Organize and find sessions +### Organize and find sessions You group, sort, and find sessions from an icon in the sidebar’s session list: @@ -580,43 +424,23 @@ To rename a session, open it and click the session title in the title bar. -### - -​ - -Check and free up context +### Check and free up context To check context usage, see Check usage. When context fills up, Claude automatically summarizes the conversation and continues working. You can also type `/compact` to trigger summarization earlier and free up context space. See [the context window](</docs/en/how-claude-code-works#the-context-window>) for details on how compaction works. -### - -​ - -Get notified when a session finishes +### Get notified when a session finishes The desktop app sends an OS notification when a Code session finishes a task and you aren’t currently viewing that session. For sessions that belong to a [project](</docs/en/claude-projects#see-what-needs-you-in-overview>), you get the project’s notifications instead. -### - -​ - -Ask a side question without derailing the session +### Ask a side question without derailing the session A side chat lets you ask Claude a question that uses your session’s context but doesn’t add anything back to the main conversation. Use it when you want to understand a piece of code, check an assumption, or explore an idea without steering the session off course. Press **Cmd+;** on macOS or **Ctrl+;** on Windows to open a side chat, or type `/btw` in the prompt box. The side chat can read everything in the main thread up to that point. When you’re done, close the side chat and continue the main session where you left off. Side chats are available in local, SSH, and WSL sessions. The desktop app doesn’t save side chats to disk, so you can’t return to one after you close the app. -### - -​ - -Watch background tasks +### Watch background tasks The tasks pane shows the background work running inside the current session: subagents, background shell commands, and [dynamic workflows](</docs/en/workflows>). Once the session has background work, open the pane with **Background tasks** in the title bar’s **⋮** menu. Click any entry to see its output in the subagent pane or stop it. To see what other sessions are doing, use the sidebar, or ask Claude to check on them for you. -### - -​ - -Work across sessions +### Work across sessions Claude can list your other Code tab sessions, read what each has been doing, and send messages between them. Ask in plain language: “which session touched the auth refactor?”, “what did the API session conclude?”, or “tell the payments session the schema changed”. You can also ask Claude to rename or archive a session. For example, ask it to archive the sessions whose PRs have merged. Through this surface, Claude sees only the sessions the desktop app runs itself: local, SSH, and [WSL](</docs/en/desktop-wsl>) sessions in the Code tab. Claude doesn’t see cloud sessions, or sessions you started from the terminal CLI or the VS Code extension, even in worktrees of the same project, so with nine terminal worktrees open and two desktop sessions, Claude answering in one of them reports the one other desktop session. Claude never lists the session you’re asking from. By default it sees the 20 most recently active sessions and skips archived sessions unless you ask for them. [Cross-session messaging](</docs/en/cross-session-messaging>) separately lets Claude message [your other Claude Code sessions](</docs/en/cross-session-messaging#see-which-sessions-claude-can-reach>), including terminal sessions. When Claude messages another session through this surface, Claude Code shows it there as a card labeled with the sending session’s title and a link back, so you can always tell where a message came from. If the receiving session is mid-task, Claude Code holds the message and Claude reads it once the current work finishes. The receiving Claude can reply, and Claude Code delivers the reply back through this surface. Claude can’t deliver to an archived session, and tells you when a message doesn’t go through. Claude Code applies three safety behaviors across sessions: @@ -624,11 +448,7 @@ * Claude Code checks each message from this surface against the receiving session’s [inbound controls](</docs/en/cross-session-messaging#control-inbound-messages>), even when the receiving session doesn’t have [cross-session messaging](</docs/en/cross-session-messaging#availability>) itself. If you set [`crossSessionInbound`](</docs/en/settings-reference#crosssessioninbound>) to `refuse` in the receiving session, Claude Code drops messages from this surface. Claude Code reports the refusal to the Claude desktop app. Before v2.1.234, Claude Code dropped every message from this surface to a receiving session without cross-session messaging. * Claude Code quotes each incoming message and attributes it to the session that sent it, and Claude still follows the receiving session’s own permission settings when acting on one. -### - -​ - -Start a task that Claude suggests +### Start a task that Claude suggests When Claude notices something worth fixing outside your current task, it suggests that work as a task. In local and SSH sessions on the current layout, the suggestion is a card in the chat, and its buttons either start the task or keep it in this session: @@ -639,11 +459,7 @@ In cloud sessions, and in local and SSH sessions on the earlier layout, the suggestion is a **Suggested task** card. To start the task where the card’s main button says, for example **Send to cloud** or **Start with worktree** , click that button. Click the caret beside the main button for other ways to start the task, including **Do it here**. -### - -​ - -Run long-running tasks in the cloud +### Run long-running tasks in the cloud For large refactors, test suites, migrations, or other long-running tasks, select an environment under **Cloud** in the environment selector when starting a session. Cloud sessions run on Anthropic-managed infrastructure by default and continue even if you close the app or shut down your computer. Check back anytime to see progress or steer Claude in a different direction. You can also monitor cloud sessions from [claude.ai/code](<https://claude.ai/code>) or the [Claude mobile app](</docs/en/mobile>). Cloud sessions also support multiple repositories. Choose the repositories: @@ -654,22 +470,14 @@ A task in an SSH session can also keep going while Desktop is disconnected, but with a Claude account it can stop when its sign-in expires. -### - -​ - -Continue in another surface +### Continue in another surface To continue a session somewhere else, open the session menu from the caret beside the session title or from the session’s row in the sidebar, then select **Open in** : * Select **Cloud** to continue the session as a [cloud session](</docs/en/claude-code-on-the-web>), with your conversation carried over as a summary. Before you confirm, the dialog states whether your files move too and whether this session is archived once the cloud one is ready. You can’t move a session that runs over SSH or in [WSL](</docs/en/desktop-wsl>) this way. * Select an installed editor or your file manager to open the session’s folder on disk there. -### - -​ - -Control which sessions appear on your other devices +### Control which sessions appear on your other devices A local session shows up on your other devices once [Remote Control](</docs/en/remote-control>) connects it. A connected session appears in the session list at [claude.ai/code](<https://claude.ai/code>) and in the Claude apps on devices signed in to your claude.ai account. A local session connects when you turn Remote Control on for it, or when it connects automatically as it starts: @@ -678,11 +486,7 @@ To see whether a session is connected, check the **Remote Control** switch in the **Environment** card of its session details panel. -#### - -​ - -Keep sessions off your other devices +#### Keep sessions off your other devices Turn Remote Control off for one session, for sessions on this computer, or for computers you manage: @@ -693,46 +497,26 @@ To hide a session that already appears on your other devices, archive it in Desktop. Desktop archives the session’s Remote Control copy too, so it leaves the default session list on those devices. To view or delete it there, see [Archive sessions](</docs/en/claude-code-on-the-web#archive-sessions>). -### - -​ - -Sessions from Dispatch +### Sessions from Dispatch [Dispatch](<https://support.claude.com/en/articles/13947068>) is a persistent conversation with Claude that lives in [Cowork](<https://claude.com/product/cowork>). You message Dispatch a task, and it decides how to handle it. A task can end up as a Code session in two ways: you ask for one directly, such as “open a Claude Code session and fix the login bug”, or Dispatch decides the task is development work and spawns one on its own. Tasks that typically route to Code include fixing bugs, updating dependencies, running tests, or opening pull requests. Research, document editing, and spreadsheet work stay in Cowork. -#### - -​ - -Follow a session that Dispatch started +#### Follow a session that Dispatch started The session that Dispatch starts appears in the Code tab’s sidebar with your other sessions. With the sidebar’s default grouping and sorting, look for the newest session in the group for the folder it runs in. You get a push notification on your phone when it finishes or needs your approval. If you have computer use enabled, Dispatch-spawned Code sessions can use it too. App approvals in those sessions expire after 30 minutes and re-prompt, rather than lasting the full session like regular Code sessions. -#### - -​ - -Set up Dispatch +#### Set up Dispatch * **Plans** : Dispatch requires a Pro, Max, or Ultra plan and is not available on Team or Enterprise plans * **Setup, pairing, and Dispatch settings** : see the [Dispatch help article](<https://support.claude.com/en/articles/13947068>) Dispatch is one of several ways to work with Claude when you’re away from your terminal. For a comparison with the other options, see [Platforms and integrations](</docs/en/platforms#work-when-you-are-away-from-your-terminal>). -## - -​ - -Extend Claude Code +## Extend Claude Code Connect external services, add reusable workflows, customize Claude’s behavior, and configure preview servers. To manage connectors, skills, and plugins in one place, click **Customize** in the sidebar. [Cowork](<https://claude.com/product/cowork>) in the Desktop app sources its skills, plugins, and connectors from this Customize configuration, which syncs through your claude.ai account, not from the CLI’s `~/.claude` directory. Claude Code also loads the skills and plugins enabled for your claude.ai account in terminal sessions where you sign in with the same account. See [Skills synced from claude.ai](</docs/en/skills#how-synced-skills-behave>) and [Plugins synced from claude.ai](</docs/en/plugins/loading#synced-plugins>). -### - -​ - -Connect external tools +### Connect external tools Connectors are [MCP servers](</docs/en/mcp>) with a graphical setup flow. Click **+** next to the prompt box, before or during the session, to add connectors in a local or SSH session with a Claude account. Select **Add connectors** to open the connector directory. If the menu shows **Connectors** instead, select it, then **Browse connectors**. @@ -743,27 +527,15 @@ Once connected, Claude can read your calendar, send messages, create issues, and interact with your tools directly. You can ask Claude what connectors are configured in your session. To manage or disconnect connectors, click **Customize** in the sidebar and open **Connectors**. For integrations not listed in Connectors, add MCP servers manually via [settings files](</docs/en/mcp#installing-mcp-servers>). You can also [create custom connectors](<https://support.claude.com/en/articles/11175166-getting-started-with-custom-connectors-using-remote-mcp>). -### - -​ - -Use skills +### Use skills [Skills](</docs/en/skills>) extend what Claude can do. Claude loads them automatically when relevant, or you can invoke one directly: type `/` in the prompt box or click the **+** button and select **Slash commands** to browse what’s available. This includes [built-in commands](</docs/en/commands>), your [custom skills](</docs/en/skills#create-your-first-skill>), project skills from your codebase, and skills from any [installed plugins](</docs/en/plugins/install>). Select one and it appears highlighted in the input field. Type your task after it and send as usual. You can send a command while Claude is working, the same as any other message, and the session returns to idle once the turn finishes. Local sessions load your personal skills from `~/.claude/skills/`. An SSH session reads `~/.claude/skills/` from the remote host’s home directory, not from your machine. Local and cloud sessions also load the skills enabled for your claude.ai account, except local sessions when your organization sets [`disableSideloadFlags`](</docs/en/settings-reference#disablesideloadflags>). Cloud sessions load them instead of `~/.claude/skills/`, as [Skills in Cowork and cloud sessions](</docs/en/skills#skills-in-cowork-and-cloud-sessions>) describes. -### - -​ - -Install plugins +### Install plugins [Plugins](</docs/en/plugins/overview>) are reusable packages that add skills, agents, hooks, MCP servers, and LSP configurations to Claude Code. You can install plugins from the desktop app without using the terminal. In a local session or an SSH session, click **+** next to the prompt box and select **Add plugins** to open the plugin browser. If the menu shows **Plugins** instead, select it, then **Browse plugins** , or **Manage plugins** to enable, disable, or uninstall plugins. You can scope plugins to your user account, a specific project, or local-only. If your organization manages plugins centrally, those plugins are available in desktop sessions the same way they are in the CLI, except the ones the desktop app [withholds under `disableSideloadFlags`](</docs/en/settings-reference#disablesideloadflags>). The plugin browser is not available in cloud sessions, and plugins you install from the desktop app aren’t available for cloud sessions. A cloud session also doesn’t install plugins that the repository’s `.claude/settings.json` declares, as [What carries over from your setup](</docs/en/cloud-environments#what-carries-over-from-your-setup>) explains. Plugins aren’t available in WSL sessions. For the full plugin reference including creating your own plugins, see [plugins](</docs/en/plugins/overview>). -### - -​ - -Configure preview servers +### Configure preview servers Claude automatically detects your dev server setup and stores the configuration in `.claude/launch.json` at the root of the folder you selected when starting the session. Preview uses this folder as its working directory, so if you selected a parent folder, subfolders with their own dev servers won’t be detected automatically. To work with a subfolder’s server, either start a session in that folder directly or add a configuration manually. To customize how your server starts, for example to use `yarn dev` instead of `npm run dev` or to change the port, edit `.claude/launch.json`. The file supports JSON with comments. @@ -781,11 +553,7 @@ You can define multiple configurations to run different servers from the same project, such as a frontend and an API. See the examples below. -#### - -​ - -Auto-verify changes +#### Auto-verify changes When `autoVerify` is enabled, Claude automatically verifies code changes after editing files. It takes screenshots, checks for errors, and confirms changes work before completing its response. Auto-verify is on by default. Disable it per-project by adding `"autoVerify": false` to `.claude/launch.json`, or turn off **Auto-verify changes** in the Browser pane’s **⋮** menu. @@ -804,11 +572,7 @@ When disabled, preview tools are still available and you can ask Claude to verify at any time. Auto-verify makes it automatic after every edit. -#### - -​ - -Configuration fields +#### Configuration fields Each entry in the `configurations` array accepts the following fields: @@ -860,11 +624,7 @@ The `url` must be `http` or `https`, and must not contain a username or password. -#### - -​ - -Port conflicts +#### Port conflicts The `autoPort` field controls what happens when your preferred port is already in use: @@ -880,11 +640,7 @@ In that case, free the port, remove the hardcoded value, or change `port` to match the script. Setting `"autoPort": true` instead works only for a script that reads `PORT`. Have your server read its port from the `PORT` environment variable, which carries the assigned port. When Claude moves your server to a different port, it also rewrites a `--port` or `-p` value in `runtimeArgs` to match. -#### - -​ - -Examples +#### Examples These configurations show common setups for different project types: @@ -947,11 +703,7 @@ ] } -## - -​ - -Environment configuration +## Environment configuration The environment you pick when starting a session determines where Claude executes and how you connect: @@ -960,11 +712,7 @@ * **SSH** : runs on a remote machine you connect to over SSH, such as your own servers, cloud VMs, or dev containers. A running task can keep going while Desktop is disconnected, but with a Claude account it can stop when its sign-in expires. * **WSL** (Windows): runs inside a [WSL 2 distribution](</docs/en/desktop-wsl>) on your machine, using its Linux toolchain and native paths -### - -​ - -Create a saved environment +### Create a saved environment A saved environment is an entry in the environment selector that records where Claude runs, so you can start later sessions there. A local or SSH environment also holds the folders Claude works in. Saved local and SSH environments are part of the current layout, so if you don’t see them, check which layout you have and how to get the current one. @@ -986,19 +734,11 @@ Select **Create environment** , or **Add environment** on the **Cloud** tab. -#### - -​ - -Environments that Desktop creates for you +#### Environments that Desktop creates for you If the environment selector lists local or SSH environments you didn’t create, Desktop created them for you. The first time you open the Code tab in the current layout, Desktop creates up to eight environments. The environments come from the local and SSH folders you used most in the last month. You can edit or delete them. -#### - -​ - -Use, edit, or remove a saved environment +#### Use, edit, or remove a saved environment Find the environment’s entry in the environment selector: @@ -1006,11 +746,7 @@ * **Edit or delete** : hover over the entry and click the gear icon. To delete a local or SSH environment, click **Delete environment** in **Edit environment**. * **Archive cloud environments** : see [Archive an environment](</docs/en/cloud-environments#archive-an-environment>). -### - -​ - -Environment variables in local sessions +### Environment variables in local sessions To set an environment variable for a local session, add it to a saved local environment, then start a new session from that environment. Variables such as `PATH` and `CLAUDE_CONFIG_DIR` have their own instructions: @@ -1023,11 +759,7 @@ On macOS or Linux, if a variable you set with `export` is missing or wrong in a command Claude runs, see Exported variable missing or wrong in commands Claude runs. -#### - -​ - -Set environment variables for local sessions +#### Set environment variables for local sessions Add the variables to a saved local environment and start your sessions from it. Desktop sets some variables itself, such as `API_TIMEOUT_MS`, and your sessions get its value for those instead of yours. @@ -1054,11 +786,7 @@ Only sessions you start from that environment get the variables. To set a variable for every local session, add it to the [`env` key](</docs/en/env-vars#set-variables-in-settings-files>) in your `~/.claude/settings.json` file. Claude Code [ignores the value](</docs/en/settings-reference#how-env-values-interact-with-your-shell>) if that variable is already in the environment Desktop starts the session with. See [environment variables](</docs/en/env-vars>) for the full list of supported variables. -#### - -​ - -Set environment variables for dev servers +#### Set environment variables for dev servers To give a dev server a secret without committing it to `launch.json`, set it in one of these places, then restart Desktop: @@ -1068,11 +796,7 @@ Dev servers don’t get the variables you add to a saved environment or to `~/.claude/settings.json`. -#### - -​ - -Use the local environment editor +#### Use the local environment editor To open the local environment editor, click the gear icon on the entry for your own computer, not the one on a saved environment: @@ -1081,11 +805,7 @@ Enter one `KEY=value` per line and select **Save changes**. Variables you save here are stored encrypted on your machine. Local sessions get them, except any variable that Desktop sets itself, such as `API_TIMEOUT_MS`. Restart Desktop to give your variables to dev servers. -#### - -​ - -Exported variable missing or wrong in commands Claude runs +#### Exported variable missing or wrong in commands Claude runs If a command Claude runs on macOS or Linux doesn’t get a variable you set with `export` in `~/.zshrc` or `~/.bashrc`, or gets the wrong value, try these in order: @@ -1115,46 +835,26 @@ Before v2.1.304, Claude Code doesn’t pass exported variables to commands, so check which version the session runs. -#### - -​ - -Environment variables Desktop sets itself +#### Environment variables Desktop sets itself If you set `API_TIMEOUT_MS` or `ANTHROPIC_BASE_URL` and nothing changed in your local sessions, it’s because Desktop sets those [variables](</docs/en/env-vars#variables>), among others, itself. A local session gets Desktop’s value whether you set yours in your shell profile, your Windows user or system variables, the local environment editor, or a saved environment. Moving yours to a settings file doesn’t help, because Claude Code [ignores that value](</docs/en/settings-reference#how-env-values-interact-with-your-shell>) in a local session. * `API_TIMEOUT_MS`: a local session gets `900000`, which is 15 minutes. For a longer timeout, [install the Claude Code CLI](</docs/en/quickstart>) and use it instead of Desktop. [Set the variable in your shell](</docs/en/env-vars#set-variables-in-your-shell>) and run `claude` in your terminal. * `ANTHROPIC_BASE_URL`: a local session gets Anthropic’s API host when you’re signed in with a Claude account. To use a gateway, set up Desktop’s [third-party inference configuration](</docs/en/llm-gateway-connect#desktop-app>) instead. -#### - -​ - -Turn off extended thinking +#### Turn off extended thinking [Extended thinking](</docs/en/model-config#extended-thinking>) is enabled by default, which improves performance on complex reasoning tasks but uses additional tokens. To turn it off, set `MAX_THINKING_TOKENS` to `0` in a saved local environment or the local environment editor. Thinking then turns off on the Anthropic API, except on Opus 5.5, Sonnet 5.5, Haiku 5.5, and the Fable models, which always use extended thinking. On Opus 5, also select effort `high` or lower before you start the session. In the current layout, open the model picker and select a level under **Effort**. If you started the session at a higher level, start a new one at `high` or lower. -#### - -​ - -Fixed thinking budgets +#### Fixed thinking budgets On models with [adaptive reasoning](</docs/en/model-config#adjust-effort-level>), Claude Code ignores the number itself in a positive `MAX_THINKING_TOKENS` value because adaptive reasoning controls thinking depth instead. On Opus 4.6 and Sonnet 4.6, set `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING` to `1` to use a fixed thinking budget; Fable models, Sonnet 5 and later, Haiku 5.5, and Opus 4.7 and later always use adaptive reasoning and have no fixed-budget mode. -### - -​ - -Local sessions on managed devices +### Local sessions on managed devices If the entry for your computer is grayed out in the environment selector, with the tooltip **Disabled by your organization** , your administrator has turned off local sessions. On Windows the [WSL](</docs/en/desktop-wsl>) entry, whose availability on managed devices is [governed separately](</docs/en/admin-setup#wsl-sessions-in-claude-code-desktop>), is grayed out the same way. New sessions default to the first SSH connection if one is configured. If you try to continue an existing local session, Desktop shows a message that local sessions aren’t available on this device. Saved local environments show this error when you select one: `Couldn’t switch environments: the Local environment isn’t available anymore.` Choose an SSH or cloud environment instead, or contact your IT team. -### - -​ - -Cloud sessions +### Cloud sessions Cloud sessions continue in the background even if you close the app. Usage counts toward your [subscription plan limits](</docs/en/costs>) with no separate compute charges. To add, edit, or [archive](</docs/en/cloud-environments#archive-an-environment>) a cloud environment, open the environment selector: @@ -1163,11 +863,7 @@ See [Configure cloud environments](</docs/en/cloud-environments>) for details on configuring network access and environment variables. -### - -​ - -SSH sessions +### SSH sessions SSH sessions let you run Claude Code on a remote machine while using the desktop app as your interface. This is useful for working with codebases that live on cloud VMs, dev containers, or servers with specific hardware or dependencies. @@ -1203,11 +899,7 @@ The remote machine can run Linux, macOS, or Windows. Desktop installs Claude Code on the remote machine automatically the first time you connect. Once connected, SSH sessions support permission modes, connectors, plugins, and MCP servers. -#### - -​ - -Remote machine requirements for SSH sessions +#### Remote machine requirements for SSH sessions A Linux or macOS remote machine needs a supported processor, an SSH server with SFTP, an install folder that isn’t mounted `noexec`, a working shell, and network access. Check each requirement before you connect, or when a connection fails after you log in: @@ -1223,11 +915,7 @@ * **Shell** : the shell set for your account on the remote machine has to run commands sent over SSH, as Bash, Zsh, and `sh` do * **Network** : Claude Code runs on the remote machine and makes its network requests from there, so the machine needs the [network access that Claude Code requires](</docs/en/network-config#network-access-requirements>). If the machine can’t download Claude Code, Desktop downloads it on your computer and uploads it. Claude Code’s other requests still go out from the remote machine. If a Linux remote machine needs a proxy or a CA certificate, set it for SSH sessions. -#### - -​ - -Check a remote machine’s host key +#### Check a remote machine’s host key A host key is the key that a remote machine presents to prove which machine it is, and a fingerprint is a short form of that key. When you trust a key, your computer saves it and connects to whatever presents it, without asking again. Check a key before you trust it, because something may be intercepting the connection. First find which machine the key belongs to, from where you see the fingerprint: @@ -1247,11 +935,7 @@ If a troubleshooting step sent you here, go back to that step after either result. -#### - -​ - -Set a proxy or a CA certificate for SSH sessions +#### Set a proxy or a CA certificate for SSH sessions If a Linux remote machine reaches the internet through a proxy or needs a CA certificate, add the [proxy and CA variables](</docs/en/network-config>) under `env` in `~/.claude/settings.json` there. Add them even if you already export them in `~/.profile`, `~/.bash_profile`, `~/.zprofile`, or `~/.zshrc` on that machine. In an SSH session, Claude Code doesn’t get the variables from those files, even when `claude` in a terminal on that machine does. The session can then hang, or show **The connection from … to the API failed** , **Authentication failed** , or **Claude Code on … couldn’t verify the API connection’s certificate**. Signing in again doesn’t help. @@ -1298,11 +982,7 @@ Restart the remote machine, or quit Desktop and end the helper’s processes, as in the first two steps to remove the helper. Do this when no task is running, because either way interrupts Claude’s work. -#### - -​ - -Use your SSH configuration +#### Use your SSH configuration You can use your SSH configuration on macOS, Linux, and Windows when Desktop connects through the OpenSSH client on your computer: @@ -1478,11 +1158,7 @@ To keep Desktop from forwarding your SSH agent or a port, run `ssh -G devbox` in a terminal on your computer. Then run it again as Desktop can run it, with the `hostname` and `user` values that it prints, as in `ssh -G -o HostName=devbox.internal.example.com -l alice devbox`. The second output can show settings from a `Match` block that the first skips. Look in both outputs for a `forwardagent` line that says anything but `no`, and for lines that begin with `localforward`, `remoteforward`, or `dynamicforward`. If you find one, remove that setting from your SSH configuration. Do the same for a host that your `ProxyCommand` reaches with `ssh`. -#### - -​ - -Reach a port on the remote machine +#### Reach a port on the remote machine To open a server that runs on the remote machine, such as a dev server on port 3000, forward the port yourself. In a terminal on your computer, run `ssh` with `-L` and the host you connect to, such as `devbox`: @@ -1490,11 +1166,7 @@ If you filled in **SSH port** or **SSH key (optional)** on the connection, add `-p` or `-i` with the same value. Leave that command running, and open `http://localhost:3000` in a browser on your computer to reach port 3000 of the remote machine. If `ssh` prints `open failed: administratively prohibited`, ask the machine’s administrator to allow TCP forwarding, which `AllowTcpForwarding` in the SSH server’s `sshd_config` controls. -#### - -​ - -Windows remote machines +#### Windows remote machines A Windows remote machine requires Claude Desktop v2.31226.0 or later. Use Microsoft’s OpenSSH Server. The machine can be x64 or ARM64. The shell that the SSH server starts can be `cmd.exe`, Windows PowerShell 5.1, or Git Bash. Windows remote machines get less testing than Linux ones. Try your own work there before you rely on it. Expect these limits, among others, on a Windows remote machine: @@ -1508,11 +1180,7 @@ * **Running while disconnected** : a task keeps running while Desktop is disconnected only if the SSH server lets a program outlive the connection that started it. To find out, test the remote machine. * **Leftover processes** : after a session ends, check the machine for programs that Claude Code started, because they can keep running. The background helper that Desktop installs doesn’t stop on its own there. -#### - -​ - -Keep a task running while Desktop is disconnected +#### Keep a task running while Desktop is disconnected If your computer sleeps, you lose your network, or you quit Desktop, the task goes on until it finishes, needs you, or reaches one of the limits. Closing the lid counts as sleep. A restart of Desktop or of your computer, including for an update, counts as a quit. Claude Code runs as a process on the remote machine, under a background helper that Desktop installs there, so it doesn’t need your SSH connection to keep running. The behavior in this section requires Claude Desktop v2.31226.0 or later. @@ -1614,11 +1282,7 @@ While a conversation’s Claude Code process is still running, don’t run [`claude --resume`](</docs/en/cli-reference#cli-flags>) for it on the remote machine. Claude Code doesn’t stop you, and both processes then write to the same conversation. If you aren’t sure, add `--fork-session`, which continues in a copy of the conversation, but both processes still work on the same files. -#### - -​ - -Choose where SSH session worktrees go +#### Choose where SSH session worktrees go Unless your organization restricts which folders sessions may use, new SSH sessions create their worktrees in the first of these locations that is set: @@ -1650,11 +1314,7 @@ In **Worktree folder** , enter a folder on the remote machine, such as `~/worktrees`, and select **Save changes**. -#### - -​ - -Files and processes on the remote machine +#### Files and processes on the remote machine Desktop installs a helper program and Claude Code under `~/.claude/remote/` in the home directory of each user who connects to a Linux or macOS remote machine. The helper listens on no network port, but Claude Code and the programs it starts, such as MCP servers and development servers, can. @@ -1703,11 +1363,7 @@ To find out who connected to a remote machine, read the SSH server’s log on that machine, where a login from Desktop looks like one from a terminal. With Desktop on macOS or Linux, expect an entry each time Desktop connects, not one for each session. If the server sets `MaxSessions 1`, expect at least two entries each time Desktop connects or reconnects. Expect at least one more for each terminal tab, and for each Desktop session in which you run commands that start with `!`. You won’t find Desktop’s SSH connections in Claude Code’s [metrics and events](</docs/en/monitoring-usage#available-metrics-and-events>). To find out from them which remote machine an SSH session ran on, see [Attribute telemetry to Desktop SSH sessions](</docs/en/monitoring-usage#attribute-telemetry-to-desktop-ssh-sessions>). For Desktop’s own record of its connections, see Get Desktop’s logs for an SSH problem. -#### - -​ - -Connections that close before login +#### Connections that close before login If the SSH server’s log shows connections that close before any login, they can be Desktop’s tests of the SSH port. Desktop tests whether a machine answers, for example after a connection to it failed. It opens a connection to the port and closes it at once, without sending anything. Expect one test or several in a row, for example eight in about two minutes. If nothing bans or refuses addresses for such connections, you don’t have to do anything about Desktop’s tests. If an address that Desktop connects from is refused or banned, check whether the SSH server itself refuses the address and whether fail2ban counts Desktop’s tests. @@ -1753,19 +1409,11 @@ * **`mode`** : set it to `normal` wherever your jail sets it, in a `mode` line or in the brackets of a line such as `filter = sshd[mode=aggressive]`. You give up every count that only the other modes make, for example of clients that connect and leave without trying to log in. * **`ignoreip`** : set it to the addresses that people connect from, for example `ignoreip = 203.0.113.7`. fail2ban then counts nothing from those addresses, failed logins included. -#### - -​ - -Use MCP servers set up on the remote machine +#### Use MCP servers set up on the remote machine To use an [MCP server](</docs/en/mcp>) from `~/.claude.json` or a project’s `.mcp.json` in an SSH session, set it up in those files on the remote machine. Claude Code starts their stdio servers there, so install the commands those servers run on the remote machine. For servers from `claude_desktop_config.json`, see Limits while Desktop is disconnected. -#### - -​ - -Open an SSH session from a link +#### Open an SSH session from a link A `claude://code/new` link opens Desktop’s new-session page, and it can name an SSH connection. Put such a link in a runbook, dashboard, or wiki page to open Desktop set up for the right machine and folder. For platforms that strip such links, see [The link renders as plain text instead of being clickable](</docs/en/deep-links#the-link-renders-as-plain-text-instead-of-being-clickable>). SSH links require Claude Desktop v2.110.0 or later. The following link names the user `dev` on `build.example.com`, port 2222, and the folder `/srv/payments`, and fills in a prompt: @@ -1798,11 +1446,7 @@ * **Desktop is older than v2.110.0** : earlier versions ignore the SSH parameters and open the new-session page with only the prompt. * **SSH sessions are turned off** : if your administrator sets the allowlist to an empty array, Desktop refuses SSH links. -#### - -​ - -Create an SSH connection from a command +#### Create an SSH connection from a command If a command-line tool makes your remote machines on demand, add its command to `sshHostCommands` in [`~/.claude/settings.json`](</docs/en/settings#settings-files>). The environment selector then lists an item named after your entry, such as **Create Dev box**. When you select it, Desktop runs the command on your computer, saves the host that the command prints as an SSH connection, and connects. @@ -2011,11 +1655,7 @@ * **Hooks are off or restricted** : your own entries work only where your own hooks can run. Remove `disableAllHooks` from your settings, or ask your administrator. * **Settings are still loading** : every entry is gray until Desktop has loaded your organization’s [server-managed settings](</docs/en/server-managed-settings>), usually a few seconds after launch. If the entries stay gray, check your connection to claude.ai. -#### - -​ - -Pre-configure SSH connections for your team +#### Pre-configure SSH connections for your team Administrators can distribute SSH connections to team members by setting `sshConfigs` in [managed settings](</docs/en/managed-settings>). @@ -2038,11 +1678,7 @@ Each entry requires `id`, `name`, and `sshHost`. The `sshPort` and `sshIdentityFile` fields are optional. Users can also add `sshConfigs` to their own `~/.claude/settings.json`. If you leave `user@` out of `sshHost`, Desktop connects as the `User` that each developer’s `~/.ssh/config` sets for the host, or else as their username on their own computer. -#### - -​ - -Restrict which SSH hosts users can connect to +#### Restrict which SSH hosts users can connect to Administrators can limit Desktop’s SSH sessions to an approved set of hosts by setting `sshHostAllowlist` in [managed settings](</docs/en/managed-settings>). When set, users can only connect to hosts whose resolved hostname matches one of the patterns. Set it to an empty array to disable SSH sessions. The [`sshHostAllowlist` reference entry](</docs/en/settings-reference#sshhostallowlist>) says how an empty array combines with lists in other managed sources. The following example allows connections to any host under `devboxes.example.com` and to a single named bastion host: @@ -2084,11 +1720,7 @@ Add each hostname, or a wildcard that covers it, to `sshHostAllowlist` in every managed source where you set a list. Then have users quit and reopen Desktop, because it fetches server-managed settings at launch. -#### - -​ - -Turn off local sessions and distribute SSH connections +#### Turn off local sessions and distribute SSH connections To turn off local sessions and limit SSH sessions to hosts that you choose, deploy [`disableDesktopLocalSessions`](</docs/en/settings-reference#disabledesktoplocalsessions>), `sshConfigs`, and `sshHostAllowlist` together. @@ -2145,19 +1777,11 @@ Add an SSH connection with a hostname that isn’t on the allowlist, such as `other.example.com`. Desktop saves the connection but refuses to connect, and says that your organization’s settings don’t allow the connection. -## - -​ - -Enterprise configuration +## Enterprise configuration Organizations on Team or Enterprise plans can manage desktop app behavior through admin console controls, managed settings files, and device management policies. -### - -​ - -Admin console controls +### Admin console controls These settings are configured through the [admin settings console](<https://claude.ai/admin-settings/claude-code>): @@ -2169,11 +1793,7 @@ The OpenTelemetry form for Cowork under **Monitoring** in the admin console’s [Data and privacy settings](<https://claude.ai/admin-settings/data-privacy-controls>) applies to Cowork sessions only. In a Cowork session on this machine, the desktop app passes that collector to Claude Code as `OTEL_*` environment variables, so the form takes effect even though Claude Code in that session never fetches admin-console settings.To export telemetry from Code tab sessions, set `CLAUDE_CODE_ENABLE_TELEMETRY` and the `OTEL_*` variables in the `env` block of your Claude Code managed settings, as shown in [administrator configuration for monitoring](</docs/en/monitoring-usage#administrator-configuration>). Local, cloud, and SSH sessions each read managed settings from different sources. For the hosts a cloud session can reach, see [network access](</docs/en/cloud-environments#network-access>). For the `service.name` that Code tab sessions report, see [service information](</docs/en/monitoring-usage#service-information>).To find out which remote machine an SSH session ran on, see [Attribute telemetry to Desktop SSH sessions](</docs/en/monitoring-usage#attribute-telemetry-to-desktop-ssh-sessions>). -### - -​ - -Managed settings +### Managed settings Managed settings override project and user settings and apply to Claude Code sessions in Desktop. You can set these keys in your organization’s [managed settings](</docs/en/managed-settings>) file or push them remotely through the admin console, unless a key’s row says otherwise. @@ -2207,11 +1827,7 @@ In local and SSH sessions, the desktop app delivers each user’s connected claude.ai connectors to Claude Code directly. No MCP setting or `managed-mcp.json` reaches those connectors, whichever settings source or file location you use. To block a connector’s tools in these sessions, use your organization’s [connector tool controls](</docs/en/mcp#organization-controls-on-connector-tools>). [How connectors reach Claude Code](</docs/en/mcp#how-connectors-reach-claude-code>) shows which settings govern connectors in each kind of session. `permissions.disableBypassPermissionsMode` and `disableAutoMode` also work in user and project settings, but placing them in managed settings prevents users from overriding them. For the permission, plugin, and delivery keys only a managed source can set, see [Keys only managed settings can set](</docs/en/managed-settings#managed-only-settings>). -#### - -​ - -Claude Code settings that behave differently in the Code tab +#### Claude Code settings that behave differently in the Code tab In a local session, these keys, among others, have a different effect or no visible one, because the Code tab replaces the terminal interface. They still apply in the terminal, so you can leave them set. @@ -2233,11 +1849,7 @@ `verbose`, `viewMode`| each user chooses the view under **Transcript view** in the session menu `worktree.baseRef`, `worktree.sparsePaths`, `worktree.symlinkDirectories`| not used for the worktree that the Code tab creates for a session -### - -​ - -Device management policies +### Device management policies IT teams can manage the desktop app through MDM on macOS, group policy on Windows, or a policy file on Linux. Available policies include enabling or disabling the Claude Code feature, controlling auto-updates on macOS and Windows, and setting a custom deployment URL. @@ -2245,11 +1857,7 @@ * **Windows** : configure via registry at `SOFTWARE\Policies\Claude` * **Linux** : configure via a root-owned file at `/etc/claude-desktop/managed-settings.json`, which holds the policy keys as a JSON object. Desktop refuses the file if anyone but root can write to it or to its folder. It’s a different file from Claude Code’s [managed settings file](</docs/en/managed-settings>). -#### - -​ - -Restrict sign-in to your organization +#### Restrict sign-in to your organization To restrict which claude.ai organizations can sign in to Claude Desktop, set `forceLoginOrgUUID` in the Claude Desktop policy. The key requires Claude Desktop v1.2581.0 or later. On Linux, a policy file that sets only this key reads: @@ -2268,11 +1876,7 @@ * **Claude Console organizations** : don’t deploy `forceLoginOrgUUID` on its own with a Claude Console organization’s ID, or you’d lock your people out of Claude Desktop. See [Which devices offer the Claude API account sign-in](<https://claude.com/docs/third-party/claude-desktop/claude-api#which-devices-offer-the-claude-api-account-sign-in>) instead. * **Enterprise Admin Console** : if it delivers your computers’ Claude Desktop configuration, update them to Claude Desktop v2.37337.0 or later first, because earlier versions ignore it once this key is set. See [Keep a device on its managed profile](<https://claude.com/docs/third-party/claude-desktop/admin-console#keep-a-device-on-its-managed-profile>). -### - -​ - -Network access requirements +### Network access requirements Desktop loads its application code and user content from Anthropic CDN hosts. @@ -2309,27 +1913,15 @@ If your organization has [IP allowlisting](<https://support.claude.com/en/articles/13200993-restrict-access-to-claude-with-ip-allowlisting>) enabled for Claude, route `bridge.claudeusercontent.com` through the same proxy egress as `claude.ai` and `api.anthropic.com`. If you can’t route it that way, add the egress address your proxy uses for that host to your organization’s IP allowlist, but only when that address is dedicated to your organization: a shared proxy egress range also admits the proxy vendor’s other customers. Anthropic checks connections to that host against your organization’s IP allowlist using the address they arrive from. If your proxy sends traffic for it out through an address that isn’t on that allowlist, Claude in Chrome and other features that connect through the bridge stop working while the rest of the app keeps working. An [artifact](</docs/en/artifacts>) that loads a typeface from [Google Fonts](</docs/en/artifacts#improve-the-visual-design>) also requests `fonts.googleapis.com` and `fonts.gstatic.com`. Both hosts are optional. If you block them, artifacts render in fallback typefaces. Block with a fast rejection rather than a silent drop so the font request fails immediately instead of delaying the page’s first render. Artifacts can also load JavaScript libraries, such as React or a charting package, from `cdnjs.cloudflare.com`, `cdn.jsdelivr.net`, `cdn.tailwindcss.com`, `code.jquery.com`, and `unpkg.com`, and from no other external host. If you block those hosts, the parts of an artifact that depend on a library don’t work, and unlike a blocked font, a blocked library has no fallback. Block with a fast rejection here too, so a blocked library request fails at once rather than hanging until it times out. -### - -​ - -Authentication and SSO +### Authentication and SSO Team and Enterprise organizations can require SSO for all users. See [authentication](</docs/en/authentication>) for plan-level details and [Setting up SSO](<https://support.claude.com/en/articles/13132885-setting-up-single-sign-on-sso>) for SAML configuration; OIDC setup is covered in the [Claude Enterprise Administrator Guide](<https://claude.com/resources/tutorials/claude-enterprise-administrator-guide>). -### - -​ - -Data handling +### Data handling Claude Code processes your code locally in local sessions, or in cloud sessions on Anthropic-managed infrastructure, unless your organization routes them to a [self-hosted environment](</docs/en/self-hosted-environments>). Cloud sessions, including in a self-hosted environment, send conversations and code context to Anthropic’s API for processing; local and SSH sessions send them to whichever model provider your deployment configures, Anthropic’s API by default. See [data handling](</docs/en/data-usage>) for details on data retention, privacy, and compliance. -### - -​ - -Deployment +### Deployment Desktop can be distributed through enterprise deployment tools: @@ -2338,11 +1930,7 @@ For the domains to allowlist in your firewall, see network access requirements above. For proxy settings, custom certificate authorities, and LLM gateways, see [network configuration](</docs/en/network-config>). For the full enterprise configuration reference, see the [enterprise configuration guide](<https://support.claude.com/en/articles/12622667-enterprise-configuration>). -## - -​ - -Coming from the CLI? +## Coming from the CLI? If you already use the Claude Code CLI, Desktop runs the same underlying engine with a graphical interface. You can run both simultaneously on the same machine, even on the same project. Each keeps its own session list, and you can bring a CLI session into Desktop. They share configuration and project memory via CLAUDE.md files. To move a CLI session into Desktop, run `/desktop` in the terminal. Claude saves your session and opens it in the desktop app, then exits the CLI. This command is available on macOS and x64 Windows when you are signed in with a Claude subscription. It is not available with API key authentication or on Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry. From your shell, [`claude --desktop`](</docs/en/cli-reference#cli-flags>) opens Desktop directly without starting a terminal session. It requires Claude Code v2.1.285 or later and has the same platform and sign-in requirements as `/desktop`. With no other arguments, it opens Desktop on the current directory. To open an existing CLI session in Desktop, add `--continue` for the most recent conversation in this directory, or `--resume` with the session ID that `/status` shows: @@ -2358,11 +1946,7 @@ When to use Desktop vs CLI: use Desktop when you want to manage parallel sessions in one window, arrange panes side by side, or review changes visually. Use the CLI when you need scripting, automation, or prefer a terminal workflow. -### - -​ - -CLI flag equivalents +### CLI flag equivalents This table shows the desktop app equivalent for common CLI flags. Flags not listed have no desktop equivalent because they are designed for scripting or automation. @@ -2379,11 +1963,7 @@ `ANTHROPIC_MODEL` env var| Model picker in the row under the prompt box `MAX_THINKING_TOKENS` env var| See Turn off extended thinking -### - -​ - -Shared configuration +### Shared configuration Desktop and CLI read the same configuration files, so your setup carries over: @@ -2393,21 +1973,13 @@ * **[Settings](</docs/en/settings>)** in `~/.claude.json` and `~/.claude/settings.json` are shared. Permission rules, allowed tools, and other settings in `settings.json` apply to Desktop sessions. Some keys behave differently in the Code tab. * **Models** : the same [models](</docs/en/model-config#available-models>) are available in both. In Desktop, select the model from the model picker in the row under the prompt box. You can change the model mid-session from the same picker. -#### - -​ - -MCP servers from the Claude Desktop chat app +#### MCP servers from the Claude Desktop chat app The Desktop app loads MCP servers from `claude_desktop_config.json` into local Code tab sessions, alongside servers from `~/.claude.json` and `.mcp.json`. A server you define in `claude_desktop_config.json` is available in both the Desktop chat surface and local Code tab sessions. If you define the same server name in `claude_desktop_config.json` and in `~/.claude.json` or `.mcp.json`, the Code tab in local sessions connects once and uses the `claude_desktop_config.json` definition. The app also re-delivers stdio servers from `~/.claude.json` to the embedded CLI in local sessions. When the top level of `~/.claude.json` (user scope) and `.mcp.json` define the same stdio server name, the Code tab uses the `~/.claude.json` definition, departing from the CLI [scope hierarchy](</docs/en/mcp#scope-hierarchy-and-precedence>). The standalone CLI does not read `claude_desktop_config.json`. On macOS and WSL, run `claude mcp add-from-claude-desktop` to copy those servers into `~/.claude.json`. See [Import MCP servers from Claude Desktop](</docs/en/mcp#import-mcp-servers-from-claude-desktop>) for the import flow and scope options. -### - -​ - -Feature comparison +### Feature comparison This table compares core capabilities between the CLI and Desktop. For a full list of CLI flags, see the [CLI reference](</docs/en/cli-reference>). @@ -2427,11 +1999,7 @@ Dispatch integration| Not available| Dispatch sessions in the sidebar Scripting and automation| [`--print`](</docs/en/cli-reference>), [Agent SDK](</docs/en/headless>)| Not available -### - -​ - -What’s not available in Desktop +### What’s not available in Desktop The following features aren’t available in Desktop, except where noted: @@ -2443,19 +2011,11 @@ * Commands with no argument form, such as `/permissions`, reply with `isn't available in this environment`. * `/config` opens **Settings > Code** or **Settings > Claude Code**. -## - -​ - -Troubleshooting +## Troubleshooting The sections below cover issues specific to the desktop app. For runtime API errors that appear in the chat such as `API Error: 500`, `529 Overloaded`, `429`, or `Prompt is too long`, see the [Error reference](</docs/en/errors>). -### - -​ - -Check your version +### Check your version To see which version of the desktop app you’re running: @@ -2464,19 +2024,11 @@ Click the version number to copy it to your clipboard. -#### - -​ - -Claude Code version in the Code tab +#### Claude Code version in the Code tab To see which version of Claude Code a session runs, type `/status` in a local session in the **Code** tab and read the **Claude Code** row, which shows a version such as `2.1.286`. To get a newer version for local sessions, open **Claude > Check for Updates…** on macOS or **Help > Check for Updates…** on Windows, then start a new session. In a local session, the **Code** tab runs its own copy of Claude Code, which has its own version number. The desktop app downloads and updates that copy, so it can differ from the `claude` command in your terminal, and updating one doesn’t update the other. -### - -​ - -Check which layout you have +### Check which layout you have If a new session shows the environment above the prompt box instead of under it, you have the earlier layout: @@ -2486,11 +2038,7 @@ In the earlier layout, choose the environment and any project folder or repository above the prompt box, and the permission mode and model in the row under it. The earlier layout lacks the session details panel and saved local and SSH environments. -### - -​ - -403 or authentication errors in the Code tab +### 403 or authentication errors in the Code tab If you see `Error 403: Forbidden` or other authentication failures when using the Code tab: @@ -2499,11 +2047,7 @@ 3. If the CLI works but Desktop does not, quit the desktop app completely, not just close the window, then reopen and sign in again. 4. Check your internet connection and proxy settings. -### - -​ - -Blank or stuck screen on launch +### Blank or stuck screen on launch If the app opens but shows a blank or unresponsive screen: @@ -2512,43 +2056,23 @@ 3. On a managed network, confirm your firewall allows the CDN hosts in network access requirements. 4. On Windows, check Event Viewer for crash logs under **Windows Logs → Application**. -### - -​ - -”Failed to load session” +### ”Failed to load session” If you see `Failed to load session`, the selected folder may no longer exist, a Git repository may require Git LFS that isn’t installed, or file permissions may prevent access. Try selecting a different folder or restarting the app. -### - -​ - -Session not finding installed tools +### Session not finding installed tools If Claude can’t find tools like `npm`, `node`, or other CLI commands, verify the tools work in your regular terminal, check that your shell profile properly sets up PATH, and restart the desktop app to reload environment variables. -### - -​ - -Git and Git LFS errors +### Git and Git LFS errors Sessions that run in their own worktree need Git. If you see “Git is required,” install [Git](<https://git-scm.com/downloads>), or [Git for Windows](<https://git-scm.com/downloads/win>) on Windows, and try again. On Windows, Claude Desktop versions before 1.49585.0 asked for Git before starting any local session; if you see that prompt and aren’t using worktrees, update the app. If you see “Git LFS is required by this repository but is not installed,” install Git LFS from [git-lfs.com](<https://git-lfs.com/>), run `git lfs install`, and restart the app. -### - -​ - -MCP servers not working on Windows +### MCP servers not working on Windows If MCP server toggles don’t respond or servers fail to connect on Windows, check that the server is properly configured in your settings, restart the app, verify the server process is running in Task Manager, and review server logs for connection errors. -### - -​ - -SSH host key verification failed +### SSH host key verification failed Each of these messages means that Desktop refused a host key: @@ -2563,11 +2087,7 @@ * **You see a Review new key button** : select it, and compare the fingerprint that Desktop shows with the machine’s own. If they match, select **Trust new key** to replace the saved key. Otherwise select **Cancel**. * **You see no Review new key button, Desktop shows`Couldn't show the new key`, or Desktop refuses the key again after Trust new key**: check the key from a terminal -#### - -​ - -Check the host key from a terminal +#### Check the host key from a terminal Run `ssh <SSH host>` on your computer, with the **SSH host** value of your SSH connection in Desktop. Add `-p <SSH port>` if the connection has an **SSH port** value. On Windows, use PowerShell, because Desktop doesn’t connect with the `ssh` in Git Bash or WSL. If PowerShell finds no `ssh`, install Microsoft’s OpenSSH client. Note which machine `ssh` names in its message, which can be a jump host and not `<SSH host>`, then follow the case that fits: @@ -2586,19 +2106,11 @@ * **A fingerprint doesn’t match, or you can’t check it** : don’t connect again. Remove the saved key: under `Host '<name>' is known`, the line `Found key in <file>:<line>` names the file that holds it. Run `ssh-keygen -R "<name>" -f <file>`. If you keep host keys in more than one file, remove the key from each. If you can’t change a file, tell whoever manages your computer. * **Every fingerprint matches** : retry in Desktop. If Desktop refuses the key again, see Get Desktop’s logs for an SSH problem. -### - -​ - -SSH host key refused on Windows without an OpenSSH client +### SSH host key refused on Windows without an OpenSSH client On Windows without an OpenSSH client, Desktop refuses even a correct host key, with `Connection failed: Host key changed or not trusted`. It needs the client to look up saved keys. To see whether you have one, run `ssh` in PowerShell. If PowerShell doesn’t recognize `ssh`, install [Microsoft’s OpenSSH client](<https://learn.microsoft.com/windows-server/administration/openssh/openssh_install_firstuse>) and restart Desktop. Then connect again. If Desktop asks whether to connect for the first time, check the machine’s host key before you trust it. If Desktop still refuses the key, follow the other cases under SSH host key verification failed. -### - -​ - -SSH connection fails after you log in +### SSH connection fails after you log in Find the card’s title, or the code that ends the error message, in this table, then do what the last column says. To see the message, select **View details** on the failure card. @@ -2615,11 +2127,7 @@ For any other message, check the remote machine requirements. -### - -​ - -Get Desktop’s logs for an SSH problem +### Get Desktop’s logs for an SSH problem You get `ssh.log`, Desktop’s record of its SSH connections, in a zip file of Desktop’s logs that you save from the **Help** menu. To save it, open **Help > Troubleshooting** and select the item for your system: @@ -2634,40 +2142,24 @@ Look through those files too before you send them. -### - -​ - -App won’t quit +### App won’t quit * **macOS** : press Cmd+Q. If the app doesn’t respond, use Force Quit with Cmd+Option+Esc, select Claude, and click Force Quit. * **Windows** : use Task Manager with Ctrl+Shift+Esc to end the Claude process. -### - -​ - -Windows-specific issues +### Windows-specific issues * **PATH not updated after install** : open a new terminal window. PATH updates only apply to new terminal sessions. * **Concurrent installation error** : if you see an error about another installation in progress but there isn’t one, try running the installer as Administrator. -### - -​ - -”Branch doesn’t exist yet” when opening in CLI +### ”Branch doesn’t exist yet” when opening in CLI Cloud sessions can create branches that don’t exist on your local machine. Click the branch name in the session and select **Copy branch name** , then fetch it locally: git fetch origin <branch-name> git checkout <branch-name> -### - -​ - -Still stuck? +### Still stuck? * Open Help → Get Support in the desktop app, or visit the [Claude support center](<https://support.claude.com/>) directly * For problems that also reproduce in the standalone `claude` CLI, search or file a bug on [GitHub Issues](<https://github.com/anthropics/claude-code/issues>)
modified Test iOS apps in the simulator View current →
Show diff (174 lines)
--- a/desktop-ios-simulator.md +++ b/desktop-ios-simulator.md @@ -2,11 +2,7 @@ The iOS Simulator pane shows your app running in Apple’s iOS Simulator next to your conversation in Claude Code Desktop. When Claude builds, installs, launches, or checks your app in a simulator, the pane opens automatically and streams the device screen live. Use it to watch Claude run and test your app, or to tap through the app yourself while Claude keeps working. The simulator pane drives the simulator directly, so it doesn’t need [computer use](</docs/en/desktop#let-claude-use-your-computer>) and never takes over your screen or hides your other windows. From the CLI, Claude reaches the iOS Simulator through [computer use](</docs/en/computer-use#test-a-simulator-flow>) instead, which controls the simulator on your screen the same way you would with a mouse. -## - -​ - -Requirements +## Requirements The simulator pane uses Apple’s simulator tooling, which the desktop app doesn’t include. Before starting a session, make sure you have: @@ -19,11 +15,7 @@ The simulator pane is available in local sessions only. In [cloud](</docs/en/desktop#run-long-running-tasks-in-the-cloud>) and [SSH](</docs/en/desktop#ssh-sessions>) sessions, Claude runs on a machine that can’t reach the simulators on your Mac. -### - -​ - -Choose which Xcode the simulator pane uses +### Choose which Xcode the simulator pane uses If you have more than one Xcode installed, such as Xcode 26.x alongside Xcode 27, the pane uses whichever one `xcode-select` points at. To use a different install, select it by its path. For example, if the Xcode you want is installed as `/Applications/Xcode-26.4.app`, run this in Terminal: @@ -31,11 +23,7 @@ Then quit and reopen Claude Desktop so the pane uses the newly selected Xcode. To check which install is selected, run `xcode-select -p`. It prints the selected install’s Developer folder, such as `/Applications/Xcode-26.4.app/Contents/Developer`. -## - -​ - -Run your app in the simulator +## Run your app in the simulator You don’t need a command or setting to open the simulator pane. Claude opens it when it runs your app in a simulator. @@ -61,11 +49,7 @@ When your request is about seeing the app, for example “does the new screen look right?”, Claude starts a simulator before it begins the work. After Claude fixes a bug or changes a screen, ask it to verify the change. The simulator pane shows whichever device the app actually launched in. To test on a specific device, name it in your request, for example “run it on the iPhone SE simulator”, and Claude targets that device when it builds and launches. A device Claude boots also appears in Apple’s Simulator app, or in Device Hub on Xcode 27. Claude can install the app on a device you already have booted. You can also open the simulator pane yourself. Once the session has a simulator attached or Claude Code detects iOS app work, an **iOS Simulator** button appears in the session’s title bar. If the pane isn’t showing a device yet, click **Attach simulator** , or pick a specific device from the device menu next to it; picking a shut-down device boots it. If Xcode or its simulators are missing, the pane shows the setup steps instead and checks them off as you complete them. -## - -​ - -Control the simulator yourself +## Control the simulator yourself The simulator pane is interactive, not only a viewer. While Claude works, or between tasks, you can: @@ -78,38 +62,22 @@ If the pane shows a **Display** menu, use it to tune the video stream from the simulator. Lower **Frame rate** or **Resolution** if the pane strains your Mac. Both settings change how the pane displays the device, not how the app runs. You and Claude drive the same device, so your taps change the app state Claude sees. To have Claude check a specific screen, tap through to it, then ask. While Claude is driving the device, the pane shows a **Claude is using this device** badge above the screen; hold off tapping until the badge clears, so the result reflects the app rather than your input. -### - -​ - -Minimize or close the simulator pane +### Minimize or close the simulator pane You can minimize or close the simulator pane, and Claude can still use the device either way. * If you minimize the pane, the device stays in view at a small size. To minimize the pane or expand it again, see [Minimize a pane](</docs/en/desktop#minimize-a-pane>). * If you close the full-size or minimized pane, the device stays attached and running. To show the device again, click **iOS Simulator** in the session’s title bar. -## - -​ - -How sessions manage devices +## How sessions manage devices If your prompt doesn’t name a simulator, Claude uses one that’s already running, even if another [parallel session](</docs/en/desktop#work-in-parallel-with-sessions>) opened it. To give each session its own simulator, name a different one in each session’s prompt. Claude Code Desktop shuts down the simulators it booted once they’re no longer in use: when you quit the app, when you archive the session, or 10 minutes after you detach a device from its pane. Devices you boot outside Claude Code Desktop, such as in Apple’s Simulator app or in Device Hub, are never shut down automatically. To shut down the attached device right away, use the shutdown button in the pane. -## - -​ - -Grant Claude access to a device +## Grant Claude access to a device Claude asks for your consent before it controls a device, while building or launching the app or opening a URL on it follows your session’s permission mode. You or your organization can also turn Claude’s access off entirely. -### - -​ - -Allow a device the first time +### Allow a device the first time The first time Claude uses a simulator, the desktop app asks you to allow it. The consent covers controlling that device and taking screenshots of it, and you give it once per device rather than once per session. Claude’s screenshots of the device are sent to Anthropic and kept under your normal conversation retention settings, so don’t sign in to real accounts on a device Claude uses. After you allow a device, Claude’s actions on it, such as tapping, typing, and taking screenshots, run without prompts, but you approve launching the app as your permission mode requires. They carry the same trust as you clicking in the pane, and they only touch the simulated device, so the pane doesn’t need the macOS Accessibility and Screen Recording permissions that computer use requires. If you decline Claude’s request, the device doesn’t attach and Desktop doesn’t boot it. To use the device yourself: @@ -119,11 +87,7 @@ The device attaches and works for your own taps, and Claude’s access stays off. After that, to give Claude access, click **Let Claude use it** in the pane. -### - -​ - -Actions that follow your permission mode +### Actions that follow your permission mode Three actions follow your session’s [permission mode](</docs/en/permissions#permission-modes>) even after you allow a device: @@ -131,11 +95,7 @@ * Building the app, because `xcodebuild` runs your project’s build scripts on your Mac. Checking on a build already in progress doesn’t prompt. * Installing and launching the app, because Claude can run any app it names, not only the one you’re building. -### - -​ - -Turn off simulator access +### Turn off simulator access You can turn Claude’s simulator access off in the desktop app’s settings. Organizations have two ways to turn it off for everyone: @@ -144,25 +104,13 @@ Claude tells you when either applies. -## - -​ - -Limitations +## Limitations Claude drives simulated devices only and can’t control a physical iPhone or iPad. To test on one, run the app on it from Xcode yourself, then describe what you see or attach a screenshot to the conversation for Claude to work from. -## +## Troubleshooting -​ - -Troubleshooting - -### - -​ - -The simulator pane doesn’t open when Claude runs the app +### The simulator pane doesn’t open when Claude runs the app Claude may not have recognized that you wanted to run or test the app, or the simulator tooling may be missing. Check the following: @@ -172,19 +120,11 @@ * If you’re in an Enterprise organization that has a HIPAA configuration enabled, or you use a [third-party provider](</docs/en/third-party-integrations>), the simulator pane isn’t available to you. * The simulator pane requires Claude Desktop v1.24012.0 or later. Open **Claude > Check for Updates…**, then restart the app. -### - -​ - -The simulator pane says no simulators were found +### The simulator pane says no simulators were found Xcode is installed but has no iOS simulators to list. The simulator pane shows the setup steps to follow and checks them off as each one completes. To install the missing piece manually, download the iOS simulator runtime from Xcode’s settings, or run `xcodebuild -downloadPlatform iOS`. -## - -​ - -See also +## See also * [Computer use in Desktop](</docs/en/desktop#let-claude-use-your-computer>): screen control for apps without a dedicated pane * [Computer use from the CLI](</docs/en/computer-use>): how the CLI reaches the iOS Simulator
modified Claude Desktop on Linux (beta) View current →
Show diff (162 lines)
--- a/desktop-linux.md +++ b/desktop-linux.md @@ -2,22 +2,14 @@ The desktop app on Linux gives you the same Chat, Cowork, and Claude Code experience as on macOS and Windows: parallel sessions, visual diff review, an integrated terminal and editor, and live app preview. See [Use Claude Code Desktop](</docs/en/desktop>) for the feature reference. -## - -​ - -Requirements +## Requirements * A Debian-based distribution: Ubuntu 22.04 or later, or Debian 12 or later * x86_64 or arm64 Other Debian-based distributions that meet these requirements may work but aren’t officially tested. On distributions that aren’t Debian-based, such as Fedora or Arch, run the [CLI](</docs/en/setup#system-requirements>) instead. If you work on Windows with WSL 2, install the Windows desktop app and run sessions inside your distribution; see [Claude Code Desktop in WSL](</docs/en/desktop-wsl>). -### - -​ - -Cowork requirements +### Cowork requirements Cowork is the part of the desktop app for [Dispatch and longer agentic work](<https://claude.com/docs/cowork/overview>). On Linux, Cowork runs those tasks in a virtual machine that the desktop app hosts with QEMU and KVM. To use Cowork, your machine needs: @@ -27,11 +19,7 @@ The app checks these requirements once at launch: restart it after installing packages, and log out and back in after joining the group. If `/dev/vhost-vsock` is missing and your running kernel has no module directory under `/lib/modules`, Cowork reports that the kernel doesn’t include the virtualization support Cowork needs and that it can’t be added manually. This combination is common on ChromeOS and in container-based Linux environments. -## - -​ - -Install +## Install Install from Anthropic’s apt repository so that updates arrive through your system’s regular package updates. Open a terminal and run the commands in each step. @@ -65,13 +53,9 @@ Launch and sign in -Launch **Claude** from your application launcher, or run `claude-desktop` from a terminal, and sign in with your Anthropic account.The Linux app signs in the same way as on macOS and Windows: with a claude.ai subscription, or through your organization’s SSO. For API-key authentication, use the [CLI](</docs/en/quickstart>). To use Desktop with Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, or an LLM gateway instead, see [Claude Desktop on 3P](<https://claude.com/docs/third-party/claude-desktop/overview>). For proxy servers and custom certificate authorities in those deployments, see [network configuration](</docs/en/network-config>). +Launch **Claude** from your application launcher, or run `claude-desktop` from a terminal, and sign in with your Anthropic account.The Linux app signs in the same way as on macOS and Windows: with a claude.ai subscription, or through your organization’s SSO. To use Desktop with a Claude API key, Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, or an LLM gateway instead, see [Claude Desktop on 3P](<https://claude.com/docs/third-party/claude-desktop/overview>). For proxy servers and custom certificate authorities in those deployments, see [network configuration](</docs/en/network-config>). -### - -​ - -Install from a downloaded file +### Install from a downloaded file If you can’t install through the apt repository, download the `.deb` package directly from the repository’s package pool. This command looks up the newest package for your architecture in the repository index, then downloads it to the current directory: @@ -83,11 +67,7 @@ If apt reports `E: Unsupported file ./claude-desktop_*.deb given on commandline`, the pattern didn’t match a `.deb` file in the current directory. Confirm the download completed, then run the command again from the directory that contains the file. The `.deb` contains Anthropic’s signing key and installs it at `/usr/share/keyrings/claude-desktop-archive-keyring.asc`, so you don’t need to download the key yourself. Unless you turned registration off with `CLAUDE_DESKTOP_ADD_REPO`, the package also registers the apt repository at `/etc/apt/sources.list.d/claude-desktop.list`, so future updates arrive with your system’s regular package updates. -## - -​ - -Update +## Update The desktop app doesn’t update itself on Linux. Updates arrive with your system’s regular package updates: @@ -95,11 +75,7 @@ Your distribution’s graphical software updater will also pick up new versions. -## - -​ - -Uninstall +## Uninstall sudo apt remove claude-desktop @@ -107,17 +83,9 @@ sudo rm /etc/apt/sources.list.d/claude-desktop.list -## +## Troubleshoot -​ - -Troubleshoot - -### - -​ - -Unable to locate package claude-desktop +### Unable to locate package claude-desktop If `sudo apt install claude-desktop` fails with `E: Unable to locate package claude-desktop`, apt didn’t find the repository you added. Check the following: @@ -128,30 +96,18 @@ If the repository is in place and reachable and the package is still not found, install from a downloaded file instead. -### - -​ - -Unmet dependencies +### Unmet dependencies If `apt` stops with `The following packages have unmet dependencies` or `Unsatisfied dependencies`, read which dependency it names: * `libc6 (>= 2.34)`: your distribution is older than the package supports. Ubuntu 20.04 ships `libc6` 2.31. Upgrade to Ubuntu 22.04 or later, or Debian 12 or later. * All missing dependencies show `not installable` with an `:amd64` or `:arm64` suffix: you downloaded the `.deb` for a different architecture than your machine’s. Run `dpkg --print-architecture` and download the matching `.deb`, or install from the apt repository, which selects the package for your architecture. -### - -​ - -Running as root without `--no-sandbox` is not supported +### Running as root without `--no-sandbox` is not supported If `claude-desktop` exits with this message, you launched it as root. Log in as a regular user and launch it from there. -### - -​ - -Your sign-in won’t be saved on this device +### Your sign-in won’t be saved on this device Claude Desktop saves your sign-in in your desktop’s keyring, such as GNOME Keyring or KDE Wallet. If it can’t reach an unlocked keyring, your sign-in isn’t saved and you sign in again each time you launch the app. Pick the case that matches your system: @@ -161,11 +117,7 @@ After the fix, restart the app and sign in. Then quit and launch it again to confirm the app opens with you still signed in. -### - -​ - -Cowork isn’t available +### Cowork isn’t available If Cowork shows one of these messages, fix the requirement it names, then restart the app: @@ -174,11 +126,7 @@ * **Claude doesn’t have permission to use virtualization (/dev/kvm)** : add your user to the `kvm` group, then log out and back in. * **Cowork requires the`vhost_vsock` kernel module**: run `sudo modprobe vhost_vsock`, then restart the app. That loads the module for the current boot only. To load it on every boot, run `echo vhost_vsock | sudo tee /etc/modules-load.d/vhost_vsock.conf`. -## - -​ - -What’s not in the Linux beta yet +## What’s not in the Linux beta yet * **Computer Use** : [app and screen control](</docs/en/desktop#let-claude-use-your-computer>) isn’t available on Linux. * **Dictation** : voice input isn’t available in the Linux desktop app. Use [voice dictation](</docs/en/voice-dictation>) in the CLI instead.
modified Get started with the desktop app View current →
--- a/desktop-quickstart.md +++ b/desktop-quickstart.md @@ -21,11 +21,7 @@ * **Using chat or Cowork** : see the [Claude Help Center](<https://support.claude.com/>) * **Need more on installing or deploying the desktop app** : see the [Claude Desktop support articles](<https://support.claude.com/en/collections/16163169-claude-desktop>) -## - -​ - -Install +## Install 1 @@ -45,11 +41,7 @@ The desktop app includes Claude Code, so you don’t need to install Node.js or the CLI to use the Code tab. -## - -​ - -Start your first session +## Start your first session With the Code tab open, choose a project and give Claude something to do. @@ -100,11 +92,7 @@ 2. Buttons to approve or decline each change 3. Real-time updates as Claude works through your request -## - -​ - -Now what? +## Now what? You’ve made your first edit. For the full reference on everything Desktop can do, see [Use Claude Code Desktop](</docs/en/desktop>). Here are some things to try next. **Interrupt and steer.** You can redirect Claude at any point. Click the stop button to interrupt immediately, or type a correction and press **Enter** to send it without stopping the running action. Either way, you don’t have to wait for it to finish or start over. **Give Claude more context.** Type `@filename` in the prompt box to pull a specific file into the conversation. The more context Claude has, the better the results. See [Add files and context](</docs/en/desktop#add-files-and-context-to-prompts>). **Use skills for repeatable tasks.** Type `/` or click **+** → **Slash commands** to browse [built-in commands](</docs/en/commands>), [custom skills](</docs/en/skills>), and plugin skills. Skills are reusable prompts you can invoke whenever you need them, like code review checklists or deployment steps. **Review changes before committing.** After Claude edits files, a `+12 -1` indicator appears. Click it to open the [diff view](</docs/en/desktop#review-changes-with-diff-view>), review modifications file by file, and comment on specific lines. Claude reads your comments and revises. To have Claude review the changes itself, enter [`/code-review`](</docs/en/desktop#review-your-code>) in the prompt box. **Adjust how much control you have.** Your [permission mode](</docs/en/desktop#choose-a-permission-mode>) sets how much Claude can do without asking for approval: @@ -115,11 +103,7 @@ **Add plugins for more capabilities.** Install [plugins](</docs/en/desktop#install-plugins>) that add skills, agents, MCP servers, and more. **Arrange your workspace.** Drag the chat, diff, terminal, file, and browser panes into whatever layout you want. Open the terminal with **Ctrl+`** to run commands alongside your session, or click a file path to open it. See [Arrange your workspace](</docs/en/desktop#arrange-your-workspace>). **Preview your app.** When you run your dev server in the desktop, your app opens in the Browser pane, which can also [open external sites](</docs/en/desktop#browse-external-sites>). Claude can view the running app, test endpoints, inspect logs, and iterate on what it sees. See [Preview your app](</docs/en/desktop#preview-your-app>). **Track your pull request.** After opening a PR, Claude Code monitors CI check results and can automatically fix failures. See [Monitor pull request status](</docs/en/desktop#monitor-pull-request-status>). **Put Claude on a schedule.** Set up [scheduled tasks](</docs/en/desktop-scheduled-tasks>) to run Claude automatically on a recurring basis: a daily code review every morning, a weekly dependency audit, or a briefing that pulls from your connected tools. **Scale up when you’re ready.** Open [parallel sessions](</docs/en/desktop#work-in-parallel-with-sessions>) from the sidebar to work on multiple tasks at once, optionally each in its own Git worktree, and open the [tasks pane](</docs/en/desktop#watch-background-tasks>) to watch the subagents and background commands a session has running. Open a [side chat](</docs/en/desktop#ask-a-side-question-without-derailing-the-session>) to ask a question without derailing the main thread. Send [long-running work to the cloud](</docs/en/desktop#run-long-running-tasks-in-the-cloud>) so it continues even if you close the app, or [move a session you already started to the cloud](</docs/en/desktop#continue-in-another-surface>) if a task takes longer than expected. [Connect external tools](</docs/en/desktop#extend-claude-code>) like GitHub, Slack, and Linear to bring your workflow together. -## - -​ - -What’s next +## What’s next * [Use Claude Code Desktop](</docs/en/desktop>): permission modes, parallel sessions, diff view, connectors, and enterprise configuration * [Coming from the CLI?](</docs/en/desktop#coming-from-the-cli>): run Desktop and the CLI on the same project, and compare features, flag equivalents, and what’s not available in Desktop
modified Schedule recurring tasks in Claude Code Desktop View current →
Show diff (153 lines)
--- a/desktop-scheduled-tasks.md +++ b/desktop-scheduled-tasks.md @@ -7,11 +7,7 @@ If your app shows the feature under its [earlier name](</docs/en/routines#where-the-name-routines-still-appears>), click **Routines** wherever this page says **Scheduled** and **New routine** where it says **New task**. -## - -​ - -Compare scheduling options +## Compare scheduling options Claude Code offers three ways to schedule recurring or one-off work: @@ -31,11 +27,7 @@ By default, local scheduled tasks run against whatever state your working directory is in, including uncommitted changes. To give each run its own [isolated Git worktree](</docs/en/desktop#run-a-session-in-its-own-worktree>) instead, select **Worktree** in the task’s **Edit** form after you create it. The checkbox is available when the task’s folder is a Git repository. -## - -​ - -Create a scheduled task +## Create a scheduled task Local scheduled tasks require Claude Desktop 1.1.5368 or later. @@ -89,21 +81,20 @@ Choose the permission mode and model -In the instructions box’s toolbar, select a permission mode and model. If you leave them unchanged, runs use your Claude Code settings and the default model. +In the instructions box’s toolbar, select a permission mode and model. + + * **Permission mode** : if you leave it unchanged, runs use your Claude Code settings. + * **Model** : if the model menu reads **Default · Set by admin** and you don’t pick another model, runs use the model your organization set in [managed settings](</docs/en/managed-settings>). A catch-up run that starts as the app opens can use the [runtime default for your account](</docs/en/model-config#default-model-setting>) instead. 9 Create the task -Click **Create**. If you haven’t trusted the folder yet, Desktop asks you to trust it at this point. The task’s detail page opens. +Click **Create**. If you haven’t trusted the folder yet, Desktop asks you to trust it at this point. The task’s detail page opens.To see which model **Default · Set by admin** stands for, click **Run now** on the detail page to run the task at once. Then open the run’s session, where the row under the prompt box shows the model’s name. On the detail page, click the pencil icon to open the **Edit** form. There you can change the **Description** that Desktop filled in from your instructions, select **Worktree** , or switch the schedule to **Manual** or **Custom**. You can also create a task by describing what you want in any session. For example, “set up a daily code review that runs every morning at 9am” creates a recurring task. A request like “remind me at 3pm tomorrow to check the deploy” creates a one-time task that disables itself after it fires. -### - -​ - -Dialog with Only on this computer at the top +### Dialog with Only on this computer at the top If **Only on this computer** is at the top of the **New scheduled task** dialog when it opens, turn it on before you enter anything. When you turn it on, a separate blank form for a local task replaces the form. Then fill in the local form’s fields: @@ -115,11 +106,7 @@ Click **Create**. The task’s detail page opens. -### - -​ - -Full-page form +### Full-page form If a menu with **Local** and **Cloud** opens, select **Local**. A page titled **New local routine** or **New local scheduled task** opens. Fill in its fields: @@ -130,11 +117,7 @@ If **Create** is unavailable, hover over it to see what the form still needs. Click **Create** , and the task’s detail page opens. -## - -​ - -Schedule options +## Schedule options When you turn on **Only on this computer** under **Advanced settings** , the **Trigger** card offers Hourly, Daily, Weekdays, and Weekly. To get **Manual** or **Custom** for such a task, open its **Edit** form after you create it. That form, the dialog with **Only on this computer** at the top, and the full-page form offer these six options: @@ -147,21 +130,13 @@ You can also ask Claude in any Desktop session to set the schedule. Claude isn’t held to the once-per-hour limit and can set a single run at a future time. For example, ask “run the test suite every 30 minutes” or “next Monday at 9am, summarize the pull requests merged since Friday.” -## - -​ - -How scheduled tasks run +## How scheduled tasks run Local scheduled tasks run on your machine. Desktop checks the schedule every minute while the app is open and starts a fresh session when a task is due, independent of any manual sessions you have open. Each task gets a small delay of a few minutes after the scheduled time to stagger API traffic. The delay is deterministic: the same task always starts at the same offset. Tasks only run while the desktop app is running and your computer is awake. If your computer sleeps through a scheduled time, the run is skipped. To prevent idle-sleep, turn on **Keep computer awake** in **Settings > Desktop app** or **Settings > This computer > System**. Closing the laptop lid still puts it to sleep. For tasks that need to run even when your computer is off, or that should trigger on an API call or GitHub event, create a [cloud scheduled task](</docs/en/routines>) instead. -### - -​ - -Find a run’s session +### Find a run’s session To open the session a run started, go to the task’s detail page and click that run’s row in the **History** list. The sidebar’s session list can show a **Scheduled** group as well, with one row per task. To open the session of a task’s latest run, click the task’s row in that group. To show the group, [check which layout you have](</docs/en/desktop#check-which-layout-you-have>): @@ -170,27 +145,15 @@ In a run’s session, whichever way you reached it, you can see what Claude did, review changes, and respond to permission prompts. Claude can edit files, run commands, create commits, and open pull requests, the same as in a session you start yourself. -## - -​ - -Missed runs +## Missed runs When the app starts or your computer wakes, Desktop checks whether each task missed any runs in the last seven days. If it did, Desktop starts exactly one catch-up run for the most recently missed time and discards anything older. A daily task that missed six days runs once on wake. Desktop shows a notification when a catch-up run starts. Keep this in mind when writing prompts. A task scheduled for 9am might run at 11pm if your computer was asleep all day. If timing matters, add guardrails to the prompt itself, for example: “Only review today’s commits. If it’s after 5pm, skip the review and post a summary of what was missed.” -## - -​ - -Permissions for scheduled tasks +## Permissions for scheduled tasks Each task has its own [permission mode](</docs/en/desktop#choose-a-permission-mode>), which you set when creating or editing the task. Allow rules from `~/.claude/settings.json` also apply to scheduled task sessions. When a run is stalled on a permission prompt, find the run’s session and answer the prompt there. To avoid stalls, click **Run now** after creating a task, watch for permission prompts, and select “always allow” for each one. Future runs skip most of those prompts. You can review and revoke these approvals from the task’s detail page. If you select “always allow” on a file edit in the task’s folder, only that session moves to **Accept edits** , so set the task’s permission mode to **Accept edits**. MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>) prompt on every call and don’t offer an always-allow option. Runs that call these tools stall each time. -## - -​ - -Manage scheduled tasks +## Manage scheduled tasks In the **Code** tab, click **Scheduled** in the sidebar, then click a task in the list to open its detail page. From here you can: @@ -201,13 +164,9 @@ * **Review allowed permissions** : see and revoke saved tool approvals for this task from the **Always allowed** panel * **Delete** : remove the task. The sessions the task created are [archived](</docs/en/desktop#organize-and-find-sessions>), not deleted. The folder holding the task’s `SKILL.md` file stays on disk at `~/.claude/scheduled-tasks/<task-name>/`, or at `scheduled-tasks/<task-name>/` under [`CLAUDE_CONFIG_DIR`](</docs/en/env-vars>) if you set that variable. To remove that folder, delete it yourself. -You can also list, create, edit, and pause tasks by asking Claude in any Desktop session. For example, “pause my dependency-audit task” or “show me my scheduled tasks.” To delete a task, use the **Delete** button on its detail page. To let a task change its own schedule or prompt with the `update_scheduled_task` MCP tool, click **Run now** and approve the call each time. To edit a task’s prompt on disk, open `~/.claude/scheduled-tasks/<task-name>/SKILL.md` (or under [`CLAUDE_CONFIG_DIR`](</docs/en/env-vars>) if set). The file uses YAML frontmatter for `name` and `description`, with the prompt as the body. Changes take effect on the next run. Schedule, folder, model, and enabled state are not in this file: change them through the Edit form or ask Claude. +You can also list, create, edit, and pause tasks by asking Claude in any Desktop session. For example, “pause my dependency-audit task” or “show me my scheduled tasks.” To delete a task, use the **Delete** button on its detail page. To let a task change its own schedule or prompt with the `update_scheduled_task` MCP tool, click **Run now** and approve the call each time. To edit a task’s prompt on disk, open `~/.claude/scheduled-tasks/<task-name>/SKILL.md` (or under [`CLAUDE_CONFIG_DIR`](</docs/en/env-vars>) if set). The file uses YAML frontmatter for `name` and `description`, with the prompt as the body. Changes take effect on the next run. Schedule, folder, and enabled state are not in this file: change them through the Edit form or ask Claude. -## - -​ - -Related resources +## Related resources * [Cloud scheduled tasks](</docs/en/routines>): run tasks in the cloud on a schedule, via API call, or in response to GitHub events, even when your computer is off * [Run prompts on a schedule](</docs/en/scheduled-tasks>): session-scoped scheduling with `/loop` in the CLI
modified Claude Code Desktop in WSL View current →
--- a/desktop-wsl.md +++ b/desktop-wsl.md @@ -1,20 +1,12 @@ On Windows, the Code tab can run a session inside a WSL 2 distribution instead of on Windows itself. The session’s Claude Code process, its tools, and git all execute inside the distribution, using its Linux toolchain and native Linux paths, the same environment your project targets. Use a WSL session when your repository lives inside the distribution’s filesystem. Working on those files from Windows goes through a network filesystem, which is slow and breaks file watching; running the session inside the distribution avoids both. -## - -​ - -Requirements +## Requirements * Windows 10 or 11 with [WSL 2](<https://learn.microsoft.com/windows/wsl/install>). WSL 1 isn’t supported. * At least one installed distribution (for example, Ubuntu). * `git` installed inside the distribution. -## - -​ - -Start a WSL session +## Start a WSL session 1 @@ -36,11 +28,7 @@ The first session in a distribution takes a little longer while Claude sets up inside it. You can also open a `\\wsl.localhost\...` folder from the normal folder picker, and it reopens inside that distribution. -## - -​ - -What works in a WSL session +## What works in a WSL session Parallel sessions, side chats, visual diff review, branch and pull request status, and worktrees all work, backed by the git and toolchain inside the distribution. “Open in editor” opens VS Code connected to the distribution through [Remote - WSL](<https://code.visualstudio.com/docs/remote/wsl>). If a Desktop feature is unavailable or limited in a WSL session, check whether it’s one of these: @@ -49,21 +37,13 @@ * **File editing** : you can view files in the [file pane](</docs/en/desktop#open-and-edit-files>) but can’t edit them there, so ask Claude to make the changes * **Attachments** : if the **+** menu shows **Add image** in place of **Add files or photos** , you can attach only images. See [Add files and context to prompts](</docs/en/desktop#add-files-and-context-to-prompts>). -### - -​ - -If the terminal or connectors are unavailable +### If the terminal or connectors are unavailable You can’t turn on the integrated terminal or connectors for a WSL session yourself: * **Claude account** : the two features are rolling out separately. Select **Help > Check for Updates…**, and if a feature is still missing after you update, there’s nothing to do. * **[Third-party provider](</docs/en/third-party-integrations>)** : WSL sessions don’t get the terminal or connectors, and updating Desktop doesn’t change that -## - -​ - -Managed devices +## Managed devices On devices managed by an organization, WSL sessions may be unavailable. If session start fails with a message that the device is managed, that’s controlled by your administrator. Administrators: see [how settings reach devices](</docs/en/admin-setup#decide-how-settings-reach-devices>) in the deployment guide.
modified Development containers View current →
--- a/devcontainer.md +++ b/devcontainer.md @@ -6,11 +6,7 @@ A dev container runs as a Docker container, either on your machine or on a cloud host such as GitHub Codespaces. An editor that supports the Dev Containers spec, such as VS Code, GitHub Codespaces, a JetBrains IDE, or Cursor, connects to that container: you browse and edit files in the editor as usual, but the integrated terminal, language servers, and build tools all run inside the container rather than on your host. Editors without dev container support, such as plain Vim, are not part of this workflow.Claude Code runs inside the container, so it sees the same files, dependencies, and tools as the rest of your project’s toolchain. In VS Code you can use either the [Claude Code extension panel](</docs/en/vs-code>) or run `claude` in the integrated terminal; both run inside the container and share the same `~/.claude` configuration. -## - -​ - -Add Claude Code to your dev container +## Add Claude Code to your dev container Claude Code installs into any dev container through the [Claude Code Dev Container Feature](<https://github.com/anthropics/devcontainer-features/tree/main/src/claude-code>). The settings work with any tool that supports the Dev Containers spec, such as VS Code, GitHub Codespaces, or JetBrains IDEs. The steps below use VS Code as an example. When you open the container in VS Code or Codespaces, the feature also adds the Claude Code VS Code extension; other editors ignore that part. @@ -54,11 +50,7 @@ For the Anthropic sign-in: if no browser opens, or it signs you in and then shows a `localhost` connection error, use the login URL shown above the terminal’s paste prompt. Copy it into your browser, sign in there, then paste the code the browser shows into that prompt. If pasting does nothing, see [OAuth login fails in WSL2, SSH, or containers](</docs/en/troubleshoot-install#oauth-login-fails-in-wsl2-ssh-or-containers>). -## - -​ - -Persist authentication and settings across rebuilds +## Persist authentication and settings across rebuilds By default, the container’s home directory is discarded on rebuild, so engineers must sign in again each time. Claude Code stores its authentication token, user settings, and session history under the [`~/.claude`](</docs/en/claude-directory>) directory. It stores your account details, personal MCP servers, and per-project trust in a separate file outside that directory: [`~/.claude.json`](</docs/en/settings-reference#global-config-settings>). To keep the directory and the file, mount a named volume at `~/.claude` and set [`CLAUDE_CONFIG_DIR`](</docs/en/env-vars>) to the same path so Claude Code writes `.claude.json` inside the volume. The following example mounts the volume and sets `CLAUDE_CONFIG_DIR` for a container whose `remoteUser` is `node`: @@ -77,11 +69,7 @@ To isolate state per project rather than sharing one volume across all repositories, include the `${devcontainerId}` variable in the source name. The [reference configuration](<https://github.com/anthropics/claude-code/blob/main/.devcontainer/devcontainer.json>) uses `source=claude-code-config-${devcontainerId}` for this purpose. In GitHub Codespaces, `~/.claude` persists when you stop and start a codespace but is cleared when you rebuild the container, so the configuration above applies there too. To carry authentication across codespaces, store `ANTHROPIC_API_KEY` or a `CLAUDE_CODE_OAUTH_TOKEN` from [`claude setup-token`](</docs/en/authentication#generate-a-long-lived-token>) as a [Codespaces secret](<https://docs.github.com/en/codespaces/managing-your-codespaces/managing-your-account-specific-secrets-for-github-codespaces>). Codespaces exposes secrets as environment variables inside the container automatically. -## - -​ - -Enforce organization policy +## Enforce organization policy A dev container is a convenient place to apply organization policy, because the same image and configuration run on every engineer’s machine. Claude Code reads `/etc/claude-code/managed-settings.json` on Linux and applies it at the highest precedence in the [settings hierarchy](</docs/en/settings#settings-precedence>), so values there override anything an engineer sets in `~/.claude` or the project’s `.claude/` directory. Copy the file into place from your Dockerfile: @@ -101,27 +89,15 @@ `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` also disables the feature-flag evaluation that [Remote Control](</docs/en/remote-control#requirements>) and the other [features that need feature-flag fetching](</docs/en/env-vars#features-that-need-feature-flag-fetching>) depend on, so sessions in the container can’t use them. The Dev Container Feature always installs the latest Claude Code release. To pin a specific Claude Code version for reproducible builds, install it from your Dockerfile with `npm install -g @anthropic-ai/claude-code@X.Y.Z` instead of using the feature, and set `DISABLE_AUTOUPDATER` to `1` in `containerEnv`. For the full list of policy controls including permission rules, tool restrictions, and MCP server allowlists, see [Set up Claude Code for your organization](</docs/en/admin-setup>). To make [MCP servers](</docs/en/mcp>) available inside the container, define them at [project scope](</docs/en/mcp#mcp-installation-scopes>) in a `.mcp.json` file at the repository root so they are checked in alongside your dev container configuration. Install any binaries that local stdio servers depend on in your Dockerfile, and add remote server domains to your network allowlist. -## - -​ - -Restrict network egress +## Restrict network egress You can limit the container’s outbound traffic to only the domains Claude Code needs. See [Network access requirements](</docs/en/network-config#network-access-requirements>) for the inference and authentication domains, and [Telemetry services](</docs/en/data-usage#telemetry-services>) for the optional telemetry and error reporting connections and how to disable them. The reference container includes an [`init-firewall.sh`](<https://github.com/anthropics/claude-code/blob/main/.devcontainer/init-firewall.sh>) script that limits outbound traffic to the destinations the script allows. Running a firewall inside a container requires extra permissions, so the reference adds the `NET_ADMIN` and `NET_RAW` capabilities through `runArgs`. The firewall script and these capabilities are not required for Claude Code itself: you can leave them out and rely on your own network controls instead. -## - -​ - -Run without permission prompts +## Run without permission prompts Because the container runs Claude Code as a non-root user and confines command execution to the container, you can pass `--dangerously-skip-permissions` for unattended operation. The CLI rejects this flag when launched as root, so confirm `remoteUser` is set to a non-root account. Skipping permission prompts removes your opportunity to review tool calls before they run. Claude can still modify any file in the bind-mounted workspace, which appears directly on your host, and reach anything the container’s network policy allows. Pair this flag with the network egress restrictions above to limit what a bypassed session can reach. If you want fewer prompts without disabling safety checks, consider [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) instead, which has a classifier review actions before they run. To prevent engineers from using `--dangerously-skip-permissions` at all, set `permissions.disableBypassPermissionsMode` to `"disable"` in [managed settings](</docs/en/settings-reference#permission-settings>). -## - -​ - -Try the reference container +## Try the reference container The [`anthropics/claude-code`](<https://github.com/anthropics/claude-code/tree/main/.devcontainer>) repository includes an example dev container that combines the CLI, the egress firewall, persistent volumes, and a Zsh-based shell. It is provided as a working example rather than a maintained base image; use it to see how the pieces fit together before applying them to your own configuration. @@ -157,11 +133,7 @@ [`Dockerfile`](<https://github.com/anthropics/claude-code/blob/main/.devcontainer/Dockerfile>)| Base image, development tools, and the Claude Code install [`init-firewall.sh`](<https://github.com/anthropics/claude-code/blob/main/.devcontainer/init-firewall.sh>)| Limits outbound network traffic to the destinations the script allows -## - -​ - -Next steps +## Next steps Once Claude Code is running in your dev container, the pages below cover the rest of an organization rollout: choosing an authentication path, delivering managed policy outside the repository, monitoring usage, and understanding what Claude Code stores and sends.
modified Environment variables View current →
Show diff (110 lines)
--- a/env-vars.md +++ b/env-vars.md @@ -5,19 +5,11 @@ * Look up the variables Claude Code reads * See which features stop working when a variable turns feature-flag fetching off -## - -​ - -Set environment variables +## Set environment variables A variable you set in your shell lasts for that terminal session, while a variable in a settings file applies every time `claude` runs. -### - -​ - -Set variables in your shell +### Set variables in your shell Set the variable before launching `claude`: @@ -56,11 +48,7 @@ echo %API_TIMEOUT_MS% -### - -​ - -Set variables 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`. @@ -84,19 +72,11 @@ See [Settings files](</docs/en/settings#where-settings-live>) for where each file lives and [Settings precedence](</docs/en/settings#settings-precedence>) for how they combine when more than one sets the same variable. -## - -​ - -Precedence +## 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 Set variables in settings files. -## - -​ - -Variables +## Variables Numeric variables such as timeouts, token budgets, and retry counts accept scientific notation and digit-separator spellings in addition to plain digits, except where a variable’s row notes it takes plain digits only. For example, Claude Code reads `2e3` as 2000 and `64_000` as 64000. Before v2.1.211, these spellings could silently set a much smaller value, such as `1e6` setting a timeout to 1. @@ -518,11 +498,7 @@ Standard OpenTelemetry exporter variables (`OTEL_METRICS_EXPORTER`, `OTEL_LOGS_EXPORTER`, `OTEL_EXPORTER_OTLP_ENDPOINT`, `OTEL_EXPORTER_OTLP_PROTOCOL`, `OTEL_EXPORTER_OTLP_HEADERS`, `OTEL_METRIC_EXPORT_INTERVAL`, `OTEL_RESOURCE_ATTRIBUTES`, and signal-specific variants) are also supported. See [Monitoring](</docs/en/monitoring-usage>) for configuration details. Set `CLAUDE_CODE_ENABLE_TELEMETRY` and the OpenTelemetry variables that turn on export, choose its destination, or capture content in your shell, user settings, or managed settings. Claude Code [ignores them in project and local settings](</docs/en/settings-reference#variables-claude-code-ignores-in-env>), apart from the off values that section describes. `OTEL_RESOURCE_ATTRIBUTES` and the export interval, timeout, and compression variables, such as `OTEL_METRIC_EXPORT_INTERVAL`, still apply from project and local settings. -## - -​ - -What the subprocess environment scrub removes +## What the subprocess environment scrub removes When you set `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB` to `1`, Claude Code removes credentials from the environments of the subprocesses it starts, such as Bash commands, hooks, and stdio MCP servers. This reduces what a prompt injection attack can read. The Claude Code process keeps the credentials for its own API calls. The scrub recognizes a credential by its variable name or by the shape of its value, so use it as one layer alongside narrow [permission rules](</docs/en/permissions>) rather than as the only control. The table shows what the scrub does to example variables: @@ -540,11 +516,7 @@ Because the scrub leaves `GITHUB_TOKEN` in place, give a GitHub Actions job the narrowest `permissions` it needs. To remove a GitHub token from sandboxed Bash commands, add a `deny` entry under [`sandbox.credentials`](</docs/en/sandboxing#protect-credentials>). Leave the scrub unset if a subprocess needs one of the removed variables. On Linux, the scrub also runs Bash subprocesses in an isolated PID namespace so they can’t read host process environments through `/proc`. As a side effect, `ps`, `pgrep`, and `kill` can’t see or signal host processes. Before v2.1.251, the scrub removed `ANTHROPIC_API_KEY` and `AWS_SECRET_ACCESS_KEY` and left the table’s other example variables unchanged. -## - -​ - -Features that need feature-flag fetching +## Features that need feature-flag fetching Claude Code turns some features on through feature flags it fetches from Anthropic. Claude Code skips that fetch in these sessions: @@ -570,22 +542,14 @@ * Have Claude [treat large pastes as pasted rather than typed text](</docs/en/terminal-config#how-claude-treats-pasted-text>); the content behind a `[Pasted text #N]` placeholder reaches Claude unmarked * Have Claude Code [exclude MCP tools whose input schema the API would reject](</docs/en/mcp#tools-with-invalid-input-schemas>) -### - -​ - -First session after an install or upgrade +### First session after an install or upgrade In your first session after you install Claude Code, or upgrade to a version that adds a feature, a flag-gated feature can be missing. When Claude Code fetches its feature flags during that session, it saves them on the machine, so your next session on that machine has the feature. In setups such as these, sessions after the first also start without freshly fetched flags: * **A clean environment on every run** : if each run starts in a CI container, or any other environment without the flags an earlier session saved, every run is a first session * **A gateway token with no API key** : if you authenticate with `ANTHROPIC_AUTH_TOKEN` and no API key, and `ANTHROPIC_BASE_URL` points at a host other than Anthropic’s, such as an [LLM gateway](</docs/en/llm-gateway>), Claude Code has no credential to fetch the flags with -## - -​ - -See also +## See also * [Settings](</docs/en/settings>): all `settings.json` configuration, including the `env` key * [CLI reference](</docs/en/cli-reference>): launch-time flags
modified Error reference View current →
Show diff (4259 lines)
--- a/errors.md +++ b/errors.md @@ -2,11 +2,7 @@ Claude Code calls the Claude API for model responses, so most runtime errors map to an underlying API error code. This page covers what each error means inside Claude Code and how to recover. For the raw HTTP status code definitions, see the [Claude Platform error reference](<https://platform.claude.com/docs/en/api/errors>). -## - -​ - -Find your error +## Find your error Match the message you see to a section below. @@ -114,6 +110,7 @@ `A request to MCP server "<name>" was sent without your stored credentials`| Authentication `This server's URL is missing or not a valid URL, so sign-in can't start`| Authentication `Issuer mismatch in authorization response (RFC 9207)`| Authentication +`Stopped an OAuth request`| Authentication `Refusing to send credentials to non-https token endpoint` / `<short-name> from the MCP SDK for <server-url>`| Authentication `Cloud gateway session expired — run /login to reconnect.`| Authentication `Cloud gateway <url> no longer accepts this session`| Authentication @@ -243,6 +240,8 @@ `Ultrareview did not start`| Command-line errors `Remote Control did not start: "<question>" got no answer`| Command-line errors ``<flag>` before `remote-control` is not carried over to the sessions Remote Control starts`| Command-line errors +`Remote Control did not start, because sessions would skip part or all of the --settings file`| Command-line errors +`The settings file <file> has changed since Remote Control started, so this session did not start`| Command-line errors `--sandbox is not supported by claude remote-control` / `--no-sandbox is not supported by claude remote-control`| Command-line errors ``claude import` is not yet available in this build`| Command-line errors `Could not read Claude Code config`| Command-line errors @@ -481,11 +480,7 @@ `bwrap: setting up uid map: Permission denied` / `bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted`| [Sandboxing troubleshooting](</docs/en/sandboxing#bwrap-uid-map-permission-denied>) Responses seem lower quality than usual| Response quality -## - -​ - -Automatic retries +## Automatic retries Claude Code retries transient failures up to 10 times with exponential backoff before showing you an error. It doesn’t always retry a failure that arrives partway through Claude’s response. When you see one of the errors on this page, Claude Code has already made whatever retries apply to that failure. Claude Code retries these failures: @@ -514,19 +509,11 @@ * A non-streaming retry of a failed streaming request that gets a success status but no Claude API message in the body. Claude Code ends the turn with that error. * A request that your organization’s policy check denied, which surfaces as an `API Error:` line carrying the denial message. Your organization’s administrators set up the check with [Inference hooks](<https://platform.claude.com/docs/en/manage-claude/inference-hooks>), a Claude Enterprise feature, and the message ends with the instructions they configured, or by default tells you to contact them. Claude Code doesn’t re-send the denied request to the same model or to a [fallback model](</docs/en/model-config#fallback-model-chains>), because the denial is about the request’s content rather than the model. Before v2.1.239, Claude Code could re-send a denied request, without streaming or on a configured fallback model, before showing you the denial. -### - -​ - -What you see while Claude Code retries or waits +### What you see while Claude Code retries or waits While retrying, the spinner shows a `Retrying in Ns · attempt x/y` countdown after an error label. The label names the specific reason from the first attempt for failures you can act on right away: the network is down, a TLS handshake failed, or you hit a rate limit. For other errors it reads `API error` at first. As of v2.1.198 it switches to the specific reason from the third attempt, or on the final attempt when `CLAUDE_CODE_MAX_RETRIES` allows fewer than three; earlier versions switch only on the final attempt. As of v2.1.198, the usual spinner tip is suppressed during retries. Once the error reason is revealed, if the failure is a 529 overload the line below the countdown also names where to check service status: `status.claude.com` on the Anthropic API, or the provider or gateway host named in the message on other configurations. -#### - -​ - -Waiting for API response +#### Waiting for API response The `Waiting for API response · will retry in … · check your network` banner means that Claude Code has waited at least 20 seconds without receiving any data for a request. The request hasn’t failed yet: the countdown runs to the point where Claude Code aborts the stalled connection. If the abort happens: @@ -536,11 +523,7 @@ The banner clears on its own once data resumes or a retry succeeds. If it reappears on every attempt, treat it as a network issue. If you connect through a gateway, see The waiting banner comes and goes behind a gateway. Before v2.1.185, the banner appeared after 10 seconds with different wording. -#### - -​ - -The waiting banner comes and goes behind a gateway +#### The waiting banner comes and goes behind a gateway If the `Waiting for API response` banner comes and goes while Claude thinks and you connect through a gateway, [update Claude Code](</docs/en/setup#update-claude-code>) to v2.1.309 or later. The banner appears after 45 seconds without data on these connections: @@ -550,11 +533,7 @@ Before v2.1.309, the banner appeared after 20 seconds on these connections. -### - -​ - -Tune retry behavior +### Tune retry behavior You can tune retry behavior with these environment variables: @@ -571,30 +550,18 @@ [`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. For each attempt’s timeout, see How long a non-streaming attempt waits. Requires Claude Code v2.1.285 or later. [`CLAUDE_STREAM_FIRST_BYTE_TIMEOUT_MS`](</docs/en/env-vars>)| unset| Deadline in milliseconds for the first response byte of a streaming request. Requires Claude Code v2.1.242 or later. For how Claude Code picks the deadline when this is unset, see No response from API. -#### - -​ - -How long a non-streaming attempt waits +#### How long a non-streaming attempt waits A non-streaming attempt ends at its request timeout or at the body idle timeout, whichever comes first: * **Request timeout** : `API_TIMEOUT_MS` when you set a positive value, otherwise 300 seconds in a local session. * **[Body idle timeout](</docs/en/network-config#streaming-idle-watchdogs>)** : 5 to 6 minutes without a response, however high you set `API_TIMEOUT_MS`, where it runs and you haven’t turned it off. -## - -​ - -Server errors +## Server errors Most of these errors come from the inference provider: Anthropic’s service on the Anthropic API, and the service behind that provider’s endpoint on Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, or a custom gateway. Auto mode cannot determine the safety of an action and Agent terminated early due to an API error also cover causes on your side, such as an Amazon Bedrock account that can’t invoke the classifier model or a subagent that hit a usage limit. -### - -​ - -API Error: 500 Internal server error +### API Error: 500 Internal server error Claude Code shows the status code and the API’s error message for any 5xx response. The example below shows a 500 response on the Anthropic API: @@ -607,11 +574,7 @@ * If [`ANTHROPIC_BASE_URL`](</docs/en/env-vars>) points at an [LLM gateway](</docs/en/llm-gateway>) and every request fails this way, check that your gateway and its upstream accept [tool search](</docs/en/mcp#tool-search-through-a-gateway>) fields. By default, Claude Code sends `defer_loading` tool fields and `tool_reference` blocks, with the `anthropic-beta` header that enables them. Before v2.1.304, tool search was off behind a gateway unless you turned it on with `ENABLE_TOOL_SEARCH`. * If the error persists with no posted incident, run `/feedback` so Anthropic can investigate with your request details. See Report an error if `/feedback` is unavailable in your environment. -### - -​ - -API Error: Repeated 529 Overloaded errors +### API Error: Repeated 529 Overloaded errors The API is temporarily at capacity across all users. Claude Code has already retried several times before showing this message: @@ -623,11 +586,7 @@ * Try again in a few minutes * Run `/model` and switch to a different model to keep working, since capacity is tracked per model. Claude Code prompts you to do this when one model is under particularly high load, for example `Opus is experiencing high load, please use /model to switch to Sonnet`. On Fable models the message names Fable. In a session the Claude Desktop app runs, such as the Code tab or Cowork, the message reads `Opus is experiencing high load. Switch to Sonnet.` and you switch models with the app’s model picker. -### - -​ - -Request timed out +### Request timed out The API didn’t respond before the connection deadline. @@ -640,11 +599,7 @@ * If a slow network or proxy is the cause, raise `API_TIMEOUT_MS` as described in Automatic retries * If timeouts are frequent and your network is otherwise healthy, see Network and connection errors below -### - -​ - -No response from API +### No response from API Claude Code sent a streaming request, and the API returned no response headers within the deadline for the first byte. Claude Code aborts such a request rather than wait for the full `API_TIMEOUT_MS` request timeout, and sends it again if the retry budget allows. When the deadline passes for the retry too, the turn ends with this message, which shows how long each attempt waited. If you set [`CLAUDE_CODE_RETRY_WATCHDOG`](</docs/en/env-vars>), Claude Code keeps retrying under the budget described in Tune retry behavior instead of ending the turn. @@ -664,11 +619,7 @@ Before v2.1.242, Claude Code waited for the full `API_TIMEOUT_MS` request timeout, 10 minutes by default, before failing an unanswered streaming request. Before v2.1.261, the retry waited the same deadline as the first attempt and the message showed no durations. Before v2.1.307, Claude Code ignored `CLAUDE_STREAM_FIRST_BYTE_TIMEOUT_MS` in a Claude apps gateway session. -### - -​ - -The response above may be incomplete +### The response above may be incomplete A streaming request failed while the response was still in progress, after Claude had completed a block of text or a tool call, or had started one after finishing its thinking. Re-sending the request could run the same tool calls twice, so Claude Code keeps the output Claude completed and appends this notice instead of discarding the turn. Which variant you see names the cause: @@ -706,11 +657,7 @@ * With `--output-format json` or `stream-json`, Claude Code reports this message in the `result` field. * To continue the turn once the connection is stable, resume the session and send `continue` as described in [Continue conversations](</docs/en/headless#continue-conversations>). -### - -​ - -Auto mode cannot determine the safety of an action +### Auto mode cannot determine the safety of an action The model that [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) uses to classify actions couldn’t produce a decision, so auto mode didn’t approve the action automatically. The message you see depends on how the classifier failed. Reads, searches, and edits inside your working directory skip the classifier, so they keep working in all of these cases. When the classifier model is unavailable: @@ -763,11 +710,7 @@ * In an interactive session, approve or deny the action in the prompt that appears * In an interactive session, run `/compact` to reduce the conversation size so subsequent actions fit within the classifier window again -### - -​ - -The server returned no safety verdict +### The server returned no safety verdict Under [server-side classifier review](</docs/en/permission-modes#server-side-classifier-review>), auto mode denies an action when the server gives no verdict for it. The denial names a category in parentheses when Claude Code can determine one, such as `(timed out)`: @@ -794,26 +737,18 @@ Before v2.1.280, Claude Code denied each action from a response without a verdict immediately and never stopped the turn. Before v2.1.302, on a direct connection to the Anthropic API, Claude Code didn’t compact a conversation that had grown too long for the server’s check. -#### - -​ - -`a hook changed this call's input after auto mode reviewed it` +#### `a hook changed this call's input after auto mode reviewed it` This denial means a hook or mod [changed the call’s input](</docs/en/hooks#pretooluse-updatedinput-in-auto-mode>) after the server reviewed it, so the review doesn’t cover what would run. It isn’t a judgment that the action is unsafe. Later calls in the same Claude response can be denied with this reason: - another call in this response was changed by a hook after auto mode reviewed it, or could not be confirmed unchanged + another call in this response was changed after auto mode reviewed it, or could not be confirmed unchanged Claude can then issue each denied call again so the server reviews it. If a permission prompt opens, answer it. You don’t need to do anything else unless Claude says in its reply that auto mode couldn’t check the call. Then stop the change or approve the call yourself, and ask Claude to try the call again: * **Stop the change** : turn off the [hook](</docs/en/hooks#disable-or-remove-hooks>) or [mod](</docs/en/plugins/mods/overview#turn-mods-on-or-off>) that changed the call or an earlier call in the same Claude response, or ask your administrator to turn it off. To look for a hook, run [`/hooks`](</docs/en/hooks#the-%2Fhooks-menu>) at the Claude Code prompt. In a terminal session, run `/plugin` to see the active mods. * **Approve the call yourself** : [switch to Manual mode](</docs/en/permission-modes#switch-permission-modes>) -### - -​ - -Was not reviewed and did not run +### Was not reviewed and did not run A `was not reviewed and did not run` denial means the conversation is too long for the [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) classifier to check the action, so the action didn’t run. Claude Code returns this message to Claude: @@ -829,11 +764,7 @@ * If the compaction the message announces succeeds, you don’t need to do anything. * If you see either of those two messages, run `/compact` at the Claude Code prompt to shorten the conversation yourself. If you turned [auto-compact](</docs/en/settings-reference#autocompactenabled>) off, turn it back on so Claude Code compacts on its own next time. -### - -​ - -Agent terminated early due to an API error +### Agent terminated early due to an API error A [subagent](</docs/en/sub-agents>)’s API request failed terminally, for example because a usage limit was reached or retries for a server error ran out, so the subagent stopped before finishing its task. This message requires Claude Code v2.1.199 or later; before then the API error text was returned to Claude as if it were the subagent’s result. @@ -846,19 +777,11 @@ When a rate limit, overload, or server error interrupts a foreground subagent that already produced text output, Claude receives that partial output marked as incomplete instead of this error. A subagent whose only output was tool calls gets this error too; in v2.1.199 that shape returned an empty partial result instead. See [API errors in subagents](</docs/en/sub-agents#api-errors-in-subagents>). -## - -​ - -Usage limits +## Usage limits Most errors in this section mean a quota tied to your account or plan has been reached. Three work differently: `Server is temporarily limiting requests` is a server-side throttle unrelated to your plan quota, `Usage credits required for 1M context` is an entitlement check rather than an exhausted quota, and `The prompt to confirm went unanswered` means a usage-credits consent prompt closed unanswered, whether or not a quota was reached. -### - -​ - -You’ve hit your session limit +### You’ve hit your session limit Subscription plans include a rolling usage allowance. When it runs out you see one of these messages: @@ -878,11 +801,7 @@ Before a window runs out, Claude Code can warn you that you’ve used most of it, with a message such as `You've used 85% of your session limit · resets 3:45pm`. To watch your remaining allowance, add the `rate_limits` fields to a [custom status line](</docs/en/statusline#rate-limit-usage>), or in the Desktop app click the [usage ring](</docs/en/desktop#check-usage>). -### - -​ - -Usage credits required for 1M context +### Usage credits required for 1M context The selected model uses the 1M-token extended context window, and your plan only includes it through usage credits. @@ -897,11 +816,7 @@ Before v2.1.268, the message ended with `run /usage-credits to turn them on, or /model to switch to standard context` and didn’t mention restarting. -### - -​ - -The prompt to confirm went unanswered +### The prompt to confirm went unanswered When the [Fable usage-credits consent prompt](</docs/en/model-config#fable-and-usage-credits>) closes with nobody answering it, Claude Code ends the turn with one of these messages: @@ -916,11 +831,7 @@ Before v2.1.236, this message didn’t appear: while a Remote Control client was connected, Claude Code waited 60 seconds for an answer and then continued the turn on your default model. -### - -​ - -Server is temporarily limiting requests +### Server is temporarily limiting requests The API applied a short-lived throttle that is unrelated to your plan quota. @@ -931,11 +842,7 @@ * Wait briefly and try again * Check [status.claude.com](<https://status.claude.com>) if it persists -### - -​ - -Request rejected (429) +### Request rejected (429) You have hit the rate limit configured for your API key, Amazon Bedrock project, or Google Cloud project. @@ -948,11 +855,7 @@ * For Anthropic API keys, see the [rate limits reference](<https://platform.claude.com/docs/en/api/rate-limits>) for how tiers work and how to set per-workspace caps * Reduce concurrency: avoid running many parallel subagents, or switch to a smaller model with `/model` for high-volume scripted runs -### - -​ - -You’ve hit your monthly spend limit +### You’ve hit your monthly spend limit Your plan’s included usage can’t cover this request, and the [usage credits](<https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans>) that would otherwise pay for it have reached a spend limit. That happens when one of your plan’s usage windows has run out, or when the request is one that only usage credits pay for, such as a request to a model that [bills to usage credits](</docs/en/model-config#fable-and-usage-credits>). The message names whose limit blocked you. The text after the `·` says how to get that limit increased, and varies with your plan and whether you manage billing: @@ -970,11 +873,7 @@ * If the message names a reset time for your plan’s window, you can wait for it instead * Run `/usage` to see your plan’s windows and when each resets -### - -​ - -Spend limit reached +### Spend limit reached You connect through a [Claude apps gateway](</docs/en/claude-apps-gateway>) and have reached a [spend cap](</docs/en/claude-apps-gateway-spend-limits>) your gateway operator set. The gateway blocks your requests until the operator raises the cap, or until the cap resets if it’s above $0. It marks each blocked `429` response `x-should-retry: false`, so in the terminal Claude Code shows this message without retrying. @@ -996,11 +895,7 @@ A related message, `spend limit unavailable`, means the gateway could not read its spend records and blocked the request as a precaution rather than over your cap. It usually clears on its own; if it persists, tell your gateway operator. -### - -​ - -Credit balance is too low +### Credit balance is too low Your Console organization has run out of prepaid credits, or Claude Code is sending your requests with a Console API key when you meant to use your subscription. @@ -1012,11 +907,7 @@ * Add credits at [platform.claude.com/settings/billing](<https://platform.claude.com/settings/billing>), and consider enabling auto-reload there so the balance refills before it hits zero * Set per-workspace spend caps in the Console to prevent a single project from draining the org balance. See [Manage costs effectively](</docs/en/costs>). -### - -​ - -Could not update your spend limit +### Could not update your spend limit The server rejected a spend limit change you made from the prompt that appears when you reach your spend limit. @@ -1028,19 +919,11 @@ * If the message shows only the generic form, retry; the failure may be transient * If the change keeps failing, make it from your [claude.ai billing settings](<https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans>) in the browser instead -## - -​ - -Authentication errors +## Authentication errors These errors mean Claude Code cannot prove who you are to the API. Run `/status` at any time to see which credential is currently active. -### - -​ - -Not logged in +### Not logged in No valid credential is available for this session. @@ -1056,11 +939,7 @@ If you are prompted to log in repeatedly, see [Not logged in or token expired](</docs/en/troubleshoot-install#not-logged-in-or-token-expired>) for system clock checks and macOS credential-storage recovery steps. -### - -​ - -Could not resolve authentication method +### Could not resolve authentication method The session reached the API client without any credential. [Background sessions](</docs/en/agent-view>) and cloud sessions show this message when the worker starts without a credential. Interactive, `-p`, and Agent SDK runs report the same condition as Not logged in and write this string only to their debug log, so if you found it there, follow that entry instead. @@ -1073,11 +952,7 @@ * For the Agent SDK, see [authentication setup in the quickstart](</docs/en/agent-sdk/quickstart#setup>) * Run `/status` in an interactive session in the same environment to confirm which credential source resolves -### - -​ - -Invalid API key +### Invalid API key The `ANTHROPIC_API_KEY` environment variable or `apiKeyHelper` script returned a key the API rejected, or Claude Code blocked a key from `ANTHROPIC_API_KEY` before sending it. @@ -1091,11 +966,7 @@ * If the key comes from an [`apiKeyHelper`](</docs/en/settings-reference#apikeyhelper>) script, run the script directly to confirm it prints a valid key on stdout * Run `/status` to confirm which credential source Claude Code is actually using -### - -​ - -Your apiKeyHelper script is failing +### Your apiKeyHelper script is failing Claude Code ran the command in your [`apiKeyHelper`](</docs/en/settings-reference#apikeyhelper>) setting and didn’t get a key back. Without one, the request reaches the API with a placeholder credential, and the API rejects it with `401`. The `Authentication` panel in the terminal shows which of these happened: @@ -1113,11 +984,7 @@ * Run `/status` to see the failure and confirm `apiKeyHelper` is the active credential source. The `apiKeyHelper` row shows `Failing` with the last failure’s detail, such as the exit code and the command’s error output, and disappears after the next successful run. Before v2.1.274, `/status` showed only the credential source, not the failure. * Each time the command fails, its exit code and error output also appear in an `Authentication` panel in the terminal. Before v2.1.212, the panel was titled `Cloud authentication`. -### - -​ - -Claude Code didn’t send your claude.ai login +### Claude Code didn’t send your claude.ai login These messages mean Claude Code refused your request and didn’t send your claude.ai login: @@ -1135,11 +1002,7 @@ Before v2.1.315, a refused prompt or file upload printed one message that began `Claude Code didn't send your claude.ai login`. -### - -​ - -Invalid request header value +### Invalid request header value A value Claude Code was about to send as a request header contains a character that HTTP headers can’t carry: a line break, a NUL byte, or a character above `U+00FF`, such as a curly quote or a zero-width space. Claude Code stops the request before anything is sent and names the variable or setting to fix. The usual cause is a credential pasted from a document or chat that carried an invisible character or a stray line break. Claude Code runs this check when it sends requests to the Claude API directly or through an [LLM gateway](</docs/en/llm-gateway>). On a third-party cloud provider such as [Amazon Bedrock](</docs/en/amazon-bedrock>), Claude Code doesn’t run it before sending. @@ -1163,11 +1026,7 @@ * For `ANTHROPIC_CUSTOM_HEADERS`, keep one `Name: Value` pair per line and rewrite the pair the message counts * Run `/status` to confirm which credential source is active -### - -​ - -This organization has been disabled +### This organization has been disabled Claude Code is using a stale `ANTHROPIC_API_KEY` from a disabled Console organization. When you have a saved subscription login, the key overrides it. @@ -1182,11 +1041,7 @@ * Run `/status` afterward to confirm the active credential is your subscription * If no environment variable is set and the error persists, contact support or sign in with a different account. -### - -​ - -Your organization has disabled API key authentication +### Your organization has disabled API key authentication This message requires Claude Code v2.1.169 or later. Your Console organization’s admin has turned off API key authentication, so the API rejects the key Claude Code is sending. The recovery hint after the `·` varies by where the key came from: @@ -1204,11 +1059,7 @@ * Run `/status` afterward to confirm the active credential is your subscription rather than an API key * If you need API key authentication for automation, ask your organization admin to re-enable it in the Console -### - -​ - -Your organization has disabled Claude subscription access +### Your organization has disabled Claude subscription access Your Claude organization doesn’t allow signing in to Claude Code with a subscription login. Running `/login` again with the same account returns the same error. @@ -1220,11 +1071,7 @@ * Authenticate with a Console API key instead of your subscription. See [Claude Console authentication](</docs/en/authentication#claude-console-authentication>) for setup. * If you are the admin and do not see an option to enable access, contact [Anthropic support](<https://support.claude.com>) -### - -​ - -Scheduled tasks are off for your organization +### Scheduled tasks are off for your organization [Cloud scheduled tasks](</docs/en/routines>) are off for your organization, so you can’t create or run them. The message from claude.ai calls them scheduled tasks or routines, and a sentence about your admin follows: @@ -1235,11 +1082,7 @@ * Ask your Team or Enterprise Owner whether they can turn on the toggle labeled **Scheduled tasks (Was Routines)** or **Routines** at [**Organization settings > Capabilities > Remote sessions**](<https://claude.ai/admin-settings/capabilities>) -### - -​ - -Remote Control requires the Anthropic API +### Remote Control requires the Anthropic API The session isn’t talking to the Anthropic API directly, which [Remote Control](</docs/en/remote-control>) requires. @@ -1258,11 +1101,7 @@ * If the variable isn’t set in your shell, check the `env` key in your [settings files](</docs/en/settings#where-settings-live>), which applies environment variables to every session * For this and the other Remote Control startup messages, see [Troubleshoot Remote Control](</docs/en/remote-control#troubleshooting>) -### - -​ - -Remote Control couldn’t refresh your login +### Remote Control couldn’t refresh your login Claude Code runs a live [Remote Control](</docs/en/remote-control>) connection on short-lived credentials that it obtains and renews using your saved claude.ai login. When claude.ai stops accepting that login, or Claude Code has no saved login left, Claude Code stops Remote Control and needs you to sign in again. Either failure can happen while Claude Code is still connecting or later, when it renews the credentials. When Claude Code asks the login service to refresh your saved login and gets no answer, it keeps Remote Control running and tries the refresh again while the connection’s current credential is still valid. A refresh gets no answer when Claude Code can’t reach the login service, the request times out, or the service fails without rejecting your login. If the login service still isn’t answering when that credential expires, Claude Code stops Remote Control and reports `OAuth token refresh failed`. When Claude Code stops Remote Control, it shows the reason in a warning and in a transcript line that starts with `Remote Control disconnected`. Your local session keeps running without Remote Control. This section covers these lines: @@ -1289,11 +1128,7 @@ Before v2.1.224, `OAuth token refresh failed — run /login to re-authenticate` read `OAuth token refresh failed — re-authenticate, then re-enable Remote Control`, and `JWT refresh failed: no OAuth token — run /login` read `no OAuth token available for recovery (code <N>)`. The `Claude.ai login expired`, `Claude.ai login was rejected`, and `OAuth token unavailable` messages were added in v2.1.225. Before v2.1.238, Claude Code reported the cases that now say `Signed out of Claude` as `JWT refresh failed: no OAuth token — run /login`, and stopped Remote Control with `Claude.ai login expired — run /login to restore Remote Control` as soon as one login refresh got no answer. -### - -​ - -Remote Control could not renew this computer’s connection +### Remote Control could not renew this computer’s connection This warning appears in the terminal running [`claude remote-control`](</docs/en/remote-control#start-a-remote-control-session>) when the server can’t use your claude.ai login to renew its connection’s credential before it expires. The warning’s last sentence says how long the current credential still works, or that it has already expired: @@ -1304,11 +1139,7 @@ * If the warning tells you to run `claude /login`, open another terminal on the machine running the server, run `claude /login` there, and sign in with your claude.ai account * If the server still can’t sign in once the connection’s credential has expired, it prints an error containing `Poll: Authentication failed (401)` and stops. Sign in again as the warning’s second sentence says, then run `claude remote-control` again in the terminal where the server stopped. -### - -​ - -Remote Control stopped because the signed-in account changed +### Remote Control stopped because the signed-in account changed Claude Code shows this line during a [Remote Control](</docs/en/remote-control>) session when you sign in to a different claude.ai account or organization on this machine. You made the switch outside the Claude Code session, for example by running `/login` in another terminal. A Remote Control session that you started while signed in through `/login` belongs to the claude.ai account and organization that were signed in at the time. @@ -1321,11 +1152,7 @@ Before v2.1.234, Claude Code didn’t notice when you switched to a different account or organization outside the Claude Code session. Claude Code kept the Remote Control session connected until a later request to the Remote Control server failed with `Remote Control server rejected the request (HTTP 404)`. That failure could come hours after the switch. -### - -​ - -Remote Control stopped because the app running the session signed out or switched accounts +### Remote Control stopped because the app running the session signed out or switched accounts When the Claude desktop app or an IDE hosts your session, Claude Code gets its login token from that app rather than from `/login`. When claude.ai rejects that token, Claude Code asks the app for a new one. If the app answers that it’s signed out, or that it’s now signed in to a different Claude account, Claude Code ends the [Remote Control](</docs/en/remote-control>) session and sends the app one of these lines: @@ -1339,11 +1166,7 @@ Before v2.1.238, Claude Code sent the app the `run /login` messages listed under Remote Control couldn’t refresh your login in both cases. -### - -​ - -OAuth token revoked or expired +### OAuth token revoked or expired Your saved login is no longer valid. A revoked token means you signed out everywhere or an admin removed access; an expired token means the automatic refresh failed mid-session. Both messages report a rejection the API returned for a request Claude Code sent. When the saved login has already been cleared after a failed refresh, you see Login expired instead. If you authenticate with a long-lived token in [`CLAUDE_CODE_OAUTH_TOKEN`](</docs/en/env-vars>), you see the same messages when that token expires or is revoked. @@ -1363,11 +1186,7 @@ * For repeated prompts to log in across launches, see the system clock checks and macOS credential-storage recovery steps in [Troubleshooting](</docs/en/troubleshoot-install#not-logged-in-or-token-expired>) * For other failures including `403 Forbidden` and OAuth browser issues, see [Login and authentication](</docs/en/troubleshoot-install#login-and-authentication>) -### - -​ - -API Error: 401 Invalid authentication credentials +### API Error: 401 Invalid authentication credentials The API recognized the format of your credential but rejected the account or organization behind it. Anthropic returns this message when a credential was recently revoked, when an organization was disabled or removed your access, or when the account itself was deactivated, so an expired token isn’t the cause. The credential can be your saved login or an approved `ANTHROPIC_API_KEY`, and the fix differs, so start by running `/status` to see which one is active. @@ -1381,11 +1200,7 @@ * If [`ANTHROPIC_BASE_URL`](</docs/en/env-vars>) points at an [LLM gateway](</docs/en/llm-gateway>), the text after `401` is your gateway’s message rather than Anthropic’s, and `/login` doesn’t change it. Fix the credential your gateway expects instead. * If every request fails with a `401` once your gateway has the credential it expects, check that the gateway and its upstream accept [tool search](</docs/en/mcp#tool-search-through-a-gateway>) fields. By default, Claude Code sends `defer_loading` tool fields and `tool_reference` blocks, with the `anthropic-beta` header that enables them. Before v2.1.304, tool search was off behind a gateway unless you turned it on with `ENABLE_TOOL_SEARCH`. -### - -​ - -Login expired +### Login expired Claude Code tried to renew your saved claude.ai login and the OAuth service rejected the stored refresh token, so Claude Code cleared the saved credentials. After that, each model request stops locally with this message before it reaches the API, because only `/login` can create new credentials. Before v2.1.206, Claude Code sent the model request anyway with whatever credential remained in the environment, and every model then failed with There’s an issue with the selected model or a 401 instead of a prompt to sign in. @@ -1402,11 +1217,7 @@ * In non-interactive mode, run `claude` in the same environment, complete `/login`, then rerun your command. For automation that can’t sign in interactively, authenticate with `ANTHROPIC_API_KEY` or [generate a long-lived token with `claude setup-token`](</docs/en/authentication#generate-a-long-lived-token>). * If signing in keeps failing, see [Login and authentication](</docs/en/troubleshoot-install#login-and-authentication>) -### - -​ - -Could not refresh your login because another Claude Code process is refreshing it +### Could not refresh your login because another Claude Code process is refreshing it This message doesn’t mean your login was rejected. Your saved claude.ai login had expired and needed renewing. Another Claude Code process on the same machine held the shared refresh lock, or exited and left it behind, and the refresh made no progress while this session waited. Claude Code stops the request before sending it: @@ -1422,11 +1233,7 @@ * If the message keeps returning, close other Claude Code windows and processes, then retry. * If it returns with no other Claude Code process running, run `/login`. Signing in again doesn’t wait on the refresh lock. -### - -​ - -Could not refresh your login: the disk that holds the Claude Code config directory is full +### Could not refresh your login: the disk that holds the Claude Code config directory is full Free space on the disk that holds the Claude Code config directory, then send your message again. Signing in wouldn’t help while the disk is full, because a new login couldn’t be saved. The config directory is `~/.claude` in your home directory unless you set [`CLAUDE_CONFIG_DIR`](</docs/en/env-vars>). @@ -1441,11 +1248,7 @@ * For a script, rerun its `claude -p` command * If the disk already shows free space, running out of disk quota or of inodes produces the same message. Delete your own files on that disk. If the message returns, delete many small files rather than a few large ones, because each file takes one inode whatever its size. -### - -​ - -Couldn’t save your login +### Couldn’t save your login You signed in with claude.ai, but Claude Code couldn’t save the login to its credential store, so the login didn’t complete. On macOS this can happen when the login keychain locks, for example on sleep or idle, after Claude Code has already read or saved credentials in it during the same session. @@ -1458,11 +1261,7 @@ * On other platforms, run `/login` again * If the login still doesn’t save, see [Not logged in or token expired](</docs/en/troubleshoot-install#not-logged-in-or-token-expired>) for the keychain unlock command and other credential-storage recovery steps -### - -​ - -Sign in again to take your previous account or API key off the config file +### Sign in again to take your previous account or API key off the config file This warning after you sign in means any account you were signed in with before may still be stored in [`~/.claude.json`](</docs/en/claude-directory#ce-claude-json>): @@ -1472,11 +1271,7 @@ * Run `claude auth login` in your shell to sign in again. Claude Code then retries the save that takes the replaced account or API key off the file. -### - -​ - -Your account or API key may still be in the config file +### Your account or API key may still be in the config file You ran `/logout` or `claude auth logout`, and Claude Code signed this process out but couldn’t confirm that [`~/.claude.json`](</docs/en/claude-directory#ce-claude-json>) no longer holds your account. Either the save didn’t land, or the file couldn’t be read back to check. @@ -1486,11 +1281,7 @@ * Run `claude auth logout` in your shell to try the save again. When the save goes through, the command prints `Successfully logged out from your Anthropic account.` -### - -​ - -Couldn’t start the local listener that receives the browser sign-in +### Couldn’t start the local listener that receives the browser sign-in Each of these messages from `/login`, `claude auth login`, or `claude setup-token` means Claude Code couldn’t open the port on `127.0.0.1` where your browser returns the sign-in result. With the notice that begins `The browser can't return the sign-in to Claude Code automatically`, the sign-in continues without that port. No browser opens, and the notice appears above a URL where you sign in instead: @@ -1509,11 +1300,7 @@ Before v2.1.305, the sign-in stopped as soon as the port couldn’t be opened and showed no URL to sign in at. The message read, for example, `Failed to start OAuth callback server: Failed to start server. Is port 0 in use?`. On those versions, update Claude Code and sign in again, or sign in with a token or API key instead of the browser. -### - -​ - -Claude login not accepted +### Claude login not accepted You tried to start a [cloud session](</docs/en/claude-code-on-the-web>), and the server refused to create it with a 401: it didn’t accept the Claude login this machine sent, usually because the login expired or was revoked. The first part of the line is the server’s own reason when it gives one. Otherwise the line reads: @@ -1523,11 +1310,7 @@ * Run `/login`, complete the sign-in, then start the session again -### - -​ - -Artifacts need a claude.ai login +### Artifacts need a claude.ai login Claude Code refused an [artifact](</docs/en/artifacts>) publish or read because the session has no claude.ai login it can use for artifacts. Every form of the message starts with the same words, followed by a remedy that depends on how your session authenticates. With no competing credential it reads: @@ -1541,11 +1324,7 @@ * When the message says the credential is injected by the session’s host environment, you can’t change it in that session; start a session that is signed in to claude.ai * See [Availability](</docs/en/artifacts#availability>) for the other requirements artifacts have, such as plan, model provider, and organization policy -### - -​ - -Administrator policy requires a Cloud gateway sign-in +### Administrator policy requires a Cloud gateway sign-in An administrator’s [managed settings](</docs/en/managed-settings>) on this machine set [`forceLoginMethod`](</docs/en/settings-reference#forceloginmethod>) to `"gateway"` or set [`forceLoginGatewayUrl`](</docs/en/settings-reference#forcelogingatewayurl>). Unless you select a cloud provider through a variable such as `CLAUDE_CODE_USE_BEDROCK`, Claude Code then accepts only the [Claude apps gateway](</docs/en/claude-apps-gateway>) sign-in. You see one of two messages: @@ -1565,11 +1344,7 @@ Before v2.1.284, the startup message listed the possible credentials instead of naming the configured one. It began `Administrator policy requires a Cloud gateway sign-in on this machine; the Anthropic-issued credential configured here (ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, or apiKeyHelper) is not used.` If you see that wording and can’t tell which credential to remove, update to v2.1.284 or later and start `claude` again. On v2.1.265, a regression also showed the first message in some LLM-gateway and proxy configurations that authenticate with an API key, `apiKeyHelper`, or custom headers, even with no administrator requirement on the machine. Update to v2.1.266 or later. You don’t need to change your configuration. Before v2.1.261, on machines that set `forceLoginMethod` to `"gateway"`, Claude Code used a leftover saved login instead of failing model requests, and reported a configured environment credential with `This machine's managed settings require a first-party login` instead of the startup message. -### - -​ - -Your account is on hold +### Your account is on hold The Claude account behind your login has been suspended. Claude Code shows the first message when it tries to renew your saved login and learns of the hold, and the second when a sign-in you complete in the browser reports it: @@ -1581,11 +1356,7 @@ * Open the link in the message to view the hold’s details or appeal it * If you have another Claude account or an API key that isn’t affected by the hold, you can keep working while the hold is resolved: run `/login` with that account, or set the key with `ANTHROPIC_API_KEY` -### - -​ - -Anthropic profile login expired +### Anthropic profile login expired Claude Code is authenticating through an Anthropic credential profile whose saved login credential has expired, and the profile holds no refresh credential Claude Code can use to renew it. Claude Code stops each request locally without retrying. @@ -1608,11 +1379,7 @@ This appears only when the active credential comes from an Anthropic credential profile, one you select with the `ANTHROPIC_PROFILE` environment variable, that Claude Code discovers as the active profile in your Anthropic configuration directory, or that Claude Code wrote when you [signed in without an API key](</docs/en/authentication#sign-in-without-an-api-key>). Sessions that authenticate with an API key, a bearer token such as `ANTHROPIC_AUTH_TOKEN`, or a third-party provider never see this message. -### - -​ - -OAuth scope requirement +### OAuth scope requirement The stored token predates a permission scope that a newer feature needs: @@ -1622,11 +1389,7 @@ * Run `/login` to get a new token with the current scopes. You don’t need to log out first. -### - -​ - -claude.ai rejected the session token +### claude.ai rejected the session token A [claude.ai connector](</docs/en/mcp#use-mcp-servers-from-claude-ai>) request failed because claude.ai rejected the token from your Claude Code login. The rejected token is your login, not the connector’s own authorization in claude.ai, so authorizing the connector again doesn’t resolve it. In `/mcp`, the connector shows as `session token rejected` and its detail view reads: @@ -1639,11 +1402,7 @@ Before v2.1.222, Claude Code marked the connector as needing authentication instead, which pointed you at the connector’s authorization flow even though completing it didn’t resolve the state. -### - -​ - -MCP server needs you to sign in again +### MCP server needs you to sign in again A remote [MCP server](</docs/en/mcp>) rejected the credential on a tool call mid-session, usually because a sign-in or token expired or because the token lacks a permission the tool needs. The tool call fails, and `/mcp` marks the server as [needing authentication](</docs/en/mcp#authenticate-with-remote-mcp-servers>). For a server you sign in to from Claude Code, including a claude.ai connector, the sign-in expired or was revoked: @@ -1671,11 +1430,7 @@ Run `/mcp`, select the server, and authenticate again from its menu. When the server’s configuration sets neither [`oauth.scopes`](</docs/en/mcp#restrict-oauth-scopes>) nor [`authServerMetadataUrl`](</docs/en/mcp#override-oauth-metadata-discovery>), Claude Code requests the scope the server named. With either setting, Claude Code requests that setting’s scopes instead. If you pinned `oauth.scopes`, add the missing scope to that list before you authenticate again. Before v2.1.274, this case showed the `needs you to sign in again` message, and before v2.1.273 it showed `requires re-authorization (token expired)` like the other cases. -### - -​ - -Couldn’t read the stored credentials for MCP server +### Couldn’t read the stored credentials for MCP server Claude Code keeps your sign-ins for OAuth [MCP servers](</docs/en/mcp>) in a credential store. This message means Claude Code couldn’t read that store, so a request to the server didn’t run: @@ -1702,11 +1457,7 @@ Before v2.1.307, a `claude -p` or Agent SDK run on a Mac with a locked login keychain reported the server as needing authentication instead of showing either message. -### - -​ - -MCP server URL is missing or not a valid URL +### MCP server URL is missing or not a valid URL Claude Code refused to start an OAuth sign-in for a remote MCP server because the server’s configured `url` doesn’t parse as a URL. Unless Claude Code has a more specific configuration problem to report for the server, running [`claude mcp login <name>`](</docs/en/mcp#authenticate-from-the-command-line>) in your shell prints the refusal as: @@ -1716,11 +1467,7 @@ * Set the entry’s `url` to the server’s real endpoint where the server is configured, or set the environment variable that its [`${VAR}` reference](</docs/en/mcp#environment-variable-expansion-in-mcp-json>) names, then run the sign-in again. -### - -​ - -Issuer mismatch in authorization response +### Issuer mismatch in authorization response During an [MCP OAuth sign-in](</docs/en/mcp#authenticate-with-remote-mcp-servers>), the authorization server redirected back to Claude Code with an `iss` parameter that doesn’t name the issuer that Claude Code expected from the server’s OAuth metadata. A wrong issuer at this step is how an authorization server mix-up attack looks, so Claude Code fails the sign-in instead of exchanging the authorization code. Claude Code shows the error in the `/mcp` server menu after the browser sign-in: @@ -1734,11 +1481,18 @@ Before v2.1.232, Claude Code used the v2 runtime only in a gradual rollout or when you set `MCP_SDK_GENERATION=v2`. -### - -​ - -Refusing to send credentials to non-https token endpoint +### Stopped an OAuth request + +This message means that Claude Code stopped an [OAuth request for an MCP server](</docs/en/mcp#authenticate-with-remote-mcp-servers>) because an OAuth endpoint redirected it. In both forms of the message, the first address is the one that sent the redirect: + + Stopped an OAuth request, which can hold secrets: https://auth.example.com redirected it to https://other.example.com. Ask the owner of https://auth.example.com to remove that redirect. + Stopped an OAuth request: https://auth.example.com redirected it more than 5 times. Ask the owner of https://auth.example.com to fix those redirects. + +**What to do:** + + * Ask whoever runs the first address, such as the MCP server’s operator, to remove or fix the redirect. Then try again from `/mcp`. + +### Refusing to send credentials to non-https token endpoint On the [v2 runtime](</docs/en/mcp#mcp-client-runtimes>), Claude Code sends an [MCP OAuth](</docs/en/mcp#authenticate-with-remote-mcp-servers>) token request only to a token endpoint served over HTTPS or at `localhost`, `127.0.0.1`, or `::1`. This message means the server’s token endpoint is neither, so Claude Code stopped before sending the request. That happens after the browser sign-in, so the browser step succeeds first, and again whenever Claude Code refreshes the server’s token. In its full form, the message comes from the MCP SDK and quotes the token endpoint it refused. In the debug log, it follows `Error during auth completion:` for a sign-in or `Token refresh failed:` for a refresh. In your shell, `claude mcp login <name>` prints it after `Couldn't complete authentication for "<name>":`, and in a session, `/mcp` shows it under the server’s menu: @@ -1749,11 +1503,7 @@ * Serve that token endpoint over HTTPS, for example by putting the server behind a reverse proxy or tunnel that terminates TLS and configuring the server to advertise the `https://` address * To connect without changing the server, start Claude Code with [`MCP_SDK_GENERATION=v1`](</docs/en/env-vars>), whose [runtime](</docs/en/mcp#mcp-client-runtimes>) doesn’t apply this rule and sends the token request over plain HTTP. That choice lasts until you exit and applies to every server. The v1 runtime also skips the issuer check, so prefer serving the endpoint over HTTPS -### - -​ - -AWS credentials expired or invalid +### AWS credentials expired or invalid Your AWS session token expired or was rejected. This message appears on a 401 from [Claude Platform on AWS](</docs/en/claude-platform-on-aws>) or the [Mantle endpoint](</docs/en/amazon-bedrock#use-the-mantle-endpoint>), which is how those providers report an expired security token. The action hint in the middle varies with your setup. The stable part is the leading `AWS credentials expired or invalid`: @@ -1766,11 +1516,7 @@ * With `awsAuthRefresh` set in an interactive session, you can instead run `/login`, choose **3rd-party platform** , then select **Claude Platform on AWS · refresh credentials** under **Using 3rd-party platforms** to run the same command without restarting Claude Code. See [Configure AWS credentials](</docs/en/claude-platform-on-aws#1-configure-aws-credentials>) * If the error repeats after the refresh command succeeds, confirm the identity is valid outside Claude Code with `aws sts get-caller-identity` in the same shell and profile -### - -​ - -AWS authentication failed +### AWS authentication failed Your AWS provider returned a 403, or [Amazon Bedrock](</docs/en/amazon-bedrock>) returned a 401. Amazon Bedrock reports an expired security token as a 403, but a 403 is also how it reports an authorization denial, such as an `AccessDeniedException` from a missing IAM permission. Claude Code can’t tell those two causes apart. A 401 from Amazon Bedrock also lands here rather than under AWS credentials expired or invalid, because Amazon Bedrock doesn’t report an expired token as a 401. A 401 from that endpoint typically comes from something else in the request path, such as a corporate proxy. A credential refresh fixes an expired token and can’t fix the other causes, so the message offers both: @@ -1783,11 +1529,7 @@ * If your credentials are current, confirm the IAM permissions in [IAM configuration](</docs/en/amazon-bedrock#iam-configuration>) are attached to the identity you’re using and that the selected model is enabled for your account and region * Run `aws sts get-caller-identity` to confirm which identity your requests use -### - -​ - -Google Cloud credentials expired or invalid +### Google Cloud credentials expired or invalid Your Google Cloud credentials for [Google Cloud’s Agent Platform](</docs/en/google-vertex-ai>) expired or were rejected: the request returned a 401, which is how Agent Platform reports credential expiry. The action hint in the middle varies with your setup. The stable part is the leading `Google Cloud credentials expired or invalid`: @@ -1803,11 +1545,7 @@ Before v2.1.273, a 401 from Agent Platform showed the generic `Please run /login` or `Failed to authenticate` message instead, which can’t refresh Google Cloud credentials. -### - -​ - -Google Cloud authentication failed +### Google Cloud authentication failed [Google Cloud’s Agent Platform](</docs/en/google-vertex-ai>) returned a 403, which it uses for authorization denials rather than expired credentials. Usually the identity you authenticate with is missing an IAM permission, or the model isn’t enabled for your project. The action hint in the middle varies with your setup. The stable part is the leading `Google Cloud authentication failed`: @@ -1821,11 +1559,7 @@ Before v2.1.273, a 403 from Agent Platform showed the generic `Please run /login` or `Failed to authenticate` message instead, which can’t refresh Google Cloud credentials. -### - -​ - -Microsoft Foundry authentication failed +### Microsoft Foundry authentication failed [Microsoft Foundry](</docs/en/microsoft-foundry>) returned a 401 or 403: the Azure credential on the request was rejected, or the identity behind it doesn’t have access to the Foundry resource. `/login` can’t mint Azure credentials. The action hint in the middle varies with your setup. The stable part is the leading `Microsoft Foundry authentication failed`: @@ -1839,11 +1573,7 @@ Before v2.1.273, a 401 or 403 from Microsoft Foundry showed the generic `Please run /login` or `Failed to authenticate` message instead, which can’t refresh Azure credentials. -### - -​ - -Could not load AWS or Google Cloud credentials +### Could not load AWS or Google Cloud credentials Claude Code couldn’t obtain usable credentials from the AWS credential provider chain or from your Google application default credentials on the machine it runs on, so no request reached your cloud provider. The detail after the `·` names the specific cause, such as an expired SSO session, missing application default credentials reported as `Could not load the default credentials`, or a revoked sign-in reported as `invalid_grant`: @@ -1855,11 +1585,7 @@ * Run your provider’s sign-in command, such as `aws sso login --profile myprofile` or `gcloud auth application-default login`, then retry. [Bedrock, Agent Platform, or Foundry credentials not loading](</docs/en/troubleshoot-install#bedrock-agent-platform-or-foundry-credentials-not-loading>) shows how to confirm the credentials outside Claude Code * If the detail reads `AWS default-chain credential resolve timed out`, the chain hung rather than failed, so follow AWS default-chain credential resolve timed out instead -### - -​ - -AWS default-chain credential resolve timed out +### AWS default-chain credential resolve timed out The AWS default credential provider chain didn’t produce credentials within 60 seconds, so Claude Code stopped the resolve and failed the request. This timeout is one cause of Could not load AWS or Google Cloud credentials. The failure is local credential resolution: the request never reached [Amazon Bedrock](</docs/en/amazon-bedrock>), [Claude Platform on AWS](</docs/en/claude-platform-on-aws>), or the [Mantle endpoint](</docs/en/amazon-bedrock#use-the-mantle-endpoint>). Claude Code clears its [credential cache](</docs/en/amazon-bedrock#credential-caching-and-resolution-timeout>) and retries before this error surfaces, so by the time you see it the chain has stalled on repeated attempts. @@ -1871,11 +1597,7 @@ * Complete the sign-in step before starting Claude Code, for example `aws sso login --profile myprofile` * If your chain runs an interactive sign-in that legitimately needs more than 60 seconds, such as SSO with MFA through a wrapper like `aws-vault`, raise the limit in milliseconds with [`CLAUDE_CODE_AWS_CHAIN_RESOLVE_TIMEOUT_MS`](</docs/en/env-vars>) -### - -​ - -Bedrock setup verification timed out waiting for AWS +### Bedrock setup verification timed out waiting for AWS A call to AWS during the [Bedrock setup wizard](</docs/en/amazon-bedrock#sign-in-with-bedrock>)’s credential verification, such as the credential lookup or the identity check, didn’t finish within the 60-second limit. The wizard stops waiting and fails the verification step: @@ -1891,11 +1613,7 @@ * Complete any interactive sign-in before opening the wizard, for example `aws sso login --profile myprofile` * If a credential helper in your AWS profile legitimately needs longer than 60 seconds to prompt you, raise the limit in milliseconds with [`CLAUDE_CODE_AWS_CHAIN_RESOLVE_TIMEOUT_MS`](</docs/en/env-vars>) -### - -​ - -Cloud gateway session expired +### Cloud gateway session expired You signed in through a [Claude apps gateway](</docs/en/claude-apps-gateway>), and the gateway session saved on this machine has expired and couldn’t be renewed, or the gateway no longer accepts it, for example after the gateway’s [JWT secret is replaced](</docs/en/claude-apps-gateway-deploy#jwt-secret-rotation>). If you see this line when you start `claude` interactively, the session has opened signed out of the gateway: @@ -1910,11 +1628,7 @@ * Run `/login` in the session and complete the browser sign-in * For a non-interactive launch, start `claude` in the same environment, run `/login`, then rerun your command -### - -​ - -Sign-in timed out while waiting for you to continue +### Sign-in timed out while waiting for you to continue During a [Claude apps gateway](</docs/en/claude-apps-gateway>) sign-in, the gateway named the account that signed in, and Claude Code asked you to confirm it before saving the credential. You left the confirmation open past the sign-in’s own expiry, and the gateway issued no refresh token that could renew it, so Claude Code stored nothing when you continued: @@ -1924,11 +1638,7 @@ * Run `/login` again and confirm the account before the sign-in expires -### - -​ - -Gateway refused the request +### Gateway refused the request You’re signed in through a [Claude apps gateway](</docs/en/claude-apps-gateway>), and a request returned a 403: the gateway, or the upstream behind it, refused it. Signing in again doesn’t change a refusal, so the message points at your gateway administrator: @@ -1941,19 +1651,11 @@ Before v2.1.273, a 403 on a gateway session showed the generic `Please run /login` or `Failed to authenticate` message instead, and signing in again didn’t clear the refusal. -## - -​ - -Network and connection errors +## Network and connection errors Most of these errors mean a network request from Claude Code failed to reach its destination, or something between Claude Code and the API altered the response on its way back; where an entry also has a local cause, such as a failed archive write, its body says so. They usually originate in your local network, proxy, or firewall, or in the cloud environment’s network policy. -### - -​ - -Unable to connect to API +### Unable to connect to API The TCP connection to the API failed or never completed. For the common connection error codes, the message names the kind of failure and keeps the code in parentheses: @@ -1981,11 +1683,7 @@ * On macOS, a VPN client that was disconnected or uninstalled can leave a tunnel interface or routing rule behind. Check `ifconfig` for stale `utun` interfaces and remove the VPN’s network extension in System Settings. * Docker Desktop and similar container runtimes can intercept outbound traffic. Quit them and retry to rule this out. -### - -​ - -Unable to connect to Anthropic services +### Unable to connect to Anthropic services During first-run setup, Claude Code checks that it can reach `api.anthropic.com` and `platform.claude.com` before showing the sign-in step. When either check fails, Claude Code prints the reason and exits. @@ -2000,22 +1698,14 @@ * Work through the checks in Unable to connect to API. The `curl` test and firewall guidance there apply to this check too. * If your network is open and the failure persists, Claude Code may not be [available in your country](<https://www.anthropic.com/supported-countries>) -### - -​ - -Socket is closed +### Socket is closed `Socket is closed` means the connection carrying a streaming response was closed while the response was still arriving. The most common cause is a corporate proxy on Windows dropping an established tunnel mid-response. Depending on how far the response had progressed, Claude Code retries the request, keeps what Claude produced, or ends the turn. See Automatic retries. Before v2.1.214, Claude Code didn’t retry this failure, and the turn stopped with an error containing `Socket is closed`. **What to do:** * If you see this error, update to v2.1.214 or later with `claude update`, then send your message again * If turns keep failing behind the same proxy after updating, work through Unable to connect to API and check the proxy setup in [Network configuration](</docs/en/network-config>) -### - -​ - -API returned an empty or malformed response +### API returned an empty or malformed response Claude Code shows this error when its non-streaming retry of a failed streaming request gets an HTTP success status but the body isn’t a Claude API message: commonly an HTML error or sign-in page, an empty body, or JSON in another format. A proxy, gateway, or network sign-in page answering in the API’s place is the usual source. Claude Code doesn’t retry the request, and the turn ends with this error. @@ -2033,11 +1723,7 @@ * On a network with a sign-in page, such as guest Wi-Fi, complete the sign-in in a browser, then retry * If only the non-streaming route through your gateway is broken, set [`CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK=1`](</docs/en/env-vars#variables>) to turn off this fallback, except when the streaming endpoint itself returns `404`, where Claude Code still falls back -### - -​ - -Streaming response ended before any complete data was received +### Streaming response ended before any complete data was received A streaming response from your model provider completed without delivering any usable data, so Claude Code re-sent the request without streaming to finish the turn. Claude Code shows the warning once per session, in interactive sessions only. Before v2.1.239, Claude Code silently retried without streaming. @@ -2048,11 +1734,7 @@ * Configure any proxy or gateway between Claude Code and your model provider to pass streaming response bodies and their headers through unmodified * On [Amazon Bedrock](</docs/en/amazon-bedrock>), see [Streaming errors behind a gateway or proxy](</docs/en/amazon-bedrock#streaming-errors-behind-a-gateway-or-proxy>) for the header and body requirements -### - -​ - -Bedrock streaming response has an unexpected content-type +### Bedrock streaming response has an unexpected content-type A gateway or proxy between Claude Code and [Amazon Bedrock](</docs/en/amazon-bedrock>) is transforming the streaming response body or its `Content-Type` header. Amazon Bedrock streams responses as `application/vnd.amazon.eventstream`. Rather than decode a body it can’t read, Claude Code rejects a successful streaming response that reports a different content-type. Claude Code doesn’t retry the request. @@ -2063,11 +1745,7 @@ * Configure the gateway to pass the `InvokeModelWithResponseStream` response body and its `Content-Type` header through unmodified. An intermediary that re-emits the stream as server-sent events is a common cause. * Setting [`CLAUDE_CODE_DISABLE_BEDROCK_CONTENT_TYPE_GUARD=1`](</docs/en/env-vars>) hides this error, but Claude Code doesn’t decode a binary body under a rewritten header, so those requests fall back to a slower non-streaming path. See [Streaming errors behind a gateway or proxy](</docs/en/amazon-bedrock#streaming-errors-behind-a-gateway-or-proxy>). -### - -​ - -SSL certificate errors +### SSL certificate errors A proxy or security appliance on your network is intercepting TLS traffic with its own certificate, and Claude Code does not trust it. @@ -2084,13 +1762,9 @@ * See [Network configuration](</docs/en/network-config#custom-ca-certificates>) for full setup instructions * Don’t set `NODE_TLS_REJECT_UNAUTHORIZED=0`, which disables certificate validation entirely -### - -​ - -Host not allowed in a cloud session - -An outbound HTTP request from a cloud session or cloud scheduled task was blocked by the environment’s network policy. +### Host not allowed in a cloud session + +In a cloud session or cloud scheduled task, a `403` or a DNS error such as `ENOTFOUND` can mean that the requested host isn’t on the [cloud environment’s allowlist](</docs/en/cloud-environments#access-levels>). To confirm, check the host against that list. A `403` with this header confirms the block, but not every blocked request’s `403` has it: HTTP 403 x-deny-reason: host_not_allowed @@ -2108,11 +1782,7 @@ See [Network access](</docs/en/cloud-environments#network-access>) for access levels and the default allowlist. Local CLI sessions are not affected by this policy. -### - -​ - -The proxy refused the connection +### The proxy refused the connection You see this message when Claude reads an [artifact](</docs/en/artifacts>) through the proxy you set in `HTTPS_PROXY` or a related [proxy variable](</docs/en/network-config#environment-variables>). Artifact content comes from `*.frame.claudeusercontent.com`, so Claude Code first sends the proxy a `CONNECT` request asking it to open a tunnel to that host. When the proxy refuses, nothing reaches the host, and the message carries the proxy’s HTTP status: @@ -2134,11 +1804,7 @@ Before v2.1.238, Claude Code reported a refused tunnel as a generic network error. -### - -​ - -The cloud environments service returned an empty or unexpected response +### The cloud environments service returned an empty or unexpected response Claude Code requests your [cloud environments](</docs/en/cloud-environments>) list at several points, such as when you create a cloud session from the CLI or run [`/remote-env`](</docs/en/cloud-environments#select-an-environment-from-the-cli>). When it can’t read the server’s answer, it shows one of these messages: @@ -2153,11 +1819,7 @@ Before v2.1.236, Claude Code showed a raw JavaScript TypeError instead of these messages. -### - -​ - -Failed to fetch session from Sessions API +### Failed to fetch session from Sessions API This message means Claude Code found the [cloud session you asked to pull into your terminal](</docs/en/claude-code-on-the-web#from-cloud-to-terminal>) but couldn’t read its conversation history from Anthropic’s servers, so it didn’t open it: @@ -2169,11 +1831,7 @@ Before v2.1.296, Claude Code didn’t retry a failed read, and after one it could open the session with an empty conversation and report success instead of printing this message. -### - -​ - -Couldn’t reconnect to your Remote Control session +### Couldn’t reconnect to your Remote Control session Couldn't reconnect to your Remote Control session. Retry, or start a fresh session without --resume. @@ -2185,11 +1843,7 @@ If the server reports instead that the previous session is gone, you don’t see this message. Claude Code starts a new session in its place or shows [`Previous session is unavailable — run /remote-control to start a new one`](</docs/en/remote-control#previous-session-is-unavailable>). -### - -​ - -Sessions ended while this machine was offline +### Sessions ended while this machine was offline Claude Code shows this message in the terminal running [`claude remote-control`](</docs/en/remote-control#start-a-remote-control-session>) after your machine was offline long enough that the server cleaned up the Remote Control environment your machine was serving. The sessions in that environment ended, and you can’t resume them. The count is the number of sessions that ended. @@ -2200,11 +1854,7 @@ * When Claude Code lists kept worktrees under this message, pick up any uncommitted work from them * Run `claude remote-control` to start a fresh environment -### - -​ - -Couldn’t share the transcript +### Couldn’t share the transcript After you agree to share your session transcript from a survey prompt, such as the [session quality survey](</docs/en/data-usage#session-quality-surveys>), Claude Code uploads it to Anthropic, or saves a local archive instead on third-party providers, on [Claude apps gateway](</docs/en/claude-apps-gateway>) sessions, and when no Anthropic credentials are available. This message means the share didn’t complete. @@ -2215,11 +1865,7 @@ * Run `/feedback` to send the transcript with a description of what happened. See Report an error if `/feedback` is unavailable in your environment * If other requests are failing too, check your network connection and see Unable to connect to API -### - -​ - -Couldn’t send feedback +### Couldn’t send feedback A message starting `Couldn't send feedback` means the feedback service didn’t confirm the report you submitted from the [`/feedback`, `/bug`, or `/share` dialog](</docs/en/commands#all-commands>), or a queued [feedback draft](</docs/en/tools-reference#sendfeedback-tool-behavior>). Treat it as not received. When a sentence about your organization follows the colon, your organization refuses feedback. The second example is an organization’s refusal: @@ -2237,11 +1883,7 @@ Issues at github.com/anthropics/claude-code are public, so leave out code, transcripts, and anything else confidential when you open one. Before v2.1.281, every send failed with this message once a Remote Control **Stop** or an urgent cross-session message had arrived while the dialog was open. On those versions, close the dialog, reopen it, and send again. -### - -​ - -Feedback payload too large +### Feedback payload too large This message in the [review screen](</docs/en/tools-reference#review-and-edit-a-draft>) for a [feedback draft](</docs/en/tools-reference#sendfeedback-tool-behavior>) means Claude Code has no confirmation that the service accepted the draft. Treat it as not received. The draft stays in your `/feedback` queue, so you can send it again. @@ -2251,11 +1893,7 @@ * In the review screen, set **Send transcript** to `no`, then send the draft again. Shortening the details removes at most 10 KB of text, which is all a draft’s details can hold. -### - -​ - -MCP server connection timed out during a sleep or clock change +### MCP server connection timed out during a sleep or clock change This message means a connection to an [MCP server](</docs/en/mcp>) timed out, and Claude Code found that your system clock jumped forward during the attempt: @@ -2270,19 +1908,11 @@ Before v2.1.307, Claude Code showed a timeout message such as `MCP server "<name>" connection timed out after <N>ms` instead of this one. -## - -​ - -Request errors +## Request errors These errors relate to the content of your request. Most come back from the API after it rejected the request; a few are produced locally by Claude Code before any request is sent. -### - -​ - -Prompt is too long +### Prompt is too long The conversation plus attached files exceeds the model’s context window. @@ -2331,11 +1961,7 @@ See [Explore the context window](</docs/en/context-window>) for an interactive view of how context fills up. -### - -​ - -Context exceeds the token limit +### Context exceeds the token limit `/context` shows this warning at the top of its output when the conversation has grown past the model’s context window: @@ -2357,11 +1983,7 @@ Before v2.1.216, `/context` showed usage above 100% with no warning line explaining what that meant or how to recover. -### - -​ - -Request too large +### Request too large The raw request body exceeded the API’s 32MB limit before tokenization, usually because of large pasted content, tool results, or attachments. This limit is separate from the context window. @@ -2379,11 +2001,7 @@ * Reference large files by path instead of pasting their contents, so Claude can read them in chunks * For images, see Image was too large below -### - -​ - -Image was too large +### Image was too large A pasted or attached image exceeds the API’s size or dimension limits. @@ -2406,11 +2024,7 @@ The `dimension limit for many-image requests` message shows the pixel limit named in the API’s error. -### - -​ - -Unable to resize image +### Unable to resize image Claude Code couldn’t downscale an attached image before sending it to the API. @@ -2422,17 +2036,13 @@ Unable to resize image — it is an animated WebP whose first frame Claude Code cannot decode, and at …px it is over the 2000x2000px limit, so it cannot be sent. Save its first frame as a PNG or JPEG and try again. Unable to resize image — its pixels could not be decoded (the file may be damaged, or use an encoding Claude Code cannot read), and it is over the … API limit (… raw, … base64), so it cannot be sent. Re-save it as a PNG or JPEG and try again. -Claude Code normally resizes large images automatically. These errors mean the image couldn’t be decoded or resized to fit within the API limits. **What to do:** +Claude Code normally resizes large images automatically. These errors mean the image couldn’t be decoded or resized to fit within the API limits. The error you see can name a different pixel limit, such as `2576x2576px` where these examples say `2000x2000px`. **What to do:** * If the message asks you to convert the image, convert it to PNG, JPEG, GIF, or WebP and attach it again. Claude Code can verify dimensions for these formats from the file header, without decoding the image. * If the message reports a dimension or size limit, resize or recompress the image below that limit before attaching. * If the message names a cause, such as a CMYK JPEG, an animated WebP, or a possibly damaged file, re-save the image in the format the message suggests and attach it again. -### - -​ - -Request rejected as unprocessable by the model +### Request rejected as unprocessable by the model The API refused the request as one the model can’t process. The message is the API’s own. @@ -2442,11 +2052,7 @@ * If the message keeps appearing in a conversation with images or documents, remove them yourself. Press Esc twice to step back past the turns that added them, or run `/clear` to start fresh. -### - -​ - -PDF errors +### PDF errors The PDF you attached couldn’t be processed. The messages are shown here in their non-interactive form; in an interactive session they instead prompt you to double press esc and try again. @@ -2465,11 +2071,7 @@ Page-range reads render pages with `pdftoppm`. Install poppler-utils with the command the message gives, or on other platforms a poppler build that puts `pdftoppm` on your `PATH`. See [Read tool behavior](</docs/en/tools-reference#read-tool-behavior>) for which PDFs are read by page range. -### - -​ - -Extra inputs are not permitted +### Extra inputs are not permitted The endpoint that received the request rejected one of the request’s fields as an input it doesn’t accept, and the endpoint’s message names that field. @@ -2484,11 +2086,7 @@ Before v2.1.302, this error could also name the field `diagnostics` with no gateway involved. It appeared when a session that had already used the Anthropic API moved to Amazon Bedrock or Google Cloud’s Agent Platform without a restart. For example, a session you left open moves to Bedrock when you run [`/setup-bedrock`](</docs/en/commands>) in another Claude Code window. On those versions, run `/clear` in that session or restart it. -### - -​ - -Tool input schema is invalid +### Tool input schema is invalid A tool in the request declared an `input_schema` that fails the API’s JSON Schema validation, so the API rejected the whole request. The number after `tools.` is the failing tool’s position in the request’s tool list, not a name you can look up. @@ -2501,11 +2099,7 @@ * Remove or [disable](</docs/en/mcp#disable-a-server-without-removing-it>) the MCP server that declares the invalid schema. The error names the tool only by position. On v2.1.216 or later, check each server’s log for a line naming a tool whose input schema would be rejected. If no log names one, disable servers one at a time. * If you maintain the server, fix the tool’s `input_schema`. The schema must be valid JSON Schema, and top-level property names must be 1 to 64 characters long and use only ASCII letters and digits, `_`, `.`, and `-`. See [Tools with invalid input schemas](</docs/en/mcp#tools-with-invalid-input-schemas>). -### - -​ - -MCP tool name over 128 characters +### MCP tool name over 128 characters An MCP server lists a tool whose full name, such as `mcp__<server>__<tool>`, is longer than the 128 characters the API accepts. Claude Code [leaves that tool out of the tools it sends to Claude](</docs/en/mcp#tools-with-names-longer-than-128-characters>), and the server’s other tools keep working. In a session you start with `claude --debug` from your shell, Claude Code writes this message to the debug log at `~/.claude/debug/<session-id>.txt`: @@ -2519,11 +2113,7 @@ Before v2.1.292, Claude Code sent the tool anyway, and the API rejected every request that included it with `API Error: 400 ... tools.N.custom.name: String should have at most 128 characters`. -### - -​ - -tool_use.name over 200 characters +### tool_use.name over 200 characters A tool call in the conversation history carries a name longer than the 200 characters the API accepts in a request: @@ -2535,11 +2125,7 @@ Before v2.1.281, the overlong name stayed in the history and the API rejected every request that re-sent the conversation, including `/compact` and `--resume`, so this error repeated and the conversation was stuck. -### - -​ - -There’s an issue with the selected model +### There’s an issue with the selected model The configured model name was not recognized or your account lacks access to it. As of v2.1.160 the trailing hint, shown here in its interactive form, varies by surface. @@ -2556,11 +2142,7 @@ * If [`ANTHROPIC_BASE_URL`](</docs/en/env-vars>) points at an [LLM gateway](</docs/en/llm-gateway>) and every model fails this way, check that your gateway and its upstream accept [tool search](</docs/en/mcp#tool-search-through-a-gateway>) fields. By default, Claude Code sends `defer_loading` tool fields and `tool_reference` blocks, with the `anthropic-beta` header that enables them. Before v2.1.304, tool search was off behind a gateway unless you turned it on with `ENABLE_TOOL_SEARCH`. * For Google Cloud’s Agent Platform deployments, see [Google Cloud’s Agent Platform troubleshooting](</docs/en/google-vertex-ai#troubleshooting>). -### - -​ - -Model is not a recognized model id +### Model is not a recognized model id The string you passed to a model switch isn’t one Claude Code can use as a model, so it refused the switch without sending a request and the session keeps its current model. You can get this error when a model is set through the [Agent SDK](</docs/en/agent-sdk/typescript>) `setModel()` method, by an app that runs the Claude Code CLI for you, such as the [Desktop app](</docs/en/desktop>), or when you pick a model from a device connected through [Remote Control](</docs/en/remote-control>). Before v2.1.200, Claude Code saved the string and failed on the next request with There’s an issue with the selected model. @@ -2573,11 +2155,7 @@ * A model saved before v2.1.200 isn’t repaired by this check. If a stale value keeps coming back, remove it from the locations listed under [Setting your model](</docs/en/model-config#setting-your-model>). * On any provider other than the Anthropic API, or behind a gateway or custom `ANTHROPIC_BASE_URL`, only an empty string gets this error. Claude Code can still write the unrecognized-model diagnostic line at request time, on every provider. -### - -​ - -Model not found +### Model not found You switched to a model by name and Claude Code couldn’t confirm that a model with that name exists. When the name isn’t a [model alias](</docs/en/model-config#model-aliases>) or another spelling Claude Code accepts locally, Claude Code verifies it with a minimal API request, and this error is usually your API endpoint’s answer. With `/model <name>`, a name that can’t be a model ID at all, such as one containing spaces, gets the same message. @@ -2590,11 +2168,7 @@ * In the Agent SDK, `setModel()` fails with this message and the session keeps running on its previous model. In the TypeScript SDK, call [`supportedModels()`](</docs/en/agent-sdk/typescript#query-object>) to list the models you can switch to. * Before v2.1.265, `/model` also rejected the `opusplan[1m]` alias spelling with this error. On those versions, update Claude Code, or set the model in [settings](</docs/en/model-config#setting-your-model>) or with `--model` instead. -### - -​ - -Couldn’t confirm model with the API +### Couldn’t confirm model with the API You switched models through the [Agent SDK](</docs/en/agent-sdk/typescript>) `setModel()` method or an app that runs the Claude Code CLI for you, such as the [Desktop app](</docs/en/desktop>), and the request that confirms the model ID with your API endpoint got no answer within 15 seconds. The session keeps its current model. @@ -2605,11 +2179,7 @@ * Switch to the model again * If the switch keeps failing, check that Claude Code can reach your API endpoint; see Network and connection errors -### - -​ - -API error when checking the picked model +### API error when checking the picked model You picked a model with `/model <name>`, or an app connected to the session requested the switch. The API refused the minimal request Claude Code sends to verify the model, for a reason that has no entry of its own, such as a rate limit or a server error. The session keeps its current model, and the message ends by saying so: @@ -2620,11 +2190,7 @@ * Act on the server’s explanation; for a rate limit or a 5xx status, wait and pick the model again * The refusals with their own wording are covered by the surrounding entries, such as Model not found and Model is restricted by your organization’s settings -### - -​ - -Claude Opus is not available with the Claude Pro plan +### Claude Opus is not available with the Claude Pro plan Your active subscription plan does not include the model you selected. @@ -2636,11 +2202,7 @@ * If you upgraded your plan recently and still see this, run `/logout` then `/login`. The stored token reflects your plan at the time you signed in, so upgrading on claude.ai does not take effect in an existing session until you re-authenticate. * See [claude.com/pricing](<https://claude.com/pricing>) for which models each plan includes -### - -​ - -Claude Code does not support this model +### Claude Code does not support this model The API refused the request with a 400 because your Claude Code version is below a required minimum. Either the model you selected requires a newer version, which the server checks per model, or your organization’s policy requires one. The 400 carries the error code `claude_code_version_too_old`, and the message says which minimum applies. @@ -2663,11 +2225,7 @@ * For the per-model wording, you can keep working in the current session by switching to another model: run `/model` in the CLI, call [`setModel()`](</docs/en/agent-sdk/typescript#query-object>) on the TypeScript SDK’s `Query` object in streaming input mode, or call [`set_model()`](</docs/en/agent-sdk/python#claudesdkclient>) on the Python SDK’s `ClaudeSDKClient` * For the organization-policy wording, update before you continue -### - -​ - -Model is restricted by your organization’s settings +### Model is restricted by your organization’s settings Your organization admin has disabled this model in the claude.ai admin console, or managed settings exclude it through an [`availableModels`](</docs/en/model-config#restrict-model-selection>) allowlist or a [`deniedModels`](</docs/en/model-config#block-specific-models-or-versions>) list. The notice appears at startup when `--model`, `ANTHROPIC_MODEL`, or the `model` setting named the restricted model, and it names the model the session uses instead. If managed settings leave no permitted model for the session to use, see Managed settings block the default model. The substitution notice can also appear mid-session after an admin disables the model a session is running on in the claude.ai admin console. @@ -2679,11 +2237,7 @@ * If the restricted model was set in `--model`, `ANTHROPIC_MODEL`, the `model` field of a settings file, or the `model` frontmatter of a [subagent](</docs/en/sub-agents#choose-a-model>), skill, or command, remove or update that value so the notice doesn’t recur * If you need access to the restricted model, ask your organization admin to enable it. See [Organization model restrictions](</docs/en/model-config#organization-model-restrictions>). -### - -​ - -Can’t switch to the default model +### Can’t switch to the default model You picked the Default model, for example by selecting the Default row in the `/model` picker or typing `/model default`. Claude Code refused the switch, so the session keeps its current model. @@ -2703,11 +2257,7 @@ If a session instead fails to start with a `Claude Code can't start` message under these managed settings, see Managed settings block the default model. -### - -​ - -Model switch was blocked by a PreModelSwitch hook +### Model switch was blocked by a PreModelSwitch hook A [PreModelSwitch hook](</docs/en/hooks#premodelswitch>) didn’t approve the model switch you or a client requested, so the session keeps its current model. When the switch came from an [Agent SDK](</docs/en/agent-sdk/overview>) host or [Remote Control](</docs/en/remote-control>) rather than a command you typed, the message reads `Model switch blocked by a PreModelSwitch hook` without naming the target model. @@ -2718,16 +2268,12 @@ * **A reason a hook wrote** : a PreModelSwitch hook supplied that reason when it [denied the switch or asked for confirmation](</docs/en/hooks#premodelswitch-decision-control>). Address what it asks, or pick a model your hooks allow. * **`PreModelSwitch hook<name> did not respond before its timeout`**: a hook that doesn’t answer before its [timeout](</docs/en/hooks#timeouts>) blocks the switch. Fix the hanging command or raise that hook’s `timeout`, then switch again. * **`confirmation required, and this session cannot ask`** : a hook answered `ask` without a reason, and a control request has no way to show the confirmation prompt. A `/model` command in a [`-p` run](</docs/en/headless>) reports the same condition with `(run /model interactively to confirm)` after the reason. Make the switch from an interactive session, or change the hook’s decision for this model. - * **`so organization-managed PreModelSwitch hooks could not be checked`** : Claude Code couldn’t tell which PreModelSwitch hooks your organization’s [managed plugins](</docs/en/settings-reference#enabledplugins>) deliver, for example because a managed plugin failed to load. One of those hooks might block the switch, so Claude Code refuses rather than apply the switch unchecked. The start of the reason names what failed. Claude Code re-checks on every switch attempt, so a failure that has since cleared stops blocking; if it keeps failing, run `claude --debug` and switch again to capture the details, then fix the plugin or ask your admin to fix it. + * **`so organization-managed PreModelSwitch hooks could not be checked`** : Claude Code before v2.1.323 refuses when it can’t tell which PreModelSwitch hooks your [managed plugins](</docs/en/settings-reference#enabledplugins>) deliver. The text before this phrase names what failed. To stop the refusal, update Claude Code. To also get a failed plugin’s hooks running, fix the plugin or ask your admin. For details, start `claude --debug` in your shell and switch models, then read the [debug log](</docs/en/hooks#debug-hooks>). * **`a PreModelSwitch hook failed before answering`** or **`PreModelSwitch hooks were cancelled (the control stream closed) before answering`** : the hook run ended without a verdict, and Claude Code doesn’t treat that as approval. Run `claude --debug` to see what failed, then switch again. Before v2.1.260, the managed-plugin refusal read `plugin hooks could not be loaded, so PreModelSwitch hooks could not be checked; see the debug log`. Claude Code retried the plugin load once and then refused later switches in the session, even when your organization managed no plugins. Restart the session to run the plugin load again on those versions. -### - -​ - -Couldn’t save it as your default +### Couldn’t save it as your default You picked a model to save as your default, for example with `/model <name>` or `Enter` in the `/model` picker, and Claude Code couldn’t write the pick to your user settings file, `~/.claude/settings.json`. The switch itself applied, so the current session runs on the model you picked, but your default is unchanged and the next session starts on the old value. @@ -2740,11 +2286,7 @@ A notice ending `couldn't confirm it was saved as your default (~/.claude/settings.json is still being written)` means the write hadn’t finished after three seconds. It continues in the background, so the default may still be saved; check which model your next session starts on, or run `/model <name>` again. Before v2.1.265, the notice said the model was `saved as your default for new sessions` even when the write failed. -### - -​ - -Advisor is less capable than the current main model +### Advisor is less capable than the current main model Your [advisor model](</docs/en/advisor>) ranks below your session’s main model, so Claude Code keeps the selection but doesn’t attach the advisor to the main model’s requests. @@ -2763,11 +2305,7 @@ Before v2.1.287, Claude Code ranked several pairings differently. It showed this note for a Sonnet 5.5 advisor with an Opus 4.7 or Opus 4.8 main model, a pairing it now accepts. It also attached some advisors that now produce this note, such as an Opus 4.8 advisor with a Sonnet 5.5 main model. -### - -​ - -thinking.type.enabled is not supported for this model +### thinking.type.enabled is not supported for this model Your Claude Code version is older than the minimum for the selected model. The CLI sent a thinking configuration the model no longer accepts. @@ -2780,11 +2318,7 @@ * If you can’t upgrade, run `/model` and select Opus 4.6 or Sonnet 4.6 instead * If you hit this in the [Agent SDK](</docs/en/agent-sdk/overview>), upgrade the SDK package instead. Opus 4.8 needs TypeScript SDK v0.3.154 or later and Python SDK v0.2.88 or later. Sonnet 5 needs TypeScript SDK v0.3.197 or later. Opus 5 needs TypeScript SDK v0.3.219 or later. Opus 5.5 needs TypeScript SDK v0.3.280 or later. Sonnet 5.5 needs TypeScript SDK v0.3.284 or later -### - -​ - -Effort isn’t available with thinking turned off +### Effort isn’t available with thinking turned off You turned [extended thinking](</docs/en/model-config#extended-thinking>) off and ran at an [effort level](</docs/en/model-config#adjust-effort-level>) above `high`. The model doesn’t accept that combination, so the API rejected the request. @@ -2797,11 +2331,7 @@ Before v2.1.242, Claude Code showed the API’s own message: `API Error: 400 output_config.effort 'xhigh' is not supported when thinking is disabled on this model. Use effort 'high' or below, or enable thinking.` Before v2.1.251, Claude Code sent the request at the effort level you set, so Opus 5 rejected every request above `high` with thinking turned off. Claude Code now sends effort `high` instead to models it knows reject the combination, such as Opus 5. -### - -​ - -Thinking budget exceeds output limit +### Thinking budget exceeds output limit The configured extended thinking budget exceeds the maximum response length, so there is no room left for the actual answer. @@ -2812,11 +2342,7 @@ * Raise [`CLAUDE_CODE_MAX_OUTPUT_TOKENS`](</docs/en/env-vars>) above the thinking budget * See [Extended thinking](</docs/en/model-config#extended-thinking>) for how the budget interacts with output length -### - -​ - -Response exceeded the output token maximum +### Response exceeded the output token maximum Claude’s reply reached the largest number of output tokens the request allowed and was cut off there: @@ -2829,11 +2355,7 @@ * If the message says to set `CLAUDE_CODE_MAX_OUTPUT_TOKENS`, see [`CLAUDE_CODE_MAX_OUTPUT_TOKENS`](</docs/en/env-vars>) for how the value is capped and [Set environment variables](</docs/en/env-vars#set-environment-variables>) for where to set it * To keep each reply under the limit, ask Claude for the output in smaller pieces, such as one file or one section per reply -### - -​ - -Tool use or thinking block mismatch +### Tool use or thinking block mismatch The conversation history reached the API in an inconsistent state. @@ -2848,11 +2370,7 @@ * If you are using Opus 4.7 or Opus 4.8, run `claude update` first. Versions before v2.1.156 can trigger this error during normal tool use, and `/rewind` doesn’t clear it. * Run `/rewind`, or press Esc twice, to step back to a checkpoint before the corrupted turn and continue from there. See [Checkpointing](</docs/en/checkpointing>) for how checkpoints are created and restored. -### - -​ - -Invalid data in redacted_thinking block +### Invalid data in redacted_thinking block The API refused the request with a 400 because it couldn’t accept a `redacted_thinking` block that an earlier turn in the conversation history carries. @@ -2863,11 +2381,7 @@ * If you’re on v2.1.281 or earlier and every turn fails with this error, run `claude update` and resume the session * If the error persists, run `/clear` to start a conversation that doesn’t carry the block -### - -​ - -Unsupported tool content removed +### Unsupported tool content removed When Claude Code connects directly to the Anthropic API and loads or previews a saved session, it removes tool content the Anthropic API doesn’t accept and leaves this line where removed content sat between two thinking blocks: @@ -2878,11 +2392,7 @@ * None needed when you see the placeholder line. The session continues without the removed content. * If every turn of a resumed session fails with the 400 error instead, run `claude update` and resume the session again. Versions before v2.1.246 don’t remove the content. -### - -​ - -role ‘system’ must precede an ‘assistant’ message +### role ‘system’ must precede an ‘assistant’ message The API refused the request with a 400 because a system message sits at a position in the conversation it doesn’t accept: @@ -2895,11 +2405,7 @@ Before v2.1.280, Claude Code didn’t recognize this wording, so the error also appeared when the refused system message was one Claude Code itself sent, and every later turn of the conversation failed the same way. -### - -​ - -Invalid encrypted_content in search_result block +### Invalid encrypted_content in search_result block The API refused the request with a 400 because the conversation history holds hosted web-search content it can’t decrypt. The wording names the field it can’t read: @@ -2914,11 +2420,7 @@ * If the error persists, or the message names `encrypted_stdout`, run `/rewind` to step back to a checkpoint before the turn that added the content, or run `/clear` to start a conversation that doesn’t carry it * If you run Claude Code behind a proxy or gateway, report the error to whoever operates it -### - -​ - -Usage Policy refusal +### Usage Policy refusal The API declined to respond because content in the conversation triggered a [Usage Policy](<https://www.anthropic.com/legal/aup>) check. If the message includes the line `Details: `[reasoning_extraction]``, see Safeguards flagged a request for Claude’s reasoning. The message includes a Request ID and a Message ID you can quote to support if you believe the refusal is incorrect. @@ -2932,11 +2434,7 @@ * If you can’t identify which turn caused it, run `/clear` to start a fresh conversation in the same project. Your previous conversation is preserved on disk and remains available in `/resume`. * In [non-interactive mode](</docs/en/headless>) (`-p`), where rewind is unavailable, retry with a rephrased prompt in a new session without `--continue`. Policy checks vary by model, so switching to a different model with `--model` may also resolve the refusal in some cases. -### - -​ - -Safety measures flagged a cybersecurity topic +### Safety measures flagged a cybersecurity topic The model’s safety measures flagged content in the conversation as a cybersecurity topic. The message names the model that flagged the request: @@ -2954,11 +2452,7 @@ * From v2.1.203 through v2.1.218, the message read `<model> has safety measures that flagged this message for a cybersecurity topic. To learn about the Cyber Verification Program and apply for access, visit our help center:` followed by the same help-center link. In interactive sessions, it continued with `If you were not engaging in a cybersecurity topic, please send feedback via /feedback.` * Before v2.1.203, it read `<model>'s safeguards flagged this message for a cybersecurity topic. If your work requires this access, you can apply for an exemption:` followed by an exemption form link -### - -​ - -Safeguards flagged a request for Claude’s reasoning +### Safeguards flagged a request for Claude’s reasoning The API declined the request because safeguards flagged it as asking the model to reproduce its internal reasoning in the response. The API names this [refusal category](<https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#refusal-response>) `reasoning_extraction`, and the refusal message includes this line: @@ -2973,11 +2467,7 @@ * You can still ask Claude to explain its answer. Ask for a short explanation, the evidence behind a result, or a summary of the actions it took. To read summaries of Claude’s thinking, see [`showThinkingSummaries`](</docs/en/settings-reference#showthinkingsummaries>). * For more examples, and what to do if a reworded request is still declined, see [Keep reasoning in thinking blocks](<https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#keep-reasoning-in-thinking-blocks>) -### - -​ - -Output blocked by content filtering policy +### Output blocked by content filtering policy The API’s output content filter stopped the response Claude was generating. The message text comes from the API: @@ -2988,19 +2478,11 @@ * Rephrase your last message or take a different approach * To step back to a checkpoint before the turn that triggered the block, press Esc twice or run `/rewind`. See [Checkpointing](</docs/en/checkpointing>) -## - -​ - -Command-line errors +## 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. -### - -​ - -Conflict between `--bg` and `--print` +### Conflict between `--bg` and `--print` This message requires Claude Code v2.1.198 or later. You combined `--bg` with `-p` or `--print` in the same `claude` invocation. `--bg` starts a [background session](</docs/en/agent-view#from-your-shell>) that you later attach to with `claude agents`, while `--print` runs [non-interactively](</docs/en/headless>) and never starts the interactive session that `claude agents` attaches to. Before v2.1.198 this combination silently created a background job that could never be attached to. @@ -3011,11 +2493,7 @@ * Drop `-p` or `--print`. `--bg` takes the prompt as its positional argument, so `claude --bg "<task>"` is the complete command. See [Dispatch new agents from your shell](</docs/en/agent-view#from-your-shell>). * To run the prompt non-interactively and print the result instead of creating a background session, drop `--bg` and run `claude -p "<task>"` -### - -​ - -Couldn’t tell whether `--bg` is a flag or text +### Couldn’t tell whether `--bg` is a flag or text You ran `claude` with `--bg` or `--background` at a position where Claude Code couldn’t tell whether you meant it as the background flag or as text. The command started nothing, printed this line, and exited with code 1: @@ -3025,11 +2503,7 @@ * To start a [background session](</docs/en/agent-view#from-your-shell>), run the command again in your shell with the flag first: `claude --bg --name nightly-audit "<task>"` -### - -​ - -Conflict between a system prompt flag and its file form +### Conflict between a system prompt flag and its file form You passed [`--append-subagent-system-prompt`](</docs/en/cli-reference#cli-flags>) together with `--append-subagent-system-prompt-file` in one `claude` invocation, so `claude` exits with code 1 instead of starting the session: @@ -3039,11 +2513,7 @@ * Keep one form of the flag and drop the other. To combine a fixed prompt file with per-run text, merge the text into the file before launching instead of passing both flags -### - -​ - -Invalid `--agents` configuration +### Invalid `--agents` configuration The value you passed to `--agents` is invalid, so `claude` exits with code 1 instead of starting the session. When you pass `--safe-mode` or set [`CLAUDE_CODE_SAFE_MODE`](</docs/en/env-vars#variables>), Claude Code ignores `--agents` entirely. With `--resume` or `--continue`, an inline JSON value isn’t checked and the session starts; a value read from a file is checked on every launch. Before v2.1.242, Claude Code started the session anyway. @@ -3065,11 +2535,7 @@ * Fix each problem the message lists, then run the command again. See [the fields a CLI-defined subagent takes](</docs/en/sub-agents#choose-the-subagent-scope>). -### - -​ - -Cloud sessions cannot be created from a `--restricted` session +### Cloud sessions cannot be created from a `--restricted` session When you start a session with [`--restricted`](</docs/en/cli-reference#cli-flags>), Claude Code refuses to create [cloud sessions](</docs/en/claude-code-on-the-web#from-terminal-to-cloud>) from it, because the new session would run outside the restricted process and wouldn’t enforce restricted mode. Claude Code refuses on the client, before contacting the server, so no cloud session is created: @@ -3082,11 +2548,7 @@ Before v2.1.248, Claude Code had no `--restricted` flag; earlier versions reject the flag itself with an unknown-option error. -### - -​ - -Cloud sessions are disabled by your organization’s policy +### Cloud sessions are disabled by your organization’s policy Your organization’s `allow_remote_sessions` policy is off, so [cloud sessions](</docs/en/claude-code-on-the-web>) and the commands that use them aren’t available: @@ -3096,11 +2558,7 @@ * Ask an [Owner](</docs/en/server-managed-settings#access-control>) in your organization to enable cloud sessions in the Claude Code admin settings at [claude.ai/admin-settings/claude-code](<https://claude.ai/admin-settings/claude-code>) -### - -​ - -Cloud sessions use your claude.ai login +### Cloud sessions use your claude.ai login When the policy denial names a credential this session is using and ends with this sentence, Claude Code checked the cloud-session policy of the organization that issued that credential. That organization can differ from the one your claude.ai login belongs to: @@ -3108,11 +2566,7 @@ The last sentence means that cloud sessions run on your claude.ai login rather than on that credential. This form appears when you start, resume, or message a cloud session from your shell, such as with `--cloud` or `--teleport`. Before v2.1.296, Claude Code printed the form that tells you to contact your organization admin in this case too. -### - -​ - -Couldn’t verify your organization’s policy for cloud sessions +### Couldn’t verify your organization’s policy for cloud sessions These messages mean Claude Code couldn’t load your organization’s policy, which it checks before it creates, resumes, or messages a [cloud session](</docs/en/claude-code-on-the-web>). While the policy request hasn’t finished, the message is: @@ -3131,11 +2585,7 @@ * For the `Couldn't verify` message, check your network connection and try again. Inside a session, restart Claude Code first * For a `Cloud sessions aren't available:` message, do what its cause calls for, such as checking your proxy or unsetting the credential it names, then run the command again -### - -​ - -Nothing was stashed because a folder replaced a tracked file +### Nothing was stashed because a folder replaced a tracked file This message means a folder in your checkout now sits where a git-tracked file or link used to be. It appears after you choose the stash option while pulling a [cloud session](</docs/en/claude-code-on-the-web#from-cloud-to-terminal>) into your terminal, for example with `claude --teleport` or `/teleport`. Stashing that state could delete the files inside the folder, so Claude Code refuses the stash and leaves your checkout and index unchanged: @@ -3145,11 +2595,7 @@ * Commit the change or move the folder somewhere else, as the message says, then run the teleport again -### - -​ - -The `--json-schema` value is not a valid JSON Schema +### The `--json-schema` value is not a valid JSON Schema The schema you passed to [`--json-schema`](</docs/en/cli-reference#cli-flags>) in [non-interactive mode](</docs/en/headless#get-structured-output>) failed JSON Schema compilation, so `claude` exits with code 1 instead of running the prompt. Before v2.1.205, an invalid schema produced unstructured output with no error, and any schema that used the `format` keyword was treated as invalid. @@ -3160,11 +2606,7 @@ * Fix the part of the schema the diagnostic names, then rerun the command * See [Get structured output](</docs/en/headless#get-structured-output>) for a working schema and command -### - -​ - -Settings file exceeds the 2MiB limit +### Settings file exceeds the 2MiB limit The file you passed to [`--settings`](</docs/en/cli-reference#cli-flags>) is larger than 2 MiB, so `claude` exits with code 1 at startup instead of loading it. Before v2.1.214, Claude Code read the file with no size check, and a multi-gigabyte file or a device file such as `/dev/zero` grew memory without bound. @@ -3174,11 +2616,7 @@ * Point `--settings` at a regular JSON settings file under 2 MiB. See [Settings](</docs/en/settings>) for the format. -### - -​ - -Configuration error in ~/.claude.json +### Configuration error in ~/.claude.json Claude Code couldn’t parse `~/.claude.json`, the file that holds your account details, MCP servers, and per-project state. A [non-interactive](</docs/en/headless>) start such as `claude -p` exits with code 1. When Claude Code finds a [backup](</docs/en/claude-directory#cleaned-up-automatically>), the output names it and prints a `cp` line that copies it back: @@ -3195,11 +2633,7 @@ * **The output has no`cp` line, or the error returns after you run it**: if `~/.claude.json` still has your configuration, fix its JSON. If you can’t, copy another `.claude.json.backup.<timestamp>` file from [`~/.claude/backups/`](</docs/en/claude-directory#cleaned-up-automatically>) over it if there is one, or rename it. With no file at `~/.claude.json`, Claude Code starts with default settings and none of what the file held. * **`~/.claude.json` no longer has your configuration**: find a `.claude.json.corrupted.<timestamp>` file that still has it, in [`~/.claude/backups/`](</docs/en/claude-directory#cleaned-up-automatically>) or your home directory. Fix its JSON, then copy it over `~/.claude.json`. If you can’t find or fix one, try the same steps with a `.claude.json.backup.<timestamp>` file that has your configuration. If none does, rename `~/.claude.json` and add your MCP servers again with [`claude mcp add`](</docs/en/mcp#installing-mcp-servers>). -### - -​ - -Claude configuration file was empty and no backup holds anything +### Claude configuration file was empty and no backup holds anything This message at startup means the file it names was blank and none of the file’s [`.backup` copies](</docs/en/claude-directory#cleaned-up-automatically>) holds anything. Claude Code started with defaults for what that file holds. Your `settings.json` files and `.mcp.json` are separate files. @@ -3212,11 +2646,7 @@ Before v2.1.318, Claude Code reported a blank file with no backup as corrupted. -### - -​ - -The current directory no longer exists +### The current directory no longer exists You started `claude` from a directory that was deleted or moved after your shell entered it, for example a worktree or temp directory another shell removed. Claude Code can’t read its working directory, so it exits with code 1 before starting the session, in interactive and [non-interactive](</docs/en/headless>) mode alike. Before v2.1.239, Claude Code crashed with minified bundle source and a raw `ENOENT ... uv_cwd` stack on stderr instead of this message. @@ -3229,11 +2659,7 @@ * If the directory was recreated at the same path, your shell still holds the deleted one. Run `cd "$PWD"` or leave and re-enter the directory, then run `claude` again * For `EPERM` on macOS, quit your terminal app with Cmd+Q, open it again, return to that folder, and run `claude`. If `ls` in that folder still fails, open **System Settings > Privacy & Security > Files and Folders**, turn on the folder for your terminal app, then reopen the terminal -### - -​ - -Temp directory refused or cannot be created +### Temp directory refused or cannot be created On macOS and Linux, Claude Code creates a private temp directory at startup, `claude-<uid>` under the system temp directory or the [`CLAUDE_CODE_TMPDIR`](</docs/en/env-vars>) override. When the directory can’t be created, or an entry already at that path fails the safety checks, Claude Code prints the failure to stderr and exits with code 1 rather than start the session: @@ -3254,11 +2680,7 @@ Before v2.1.309, Claude Code printed only the operating system’s error text when the volume was full or your quota was used up. An example is `ENOSPC: no space left on device, mkdir '/tmp/claude-501'`, and the same steps apply. -### - -​ - -Claude Code could not save because the disk is full +### Claude Code could not save because the disk is full This line on stderr after a [`claude -p`](</docs/en/headless>) run means the disk is full or your disk quota is used up, so Claude Code couldn’t save everything from the run: @@ -3269,11 +2691,7 @@ * **`the disk is full (ENOSPC)`** : before your next run, free up space on the disk that holds the path in the message * **`your disk quota is used up (EDQUOT)`** : before your next run, free up space or ask for a larger quota -### - -​ - -Directory couldn’t be resolved to a real location +### Directory couldn’t be resolved to a real location You ran `/add-dir` for a subdirectory of your working directory, and Claude Code couldn’t resolve the directory to its real location. You already have file access to a subdirectory of the working directory, so `/add-dir` only loads its skills, commands, and agents. Before loading them, Claude Code checks that the directory’s real location, with any symlinks resolved, is inside the working directory. When Claude Code can’t resolve that location, it loads nothing and shows this message: @@ -3286,11 +2704,7 @@ Before v2.1.261, this message also appeared for every `/add-dir <subdirectory>` when the working directory was on a `/net/<host>` automount, where Claude Code declines to resolve paths by design; the directory was fine and retrying couldn’t help. -### - -​ - -Workspace not trusted when starting Remote Control +### Workspace not trusted when starting Remote Control If `claude ultrareview` printed `Error: Workspace not trusted`, see Workspace not trusted when running claude ultrareview instead. @@ -3309,11 +2723,7 @@ Before v2.1.284, the command never asked, even in a terminal. -### - -​ - -Workspace not trusted when running claude ultrareview +### Workspace not trusted when running claude ultrareview In a folder you haven’t trusted, when [`claude ultrareview`](</docs/en/ultrareview#trust-the-folder-before-the-review-runs>) can’t ask whether you trust it, the run exits with code 1 before the review starts: @@ -3334,11 +2744,7 @@ Before v2.1.309, `claude ultrareview` didn’t accept `--trust-workspace`. -### - -​ - -Remote Control did not start because a question got no answer +### Remote Control did not start because a question got no answer This message means [`claude remote-control`](</docs/en/remote-control>) asked the first-run question quoted in the message and got no answer: @@ -3350,15 +2756,11 @@ * **`Enable Remote Control?`** : in a script or a service, standard input ends before anyone can answer. Run `claude remote-control` once in a terminal, as the user your script or service runs as, and answer `y`. * **`Choose [1/2] (default: 1):`** : run `claude remote-control` again and [choose a spawn mode](</docs/en/remote-control#set-the-default-spawn-mode-for-a-project>), or pass [`--spawn=same-dir` or `--spawn=worktree`](</docs/en/remote-control#start-a-remote-control-session>) to skip the question -### - -​ - -Not carried over to the sessions Remote Control starts +### Not carried over to the sessions Remote Control starts You started [Remote Control](</docs/en/remote-control>) with a global `claude` flag before the `remote-control` verb, one that would restrict or configure the sessions Remote Control starts, such as `--settings`, `--setting-sources`, `--permission-mode`, `--disallowed-tools`, or `--mcp-config`. A flag placed before the verb never reaches those sessions. Claude Code refuses to start instead, naming the flag: - Error: `--settings` before `remote-control` is not carried over to the sessions Remote Control starts, so Remote Control refuses to start rather than drop it — remove it, and give Remote Control's own options after the verb (see `claude remote-control --help`). + Error: `--settings` before `remote-control` is not carried over to the sessions Remote Control starts, so Remote Control refuses to start rather than drop it — remove it, and give Remote Control's own options after the verb (see `claude remote-control --help`). Pass settings with `claude remote-control --settings <file>`. Claude Code doesn’t refuse global flags that are harmless to drop, such as `--verbose`, `--model`, or a wrapper-injected `--session-id` or `--plugin-dir`: it ignores them and Remote Control starts. Claude Code also refuses to start for a global flag it doesn’t yet recognize as harmless, so a flag added in a newer release can appear in this message until a later release marks it harmless. **What to do:** @@ -3367,11 +2769,28 @@ Before v2.1.248, `claude remote-control` didn’t accept its own flags when a global flag came first, and the command failed with an `unknown option` error. -### - -​ - -`--sandbox` or `--no-sandbox` is not supported by claude remote-control +### Remote Control did not start because of the `--settings` file + +The file you passed to [`claude remote-control --settings`](</docs/en/remote-control#start-a-remote-control-session>) has a problem: + + Error: Remote Control did not start, because sessions would skip part or all of the --settings file ./rc-settings.json: Invalid or malformed JSON + +**What to do:** + + * Fix the problem the message names, then run your `claude remote-control` command again + +### The settings file has changed since Remote Control started + +This message in the terminal running `claude remote-control` means that sessions won’t start from the file you passed to [`--settings`](</docs/en/remote-control#start-a-remote-control-session>) as it is now: + + Session failed: Error: The settings file /path/to/settings.json has changed since Remote Control started, so this session did not start. Restart `claude remote-control` to use it as it is now. + +**What to do:** + + * To use the file as it is now, stop `claude remote-control` and run the same command again. To bring back the sessions it was serving, see [Resume sessions after stopping the server](</docs/en/remote-control#resume-sessions-after-stopping-the-server>). + * To keep the settings Remote Control started with, put the file’s contents back as they were, then run the command again if `claude remote-control` has exited + +### `--sandbox` or `--no-sandbox` is not supported by claude remote-control This error means the command that starts your [Remote Control](</docs/en/remote-control>) server passes `--sandbox` or `--no-sandbox` after `remote-control`, and `claude remote-control` accepts neither flag. The server exits with code 1 instead of starting: @@ -3385,11 +2804,7 @@ Both flags were removed from `claude remote-control` in v2.1.300, so a command written for an earlier version can still carry one. -### - -​ - -claude import is not yet available in this build +### claude import is not yet available in this build You ran [`claude import`](</docs/en/cli-reference#cli-commands>), and Claude Code found the import flow turned off, so the command exits with code 1 instead of starting the import. Before v2.1.222, a build with the import flow off treated `import` as a prompt and started an interactive session instead of printing this message. @@ -3406,11 +2821,7 @@ * On a fresh installation, start `claude`, wait for the session to load, exit, and run `claude import` again * Where feature-flag fetching stays off, set the configuration up yourself: add MCP servers with [`claude mcp add`](</docs/en/mcp#installing-mcp-servers>), and create the [`CLAUDE.md` files](</docs/en/memory#how-claude-md-files-load>), [skills and commands](</docs/en/skills#where-skills-live>), and [subagents](</docs/en/sub-agents#choose-the-subagent-scope>) you want to carry over. The message also names `~/.claude/settings.json`. Of the configuration `claude import` carries, that file holds only the [permission mode](</docs/en/settings-reference#permission-settings>); Claude Code doesn’t read MCP servers from it. -### - -​ - -Could not read Claude Code config +### Could not read Claude Code config You ran [`claude import`](</docs/en/cli-reference#cli-commands>) while Claude Code couldn’t parse `~/.claude.json`, the file where it stores your account details and per-project state. The subcommand reads that file to check availability but doesn’t show the recovery dialog the interactive session shows, so it exits with code 1. Before v2.1.222, `claude import` with an unreadable config file started an interactive session, whose recovery dialog handled the file. @@ -3421,11 +2832,7 @@ * Run `claude` with no arguments. Claude Code detects the invalid file and offers to reset it. Then run `claude import` again. * To keep manual edits you’ve made, fix the JSON syntax in `~/.claude.json` in an editor instead, then rerun `claude import` -### - -​ - -Could not import a server from Claude Desktop +### Could not import a server from Claude Desktop Claude Code couldn’t add one of the servers you selected in `claude mcp add-from-claude-desktop`. The command still imports the other selected servers and prints one line per server it couldn’t add. Before v2.1.205, the first server that failed stopped the import. @@ -3436,11 +2843,7 @@ * Rename the server in `claude_desktop_config.json` to use only letters, numbers, hyphens, and underscores, then run `claude mcp add-from-claude-desktop` again * Add that server directly with `claude mcp add` or `claude mcp add-json` under a valid name. See [Import MCP servers from Claude Desktop](</docs/en/mcp#import-mcp-servers-from-claude-desktop>). -### - -​ - -Cannot add MCP server to the managed scope +### Cannot add MCP server to the managed scope You ran `claude mcp add` or `claude mcp add-json` with `--scope managed`. That scope holds the servers your organization provides through the [`managedMcpServers`](</docs/en/settings-reference#managedmcpservers>) managed setting. Claude Code reads them from managed settings only, so the command can’t write a server to that scope. @@ -3451,11 +2854,7 @@ * Add the server to a scope you can write: `local`, `user`, or `project`. Without `--scope`, the command uses `local`. See [MCP installation scopes](</docs/en/mcp#mcp-installation-scopes>) * To provide the server to every user in your organization, add it to [`managedMcpServers`](</docs/en/settings-reference#managedmcpservers>) in the managed settings you deploy -### - -​ - -Cannot add MCP server when managed settings allow only plugin servers +### Cannot add MCP server when managed settings allow only plugin servers You ran `claude mcp add` or `claude mcp add-json` while your organization’s managed settings set [`strictPluginOnlyCustomization`](</docs/en/settings-reference#strictpluginonlycustomization>) to `true` or to a list that includes `mcp`. With that setting, Claude Code doesn’t load MCP servers from `~/.claude.json` or `.mcp.json`, so the command exits with code 1 instead of saving a server that would never load: @@ -3466,11 +2865,7 @@ * Install a [plugin](</docs/en/plugins/install>) that provides the server * Ask your administrator to distribute the server in a [plugin](</docs/en/plugins/org>), or to provide it through [`managedMcpServers`](</docs/en/settings-reference#managedmcpservers>) if it’s a remote HTTP or SSE server -### - -​ - -Can’t read .mcp.json +### Can’t read .mcp.json A command that reads the project’s [`.mcp.json`](</docs/en/mcp#project-scope>), such as `claude mcp add` or `claude mcp add-json` with `--scope project`, or `claude mcp remove`, found that the file in your current directory isn’t a regular file or is larger than 2 MiB, so it exits with this error instead of reading the file. @@ -3480,11 +2875,7 @@ * Check what sits at `.mcp.json` in your current directory. Replace it with an ordinary JSON file in the [project-scope format](</docs/en/mcp#project-scope>), or delete it, then run the command again. -### - -​ - -MCP server was not saved or removed +### MCP server was not saved or removed This error means a command such as `claude mcp add` or `claude mcp remove` didn’t get your change into `~/.claude.json`. Other Claude Code processes may have kept the file locked, or the file may be read-only or protected by a sandbox. @@ -3497,11 +2888,7 @@ Before v2.1.283, `claude mcp add`, `claude mcp add-json`, and `claude mcp remove` reported success even when the change didn’t reach the file. Before v2.1.318, the message didn’t mention the lock, and Claude Code didn’t read [`CLAUDE_CODE_CONFIG_LOCK_WAIT_MS`](</docs/en/env-vars#variables>). -### - -​ - -MCP server may not have been saved or removed +### MCP server may not have been saved or removed You ran `claude mcp add`, `claude mcp add-json`, or `claude mcp remove` for a server in the `user` or `local` [scope](</docs/en/mcp#mcp-installation-scopes>), and Claude Code couldn’t read `~/.claude.json` back to confirm the change. The change may or may not be on disk. The parentheses after `to confirm the change` give the reason. @@ -3512,11 +2899,7 @@ * Run `claude mcp get <name>` to check whether the change is on disk. For a `local`-scope server, run it from the project directory the server belongs to, since local scope is per project. * If the server is missing after an add, or still listed after a remove, run the same add or remove command again. -### - -​ - -Server is Anthropic-hosted and doesn’t support local OAuth +### Server is Anthropic-hosted and doesn’t support local OAuth You started a sign-in for an MCP server whose URL points at an Anthropic-hosted connector host that authenticates through a third-party identity provider. These hosts include `microsoft365.mcp.claude.com`, `gmail.mcp.claude.com`, and `gcal.mcp.claude.com`. Claude Code refuses to start its local OAuth flow for these hosts from both the `/mcp` panel and `claude mcp login`, because [their sign-in works only through claude.ai](</docs/en/mcp#use-mcp-servers-from-claude-ai>). @@ -3527,11 +2910,7 @@ * Remove your entry with `claude mcp remove <name>`, so it can’t hide the claude.ai connector at the same URL * After removing it, connect the service at [claude.ai/customize/connectors](<https://claude.ai/customize/connectors>), while signed in to the account you use in Claude Code. Once connected, [the connector appears in Claude Code automatically](</docs/en/mcp#use-mcp-servers-from-claude-ai>) if your active authentication method is a claude.ai subscription login -### - -​ - -Server rejected the Authorization header minted by the configured headersHelper +### Server rejected the Authorization header minted by the configured headersHelper An MCP server whose [`headersHelper`](</docs/en/mcp#use-dynamic-headers-for-custom-authentication>) supplies the `Authorization` header answered the connection with HTTP 401 or 403, so Claude Code reports the connection as failed. Because the helper supplies the `Authorization` header, Claude Code [doesn’t fall back to OAuth](</docs/en/mcp#authenticate-with-remote-mcp-servers>) for the server: @@ -3544,11 +2923,7 @@ Before v2.1.248, Claude Code ran OAuth discovery for a server whose helper supplied the `Authorization` header. That discovery could fail with `Incompatible auth server: does not support dynamic client registration` instead of reporting the rejected credential. -### - -​ - -MCP server rejected the elicitation capability +### MCP server rejected the elicitation capability An MCP server built on Java MCP SDK 0.11.0 through 0.17.0 refused the connection. Those SDK versions can’t parse the `form` and `url` [elicitation modes](</docs/en/mcp#elicitation-modes-claude-code-declares>) that Claude Code declares in its handshake. The message reads: @@ -3573,11 +2948,7 @@ After the restart, `/mcp` shows the server as connected. Claude Code declares form mode only to that server, so remove the field once you upgrade it. A server can also fail with its own error text, such as one containing `Unrecognized field "form"`. The same fixes apply. -### - -​ - -MCP permission prompt tool not found +### MCP permission prompt tool not found The tool you passed to [`--permission-prompt-tool`](</docs/en/cli-reference#cli-flags>) wasn’t among the connected MCP tools when the run first needed a permission decision, either because its server never connected or because no connected server exposes a tool by that name. Claude Code still sends your prompt: the [non-interactive](</docs/en/headless>) run exits with this error, and exit code 1, on the first tool call, so it produces no answer even though the request was made. Before the first prompt, Claude Code waits up to the per-server connection timeout of 30 seconds set by [`MCP_TIMEOUT`](</docs/en/env-vars>) for that server to connect. Before v2.1.206, startup didn’t wait for the server to finish connecting, so a slow-starting but healthy server produced this error too. @@ -3589,11 +2960,7 @@ * Confirm the tool name matches the `mcp__<server>__<tool>` name the server exposes * If the server needs longer than 30 seconds to start, raise [`MCP_TIMEOUT`](</docs/en/env-vars>) -### - -​ - -OAuth callback port is already in use +### OAuth callback port is already in use When you sign in to a remote MCP server with OAuth, Claude Code starts a local listener to receive the sign-in callback. If the port that listener needs is held by another process, the sign-in fails with this message. This mostly happens with a [fixed callback port](</docs/en/mcp#use-a-fixed-oauth-callback-port>) set through the [`MCP_OAUTH_CALLBACK_PORT`](</docs/en/env-vars>) variable or `--callback-port`, since without one Claude Code picks an available port. @@ -3605,11 +2972,7 @@ * If another program needs that port permanently, register a different redirect URI with the server and set its port with `MCP_OAUTH_CALLBACK_PORT` or `--callback-port`, whichever you use * Then start the sign-in again, for example by selecting the server in `/mcp` -### - -​ - -No available ports for OAuth redirect +### No available ports for OAuth redirect When you sign in to a remote MCP server with [OAuth](</docs/en/mcp#authenticate-with-remote-mcp-servers>), Claude Code starts a local listener to receive the sign-in callback. The sign-in fails with this message when Claude Code can’t bind a local port for it. Something on the machine is preventing it from listening on `127.0.0.1`, for example security software or a sandbox policy that denies local listeners. @@ -3620,11 +2983,7 @@ * Check whether security software or a sandbox policy blocks processes from listening on `127.0.0.1`, and allow Claude Code to bind a local port * Then start the sign-in again, for example by selecting the server in `/mcp` -### - -​ - -/security-review fails without origin/HEAD +### /security-review fails without origin/HEAD [`/security-review`](</docs/en/commands#all-commands>) builds its review context by diffing your branch against `origin/HEAD`, the local ref that records which branch is the default on your `origin` remote. When that ref doesn’t exist, the git commands that gather the diff fail and the review stops before it starts. @@ -3650,11 +3009,7 @@ * If you’d rather not name the branch, run `git fetch origin` and then `git remote set-head origin --auto`, which asks the remote which branch is its default. It fails with `error: Cannot determine remote HEAD` when the remote advertises no default branch, because it is empty or its HEAD points at a branch nobody pushed; name the branch explicitly instead. It fails with `error: Not a valid ref` when your clone doesn’t fetch that branch; widen the refspec as above first. * If the repository has no remote, add one with `git remote add origin <url>` and fetch before creating the ref. If the remote is empty, push your branch first with `git push -u origin HEAD` and name that branch in the set-head command; `origin/HEAD` then points at the branch you just pushed, so `/security-review` sees an empty diff until the branch diverges from it. -### - -​ - -No shell command in a skill or command was run +### No shell command in a skill or command was run `No shell command in <name> was run` means a `!`<command>`` [dynamic context command](</docs/en/skills#inject-dynamic-context>) in that skill or command file contains a character that the Bash or PowerShell tool refuses: @@ -3670,11 +3025,7 @@ * Find each `�` in the command quoted at the end of the message. Remove the character it stands for from the [skill or command file](</docs/en/skills#where-skills-live>), or from the arguments or [options](</docs/en/plugins/manifest-reference#user-configuration>) substituted into the file. -### - -​ - -Input must be provided when using `--print` +### Input must be provided when using `--print` Bare `claude` needs stdout to be a terminal to start the interactive UI. When stdout is redirected, or the console isn’t a real terminal, such as PowerShell ISE and some IDE output panes, `claude` runs [non-interactively](</docs/en/headless>) instead. That is the same mode as `claude -p`, which requires a prompt, so the message names `--print` even when you didn’t pass the flag. Passing `-p`/`--print` with no prompt and nothing piped on stdin produces the same error anywhere. @@ -3685,11 +3036,7 @@ * For interactive use, run `claude` in a real terminal: Windows Terminal or the PowerShell console rather than ISE, and your IDE’s integrated terminal rather than an output pane * For one-shot use, pass the prompt: `claude -p "your question"`, or pipe it with `echo "your question" | claude -p` -### - -​ - -Claude Code can’t read the keyboard here +### Claude Code can’t read the keyboard here You ran `claude` without [`-p`](</docs/en/headless>), which starts an [interactive session](</docs/en/interactive-mode>), but its standard input isn’t a terminal. Something piped or redirected it, or the program that launched `claude` supplied its own input stream. An interactive session needs a terminal to read your keystrokes from, and what Claude Code does without one depends on your platform: @@ -3709,11 +3056,7 @@ Before v2.1.287, Claude Code started the interface instead of printing this message, then either showed nothing on screen or failed with an error containing `Raw mode is not supported`. If you see `Raw mode is not supported` during `claude install` instead, see [`Raw mode is not supported` during install](</docs/en/troubleshoot-install#raw-mode-is-not-supported-during-install>). -### - -​ - -Input contained only whitespace +### Input contained only whitespace In [non-interactive mode](</docs/en/headless>), Claude Code refuses a prompt made up entirely of spaces, tabs, or newlines instead of sending it, because the API rejects messages with no visible text. Which message you see depends on where the blank prompt came from: @@ -3724,11 +3067,7 @@ * Include visible text in the prompt. If a script builds the prompt from a variable or file, check that the source isn’t empty before calling Claude Code. -### - -​ - -stream-json input carried over 256M characters with no newline +### stream-json input carried over 256M characters with no newline Your program sent more than 268,435,456 characters on stdin without a newline to a `claude -p --input-format stream-json` run, so Claude Code prints this error to stderr and exits with code 1 instead of buffering more input. The message states that budget as `256M`. Before v2.1.257, Claude Code buffered such input without limit, growing memory until the process crashed or was killed. @@ -3739,11 +3078,7 @@ * Check what’s piped to stdin. With [`--input-format stream-json`](</docs/en/cli-reference#cli-flags>), every message must be one newline-terminated JSON line * To send plain text instead, drop `--input-format stream-json`; `claude -p` reads a plain-text prompt from stdin by default -### - -​ - -Unknown command +### Unknown command In an interactive terminal session, you submitted a `/` name that doesn’t match any command in this session, so Claude Code reports the name instead of running anything: @@ -3768,11 +3103,7 @@ * Run the suggested name, or type `/` followed by part of the name to see what’s available in this session * If Claude Code reports a documented command as unknown, check its row in the [commands reference](</docs/en/commands>) for the requirement it names -### - -​ - -Diff is too large for ultrareview +### Diff is too large for ultrareview The diff between your branch and the base branch, including uncommitted and staged changes, exceeds the size limits for an [ultrareview](</docs/en/ultrareview>), so `/code-review ultra` and the `claude ultrareview` subcommand refuse the review before the cloud session starts. A refused review doesn’t use a free run and doesn’t bill usage credits. The message names the limits in effect, the size of your diff, and the files that contribute the most changed lines. Before v2.1.216, the message showed only the raw diff statistics. @@ -3783,11 +3114,7 @@ * Pass a base branch closer to your work, such as `/code-review ultra develop`, so the review covers only the diff against that branch * Split the change into smaller branches and review each one. The files the message names contribute the most changed lines, so start by moving those to their own branch. -### - -​ - -Could not find merge-base with the base branch +### Could not find merge-base with the base branch `/code-review ultra` and the `claude ultrareview` subcommand review the diff between your branch and a base branch, which needs a commit the two share. When `git merge-base` finds none, Claude Code refuses the review before the cloud session starts. On a clone Claude Code can verify is complete, with at least one branch, it falls back to [reviewing every tracked file](</docs/en/ultrareview#diff-limits-and-fallbacks>) instead of refusing. You see this refusal when the base branch can’t be found at all, when Claude Code can’t verify that your clone is complete, or in the rare repository where the whole-tree diff isn’t possible, such as the SHA-256 object format. @@ -3804,11 +3131,7 @@ * If another branch is your real base, pass it explicitly: `/code-review ultra <branch>` * If your clone might not have full history, run `git fetch --unshallow origin` and rerun the review -### - -​ - -Your checkout has no branches +### Your checkout has no branches A checkout can have commits but no branches: if you run `git init` followed by `git fetch <url>` and `git checkout FETCH_HEAD`, you get a detached HEAD with no refs. Claude Code packages your repository as a git bundle to upload it for an [ultrareview](</docs/en/ultrareview>), and it can’t bundle a repository that has no branches or other refs, so `/code-review ultra` and the `claude ultrareview` subcommand refuse the review before the cloud session starts. @@ -3818,11 +3141,7 @@ * Create a branch at your current commit with `git checkout -b <name>`, then rerun the review -### - -​ - -No GitHub account is connected to your Claude account +### No GitHub account is connected to your Claude account You ran `/code-review ultra <PR#>` or `claude ultrareview <PR#>`, and before creating the cloud session Claude Code asks the server whether [the GitHub account connected to your Claude account](</docs/en/ultrareview#review-a-pull-request>) can reach the PR’s repository. No account is connected, or the connection expired, so the cloud clone would fail and Claude Code refuses the launch. Claude Code doesn’t spend a free run or bill usage credits for a refused launch. @@ -3835,11 +3154,7 @@ Before v2.1.248, Claude Code didn’t check this before launch. -### - -​ - -Your connected GitHub account can’t see the repository +### Your connected GitHub account can’t see the repository You ran `/code-review ultra <PR#>` or `claude ultrareview <PR#>`, and [the GitHub account connected to your Claude account](</docs/en/ultrareview#review-a-pull-request>) can’t read the PR’s repository, so the cloud clone would fail and Claude Code refuses the launch. Claude Code doesn’t spend a free run or bill usage credits for a refused launch. @@ -3852,11 +3167,7 @@ Before v2.1.248, Claude Code didn’t check this before launch. -### - -​ - -The GitHub App preflight failed transiently +### The GitHub App preflight failed transiently You started a [cloud session](</docs/en/claude-code-on-the-web>) from a local repository, and two steps failed together. Claude Code couldn’t build or upload the bundle of your repository. Before the upload, it checked whether the cloud service can clone the repository from GitHub, and rather than a definite answer, that check ended in an error that a retry could clear, such as a network error, a timeout, or a temporary server error. The full message starts with what stopped the bundle, for example `Could not upload repo bundle (<error>)`, and ends with the preflight sentence: @@ -3869,11 +3180,7 @@ Before v2.1.251, Claude Code ended the message with `Please set up GitHub on https://claude.ai/code` even when the GitHub check failed only transiently, and setup advice can’t clear a transient failure. -### - -​ - -The repository upload can’t follow a git setting +### The repository upload can’t follow a git setting You started a [cloud session that uploads your local repository](</docs/en/claude-code-on-the-web#send-local-repositories-without-github>), or an [ultrareview](</docs/en/ultrareview>) of a branch, and the upload can’t follow one of the git settings that decide which attribute rules apply to your files. If the upload went ahead and missed a rule, a file that git transforms before storing it, such as one a clean filter encrypts, could reach the cloud as it is on disk. Claude Code refuses the upload instead, and nothing is uploaded: @@ -3883,11 +3190,7 @@ * Apply the fix in the message’s final sentence -### - -​ - -GitHub isn’t connected to your Claude account +### GitHub isn’t connected to your Claude account You started a [cloud session](</docs/en/claude-code-on-the-web>) from your local repository, for example with `/autofix-pr`. No GitHub account is connected to your Claude account, or the connection expired, so Claude Code refuses the launch: @@ -3900,11 +3203,7 @@ Before v2.1.268, Claude Code reported this as a temporary failure of the Claude GitHub App check and suggested retrying or installing the app; neither connects a GitHub account. -### - -​ - -A GitHub organization policy is blocking Claude +### A GitHub organization policy is blocking Claude You ran a command at the Claude Code prompt that starts a cloud session, such as [`/autofix-pr`](</docs/en/claude-code-on-the-web#auto-fix-pull-requests>). Before it creates the session, Claude Code checks Claude’s access to the repository on GitHub, and GitHub refused because your GitHub organization has a policy that blocks Claude. Claude Code stops there and shows a message naming the policy. When an IP allow list is what blocks the access, the message reads: @@ -3925,11 +3224,7 @@ * **Conditional Access policy** : ask your GitHub Enterprise or Microsoft Entra ID administrator to allow Claude in that policy * After the change, run the command again -### - -​ - -Single sign-on authorization needed +### Single sign-on authorization needed You ran [`/install-github-app`](</docs/en/github-actions#quick-setup>) and chose a repository whose organization enforces SAML single sign-on. Before setup, Claude Code checks your access to the repository with the GitHub CLI, and GitHub refused that check because your `gh` token isn’t authorized for the organization yet. The wizard shows the warning with the steps to authorize: @@ -3944,11 +3239,7 @@ Before v2.1.273, Claude Code showed the `Admin permissions required` warning for this condition instead. -### - -​ - -Failed to resume the conversation +### Failed to resume the conversation Claude Code couldn’t read or process the saved transcript for the session you selected from the [`claude --resume` picker](</docs/en/sessions#use-the-session-picker>), so it ends the process rather than continue in a partially loaded state. The message includes the command to retry: @@ -3961,11 +3252,7 @@ * On a version before v2.1.285, if the retry fails the same way, run `claude update` and resume again. Those versions fail the resume when the saved transcript contains an entry they can’t read. * If the retry fails again, run `claude` to start a new session -### - -​ - -No conversation found with the session ID +### No conversation found with the session ID You passed a session ID to `claude --resume <session-id>` and no saved transcript matched it: @@ -3983,11 +3270,7 @@ * For an interactive session, open the [session picker](</docs/en/sessions#use-the-session-picker>) with `claude --resume` and press `Ctrl+A` to widen it to every project on this machine, then select the session * Sessions created with `claude -p` or the [Agent SDK](</docs/en/agent-sdk/overview>) don’t appear in the picker, so re-check the ID against the `session_id` your original run printed -### - -​ - -Windows reported an error (EBADF) when Claude Code read this session’s transcript file +### Windows reported an error (EBADF) when Claude Code read this session’s transcript file You resumed a session on Windows, its saved [transcript file](</docs/en/sessions#where-transcripts-are-stored>) opened normally, and reading it then failed with the system error EBADF. The system error doesn’t say why the read failed, so the message suggests likely causes and what to try: @@ -4001,11 +3284,7 @@ Before v2.1.282, the failure came with no explanation: `claude --resume <session-id>` ended at `Failed to resume session <session-id>`, and a `-p` run printed only the system error text, such as `Failed to resume session: EBADF: bad file descriptor, read`. -### - -​ - -Cannot switch renderers in this session +### Cannot switch renderers in this session When you switch renderers, Claude Code restarts its process. You ran [`/tui`](</docs/en/fullscreen#enable-fullscreen-rendering>) in a session Claude Code declines to restart, so it doesn’t switch and saves nothing. Which message you see tells you the cause: @@ -4027,19 +3306,11 @@ * 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 -### - -​ - -Can’t restart while work is running or Remote Control is connected +### Can’t restart while work is running or Remote Control is connected Claude Code didn’t restart, and your session keeps running as it was. Follow the fix in the message. -### - -​ - -Claude Code couldn’t restart +### Claude Code couldn’t restart When this message says your conversation is saved, the conversation is on disk and you can pick it up where it stopped. Claude Code was restarting itself, for example to switch to or from fullscreen rendering after you ran [`/tui`](</docs/en/fullscreen#enable-fullscreen-rendering>), and couldn’t start the new process, so it exited with status 1: @@ -4050,11 +3321,7 @@ * Run `claude` again in your shell. If the message said your conversation is saved, run [`/resume`](</docs/en/sessions#resume-a-session>) in the new session and select the conversation. If it isn’t in the list, [widen the session picker](</docs/en/sessions#where-the-session-picker-looks>) * 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 -### - -​ - -Couldn’t open Claude Desktop +### Couldn’t open Claude Desktop You ran [`/desktop`](</docs/en/desktop#coming-from-the-cli>) or its alias `/app` in a session, or [`claude --desktop`](</docs/en/cli-reference#cli-flags>) in your shell, and the system command Claude Code uses to open Claude Desktop failed. After `/desktop`, the session stays in the terminal; `claude --desktop` prints the message without the `Error:` prefix and exits with status 1. The text in parentheses names the command that failed, with its exit status and the first line of its error output when it produced them. On macOS that command is `open`, as in this example; on Windows it is `rundll32`: @@ -4067,11 +3334,7 @@ Before v2.1.285, the message ended `Open Claude Desktop and run /desktop again.` Before v2.1.275, it was `Failed to open Claude Desktop. Please try opening it manually.` and didn’t say what failed. -### - -​ - -/terminal-setup left your Zed keymap unchanged +### /terminal-setup left your Zed keymap unchanged You ran [`/terminal-setup`](</docs/en/terminal-config#enter-multiline-prompts>) in Zed, and Claude Code couldn’t complete the update to your Zed `keymap.json`, so it left the file as it was. Each message names the path to your keymap and ends with the keybinding block to add yourself: @@ -4093,11 +3356,7 @@ Before v2.1.247, `/terminal-setup` couldn’t parse a Zed keymap that used `//` comments or trailing commas, and it replaced the entire file with only its own binding while reporting the binding as installed. To restore a keymap an earlier version replaced, use the `.bak` backup file described under [Enter multiline prompts](</docs/en/terminal-config#enter-multiline-prompts>). -### - -​ - -Skill usage reports are not available on this connection +### Skill usage reports are not available on this connection You ran [`/skill-doctor`](</docs/en/skills#find-unused-skills>) over [Remote Control](</docs/en/remote-control>), from your phone or browser. Claude Code doesn’t send the skill usage report over Remote Control and replies with this message instead: @@ -4107,11 +3366,7 @@ * Run `/skill-doctor` in the terminal on the machine where the session is running, or run `claude -p "/skill-doctor"` there -### - -​ - -Custom output styles can’t be selected over Remote Control +### Custom output styles can’t be selected over Remote Control You ran [`/output-style`](</docs/en/output-styles#change-your-output-style>) from the mobile app or web via [Remote Control](</docs/en/remote-control>), or the command arrived in a message relayed into the session. Because such a turn may not come from the account owner, Claude Code lists and selects only [built-in styles](</docs/en/output-styles#built-in-output-styles>) on it, and adds this notice whenever the command lists the styles or doesn’t recognize the name you gave. A [custom style](</docs/en/output-styles#create-a-custom-output-style>) name gets the same reply as a name that doesn’t exist: @@ -4122,11 +3377,7 @@ * Pick a built-in style, for example `/output-style concise` * To use a custom style, set [`outputStyle`](</docs/en/settings-reference#outputstyle>) in the project’s `.claude/settings.local.json`, or run `/output-style <style>` at the session’s own terminal if it has one -### - -​ - -Output styles are saved to local settings which this session doesn’t load +### Output styles are saved to local settings which this session doesn’t load You tried to switch [output styles](</docs/en/output-styles>) with `/output-style <style>` or `/config outputStyle=<style>` in a session whose setting sources exclude `local`. Examples are an [Agent SDK](</docs/en/agent-sdk/typescript>) session whose [`settingSources`](</docs/en/agent-sdk/typescript#options>) leaves out `"local"` and a CLI session started with a [`--setting-sources`](</docs/en/cli-reference#cli-flags>) value that leaves out `local`. Both commands save the style to `.claude/settings.local.json`, a file such a session never reads back, so Claude Code refuses instead of writing a setting that would have no effect: @@ -4137,11 +3388,7 @@ * Add `local` to the session’s setting sources and switch again * Set the [`outputStyle`](</docs/en/settings-reference#outputstyle>) key in a settings file the session does load, such as `.claude/settings.json` in the project or `~/.claude/settings.json`. In the TypeScript SDK, set `outputStyle` inside the inline `settings` object instead; see [Activate an output style](</docs/en/agent-sdk/modifying-system-prompts#activate-an-output-style>) -### - -​ - -/recap only runs when you ask for it yourself +### /recap only runs when you ask for it yourself The [`/recap`](</docs/en/interactive-mode#session-recap>) request didn’t come from your own input. It arrived in a message relayed into the session from a Slack, Teams, or [project](</docs/en/claude-projects>) thread, or in a prompt that a [cloud scheduled task](</docs/en/routines>) or another program sent. A relayed message gets the notice even when you wrote it yourself. Claude Code can’t tell that a relayed or automated message came from the person whose account runs the session, so it answers with this notice instead of a summary: @@ -4152,11 +3399,7 @@ * Open the session yourself and run `/recap` there: in its terminal, in the [Desktop app](</docs/en/desktop>) or the [mobile app](</docs/en/mobile>), at [claude.ai/code](<https://claude.ai/code>), or over [Remote Control](</docs/en/remote-control>) * If a cloud scheduled task or another program sent it, remove `/recap` from that prompt -### - -​ - -/feedback is disabled by your organization’s policy +### /feedback is disabled by your organization’s policy This message means product feedback is turned off, so the command you typed doesn’t open the feedback dialog. An organization’s policy and an earlier refusal both produce the message: @@ -4174,19 +3417,11 @@ Before v2.1.319, an earlier refusal didn’t produce this message. Before v2.1.302, the full message read `/feedback is disabled by your organization's policy. Contact your organization admin to enable it.` -## - -​ - -Plugin errors +## Plugin errors These errors come from [plugin](</docs/en/plugins/overview>) and [marketplace](</docs/en/plugins/overview>) configuration. For plugin problems that don’t produce one of the messages on this page, such as a marketplace URL that doesn’t load or a plugin that installs but doesn’t appear, see [Plugin troubleshooting](</docs/en/plugins/troubleshooting>). -### - -​ - -plugin eval is currently in early access +### plugin eval is currently in early access You ran [`claude plugin eval`](</docs/en/plugin-evals>) or `claude plugin eval init` and it exited 1 with one of these messages before doing anything: @@ -4199,11 +3434,7 @@ * Run `claude --version`, then `claude update`, and run the command again in a fresh session. See the [requirements for plugin evals](</docs/en/plugin-evals#requirements>) * If you see the second message on a current build, try again later after another `claude update` -### - -​ - -Marketplace is registered from an untrusted source +### Marketplace is registered from an untrusted source The marketplace is registered under a name that is [reserved for official Anthropic marketplaces](</docs/en/plugins/marketplace-reference#marketplace-file>), but its registered source isn’t an `anthropics` GitHub repository. Claude Code re-checks reserved names every time it loads or refreshes a marketplace, so the marketplace and the plugins installed from it stop loading. Before v2.1.205, an entry registered before its name became reserved kept loading. @@ -4215,11 +3446,7 @@ * If you publish a third-party marketplace that used the name before it became reserved, rename it and ask users to re-add it from your source * See the reserved name list under [Marketplace schema](</docs/en/plugins/marketplace-reference#marketplace-file>) -### - -​ - -Marketplace name is another spelling of a reserved name +### Marketplace name is another spelling of a reserved name The marketplace’s name isn’t itself a reserved name, but Claude Code treats it as another spelling of one. [Reserved names](</docs/en/plugins/marketplace-reference#reserved-name-spellings>) lists which spellings count as a reserved name. Claude Code refuses such a name when you add the marketplace: @@ -4234,11 +3461,7 @@ * Rename the marketplace to a name that doesn’t spell a reserved name and add it again * For the ignored-entry warning, run the `claude plugin marketplace remove` command it gives, or remove the entry from `~/.claude/plugins/known_marketplaces.json` -### - -​ - -Claude Code refuses the marketplace name +### Claude Code refuses the marketplace name A registered marketplace’s name [impersonates an official Anthropic marketplace](</docs/en/plugins/marketplace-reference#reserved-names>) under the rules that section lists. If a marketplace was registered under such a name before the check blocked it, the marketplace and the plugins installed from it stop loading, because Claude Code checks the name every time it reads the marketplace’s catalog. When the name imitates an official one, `claude plugin list` and the `/plugin` **Errors** tab report each affected plugin with a message that begins: @@ -4254,11 +3477,7 @@ * To remove the marketplace, run `claude plugin marketplace remove <name>`. This also uninstalls the plugins installed from the marketplace and deletes their data, options, and secrets * If you publish the marketplace, rename it in your `marketplace.json`; users then update the marketplace instead of removing it -### - -​ - -Marketplace is already added from a different source +### Marketplace is already added from a different source You named a new marketplace source with [`--marketplace <source>` on the install command](</docs/en/plugins/install#add-a-marketplace-and-install-in-one-command>), in a session or from your shell. The catalog Claude Code fetched from that source has the same name as a marketplace you already added from a different source. Claude Code keeps the existing marketplace instead of replacing it, and the plugin isn’t installed. @@ -4269,11 +3488,7 @@ * If the marketplace you already added is the one you want, install from it by name: `/plugin install <plugin>@<name>` * To switch to the new source, run `/plugin marketplace remove <name>`, then retry the install -### - -​ - -Plugin command references user_config in a shell command +### Plugin command references user_config in a shell command A plugin hook, [monitor](</docs/en/plugins/components#monitors>), or MCP [`headersHelper`](</docs/en/mcp#use-dynamic-headers-for-custom-authentication>) command references a `${user_config.KEY}` [plugin option](</docs/en/plugins/manifest-reference#user-configuration>), and the substituted string would be passed to a shell. A configured value containing `$(...)`, backticks, or `;` would run as code there, so Claude Code refuses to start the component instead of substituting the value. The check runs on the command template, so the error appears even when no value is configured yet. Before v2.1.207, the value was substituted into the shell command. The wording depends on which surface referenced the option. A shell-form hook reports: @@ -4293,11 +3508,7 @@ * For a monitor, drop the reference and have the monitor script read the value from a config file * For a `headersHelper`, move `${user_config.KEY}` into the server’s `headers` field, which isn’t shell-parsed, or read the value inside the helper script -### - -​ - -Plugin archive integrity check failed +### Plugin archive integrity check failed The plugin’s marketplace entry uses an [`archive` source](</docs/en/plugins/marketplace-reference#archive-plugin-source>) with a `sha256` pin, and the digest of the downloaded file doesn’t match the pin. Claude Code refuses the install, so nothing changes in the plugin cache. The mismatch has three possible causes: @@ -4313,11 +3524,7 @@ * If you install the plugin, run `/plugin marketplace update <name>` to refresh the catalog in case the entry was corrected, then retry the install * If the digests still disagree after a refresh, ask the marketplace owner which file they pinned before installing -### - -​ - -Path escapes plugin directory +### Path escapes plugin directory One of the plugin’s component paths leads outside the plugin directory or couldn’t be confirmed inside it, so Claude Code drops that path and loads the rest of the plugin. For a path the plugin declares in `plugin.json` or its [marketplace entry](</docs/en/plugins/marketplace-reference#plugin-entries>), the component name in the message, such as `commands` or `hooks`, names the field that declared the path. @@ -4327,11 +3534,10 @@ commands path escapes plugin directory: ./commands/deploy.md — it resolves to /home/user/shared/deploy.md, outside the plugin directory -A message that gives the full path of one of a marketplace plugin’s own files, such as `hooks/hooks.json`, means Claude Code skipped that file. That happens when Claude Code can’t confirm the file is inside the plugin or, for a plugin in a [local marketplace](</docs/en/plugins/loading#in-place-and-copied-plugins>), inside that marketplace. The message reports each of these files under the component name shown: +A message that gives the full path of one of a marketplace plugin’s own files, such as `hooks/hooks.json`, means Claude Code skipped that file. When Claude Code can’t confirm the file is inside the plugin, or inside its marketplace for a plugin in a [local marketplace](</docs/en/plugins/loading#in-place-and-copied-plugins>), it skips the file. The message reports these files under the component name shown: * `hooks/hooks.json`: `hooks` * `monitors/monitors.json`: `monitors` - * `settings.json`: `settings` * `SKILL.md` at the plugin root: `skills` For example, this message is for a `hooks/hooks.json` that resolves outside both the plugin and its local marketplace: @@ -4351,11 +3557,7 @@ * If the message ends with `EACCES`, restore your execute permission on every directory leading to the file or folder the path names. Check the directories above the path, then follow each symlink you reach and check the directories leading to where it points. For any other error code, look it up in the causes and steps for a path that couldn’t be checked. * To share files with other plugins in the same marketplace, link them with a symlink inside the plugin directory, following the [symlink rules](</docs/en/plugins/host-marketplace#share-files-within-a-marketplace-with-symlinks>) -### - -​ - -Server file path not read +### Server file path not read The `path not read` message means Claude Code didn’t read an MCP or LSP server file that a plugin names, because of the file’s path. The rest of the plugin loads, without the servers the file defines. A `..` part counts even when the path stays inside the plugin, as in this example: @@ -4367,11 +3569,7 @@ * If you maintain the plugin, keep the server file inside the plugin directory. Name it in the manifest or marketplace entry with a path that starts with `./` and has no `..`, for example `./servers/x.json` * To share one server file between plugins in the same marketplace, link the file into each plugin with a symlink, following the [symlink rules](</docs/en/plugins/host-marketplace#share-files-within-a-marketplace-with-symlinks>) -### - -​ - -Plugin not loaded: its manifest was not read +### Plugin not loaded: its manifest was not read Claude Code couldn’t confirm that a marketplace plugin’s [manifest](</docs/en/plugins/manifest-reference>) at `.claude-plugin/plugin.json` is inside the plugin, so it loads nothing from that plugin. For a plugin in a [local marketplace](</docs/en/plugins/loading#in-place-and-copied-plugins>), Claude Code also couldn’t confirm that the manifest is inside that marketplace. The message appears in the `/plugin` **Errors** tab, and the reason at its end says what Claude Code found. For example, this message is for a plugin in a local marketplace whose `.claude-plugin` folder is a symlink leading outside the marketplace: @@ -4383,11 +3581,7 @@ * If you maintain the plugin and the reason says where the manifest resolves, the `.claude-plugin` folder or `plugin.json` itself is a symlink that leads there. Replace that link with a copy of what it points to. * If you installed the plugin and don’t maintain it, report the message to its author -### - -​ - -Path could not be checked +### Path could not be checked Claude Code asked the operating system whether a plugin path exists and got an error other than “not found”, so it doesn’t load what the path names. How much of the plugin loads depends on which path failed: @@ -4413,11 +3607,7 @@ Before v2.1.265, Claude Code treated a default component folder it couldn’t check as absent and loaded the plugin without that component, with no error. -### - -​ - -Marketplace entry path does not stay inside the marketplace directory +### Marketplace entry path does not stay inside the marketplace directory The plugin’s [marketplace entry](</docs/en/plugins/marketplace-reference#plugin-entries>) declares a source path that Claude Code can’t resolve to a location inside the marketplace’s own directory, so the plugin doesn’t install or load. The refusal covers: @@ -4439,11 +3629,7 @@ * If you maintain the marketplace, write the entry’s `source` as a plain relative path with forward slashes, such as `./plugins/my-plugin`, and keep any symlink it crosses pointed inside the marketplace directory * If you added the marketplace from a direct URL, relative entries can’t resolve. Ask the marketplace author to use [another plugin source](</docs/en/plugins/marketplace-reference#plugin-sources>), or add the marketplace from its git repository instead -### - -​ - -Failed to load marketplace configuration +### Failed to load marketplace configuration Claude Code keeps the plugin marketplaces you’ve added in a registry file at `~/.claude/plugins/known_marketplaces.json`. A plugin command that needs the registry, such as `claude plugin install`, fails with one of two messages when Claude Code can’t use the file: @@ -4459,11 +3645,7 @@ * Open `~/.claude/plugins/known_marketplaces.json` and repair the JSON, or fix the entries the message names as not matching the registry schema * If you can’t repair it, delete the file or replace its contents with `{}`, then re-add each marketplace with `claude plugin marketplace add <source>`. Claude Code re-registers the marketplaces your user or managed settings declare in [`extraKnownMarketplaces`](</docs/en/settings-reference#extraknownmarketplaces>) the next time you start it in a folder you’ve trusted. -### - -​ - -Plugin is required by your organization +### Plugin is required by your organization You ran `claude plugin disable`, or used the `/plugin` **Installed** tab, to turn off a [plugin synced from claude.ai](</docs/en/plugins/loading#synced-plugins>) that your organization marks as required: @@ -4473,11 +3655,7 @@ * Ask an admin of your claude.ai organization to change the plugin’s required status on claude.ai -### - -​ - -Plugin was not uninstalled +### Plugin was not uninstalled You ran [`claude plugin uninstall`](</docs/en/plugins/cli-reference#plugin-uninstall>), or chose **Uninstall** in the `/plugin` **Installed** tab, and the uninstall stopped with a message starting `"<plugin>" was not uninstalled:`. If the text after that colon starts with `installed_plugins.json` instead of naming a settings file, the cause is content in `installed_plugins.json` that this version of Claude Code can’t read. For that form, see [`installed_plugins.json` holds a record this version can’t read](</docs/en/plugins/troubleshooting#installed-plugins-json-holds-a-record-this-version-cannot-read>). When Claude Code removed the plugin’s entry from `enabledPlugins` and read that scope’s settings files back, either the plugin was still switched on there, or a file that could switch it on couldn’t be read or checked. Deleting the plugin’s saved options, secrets, and data while a settings entry could switch it back on would lose them, so the uninstall stops instead: the plugin stays installed and nothing it saved is deleted. @@ -4494,11 +3672,7 @@ * Follow the last sentence of the message: repair or replace the settings file it names, or remove the plugin’s entry from `enabledPlugins` in that file yourself, then run the uninstall again -### - -​ - -Skipping connection (recent failure cached; retries automatically in 15 min, or edit the plugin config to retry now) +### Skipping connection (recent failure cached; retries automatically in 15 min, or edit the plugin config to retry now) This message means Claude Code didn’t start a stdio [MCP server that a plugin provides](</docs/en/mcp#plugin-provided-mcp-servers>), because a connection to that server failed less than 15 minutes earlier: @@ -4513,19 +3687,11 @@ The message replaces the error from the failed connection. If the new attempt fails too, Claude Code reports that attempt’s error instead of this message. -## - -​ - -Tool errors +## Tool errors These errors come from Claude’s tool calls. Claude corrects most tool errors on its own. When one needs a change from you, that error’s **What to do** list says what to change. -### - -​ - -No such tool available +### No such tool available Claude called a tool by a name that isn’t in the session’s tool list. Claude Code returns the error to Claude as the tool call’s result, and the turn continues. When Claude Code can tell why the tool is missing, it adds a sentence after the tool name that gives the reason or names the tool to call instead, as in the second line: @@ -4537,11 +3703,7 @@ * If it happens once, you don’t need to do anything. Claude reads the error and the turn continues. * If calls to an MCP server’s tools keep failing with this error, run `/mcp` in the session or `claude mcp list` in your shell to check the server’s [status](</docs/en/mcp#server-status>), and reconnect a failed server from `/mcp`. In the Agent SDK, see [Error handling](</docs/en/agent-sdk/mcp#error-handling>). -### - -​ - -MCP server connection closed before the tool call was answered +### MCP server connection closed before the tool call was answered A tool call to an HTTP [MCP server](</docs/en/mcp>) or a [claude.ai connector](</docs/en/mcp#use-mcp-servers-from-claude-ai>) lost its connection before the server answered, so Claude Code can’t tell whether the tool ran: @@ -4554,11 +3716,7 @@ * If the action didn’t happen, ask Claude to run the tool again. You don’t need to reconnect the server first, because Claude Code connects to it again for the next call to one of its tools. If that connection fails too, see [Mid-session drops of a remote server](</docs/en/mcp#mid-session-drops-of-a-remote-server>). * If you build the server and the tool is safe to call twice, [mark it as safe to repeat](</docs/en/mcp#tool-calls-pending-when-a-connection-closes>) so that Claude Code can repeat a lost call -### - -​ - -MCP server is disabled +### MCP server is disabled This message in a tool result means Claude called a tool on an [MCP server](</docs/en/mcp>) that is [turned off](</docs/en/mcp#disable-a-server-without-removing-it>). Claude Code didn’t connect to the server, so the tool didn’t run, and Claude received this text in place of a result: @@ -4570,11 +3728,7 @@ * If Claude needs the server’s tools, turn it back on from `/mcp` at the Claude Code prompt * In an [Agent SDK](</docs/en/agent-sdk/overview>) application, turn the server back on by calling [`toggleMcpServer()`](</docs/en/agent-sdk/typescript#togglemcpserver>) in TypeScript with `enabled` set to `true`, or [`toggle_mcp_server()`](</docs/en/agent-sdk/python#claudesdkclient>) in Python with `enabled` set to `True` -### - -​ - -MCP tool call timed out with the server’s question unanswered +### MCP tool call timed out with the server’s question unanswered In [non-interactive mode](</docs/en/headless>), an [MCP server](</docs/en/mcp>) asked for input through [elicitation](</docs/en/mcp#respond-to-mcp-elicitation-requests>) during a tool call, and the call’s time limit ran out before an answer came: @@ -4587,11 +3741,7 @@ * To give an answer more time, set a longer [`timeout`](</docs/en/mcp#time-limits-on-mcp-tool-calls>) in milliseconds in the server’s configuration entry, such as `"timeout": 600000` for 10 minutes * Run the task in an interactive session instead and answer the server’s [dialog](</docs/en/mcp#respond-to-mcp-elicitation-requests>) yourself -### - -​ - -Permission prompt tool returned an invalid result +### Permission prompt tool returned an invalid result The tool you passed to [`--permission-prompt-tool`](</docs/en/cli-reference#cli-flags>) returned an answer Claude Code couldn’t read, so the tool call waiting on it didn’t run, even if the answer allowed the call: @@ -4606,11 +3756,7 @@ * **MCP TypeScript SDK** : without `outputSchema` * If the error comes only with inputs of about 40 KB or more, don’t copy the input into `updatedInput` or a deny’s `message`. To change an input that large, [raise your prompt tool’s output limit](</docs/en/mcp#raise-the-limit-for-a-specific-tool>). -### - -​ - -Agent would be spawned with zero tools +### Agent would be spawned with zero tools Every entry in the subagent’s [`tools` list](</docs/en/sub-agents#supported-frontmatter-fields>) failed to match a usable tool, so Claude Code refused to launch the subagent: with no tools, it couldn’t act. The message groups your entries by what went wrong: @@ -4632,11 +3778,7 @@ * Delete the `tools` field instead of listing tools to give the subagent every [tool available to subagents](</docs/en/sub-agents#available-tools>) * For a `tools` list that contains only `Agent`, raise the [depth limit](</docs/en/sub-agents#let-subagents-spawn-their-own-subagents>) or give the agent at least one other tool: Claude Code withholds `Agent` at that limit, so a list with nothing else in it resolves to no tools -### - -​ - -File is covered by a Read deny rule +### File is covered by a Read deny rule The Edit or Write tool was called on a path matched by a [`Read` deny rule](</docs/en/permissions#read-and-edit>), including creating a new file at that path. Both tools change content Claude has to be able to read back, so Claude Code refuses the call before any file access. NotebookEdit isn’t covered by `Read` deny rules. Before v2.1.228, the rule blocked the Edit tool only, and before v2.1.208, only an `Edit` deny rule blocked edits. @@ -4647,11 +3789,7 @@ * If Claude should be able to change the file, remove or narrow the `Read` deny rule in `/permissions` or in [settings](</docs/en/settings-reference#permission-settings>) * If the file must stay untouched, keep the rule and add an `Edit` deny rule for the same path to block the NotebookEdit tool too -### - -​ - -Setting blocks writes outside the working directories +### Setting blocks writes outside the working directories When Claude tries to write a file and the tool call fails with this message, the path is outside the session’s [working directories](</docs/en/permissions#working-directories>) and [`permissions.blockWritesOutsideWorkingDirectories`](</docs/en/settings-reference#permissions-blockwritesoutsideworkingdirectories>) is on: @@ -4670,11 +3808,7 @@ * To turn `permissions.blockWritesOutsideWorkingDirectories` off, remove it from every settings file that sets it, then restart Claude Code * If none of your settings files has `permissions.blockWritesOutsideWorkingDirectories`, it can come from `--settings` or from a host application. Claude Code also refuses these writes while it can’t read `permissions` in your [managed settings](</docs/en/managed-settings#keys-that-fail-closed>). Ask whoever launches or manages the session. -### - -​ - -Writes to Claude Code settings files are blocked +### Writes to Claude Code settings files are blocked When Claude tries to write a file and the tool call fails with this message, Claude Code treats the file as one of its settings files and [`permissions.blockWritesOutsideWorkingDirectories`](</docs/en/settings-reference#permissions-blockwritesoutsideworkingdirectories>) is on: @@ -4689,11 +3823,7 @@ * **The stored copy of[server-managed settings](</docs/en/server-managed-settings#security-considerations>) and the files kept with it**: ask an [Owner](</docs/en/server-managed-settings#access-control>) to change the setting in server-managed settings. * **Any`.json` file, while Claude Code can’t work out where the [`managed-settings.d/`](</docs/en/managed-settings#split-a-file-based-policy-across-teams>) folder leads**: ask your administrator to check that folder -### - -​ - -Path cannot contain null bytes +### Path cannot contain null bytes A file tool call’s path or pattern argument contained a null byte, which file systems and search tools can’t accept. Read, Write, Edit, NotebookEdit, Glob, and Grep check for this, and the message names the tool and the argument: @@ -4705,11 +3835,7 @@ Before v2.1.281, a null byte in a Read, Write, Edit, or NotebookEdit path ended the whole turn with an error naming `Path contains null bytes`, and the tool never ran. -### - -​ - -Command contains an invisible character +### Command contains an invisible character The [PowerShell tool](</docs/en/tools-reference#powershell-tool>) refused to run a command that contains U+FEFF or U+180E: @@ -4720,11 +3846,7 @@ * **For a command Claude wrote** : you have nothing to fix. The message tells Claude how to rewrite the command. * **For a skill or command file** : the message follows `No shell command in <name> was run`. See where to find the character and remove it. -### - -​ - -Command approved before Claude Code restarted was not run +### Command approved before Claude Code restarted was not run A shell command you approved didn’t run, and Claude receives this message as the command’s result: @@ -4734,11 +3856,7 @@ * Let Claude continue, and answer the prompt if you’re asked to approve the command again. -### - -​ - -File is too large to read as an image +### File is too large to read as an image Claude tried to read a file as an image with the [Read tool](</docs/en/tools-reference#read-tool-behavior>), and the file is larger than 128 MB, the most Read loads from an image file. Nothing was read, and Claude receives this error as the tool result: @@ -4754,11 +3872,7 @@ * If Claude stopped at the error, export a copy under 128 MB yourself, for example at a lower resolution, and point Claude at that file * If the path was a pipe or a device, point Claude at a regular image file instead -### - -​ - -subagent_type is required +### subagent_type is required subagent_type is required: the general-purpose agent is not available in this session. Available agents: ... @@ -4774,11 +3888,7 @@ Before v2.1.235, the same call failed with `Agent type 'general-purpose' not found`. -### - -​ - -Memory index is over its read limit +### Memory index is over its read limit Claude wrote to the [auto memory](</docs/en/memory#auto-memory>) index `MEMORY.md` and left it over one of its read limits: 200 lines or 25KB. The write succeeded, but only the first 200 lines or 25KB, whichever comes first, load at the start of a session, so everything past the limit is dropped each time the index is read. Before v2.1.210, an over-limit index was silently truncated on the next load with no write-time signal. @@ -4789,11 +3899,7 @@ * Let Claude rewrite `MEMORY.md`, or ask it to: keep one line per entry, move detail into topic files, and merge or drop stale entries * To trim the index yourself, see [Audit and edit your memory](</docs/en/memory#audit-and-edit-your-memory>) -### - -​ - -pkill pattern matches the Claude Code process +### pkill pattern matches the Claude Code process A `pkill` command in a Bash tool call used a pattern, typically with `-f`, that matches the Claude Code process itself, so Claude Code refuses the command instead of letting it end the session. Claude Code tests the pattern with `pgrep` before running `pkill` and refuses when its own process ID is in the result. The check runs on Linux only; on macOS, `pkill` runs unmodified. Before v2.1.214, the command ran, and a matching pattern killed the Claude Code session mid-turn. @@ -4804,11 +3910,7 @@ * Narrow the pattern so it matches only the intended process, for example the full path of the target binary rather than a short substring * To stop processes started by the current shell, use `pkill -P $$` with the pattern, which limits the match to the shell’s own child processes -### - -​ - -Failed to write to a teammate’s inbox +### Failed to write to a teammate’s inbox Claude Code couldn’t write a message to a teammate’s mailbox file under `~/.claude/teams/{team-name}/inboxes/`, so the recipient received nothing. The write fails when Claude Code can’t create or update the file, for example because the disk is full, the directory isn’t writable, or another agent holds the inbox lock for too long. Before v2.1.224, Claude Code reported the message as sent even when the write failed. The error appears in the sending agent’s tool result rather than as a banner in your terminal, and its text tells Claude to try again: @@ -4825,11 +3927,7 @@ * Ask the sender to resend the message; contention for the inbox lock is transient and clears on retry * Check free disk space, and check that `~/.claude/teams` and the files under it are writable by your user -### - -​ - -Teammate’s agent definition was not restored +### Teammate’s agent definition was not restored Claude messaged a stopped [agent team](</docs/en/agent-teams>) teammate, and Claude Code brought it back without re-applying the [subagent definition](</docs/en/agent-teams#use-subagent-definitions-for-teammates>) it was spawned from. The notice follows the resume report in the sending agent’s tool result and names the reason. When the definition file came from a folder with no saved trust, it reads: @@ -4840,11 +3938,7 @@ * Run `claude` in the folder the [debug log](</docs/en/debug-your-config>) names and accept the trust dialog. The definition is re-applied the next time Claude Code brings the teammate back; you don’t need to restart the lead session * Or set the `hasTrustDialogAccepted` entry to `true` in `~/.claude.json`, using the exact `projects["<path>"]` key the debug log prints -### - -​ - -Only a teammate can approve a shutdown request +### Only a teammate can approve a shutdown request Claude Code refused an [agent team](</docs/en/agent-teams>) shutdown approval because the session that sent it isn’t running as a teammate. Nothing was sent and nothing shut down. The refusal appears in the sending session’s tool result: @@ -4856,11 +3950,7 @@ * If the teammate is still running, ask the lead at its prompt to shut the teammate down, for example `Ask the researcher teammate to shut down`. See [Shut down teammates](</docs/en/agent-teams#shut-down-teammates>). * If a former teammate you resumed yourself with `claude --resume` got this refusal, nothing was sent. To end that session, run `/exit` at its prompt. -### - -​ - -A command-line deny rule cannot be handed to a teammate intact +### A command-line deny rule cannot be handed to a teammate intact This message means Claude Code didn’t start a [split-pane](</docs/en/agent-teams#choose-a-display-mode>) teammate in your [agent team](</docs/en/agent-teams>). Claude Code passes the lead’s command-line deny rules to a split-pane teammate on the teammate’s own command line, and stops when the teammate would read one of them differently: @@ -4871,11 +3961,7 @@ * Run `/config` in the lead session and set **Teammate mode** to `in-process`, then ask Claude to start the teammate again. You don’t need to find the rule or restart the lead. An in-process teammate [runs under the lead’s live deny rules](</docs/en/agent-teams#permissions>). * Later sessions that take [`teammateMode`](</docs/en/settings-reference#teammatemode>) from your user settings start teammates in-process too, because `/config` saves the choice there. To go back to split panes in a later session, set **Teammate mode** to `auto`, `tmux`, or `iterm2`, whichever you used before. -### - -​ - -Message too large for cross-session delivery +### Message too large for cross-session delivery Claude’s [cross-session message](</docs/en/cross-session-messaging>) to another of your sessions on this machine was too long to send. Claude Code refused it, and the receiving session got nothing. The refusal appears in the sending session’s tool result, not as a banner in your terminal. It names both sizes and how to make the message fit: @@ -4888,11 +3974,7 @@ Before v2.1.235, Claude Code reported an oversized message as sent. The receiving session dropped it unread. -### - -​ - -Too many messages to this session just now +### Too many messages to this session just now Claude sent a rapid burst of [cross-session messages](</docs/en/cross-session-messaging>) to one of your sessions on this machine, and the burst reached what that session’s inbox accepts. Claude Code refused the next send, and the receiving session got nothing from it. The refusal appears in the sending session’s tool result, not as a banner in your terminal: @@ -4905,11 +3987,7 @@ Before v2.1.236, Claude Code reported these sends as sent. The receiving session dropped them unread. -### - -​ - -Cross-session message was dropped at the recipient session’s inbox +### Cross-session message was dropped at the recipient session’s inbox Claude sent a [cross-session message](</docs/en/cross-session-messaging>) to another of your sessions on this machine, and that session’s inbox discarded it before Claude in that session read it. The line names the recipient and, when the recipient gave a reason, adds the reason after a dash: @@ -4930,11 +4008,7 @@ Before v2.1.238, the sending session got no report when the recipient’s inbox discarded a message. -### - -​ - -Refusing to send a cross-session message +### Refusing to send a cross-session message Before Claude Code writes a [cross-session message](</docs/en/cross-session-messaging>) to another of your sessions on this machine, it checks that the target session’s inbox socket is the endpoint the message was addressed to. When a check fails, Claude Code refuses the send in the sending session, and the target session receives nothing. For a message Claude sends, the refusal appears in the sending session’s tool result: @@ -4950,11 +4024,7 @@ * Usually nothing: the checks keep a message from reaching an endpoint other than the session it was addressed to, and nothing was sent * If `reply target is a symlink` repeats for one session, check what created a link at that session’s socket path, shown in its `/status` under `Peer address` -### - -​ - -Refusing to read, write, or search a path +### Refusing to read, write, or search a path Claude Code checks a file path’s [permission rules](</docs/en/permissions#read-and-edit>), then confirms that resolution again when the tool opens the file or starts the search. When it can’t confirm that the path still leads to the location the check approved, Claude Code refuses the operation instead of following it. The refusal appears in the tool result: @@ -4983,11 +4053,7 @@ Before v2.1.251, Claude Code re-checked a path’s resolution only for file writes, so a link replaced after the permission check could redirect a read or search to a different location without a message. Of these, only the parent-directory, through-symlink, and symlinked-directory write refusals appear on earlier versions. Before v2.1.280, the `where it leads on disk could not be determined` refusal didn’t appear. -### - -​ - -The search failed, so this is not a “no matches” result +### The search failed, so this is not a “no matches” result A [Grep](</docs/en/tools-reference#grep-tool-behavior>) or [Glob](</docs/en/tools-reference#glob-tool-behavior>) search Claude ran failed before returning any result, so whether matches exist is unknown. The message Claude receives in place of results starts: @@ -5002,11 +4068,7 @@ 3. If the search fails again, find the line containing `rg error (signal=` in `claude-debug.log` 4. Include that line when you report the problem -### - -​ - -Task output swap refused +### Task output swap refused Claude Code saves each Bash command’s output to a file under its temp directory. Every time it opens one of these files, it checks that the path still leads to the file it created, with no symbolic link, extra hard link, or moved directory redirecting it. This message means that check failed, so Claude Code refused the operation rather than write or read output through that path. The message appears in the Bash tool result: @@ -5023,11 +4085,7 @@ * Or check your project’s directory under the Claude Code temp directory, `/private/tmp/claude-501/-Users-you-my-project` in the example message. If that path is a symbolic link, or a directory that shouldn’t be there, remove the link or directory itself rather than the link’s target, and restart Claude Code * If the refusal repeats, a process is replacing, linking, or removing entries under Claude Code’s temp directory while the session runs. Set [`CLAUDE_CODE_TMPDIR`](</docs/en/env-vars>) to a directory nothing else manages and restart -### - -​ - -Disk full or disk quota used up +### Disk full or disk quota used up Free up space, inodes, or disk quota on the volume that holds Claude Code’s temporary directory. A line in a command’s result starting `Disk full:`, `Disk quota used up:`, or `Nearly out of inodes:` names that directory. Claude Code saves each Bash and PowerShell command’s output to a file under that directory. If it can’t create that file because the volume or your quota on it is full, your command doesn’t start, and the result Claude reads is: @@ -5055,11 +4113,7 @@ Before v2.1.305, a command that Claude Code couldn’t start because the disk was full returned only the operating system’s error text. That text read, for example, `ENOSPC: no space left on device, open <path>.output`. -### - -​ - -git is not installed on this Mac +### git is not installed on this Mac This message means a step in Claude Code needed git, and the git it found is Apple’s stand-in at `/usr/bin/git`. The developer tools that provide git aren’t installed. Claude Code doesn’t start the stand-in and shows this text instead, for example inside a longer message: @@ -5069,11 +4123,7 @@ * In Terminal, run `xcode-select --install`, finish the installation it starts, then retry what you were doing in Claude Code -### - -​ - -File is not valid UTF-8 +### File is not valid UTF-8 Claude used the Edit or NotebookEdit tool on a file whose bytes don’t decode as UTF-8, and Claude Code refused the change. Nothing was written, so the file is as it was. Those tools save the whole file back as UTF-8, which would have turned every byte they couldn’t decode into the replacement character `U+FFFD`. The message appears in the tool result: @@ -5086,11 +4136,7 @@ Before v2.1.296, Edit and NotebookEdit applied such an edit and saved every byte they couldn’t decode as `U+FFFD`. On those versions, update Claude Code. -### - -​ - -Refusing to apply edits: a hook is configured for file edits in this session +### Refusing to apply edits: a hook is configured for file edits in this session Claude tried to publish an [artifact](</docs/en/artifacts>) with a [one-step update](</docs/en/artifacts#turn-off-one-step-artifact-updates>), a small change to the artifact’s file included in the publish, and Claude Code refused. Nothing was published and the file is unchanged. The message appears in the Artifact tool result: @@ -5103,11 +4149,7 @@ * If the message keeps coming back, quit and relaunch Claude Code * If the message comes back even after a relaunch, [turn off one-step updates](</docs/en/artifacts#turn-off-one-step-artifact-updates>) -### - -​ - -The source file is not valid UTF-8 text +### The source file is not valid UTF-8 text Claude tried to publish an [artifact](</docs/en/artifacts>) from a file whose bytes don’t decode as text, or whose text already contains the replacement character `U+FFFD`, so Claude Code refused the publish before uploading anything. The message appears in the Artifact tool result and names the first position to fix: @@ -5123,11 +4165,7 @@ Before v2.1.267, Claude Code uploaded such a file without checking it, and the server refused the publish instead. -### - -​ - -Not published: that file is on a network share +### Not published: that file is on a network share Claude tried to publish an [artifact](</docs/en/artifacts>) from a file at a path that names a network host: @@ -5145,11 +4183,7 @@ * On Windows, to let Claude publish directly from the share, map it to a drive letter and pass the drive when you start Claude Code. In PowerShell, for example, run `net use Z: \\server\share` and then `claude --add-dir Z:\`. Claude can then publish files from that drive. Adding the drive mid-session with `/add-dir` isn’t enough. * On macOS or Linux, mount the share at a directory such as one under `/mnt` or `/Volumes`, and publish from that path instead of the automount path -### - -​ - -Not published: Claude sent the same content again after a newer version of the artifact turned it away +### Not published: Claude sent the same content again after a newer version of the artifact turned it away This red line under an Artifact call means Claude Code stopped a repeated publish: the [artifact](</docs/en/artifacts>) wasn’t updated, and nothing was written to the file Claude publishes from. You don’t need to do anything unless Claude stops without publishing. Earlier in the session, Claude Code turned a publish away because the artifact had a newer version, for example one that an [editor](</docs/en/artifacts#let-someone-edit-with-you>) or another of your sessions published. The line’s ending says what Claude has to do next: @@ -5163,11 +4197,7 @@ * **Ends with`Claude needs to work from that newer version first`**: if Claude stopped there, ask it to fetch the artifact’s current version, merge its changes in, and publish again * **Ends with`should go through`**: if Claude stopped there, ask it to publish again -### - -​ - -Reading a local file from outside the connected folders in a Cowork session +### Reading a local file from outside the connected folders in a Cowork session In a [Cowork](<https://claude.com/docs/cowork/overview>) session running on your machine in the Claude Desktop app, Claude named a local file for an [artifact](</docs/en/artifacts>). Claude Code couldn’t confirm the file is a plain file inside the session’s connected folders: the path sits outside those folders, passes through a symbolic link, or is spelled in a way that can name a different file than it appears to. Reading such a file needs your approval, and in a session that can’t show you the approval card, such as one set to skip all approvals, Claude Code refuses the read. The refusal appears in the Artifact tool result; when the file couldn’t be examined at all, it names that failure instead: @@ -5180,11 +4210,7 @@ * Usually nothing: the message tells Claude to use a plain file inside the connected folders instead * To put that exact file in the artifact, copy it into one of the session’s connected folders as a regular file, not a symlink, and ask again -### - -​ - -WebFetch cannot fetch localhost +### WebFetch cannot fetch localhost Claude called [WebFetch](</docs/en/tools-reference#webfetch-tool-behavior>) with a URL whose hostname has no dot, such as `http://localhost:3000` or a bare intranet name like `http://wiki/`. WebFetch refuses these URLs before making any request: @@ -5196,11 +4222,7 @@ Before v2.1.268, WebFetch reported these URLs with a generic `Invalid URL` error. -### - -​ - -WebFetch domain safety check failed +### WebFetch domain safety check failed Before fetching a URL, WebFetch sends the URL’s hostname to `api.anthropic.com` to check it against Anthropic’s [domain safety blocklist](</docs/en/data-usage#webfetch-domain-safety-check>). If the check can’t complete, WebFetch can’t confirm that the domain is safe, so it doesn’t fetch the page and the tool result carries one of these messages instead: @@ -5213,19 +4235,11 @@ Before v2.1.286, the rate-limited message read `The safety check for domain example.com is temporarily rate-limited (too many domain checks from this network). Retry after about a minute; retrying sooner will fail the same way.`. Before v2.1.285, a rate-limited check was reported with the `Unable to verify` message instead. -## - -​ - -Background session errors +## Background session errors [Background sessions](</docs/en/agent-view>) run without an interactive terminal of their own, so commands that need one behave differently there. These messages appear in the transcript of a background session, in the terminal that attaches to one, in the session or shell you dispatch from, or, for the worktree-guard entries below, in any session isolated in a worktree or running a worktree-isolated subagent; where a message is specific to one surface, its entry says so. -### - -​ - -Commands refused in a background session +### Commands refused in a background session Commands that open an interactive dialog can’t do so while no terminal is attached to a background session. `/install-github-app`, the `/mcp` settings list, and the authentication actions in the MCP server menu respond with a message. For `/install-github-app` and the `/mcp` settings list, the session also appears under **Needs input** in [agent view](</docs/en/agent-view>) so you can find it, attach, and run the command again. While a terminal is attached, these commands work normally. Before v2.1.216, the session didn’t appear under **Needs input** after `/install-github-app` or the `/mcp` settings list was refused. In v2.1.213 through v2.1.215, the commands still worked while a terminal was attached, and the refusal message told you to attach and run the command again. From v2.1.208 through v2.1.212, Claude Code refused them even while a terminal was attached, with a message such as `Can't open MCP settings in a background session`; on those versions, run the command from a regular `claude` session instead, or upgrade. Before v2.1.208, they opened their dialog inside the background session. In v2.1.208 only, Claude Code also refused the `/model` picker in a background session, and `/upgrade` printed the upgrade URL instead of opening a browser. The wording names the command. The `/mcp` settings list reports: @@ -5236,11 +4250,7 @@ * Attach to the session from agent view and run the command again * Or use the form the message names, such as `/mcp reconnect <server>`, `/mcp enable`, or `/mcp disable`, which work without attaching -### - -​ - -Write or command blocked because the path cannot be safely resolved +### Write or command blocked because the path cannot be safely resolved Claude addressed a file or working directory through a spelling that the [worktree-isolation guard](</docs/en/agent-view#how-file-edits-are-isolated>) can’t resolve to one verifiable location. The guard checks writes and command working directories in [any session isolated in a worktree](</docs/en/worktrees#how-claude-code-enforces-isolation>), interactive or background, and in [worktree-isolated subagents](</docs/en/worktrees#isolate-subagents-with-worktrees>). It resolves symlinks before checking that the operation doesn’t reach the shared checkout, and when resolution fails, it blocks the operation rather than letting it land there. The message names the path forms it refuses and how to retry: @@ -5251,11 +4261,7 @@ * Usually nothing: the full message goes to Claude as a tool error, and Claude retries with the direct path it names. For a blocked file edit, the conversation view shows only a short `Error editing file` line; the full message appears in the transcript view, which you open with `Ctrl+O`. A blocked command prints it in its command output. * If the block repeats on the same file, the path likely runs through a committed symlink whose target contains `..`, such as `docs/current -> ../README.md`; ask Claude to edit the target file by its real path instead of through the link -### - -​ - -Write or command blocked because the path names a network location +### Write or command blocked because the path names a network location Claude addressed a file or working directory through a path that names a drive that isn’t on your machine, a UNC share such as `\\server\share\file` or a `/net` automount path, while the session’s checkout is on a local disk. The same worktree-isolation guard can’t verify that such a path stays out of the shared checkout, so it blocks the operation. Isolating the session in a worktree doesn’t lift the block. The message names the form of path to use instead: @@ -5265,11 +4271,7 @@ * Usually nothing: Claude retries with the local spelling the message asks for -### - -​ - -Command blocked by the worktree isolation checks +### Command blocked by the worktree isolation checks 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: @@ -5286,11 +4288,7 @@ * **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 -### - -​ - -This session has no saved transcript +### This session has no saved transcript You attached to a session that you [moved to the background](</docs/en/agent-view#from-inside-a-session>) with `←` or `/background` and that stopped before it ran a turn of its own. Claude Code couldn’t find the conversation you moved it from, so the session has nothing to resume. The message ends with the `claude respawn` command for this session: @@ -5301,31 +4299,24 @@ * To start the stopped session fresh, run `claude respawn <id>` with the ID from the message, or press `Enter` twice on its row in agent view * If the session did finish a response and you still see this refusal on a version before v2.1.214, an unreadable folder in `~/.claude/projects` could make the transcript scan miss the saved conversation; update to v2.1.214 or later, which tolerates unreadable folders during the scan -### - -​ - -This session is running in another terminal +### This session is running in another terminal You opened a stopped session’s row in [agent view](</docs/en/agent-view>), and its saved conversation is already open in another live Claude Code process on this machine, so Claude Code refuses to start a second process that would write to the same transcript. Which message you see depends on [what holds the conversation](</docs/en/agent-view#opening-a-session-says-the-conversation-is-already-open>): Can't open — this session is running in another terminal This conversation is already open in another running Claude session — use that one, or close it and try again - * **`running in another terminal`** : a terminal holds the conversation, for example one where you resumed it with `claude --resume` or `/resume`. The row also shows `Open in a terminal`. - * **`already open in another running Claude session`** : another non-interactive Claude Code process holds it, for example a [background session](</docs/en/agent-view#the-supervisor-process>) process for the same conversation that hasn’t exited yet. - -**What to do:** - - * Continue the conversation in the process that has it open, or exit that process and open the row again + * **`running in another terminal`** : a process other than a background session holds the conversation, for example a `claude -p` run, or a terminal where you resumed it with `claude --resume` or `/resume`. The row also shows `Open in a terminal`. + * **`already open in another running Claude session`** : another [background session](</docs/en/agent-view#the-supervisor-process>) holds it. + +**What to do:** + + * For `running in another terminal`: continue in that terminal, or exit that process or let it finish, and then try again + * For `already open in another running Claude session`: use that session, or stop it and then try again Before v2.1.248, only the `already open in another running Claude session` refusal existed: a conversation resumed in a terminal didn’t count as open, and opening the row started a second Claude Code process writing to the same conversation. -### - -​ - -This session’s saved conversation is no longer on disk +### This session’s saved conversation is no longer on disk You opened a [background session](</docs/en/agent-view>) that ended while the background service was off, and [transcript cleanup](</docs/en/settings-reference#cleanupperioddays>) has since removed its saved conversation, for example after the machine was off for weeks. Opening such a row normally [resumes its saved conversation](</docs/en/agent-view#sessions-show-as-failed-after-shutdown>). With nothing left to resume, Claude Code refuses rather than re-run the session’s original prompt without asking: @@ -5338,11 +4329,7 @@ Before v2.1.248, opening such a row re-ran the session’s original prompt instead of refusing, pulling a weeks-old task back into the foreground. -### - -​ - -Worktree has commits that are not pushed anywhere +### Worktree has commits that are not pushed anywhere You tried to delete a [background session](</docs/en/agent-view#what-deleting-a-session-removes>) whose worktree holds commits Claude Code can’t confirm are saved elsewhere. Claude Code keeps the worktree and the session row rather than destroy the commits unseen. `claude rm` names the branch and the unpushed commits, and says how to proceed: @@ -5358,11 +4345,7 @@ Before v2.1.268, `claude rm` put the commit summary on the `kept` line itself. When `claude rm` couldn’t summarize the commits, the `kept` line read `worktree has commits that are not pushed anywhere` in place of the summary. Before v2.1.260, the message didn’t name the branch or commits, and there was no discard route. You can still delete the session, losing uncommitted changes but keeping the branch and commits. Run `git worktree remove --force --force <path>` with the path the refusal printed, then `claude rm <id>`. Git needs `--force` twice for a locked worktree. Before v2.1.248, the default branch checked out in your main checkout didn’t count: a branch you had already merged there still triggered this refusal until its commits reached a remote. -### - -​ - -Terminal host process died +### Terminal host process died Each [background session’s](</docs/en/agent-view>) terminal runs in a host process under the background service, and that process died while the service still held its connection, so the session couldn’t be reached. On Linux and WSL, the background service checks each host process every few seconds, marks the session failed when the process has exited but its connection to the service never closed, and shows the reason on its row in [agent view](</docs/en/agent-view#read-session-state>): @@ -5380,11 +4363,7 @@ Before v2.1.247, a dead host process could pass every liveness check the background service ran, so opening the session showed `opening… · esc to cancel` indefinitely and `claude attach <id>` waited without reporting an error. -### - -​ - -Session isn’t responding +### Session isn’t responding You opened a [background session](</docs/en/agent-view>) and the background service accepted the open, but no output arrived for about ten seconds, so Claude Code concludes that the process relaying the session’s terminal can’t deliver output, and ends the attempt instead of waiting. In agent view, Claude Code offers a restart in the footer: @@ -5400,11 +4379,7 @@ * From the shell, run `claude stop <id>`, then `claude attach <id>` * For a shell-command row, press `Ctrl+X` in agent view or run `claude stop <id>` to stop it; dispatch the command again to rerun it -### - -​ - -Session was stopped while the respawn was in flight +### Session was stopped while the respawn was in flight You opened a [background session](</docs/en/agent-view>) whose process wasn’t running, and while Claude Code was restarting it, another Claude Code process stopped it, for example `claude stop` in another terminal. Claude Code keeps the session stopped: @@ -5415,11 +4390,7 @@ * If you didn’t stop the session, open its row again in agent view or run `claude respawn <id>` to restart it * If you stopped it yourself, nothing remains to do: the session stays stopped -### - -​ - -Session agent no longer available +### Session agent no longer available You resumed a session that was running a [custom agent](</docs/en/sub-agents#invoke-subagents-explicitly>), started with `--agent` or the `agent` setting, and Claude Code didn’t find an agent by that name. It searches the session’s original directory first, when you have [trusted that workspace](</docs/en/permissions#project-allow-rules-and-workspace-trust>), then the directory you resume from. The session still resumes, but with the default tools, so the agent’s tool restrictions no longer apply: @@ -5431,11 +4402,7 @@ * 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 +### 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: @@ -5446,11 +4413,7 @@ * 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 -### - -​ - -No LLM gateway: a gateway set in your shell isn’t passed to a session opened from another folder +### No LLM gateway: a gateway set in your shell isn’t passed to a session opened from another folder The [background session](</docs/en/agent-view>) showing this message isn’t using your [LLM gateway](</docs/en/llm-gateway>): it didn’t get the gateway’s address, so its requests fail. The message appears in the conversation in place of Claude’s reply, with your session’s ID and folder filled in: @@ -5464,11 +4427,7 @@ Before v2.1.302, a background session in this situation showed a sign-in error such as `Not logged in · Please run /login` instead, without naming the folder. -### - -​ - -CLAUDE_CODE_PROCESS_WRAPPER launcher errors +### CLAUDE_CODE_PROCESS_WRAPPER launcher errors [`CLAUDE_CODE_PROCESS_WRAPPER`](</docs/en/corporate-launcher>) is set, and its value can’t be used, so Claude Code refuses to start the affected process rather than run it without the launcher. Configuration problems are reported with a message that starts with the variable name and states the reason, for example: @@ -5480,11 +4439,7 @@ * Check `/status`, which shows the resolved launch command in its Self-exec entry and warns when the running background service doesn’t match it, or run `claude daemon status` from a shell * After fixing the value in the `env` block of [settings](</docs/en/corporate-launcher#set-up-the-launcher>), restart the background service with `claude daemon stop --any` so the next dispatch starts a wrapped one -### - -​ - -EUNKNOWN when starting a background session +### EUNKNOWN when starting a background session Windows refused to start a program with an error code that has no standard name, so the failure surfaces as `EUNKNOWN`. The usual trigger is a software restriction policy, such as Group Policy or AppLocker, blocking the program being started. The error appears when you start a [background session](</docs/en/agent-view>) with `/background` or `claude --bg`: @@ -5497,11 +4452,7 @@ * If the error appears on v2.1.212 or later while no npm install is running, check with your Windows administrator whether a restriction policy blocks the Claude Code executable * If the background service stops when you close the terminal, Claude Code started it without PowerShell. Install PowerShell 7, or ask your administrator to unblock PowerShell, so the service can outlive the terminal. -### - -​ - -EACCES when starting a background session +### EACCES when starting a background session Claude Code couldn’t run its own binary to start the [background service](</docs/en/agent-view#the-supervisor-process>) that hosts background sessions. On an npm installation, this usually means `npm install -g @anthropic-ai/claude-code` was replacing the binary at that moment, whether you ran it or the [auto-updater](</docs/en/setup#auto-updates>) did. The error appears when you open a session from [agent view](</docs/en/agent-view>): @@ -5516,11 +4467,7 @@ * Wait a few seconds, then open the session or dispatch again. When the message says Claude Code is being updated, retry after the update finishes. * If the error persists while no npm install is running, your user can’t run the installed binary. Check its permissions and its directory’s, or reinstall Claude Code. -### - -​ - -Background service exited before it became reachable +### Background service exited before it became reachable The process Claude Code started as the [background service](</docs/en/agent-view#the-supervisor-process>) exited before it accepted connections, so Claude Code couldn’t open your session. When the service printed an error before exiting, the reason in parentheses gives the exit code or signal and the first line the service printed, which names what stopped it: @@ -5536,11 +4483,7 @@ * If the message quotes a line, fix what it names, then open the session or dispatch again. The next attempt starts the service again * Run `claude daemon status` to check whether a service is running now -### - -​ - -Working directory no longer exists when starting a background session +### Working directory no longer exists when starting a background session The directory you started a [background session](</docs/en/agent-view>) in was removed while the session was starting. Claude Code doesn’t start the session, and the message names the missing directory: @@ -5550,11 +4493,7 @@ * Recreate the directory the message names, or dispatch from a directory that exists, then try again -### - -​ - -This forked session could not be started +### This forked session could not be started You [forked a Remote Control session](</docs/en/remote-control#fork-a-session-from-your-browser>) from claude.ai, and Claude Code couldn’t finish starting the [background session](</docs/en/agent-view>) that runs the fork on your machine. This notice appears in the forked session’s transcript: @@ -5564,11 +4503,7 @@ * Go back to the session you forked and fork it again once the session is idle -### - -​ - -Workspace not trusted when dispatching a background session +### Workspace not trusted when dispatching a background session You started or restarted a [background session](</docs/en/agent-view>) in a directory you haven’t [trusted](</docs/en/permissions#project-allow-rules-and-workspace-trust>), and the workspace trust dialog couldn’t appear to ask you. Claude Code doesn’t start the session: @@ -5585,19 +4520,11 @@ * For the home-directory message, run the command from a terminal in your home directory so the dialog can appear, or start the session from a project directory instead * For the `could not be resolved on disk` message, recreate the directory, or start a new session from a directory that exists -## - -​ - -Wrapper and IDE errors +## Wrapper and IDE errors These errors come from the program that launched Claude Code for you, such as an IDE extension or an [Agent SDK](</docs/en/agent-sdk/overview>) application, rather than from Claude Code itself. -### - -​ - -Claude Code process exited with code N +### Claude Code process exited with code N The underlying `claude` process exited with a non-zero code. The exit code alone doesn’t say what failed: the real error is in the process’s own output, which the wrapper appends when it captured any and otherwise keeps in its logs. @@ -5610,11 +4537,7 @@ * Run `claude` in a terminal in the same project. The failure usually reproduces there with its real error message, which you can then look up on this page. * Run `claude doctor` in a terminal to check the installation and configuration -### - -​ - -Could not locate the Claude CLI on PATH +### Could not locate the Claude CLI on PATH The [VS Code extension](</docs/en/vs-code>) shows this error on Windows when you open Claude Code in the integrated terminal, the terminal’s shell is PowerShell, and the extension can’t find the installed `claude` executable on PATH. The extension refuses to launch Claude Code until it finds the installed `claude` on PATH. @@ -5626,11 +4549,7 @@ * Set the PATH entry as a user or system environment variable, not in your PowerShell profile. The extension doesn’t run your profile, so a PATH edit that lives only there never reaches it. * Restart VS Code after changing PATH. The extension checks the PATH that VS Code captured at startup, so a PATH change takes effect only after a restart. -### - -​ - -The Claude Code program for this computer could not be found +### The Claude Code program for this computer could not be found The [VS Code extension](</docs/en/vs-code>) looked for the copy of Claude Code bundled inside it and found none built for your computer. The message names the build your computer needs: @@ -5644,11 +4563,7 @@ Before v2.1.290, this appeared as `Unsupported platform: <platform>-<arch>. No compatible Claude Code binary found.` -### - -​ - -The connection to Claude Code ended before this message completed +### The connection to Claude Code ended before this message completed The [VS Code extension](</docs/en/vs-code>) sent your message to the `claude` process, and the connection ended without an error before the process acknowledged or finished it. The extension can’t tell whether the message was processed, so it asks you to send it again: @@ -5659,19 +4574,11 @@ * Send the message again. The next message starts a fresh `claude` process that resumes the conversation. * If it repeats, run `claude` in a terminal in the same project. A failure that keeps ending the process usually reproduces there with its real error message. -## - -​ - -Rewind warnings and errors +## Rewind warnings and errors These messages come from a [`/rewind`](</docs/en/checkpointing>) code restore. `Restored the code, but skipped N files` is a warning that Claude Code skipped some paths. `No files were restored` is an error that means it restored nothing. -### - -​ - -Restored the code, but skipped files +### Restored the code, but skipped files A `/rewind` code restore skipped one or more tracked paths instead of writing or deleting through them. Claude Code skips a path when: @@ -5689,11 +4596,7 @@ * If a skipped file is a link you created on purpose, such as a config file managed by a dotfile manager or a file hard-linked by tools like pnpm, the rewind left its contents alone. To undo the session’s changes to it, ask Claude to reverse the edit or edit the file yourself * If you didn’t create the link, inspect the path before trusting its contents -### - -​ - -No files were restored +### No files were restored Claude Code shows this message when you restore code with [`/rewind`](</docs/en/checkpointing>) and it can’t restore any of the files in that checkpoint. For each file, either the backup Claude Code saved before editing it is missing, or Claude Code couldn’t write to or delete the file. @@ -5708,19 +4611,11 @@ Before v2.1.260, Claude Code silently skipped files whose backups were missing, and the rewind appeared to succeed. -## - -​ - -Session saving warnings +## Session saving warnings Claude Code shows these warnings on a persistent line below the input box when it isn’t saving your session transcript. The session keeps working either way; the warnings tell you the session may be missing from [`--resume`](</docs/en/sessions>) later. -### - -​ - -Transcript writes are failing +### Transcript writes are failing Claude Code saves the transcript to disk as you work, and its writes to [the transcript file](</docs/en/sessions#where-transcripts-are-stored>) are failing. The message names the cause with the underlying error code, for example a full disk: @@ -5737,11 +4632,7 @@ * The warning clears on its own at the next successful write; no restart is needed * Messages sent while the warning was showing may still be missing when you resume the session later -### - -​ - -Transcript saving is off because CLAUDE_CODE_SKIP_PROMPT_HISTORY is set +### Transcript saving is off because CLAUDE_CODE_SKIP_PROMPT_HISTORY is set This session started with [`CLAUDE_CODE_SKIP_PROMPT_HISTORY`](</docs/en/env-vars>) set, so Claude Code writes no transcript or prompt history for it: @@ -5752,11 +4643,7 @@ * If you set the variable on purpose, no action is needed; the notice confirms the session won’t appear in `--resume`, `--continue`, or up-arrow history * If you didn’t, remove the variable from the shell or script that launches `claude`, then start a new session. Messages from the current session aren’t saved retroactively. -### - -​ - -Transcript saving is off because of an inherited CLAUDE_CODE_CHILD_SESSION marker +### Transcript saving is off because of an inherited CLAUDE_CODE_CHILD_SESSION marker Claude Code sets [`CLAUDE_CODE_CHILD_SESSION`](</docs/en/env-vars>) in the subprocesses it spawns, and treats an interactive session that inherits it as nested: Claude Code saves no transcript for it, so sessions that Claude itself starts don’t fill your `--resume` list. This notice means your current session inherited the marker: @@ -5768,11 +4655,7 @@ * If this is a top-level session, exit and restart with [`CLAUDE_CODE_FORCE_SESSION_PERSISTENCE=1`](</docs/en/env-vars>) set. Saving applies from the restart, so messages sent before it aren’t saved. * To fix future launches from the same terminal or launcher, remove `CLAUDE_CODE_CHILD_SESSION` from its environment -## - -​ - -Configuration warnings +## Configuration warnings To find a warning that Claude Code gave at startup in an interactive session, look below the startup banner first, then in the debug log: @@ -5781,11 +4664,7 @@ In [non-interactive mode](</docs/en/headless>) with text output, outside a [background session](</docs/en/agent-view>), look for startup warnings on stderr. Before v2.1.305, look on stderr in an interactive session as well, including for the permission-rule warnings that now show as rows below the banner. -### - -​ - -Claude Code exited after an unrecoverable interface error +### Claude Code exited after an unrecoverable interface error Claude Code prints this message when it exits because its terminal interface hit an error it can’t recover from, in either renderer. The second sentence appears only when the error happened while the [fullscreen](</docs/en/fullscreen>) renderer was starting: @@ -5798,11 +4677,7 @@ Before v2.1.236, Claude Code exited without printing a message after this kind of error. -### - -​ - -Agent descriptions are over the 15.0k-token limit +### Agent descriptions are over the 15.0k-token limit Claude Code shows this warning as a startup notice in the conversation view rather than on stderr. The combined descriptions of your [subagents](</docs/en/sub-agents>), except the built-in ones, exceed 15,000 tokens as Claude Code estimates them. Each agent counts its name plus its `description` frontmatter. Claude Code loads every agent whether or not the total is over the limit, so the warning doesn’t change what loads. @@ -5813,11 +4688,7 @@ * Shorten the `description` frontmatter of your agent files, or ask Claude to trim them for you. * Remove agent files you no longer use. -### - -​ - -Hook needs quotes around a path with a space +### Hook needs quotes around a path with a space This notification in the conversation view means a hook’s script didn’t run because its path has a space and isn’t quoted. That hook is an [`asyncRewake`](</docs/en/hooks#run-hooks-in-the-background>) hook in shell form. In its `command`, an interpreter such as `python3` is followed by an unquoted path placeholder, and the resolved path contains a space. The notification starts with the hook’s event name and names the script: @@ -5827,11 +4698,7 @@ * In the `command` of the hook that runs the script the notification names, wrap the path in double quotes. In a JSON file, write it as `"command": "python3 \"${CLAUDE_PLUGIN_ROOT}/hooks/check.py\""`. -### - -​ - -Instruction file not loaded +### Instruction file not loaded This notice in the conversation view of an interactive session means a [memory file](</docs/en/memory#how-claude-md-files-load>) that exists wasn’t loaded. A read restriction is in force. @@ -5853,11 +4720,7 @@ Before v2.1.292, the notice named the file at the end of the same line after the reason. -### - -​ - -A skill, command, or workflow wasn’t loaded because its name is reserved +### A skill, command, or workflow wasn’t loaded because its name is reserved A skill folder, a frontmatter `name`, a file or subfolder in `.claude/commands/`, or a [saved workflow](</docs/en/workflows#save-the-workflow-for-reuse>) uses the name `anthropic-skills` or a name that starts with `anthropic-skills:`. Claude Code [reserves that name for skills synced from claude.ai](</docs/en/skills#names-reserved-for-synced-skills>) and doesn’t load that item. Claude Code shows this warning as a startup notice in the conversation view rather than on stderr: @@ -5869,11 +4732,7 @@ Before v2.1.282, Claude Code loaded skills and commands with these names. -### - -​ - -Skill or command name refused +### Skill or command name refused This startup notice means Claude Code refused the name of at least one [skill or custom command](</docs/en/skills>), so it didn’t load or loaded without its `name` field: @@ -5887,11 +4746,7 @@ * Start Claude Code with `claude --debug` from your shell and search the [debug log](</docs/en/debug-your-config>) for `[names]`. Each name the notice counts has one line there. The line spells out some hidden characters as codes, such as `\u{200B}` for a zero-width space, so you can see where they are. * Remove the [characters a skill name can’t hold](</docs/en/skills#characters-a-skill-name-cant-hold>) by renaming the folder or file or editing the `name:` line, or shorten a name that is over 256 characters. Then restart the session, unless the file is in a directory Claude Code [watches for changes](</docs/en/skills#live-change-detection>). For a skill from a plugin you didn’t write, ask the plugin’s author to rename it. -### - -​ - -Workspace has not been trusted +### Workspace has not been trusted Claude Code found `permissions.allow` rules or `permissions.additionalDirectories` entries in the project’s `.claude/settings.json` or `.claude/settings.local.json` and didn’t apply them, because [allow rules from project settings require workspace trust](</docs/en/permissions#project-allow-rules-and-workspace-trust>). The count, the setting name, and the file named in the message vary with your configuration. `deny` and `ask` rules aren’t affected. @@ -5903,11 +4758,7 @@ * In [non-interactive mode](</docs/en/headless>) with `-p` no dialog is shown. Set the `hasTrustDialogAccepted` entry in `~/.claude.json` using the exact `projects` key the message prints. * If the message names `.claude/settings.local.json` and you started Claude Code outside a git repository or in your home directory, update to v2.1.200 or later. Versions 2.1.196 through 2.1.199 treated your own `.claude/settings.local.json` as repository-supplied in those workspaces. On v2.1.207 and later, updating isn’t enough outside a git repository if you haven’t trusted the folder: determining that a folder isn’t inside a repository runs git, and Claude Code runs that check only after you accept the trust dialog, so use the first step. Your home directory and any other [configuration home](</docs/en/permissions#project-allow-rules-and-workspace-trust>) are exempt and don’t wait for the dialog. See [Project allow rules and workspace trust](</docs/en/permissions#project-allow-rules-and-workspace-trust>). -### - -​ - -Working directory is a network path +### Working directory is a network path Claude Code doesn’t add network paths as working directories. Looking up a network path can contact the host it names, and on Windows that contact can send the host your credentials. Claude Code therefore refuses the path without looking it up. You see this message when you run `/add-dir` with a network path: @@ -5927,11 +4778,7 @@ Before v2.1.257, Claude Code accepted a reachable network path as a working directory. -### - -​ - -Remote managed settings failed to load +### Remote managed settings failed to load Your session is eligible for [server-managed settings](</docs/en/server-managed-settings>), but Claude Code couldn’t fetch them or couldn’t apply what the server returned, so it shows this warning in interactive sessions and in Claude Desktop’s Code tab. The parenthesized cause names what failed, such as `network error`, `request timed out`, or `authentication rejected (401)`. The cause `no setting in the server response could be applied as written` means the server answered but none of the settings it returned passed [validation](</docs/en/server-managed-settings#invalid-entries-in-delivered-settings>). Before v2.1.282, this cause read `server returned invalid settings`. The rest of the line says which policy the session runs on: @@ -5952,11 +4799,7 @@ Before v2.1.248, Claude Code reported a failed settings fetch only in the debug log. -### - -​ - -Claude Code couldn’t load your organization’s settings +### Claude Code couldn’t load your organization’s settings Your session hasn’t started because your organization’s settings, including its [server-managed settings](</docs/en/server-managed-settings>), have to load first and Claude Code couldn’t load them. For example: @@ -5970,11 +4813,7 @@ * **`Your Claude session has expired`** : the sign-in stored on this machine is no longer valid, so retrying won’t help. In the dialog, select **Sign in again** to close Claude Code; then, in your shell, run `claude auth login`, which works even while sessions can’t start. * **`none of the settings the server returned could be applied as written`** : ask your administrator to correct the organization’s [server-managed settings](</docs/en/server-managed-settings#invalid-entries-in-delivered-settings>), then retry. -### - -​ - -Managed settings were not approved +### Managed settings were not approved Your organization’s [server-managed settings](</docs/en/server-managed-settings>) include settings that need your approval, and you declined the [security approval dialog](</docs/en/server-managed-settings#security-approval-dialogs>), so Claude Code exits without applying them: @@ -5985,11 +4824,7 @@ * Start Claude Code again and approve the dialog to continue under your organization’s settings. A declined dialog isn’t remembered, so it appears again at the next start. * If you’re unsure about a setting the dialog lists, ask whoever maintains your organization’s managed settings before approving -### - -​ - -Managed settings need your approval +### Managed settings need your approval Your organization’s [server-managed settings](</docs/en/server-managed-settings>) include settings that need your approval in the [security approval dialog](</docs/en/server-managed-settings#security-approval-dialogs>). The `claude plugin` command you ran couldn’t read from the keyboard, so it couldn’t show that dialog. That happens when you pipe or redirect its input and, on macOS and Linux, it also can’t open `/dev/tty`. The command stopped before making any changes: @@ -5999,11 +4834,7 @@ * Run `claude` in a terminal and approve the settings when the dialog appears, then run the same `claude plugin` command again. Claude Code keeps the approval and the approved settings in your [configuration directory](</docs/en/server-managed-settings#approval-memory>). If the command that stopped ran as another user or with `CLAUDE_CONFIG_DIR` set, run `claude` the same way so that both use the same directory. -### - -​ - -Managed settings block the default model +### Managed settings block the default model Your organization’s [managed settings](</docs/en/managed-settings>) block the model the Default option resolves to and every model it could step down to. A session that would start on the Default option exits at startup instead of running a blocked model. Which message you see depends on the setting that blocks it. When a [`deniedModels`](</docs/en/model-config#block-specific-models-or-versions>) list blocks it, the message reads: @@ -6018,11 +4849,7 @@ * If you administer the settings, add a model your users can run to `availableModels`, or narrow the `deniedModels` entries that block every fallback. [Block specific models or versions](</docs/en/model-config#block-specific-models-or-versions>) describes how the Default option steps down * If you don’t administer them, send the message to your administrator. Your own settings files can’t widen a managed `availableModels` or `deniedModels` list -### - -​ - -Managed settings don’t allow this API provider +### Managed settings don’t allow this API provider Your organization’s [managed settings](</docs/en/managed-settings>) set an [`allowedProviders`](</docs/en/settings-reference#allowedproviders>) list, and the session’s API provider isn’t on it or the session uses an endpoint that isn’t pinned the way that entry requires. Claude Code refuses at startup, before a login, or when the session next contacts the API. The message begins with the permitted providers: @@ -6037,11 +4864,7 @@ * Follow the message’s `To continue:` steps * If you administer the settings, the message’s lines starting `Admins:` name the entry to add or the value to pin, and the [`allowedProviders`](</docs/en/settings-reference#allowedproviders>) entry says which source’s `env` block can pin it -### - -​ - -MCP server is blocked by enterprise managed policy +### MCP server is blocked by enterprise managed policy You selected **Reconnect** on a server in `/mcp`, or turned a disabled server back on there, and a setting that [restricts MCP servers](</docs/en/managed-mcp>) blocks that server. Claude Code refuses to connect it and shows: @@ -6061,11 +4884,7 @@ Before v2.1.257, **Reconnect** and re-enable in `/mcp` could connect a server that a mid-session policy update blocked. -### - -​ - -MCP server name is reserved +### MCP server name is reserved This message names one of your MCP servers, whose name is among those Claude Code reserves, such as the names of its built-in servers: @@ -6076,11 +4895,7 @@ * Rename the server where you define it, for example from `workspace` to `my-workspace` * For other reserved names to avoid, see [MCP configuration warnings](</docs/en/mcp#configuration-warnings>) -### - -​ - -Managed settings document could not be parsed +### Managed settings document could not be parsed Your organization deploys [managed settings](</docs/en/managed-settings>), and one of the deployed documents is present but can’t be parsed as a JSON object, so Claude Code exits with code 1 at startup instead of running without the policy the document carries. The line names the failed source before the message: @@ -6097,11 +4912,7 @@ * If you administer the machine, fix the named document so it parses as a JSON object, or remove the file, profile, or registry value. An empty `managed-settings.json` counts as `{}` and doesn’t block launch. * If you don’t, ask your administrator to fix the deployed document. Nothing in your own settings files causes or clears this error. -### - -​ - -Unable to read managed policy settings +### Unable to read managed policy settings Your organization deploys [managed settings](</docs/en/managed-settings>), and one of the deployed sources exists but couldn’t be read, for a reason such as an I/O error rather than the operating system denying the read. With no other admin source supplying a policy, Claude Code exits at startup rather than run without the policy the source may carry: @@ -6118,11 +4929,7 @@ Before v2.1.285, only sessions signed in with claude.ai or Claude Console credentials exited with this message, and a read that the operating system denied produced it too. -### - -​ - -Managed settings contain invalid entries, including PreToolUse/PermissionRequest hooks that are NOT loaded +### Managed settings contain invalid entries, including PreToolUse/PermissionRequest hooks that are NOT loaded This stderr block from a `-p` run means that a [managed settings](</docs/en/managed-settings>) source holds a hook entry Claude Code can’t load. That hook doesn’t run, and when a line lists the source’s `hooks` field as ignored, none of that source’s hooks run. Each line names the source, the field when there is one, and the problem, such as an unknown hook `type` or a hook declared outside the `hooks` key: @@ -6137,11 +4944,7 @@ Before v2.1.300, a `-p` run listed this case under the `Managed settings failed to load; policies from the failed source are NOT in effect:` header. -### - -​ - -otelHeadersHelper failed +### otelHeadersHelper failed Claude Code shows this warning as a notification in the terminal interface, once per interactive session, when the [`otelHeadersHelper`](</docs/en/settings-reference#otelheadershelper>) script fails or prints output that doesn’t meet the [script requirements](</docs/en/monitoring-usage#script-requirements>). While the script keeps failing, exports fail and your telemetry backend receives nothing from the session. The text after `See /status:` says what failed, such as the script’s exit code followed by its error output: @@ -6155,11 +4958,7 @@ In [non-interactive mode](</docs/en/headless>) with `-p`, the same failure appears on stderr as `otelHeadersHelper failed (OpenTelemetry export headers unavailable): <error>` instead. -### - -​ - -headersHelper not run +### headersHelper not run Claude Code connected an MCP server with its static `headers` alone and skipped the server’s [`headersHelper`](</docs/en/mcp#use-dynamic-headers-for-custom-authentication>), because the helper is a shell command and the folder has no saved trust. A folder gets saved trust when you set its entry in `~/.claude.json` by hand or, outside your home directory, when you accept the trust dialog for it in an interactive session. See [Trust a folder before its headersHelper runs](</docs/en/mcp#trust-a-folder-before-its-headershelper-runs>) for which servers this check applies to. Claude Code writes this line in [non-interactive mode](</docs/en/headless>) only, once per server. In an interactive session it writes the same refusal to the debug log instead. @@ -6171,11 +4970,7 @@ * Set the `hasTrustDialogAccepted` entry in `~/.claude.json` yourself, using the exact `projects` key the message prints * If you started the session in your home directory, work from a project directory you have trusted. When you accept the trust dialog in your home directory, Claude Code holds that trust for the current session only. -### - -​ - -Malformed Tool(content) rule +### Malformed Tool(content) rule A [permission rule](</docs/en/permissions#permission-rule-syntax>) in one of your settings files doesn’t have the shape `Tool` or `Tool(content)`, for example because text follows the closing parenthesis or one of the parentheses is missing. Claude Code skips the rule and lists it in the invalid-settings dialog when an interactive session starts, and in [`claude doctor`](</docs/en/debug-your-config#check-resolved-settings>) output: @@ -6188,11 +4983,7 @@ Before v2.1.260, Claude Code reported a rule with unmatched parentheses as `Mismatched parentheses`. -### - -​ - -Matches no tool · check for typos +### Matches no tool · check for typos This row below the startup banner names a deny or ask [permission rule](</docs/en/permissions>) whose tool name Claude Code doesn’t recognize, so the rule doesn’t apply to the tool you meant. A deny rule written as `Bsh` isn’t applied to Bash, and neither is one that uses the label a tool shows in the transcript instead of its canonical name. The row repeats the rule as you wrote it: @@ -6210,11 +5001,7 @@ In a [background session](</docs/en/agent-view>) or with `--output-format json` or `stream-json`, Claude Code writes the warning to the debug log instead of stderr. Run with `--debug` to capture it at `~/.claude/debug/<session-id>.txt`. Before v2.1.305, an interactive session printed the longer form on stderr at startup instead of showing the row. -### - -​ - -Is not matched by file permission checks +### Is not matched by file permission checks Claude Code found a `Write`, `NotebookEdit`, `MultiEdit`, or `Glob` [permission rule](</docs/en/permissions#read-and-edit>) with a path in one of your [settings files](</docs/en/settings#where-settings-live>), in [managed settings](</docs/en/managed-settings>), or in a `--allowedTools`, `--disallowedTools`, or `--settings` flag value. It checks file permissions against `Edit` and `Read` rules only, so it never consults a path rule that names one of the other file tools. It keeps the rule and changes nothing else. @@ -6239,11 +5026,7 @@ Before v2.1.210, Claude Code accepted these rules without a warning. Before v2.1.305, an interactive session printed the full warning on stderr. -### - -​ - -Has a wildcard before the rest of the command +### Has a wildcard before the rest of the command Claude Code found a `Bash` allow rule whose `*` comes before a later word that determines which command it is, such as `Bash(git * main)` or `Bash(git -C * status *)`, in one of your [settings files](</docs/en/settings#where-settings-live>), in [managed settings](</docs/en/managed-settings>), or in an `--allowedTools` or `--settings` flag value. The `*` matches any text, including options inserted at that position: `Bash(git * main)` also approves `git -c core.fsmonitor=<script> diff main`, where `-c` makes git run a program the command names. [Wildcard patterns](</docs/en/permissions#wildcard-patterns>) shows the matching rules. The warning exists so you can narrow a rule whose wildcard is broader than you intended. Claude Code keeps the rule and changes nothing about how it matches. In [non-interactive mode](</docs/en/headless>) with text output, the warning on stderr names the rule and its source in parentheses: @@ -6262,11 +5045,7 @@ In a [background session](</docs/en/agent-view>) or with `--output-format json` or `stream-json`, Claude Code writes the warning to the debug log instead of stderr, so machine-read output stays clean. Run with `--debug` to capture it at `~/.claude/debug/<session-id>.txt`. Before v2.1.246, Claude Code accepted these rules without a warning. Before v2.1.305, an interactive session printed the full warning on stderr instead of showing a row. -### - -​ - -Denying Bash also turns off the PowerShell tool +### Denying Bash also turns off the PowerShell tool You removed the whole Bash tool, for example with `--disallowedTools Bash` or with a bare `Bash` or `Bash(*)` [deny rule](</docs/en/permissions#match-all-uses-of-a-tool>) in one of your settings files. On Windows with Git Bash installed, [denying Bash also turns the PowerShell tool off](</docs/en/tools-reference#bash-deny-rules-also-turn-off-the-powershell-tool>), so the session starts with no shell tool. In [non-interactive mode](</docs/en/headless>) with text output, Claude Code prints this warning on stderr at startup, and an interactive session writes it only to the debug log: @@ -6279,11 +5058,7 @@ In a [background session](</docs/en/agent-view>) or with `--output-format json` or `stream-json`, Claude Code writes the warning to the debug log instead of stderr. Run with `--debug` to capture it at `~/.claude/debug/<session-id>.txt`. Before v2.1.287, Claude Code turned the PowerShell tool off the same way without printing a warning. Before v2.1.305, an interactive session printed the warning on stderr at startup too. -### - -​ - -crossSessionInbound must be one of accept, hold, refuse +### crossSessionInbound must be one of accept, hold, refuse A settings file sets [`crossSessionInbound`](</docs/en/settings-reference#crosssessioninbound>) to a value Claude Code doesn’t recognize, such as the typo `"reject"`. The warning’s second sentence depends on which file holds the value; in a user, project, local, or `--settings` file it reads: @@ -6296,11 +5071,7 @@ Before v2.1.248, Claude Code ignored an unrecognized value without warning. -### - -​ - -ANTHROPIC_FOUNDRY_RESOURCE must be a Foundry resource name +### ANTHROPIC_FOUNDRY_RESOURCE must be a Foundry resource name You set [`ANTHROPIC_FOUNDRY_RESOURCE`](</docs/en/env-vars>) to something other than a bare [Microsoft Foundry](</docs/en/microsoft-foundry>) resource name, such as the endpoint URL or its host name. Claude Code refused the value before sending a request. The message appears in place of Claude’s reply, not as a startup warning: @@ -6311,11 +5082,7 @@ * Set `ANTHROPIC_FOUNDRY_RESOURCE` to the resource name alone and restart Claude Code. For the endpoint `https://my-resource.services.ai.azure.com/anthropic`, the name is `my-resource`. * To give the full endpoint URL instead, set [`ANTHROPIC_FOUNDRY_BASE_URL`](</docs/en/env-vars>) to the URL and remove `ANTHROPIC_FOUNDRY_RESOURCE`, then restart Claude Code. Claude Code accepts only one of the two variables. -### - -​ - -The 200K limit isn’t enforced +### The 200K limit isn’t enforced You set [`CLAUDE_CODE_DISABLE_1M_CONTEXT=1`](</docs/en/env-vars>), which normally makes [auto-compaction](</docs/en/model-config#default-auto-compact-thresholds>) hold sessions on 1M-context models to a 200K window, but no compaction threshold caps this session at or below 200K, so the conversation can grow past it. @@ -6334,11 +5101,7 @@ In [non-interactive mode](</docs/en/headless>) with text output, this warning appears on stderr. In an interactive session, a [background session](</docs/en/agent-view>), or with `--output-format json` or `stream-json`, it goes to the debug log instead. Run with `--debug` to capture it at `~/.claude/debug/<session-id>.txt`. Before v2.1.305, an interactive session printed the warning on stderr at startup. -### - -​ - -Unrecognized model ID on a request +### Unrecognized model ID on a request Claude Code sent a request for a model ID that your Claude Code version doesn’t recognize, and found no [`modelOverrides`](</docs/en/model-config#override-model-ids-per-version>) entry that maps that ID to a model it does recognize. Claude Code still sends the request with the ID as you configured it, and doesn’t exit or switch models. @@ -6370,11 +5133,7 @@ Before v2.1.233, Claude Code wrote no line when it sent a request for a model ID it didn’t recognize. -### - -​ - -Sandbox allow entries are ignored under a managed lock +### Sandbox allow entries are ignored under a managed lock This warning in `/status` and `claude doctor` means managed settings set [`allowManagedReadPathsOnly`](</docs/en/settings-reference#sandbox-filesystem-allowmanagedreadpathsonly>) or [`allowManagedDomainsOnly`](</docs/en/settings-reference#sandbox-network-allowmanageddomainsonly>), so the [`allowRead`](</docs/en/settings-reference#sandbox-filesystem-allowread>) or [`allowedDomains`](</docs/en/settings-reference#sandbox-network-alloweddomains>) entries in the file it names don’t apply: @@ -6386,11 +5145,7 @@ * If you need those paths or domains and your organization’s managed settings set the lock, ask your administrator to add them to those settings. The warning stays until you also remove the entries from the named file. * To clear the warning, remove the entries from the named file. For a file you share, such as a project’s `.claude/settings.json`, you can leave the entries in for teammates without the lock and leave the warning showing. -### - -​ - -Sandbox mask files left behind at write-deny paths +### Sandbox mask files left behind at write-deny paths This warning in `claude doctor` and `/status` lists mask files: 0-byte read-only placeholder files at paths the [sandbox](</docs/en/sandboxing>) denies writes to. It appears on Linux and WSL2 when sandboxing is enabled with filesystem isolation on. Delete them from your shell once no Claude Code session is open in the project that holds them. The sandbox creates a placeholder while a sandboxed command runs and removes it when the command ends. One stays behind in cases such as these: @@ -6410,11 +5165,7 @@ Before v2.1.309, the warning read `Stale sandbox mask files left by a killed session`. Before v2.1.257, `claude doctor` didn’t flag these files; earlier versions leave the same placeholders behind when a session is killed. -### - -​ - -Two Claude Code config files exist +### Two Claude Code config files exist Claude Code is using the first file this message names, so what’s in the second file isn’t in effect. The first is `.config.json`, an older name for [`.claude.json`](</docs/en/claude-directory#ce-claude-json>). The message includes a check for which file holds your setup: @@ -6455,11 +5206,7 @@ The message stops once one of the two files is gone. -### - -​ - -Make this change again later: ~/.claude.json could not be updated +### Make this change again later: ~/.claude.json could not be updated This notice on stderr means a change to [`~/.claude.json`](</docs/en/claude-directory#ce-claude-json>), such as a sign-in or an answer to a trust prompt, wasn’t saved to the file: @@ -6469,11 +5216,7 @@ * Make the change again in a later session. For example, run `/login` again or answer the trust prompt again. -## - -​ - -Responses seem lower quality than usual +## Responses seem lower quality than usual If Claude’s answers seem less capable than you expect but no error is shown, the cause is usually conversation state rather than the model itself. Claude Code doesn’t silently change model versions. It can switch to a fallback model in these cases: @@ -6490,11 +5233,7 @@ When a response goes wrong, rewinding usually works better than replying with corrections. Press Esc twice or run `/rewind` to step back to before the bad turn, then rephrase the prompt with more specifics. Correcting in-thread keeps the wrong attempt in context, which can anchor later answers to it. See [Checkpointing](</docs/en/checkpointing>). If quality still seems off after checking the above, run `/feedback` and describe what you expected versus what you got. Feedback submitted this way includes the conversation transcript, which is the fastest way for Anthropic to diagnose a real regression. See Report an error if `/feedback` is unavailable in your environment. If Claude warns about a suspected prompt injection, or refuses a request because of a suspected injection, and the text the warning names is context Claude Code adds to the conversation automatically rather than file or web content, run `claude update` and retry. If the warning repeats after updating, report it rather than pasting the flagged content back into the prompt. Before v2.1.201, Sonnet 5 refused some requests the same way. -## - -​ - -Report an error +## Report an error For errors from components this page doesn’t cover, see the relevant guide:
modified React to events with a mod View current →
Show diff (320 lines)
--- a/events.md +++ b/events.md @@ -1,18 +1,10 @@ A hook is an event handler: a function that Claude Code runs when a named event happens. Claude Code fires an event at each point where it’s about to act, such as when it runs a tool, submits a prompt, sends a request to the model, or starts or ends a session. Your hook runs before Claude Code acts, so it can observe the event, rewrite it, or answer it in Claude Code’s place. You register a hook with [`on(eventName, handler)`](</docs/en/plugins/mods/reference#the-hook-function>). Build your [first mod](</docs/en/plugins/mods/create>) before you start here. For every event and its exact fields, see the [reference](</docs/en/plugins/mods/reference#events>) or read [the types for your build](</docs/en/plugins/mods/create#get-the-types-for-your-build>). -## - -​ - -How a hook handles an event +## How a hook handles an event A hook sits between an event and what Claude Code would do about it, so it can observe the event, rewrite it, or answer it itself. It receives three arguments: the [mods API](</docs/en/plugins/mods/api>) as `$`, the event as `e`, and the next handler as `next`. The handlers for an event form a middleware chain. `next(e)` calls the next handler, which is another mod’s hook or, at the end of the chain, Claude Code’s own behavior, and it resolves to the result. What your hook does with `next` decides which of the three it does. -### - -​ - -Observe an event +### Observe an event To observe an event without changing it, do your work and return `next(e)`. This hook logs each tool Claude is about to use: @@ -36,11 +28,7 @@ The line now appears after each tool finishes. Claude reads the same result either way, because the hook returns what `next(e)` resolved to. -### - -​ - -Rewrite an event +### Rewrite an event To change what Claude Code acts on, such as the text of a prompt, call `next` with a modified copy of the event. The event itself is immutable: it’s deeply frozen, and assigning to a field throws. This hook trims each prompt before it’s sent: @@ -51,11 +39,7 @@ Later handlers and Claude Code receive the trimmed prompt and never see the original. You can also change the result: `await next(e)`, then return a copy of the result with a field replaced. -### - -​ - -Answer an event +### Answer an event To handle an event yourself, return a result without calling `next`. That short-circuits the chain, so later mods and Claude Code’s own behavior don’t run. This hook refuses every Bash command: @@ -66,11 +50,7 @@ When Claude tries a Bash command, the command doesn’t run, and Claude reads the `deny` text as the tool’s result. Each event has its own result shape, which the [events reference](</docs/en/plugins/mods/reference#events>) lists. -### - -​ - -Filter which events a hook handles +### Filter which events a hook handles To run a hook for some events only, pass a filter as the second argument to `on`. Claude Code calls the filter a matcher. It’s an object whose fields are compared with the event’s, and the hook runs only when every field matches. A field can be a value, an array of allowed values, or a regular expression. Each line in this example registers the same function, `hook`, for a narrower set of tool calls: @@ -83,19 +63,11 @@ `hook` runs once for a Bash, Edit, or Write call, and once for a call to a tool whose name starts with `mcp__github__`. A call to any other tool, such as Read, matches none of the three, so `hook` doesn’t run for it. The event name can be a wildcard. `'classic.*'` matches every settings hook event. `'*'` matches every event except the [telemetry events](</docs/en/plugins/mods/reference#telemetry>), which take their own name and a `{ to: 'collector' }` filter. Register each event once per matcher. If you call `on` twice for `session.start` with no matcher, the module fails to load with `on("session.start") is registered twice without a matcher`. Put everything your mod does at session start in one hook. -## - -​ - -Hook what Claude is doing +## Hook what Claude is doing Handle these events to see or change a tool call, a prompt, a turn, or a settings read as it happens. For every event and what a hook can return, see the [events reference](</docs/en/plugins/mods/reference#events>). -### - -​ - -Guard or change a tool call +### Guard or change a tool call A `tool.call` hook sees each tool Claude is about to use, so it can refuse the call, change its arguments, or let it through. `tool.call` fires when Claude Code is about to run a tool, including calls a subagent makes and calls to MCP tools. `e.tool` is the tool’s name and the tool’s arguments are fields of `e`, such as `e.command` for Bash. When you call `next(e)`, Claude Code runs the permission check and then the tool. This hook refuses a Bash command that force-pushes, and tells Claude why: @@ -130,11 +102,7 @@ Hooks in your organization’s [managed settings](</docs/en/server-managed-settings>) run before any mod’s `tool.call` hook. When a managed hook blocks the call, no mod’s `tool.call` hook runs for that call. -#### - -​ - -Hold a tool call until the user decides +#### Hold a tool call until the user decides A hook can pause a tool call and ask the user what to do before it goes ahead. A `tool.call` hook can `await` before it calls `next` or returns, and the tool call stays pending until then. To put the question to the user, call `$.ui.ask`. It shows your question above a numbered list of your options, in the dialog Claude uses to ask you something, and resolves to the label the user picks. After your options, the dialog adds a row for typing a different answer and a **Chat about this** row. The `RISKY` pattern in this example matches `rm -r`, `rm -rf`, `git reset --hard`, and `git push` with `--force`, and it misses other spellings such as `git push -f`. This module asks before it runs a Bash command that matches the pattern: @@ -169,11 +137,7 @@ Keep the wait inside a mods API call such as `$.ui.ask`, because that time doesn’t count against the hook’s [time limit](</docs/en/plugins/mods/reference#limits>). Time spent awaiting a promise of your own does count. Claude Code skips a hook that times out, so the held command would run. To refuse it instead, chain a `.catch` handler onto the registration that `on` returns. That handler is separate from the `catch` block inside the hook. -#### - -​ - -Approve or refuse a tool call before the user is asked +#### Approve or refuse a tool call before the user is asked To decide whether a tool call may run, handle [`tool.check`](</docs/en/plugins/mods/reference#tools>), the event where Claude Code makes that decision. For a fixed command or path, use a [permission rule](</docs/en/permissions#permission-rule-syntax>) such as `Bash(npm test)`, which takes no code. Handle `tool.check` when the decision depends on what’s true at that moment, such as the current Git branch or a value another hook recorded. @@ -203,11 +167,7 @@ A `tool.check` hook can also return `allow` or `ask`. In [plan mode](</docs/en/permissions#hook-approvals-in-plan-mode>), for a call that isn’t read-only, such as a file edit, your hook can tighten the decision `next(e)` returns but can’t loosen it. For the permission rules and `PreToolUse` hook decisions your hook’s `allow` can’t replace, see [Extend permissions with hooks](</docs/en/permissions#precedence-among-rules-hooks-and-mods>). -#### - -​ - -Check whether a tool call is read-only +#### Check whether a tool call is read-only In a `tool.check` hook, `e.isReadOnly` is `true` when the tool reports the call as read-only. Otherwise the field is absent, not `false`. `e.isReadOnly` requires Claude Code v2.1.304 or later. Some tools, such as Read, Grep, Glob, and WebSearch, report every call as read-only. Bash and MCP tools report a call as read-only in these cases: @@ -223,22 +183,14 @@ return { decision: 'ask', reason: 'This tool can change the GitHub repository' } }) -#### - -​ - -Filter a `tool.check` hook by whether the call is read-only +#### Filter a `tool.check` hook by whether the call is read-only To limit which calls your hook handles by `e.isReadOnly`, use the matcher for read-only calls and the hook body for the rest: * **Read-only calls only** : add `isReadOnly: true` to the matcher, as in `on('tool.check', { tool: 'Bash', isReadOnly: true }, hook)` * **Calls that aren’t read-only** : test `e.isReadOnly` in the hook body, as the `mcp__github__` example does. If you put `isReadOnly: false` in a matcher, your hook never runs. -### - -​ - -Rewrite or add to a prompt +### Rewrite or add to a prompt A `prompt.submit` hook sees each prompt before the turn starts, so it can rewrite the text or add to it. `e.text` is what was typed. @@ -267,11 +219,7 @@ [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. To change a section after a conversation has started, see [Send a changed system prompt section or tool description](</docs/en/plugins/mods/reference#break-prompt-cache>). In a `skill.prompt` hook, you can also read [which plugin or file the skill came from](</docs/en/plugins/mods/reference#skill-prompt-fields>). -### - -​ - -Follow a turn +### Follow a turn A turn is everything Claude does in answer to one prompt. Handle `turn.start`, `turn.step`, and `turn.complete` to follow one: @@ -297,19 +245,11 @@ Claude’s response streams to the screen as it does without the mod. After each request finishes, a dim line in the transcript gives the number of tokens read from the cache and the number written to it. A turn with tool calls has several requests, so it adds several lines. `result.usage` holds the token counts the Claude API reports for a request, plus the `model` that answered: `input_tokens`, `output_tokens`, `cache_read_input_tokens`, and `cache_creation_input_tokens`. The hook runs for subagents’ requests too, so check `e.agentId` when you want only the main conversation. To see the tool calls that the API ran itself during the request, such as calls to the [advisor tool](</docs/en/advisor>), read `result.serverToolUses`. Claude Code doesn’t run these calls, so no `tool.call` or `tool.check` hook fires for them. The field is absent when the response has no such calls, and it requires Claude Code v2.1.290 or later. -#### - -​ - -Send a request to a different model +#### Send a request to a different model If a `turn.step` request fails with a model error when `model` is an alias such as `haiku`, update to Claude Code v2.1.309 or later, or use a full model id. Before v2.1.309, an alias went out as written. To send a request to a different model, pass `next` the event with `model` changed, as in `yield* next({ ...e, model: 'haiku' })`. -### - -​ - -Change or refuse a settings read +### Change or refuse a settings read Use a `settings.read` hook to change or refuse a settings read, either a mod’s or Claude Code’s own: @@ -321,11 +261,7 @@ * **The built-in guard** : where the [built-in guard](</docs/en/plugins/mods/admin#know-what-happens-by-default>) loads, it can skip this hook in a mod you install or load with `--plugin-dir`. To check, search the [debug log](</docs/en/plugins/mods/troubleshoot#read-the-debug-log>) for `settings.read bypassed by cc-plugin-sec-default`. If a line with that text names your mod, ask your organization’s administrator to [install the mod as one of the organization’s mods](</docs/en/plugins/mods/admin#install-your-organizations-mods>). * **The version** : the event firing on Claude Code’s own read, and the `e.layers` field, require Claude Code v2.1.304 or later. -#### - -​ - -What a `settings.read` hook receives +#### What a `settings.read` hook receives Field| Type| What it holds ---|---|--- @@ -334,22 +270,14 @@ In `e.layers`, `plugin` holds settings that enabled plugins supply, and is a layer name only, not a `source` you can pass to `$.settings.read`. `flag` holds the settings passed with `--settings`, and `policy` holds managed settings. -#### - -​ - -Tell Claude Code’s own read from a mod’s read +#### Tell Claude Code’s own read from a mod’s read Check [`next.origin`](</docs/en/plugins/mods/reference#the-hook-function>): * **Claude Code’s own read** : `{ plugin: 'engine', tier: 'core' }` * **A mod’s read** : `plugin` is the calling mod’s name -#### - -​ - -What a `settings.read` hook can return +#### What a `settings.read` hook can return Return `next(e)`’s result unchanged to leave the read as it is, or return one of these: @@ -360,22 +288,14 @@ On Claude Code’s own read, build your `{ value }` from `next(e)`’s `value`, since a key you leave out is unset. Where Claude Code reads a key such as `env` from each source separately, changing it in your `value` [has no effect](</docs/en/plugins/mods/troubleshoot#settings-read-key-no-effect>). -#### - -​ - -What `next(e)` gives a `settings.read` hook +#### What `next(e)` gives a `settings.read` hook `next(e)` resolves to `{ value }` or to `{ deny }`: * **`{ value }`** : `value` is the merged settings, or one source’s settings when `e.source` is set. If a hook that runs after yours returned a `{ value }` of its own, you get that hook’s `value` instead. * **`{ deny }`** : a hook that runs after yours refused the read. Return that `{ deny }` unchanged. -#### - -​ - -Change one setting from a `settings.read` hook +#### Change one setting from a `settings.read` hook First check which mods get this event, and from which version. To change one key, spread the `value` from [`next(e)`](</docs/en/plugins/mods/reference#the-hook-function>) and set that key, as this hook does with [`spinnerTipsEnabled`](</docs/en/settings-reference#spinnertipsenabled>). The hook doesn’t check `next.origin`, so the hook changes the key on Claude Code’s own read and on a mod’s merged read alike: @@ -390,11 +310,7 @@ On Claude Code’s own read, if your hook returns a value outside the key’s schema, such as a string, that key alone keeps the value merged before any hook answered. The debug log then says [`the answer for <key> is no value the key can hold`](</docs/en/plugins/mods/troubleshoot#settings-read-key-refused>). If your value fits and the key still doesn’t change, see [why a key doesn’t take effect](</docs/en/plugins/mods/troubleshoot#settings-read-key-no-effect>). -### - -​ - -Handle the settings hook events +### Handle the settings hook events Settings hooks are the command, HTTP, prompt, and agent hooks you configure in settings files. Each [settings hook event](</docs/en/hooks#hook-events>), such as `Stop`, `SessionEnd`, or `PostToolUse`, is also an event named `classic.` followed by the settings hook event’s name, such as `classic.Stop`. `e` is the JSON a settings hook receives on stdin, including `transcript_path`. Where the [built-in guard](</docs/en/plugins/mods/admin#know-what-happens-by-default>) loads, [a hook on these events in a mod you install doesn’t run](</docs/en/plugins/mods/admin#hooks-the-guard-passes-over>). This hook uses `Stop`, which fires when Claude finishes responding, to log where the session’s transcript is saved: @@ -407,19 +323,11 @@ Each time Claude finishes responding, a dim line in the transcript gives the path of the transcript file. The hook returns `next(e)`, so it observes the event and changes nothing about how the turn ends. -## - -​ - -Run alongside other mods +## Run alongside other mods Several mods can handle the same event, and any one of them can fail. If your mod blocks tool calls, check its position in the chain and what happens when its hook fails. -### - -​ - -The order mods run in +### The order mods run in Hooks on the same event form one middleware chain. Each mod’s `next` calls the following mod’s hook, and the last `next` reaches Claude Code’s own behavior. The first mod is outermost: it sees the event before the others and the result after them, and it decides whether the others run at all. A later mod can’t stop an earlier one from seeing an event. Claude Code orders the chain by where each mod comes from: @@ -430,11 +338,7 @@ Among the mods you install, a mod runs before the mods it lists under `dependencies` in its manifest. Within one module, hooks run in the order `register` called `on`. -#### - -​ - -Where settings hooks run in the order +#### Where settings hooks run in the order The `PreToolUse` hooks configured in settings files also run during a tool call, at fixed points in the chain of mods: @@ -443,11 +347,7 @@ `tool.check` fires after the `PreToolUse` hooks have run. For the permission rules and `PreToolUse` hook decisions a `tool.check` hook’s `allow` can’t replace, see [Extend permissions with hooks](</docs/en/permissions#precedence-among-rules-hooks-and-mods>). -### - -​ - -Handle a hook that fails +### Handle a hook that fails A hook that fails doesn’t break the session, and you can decide what happens instead. When a hook with no `.catch` handler throws, times out, or returns a result of the wrong shape, what happens next depends on whether it had called `next`: @@ -476,11 +376,7 @@ At `tool.call`, a `deny` returned after `next` resolved withholds the result from Claude. -## - -​ - -Next steps +## Next steps * [Use the mods API](</docs/en/plugins/mods/api>): add commands and tools, call a model, and run work on a timer * [Draw in the interface](</docs/en/plugins/mods/interface>): show what your hooks collect in a pane or above the prompt
modified Examples View current →
--- a/examples.md +++ b/examples.md @@ -1,36 +1,20 @@ This page routes you to complete, runnable Agent SDK projects and guided Claude Cookbook recipes. The applications live in the [`claude-agent-sdk-demos`](<https://github.com/anthropics/claude-agent-sdk-demos>) repo, and Python recipes live in the [Claude Cookbook](<https://platform.claude.com/cookbook>). -## - -​ - -Run a minimal agent first +## Run a minimal agent first If you haven’t built anything with the SDK yet, start with one of these before a full application: * [Agent SDK quickstart](</docs/en/agent-sdk/quickstart>): build your first working agent in TypeScript or Python, with setup steps included. The agent finds and fixes bugs in a sample file. * [Hello World](<https://github.com/anthropics/claude-agent-sdk-demos/tree/main/hello-world>): a minimal TypeScript project to clone when you want to start from repo code -## - -​ - -Explore a demo application +## Explore a demo application The applications in [`claude-agent-sdk-demos`](<https://github.com/anthropics/claude-agent-sdk-demos>) are demos for local development, from an email client to a multi-agent research system. Clone the demo whose shape matches what you’re building. -## - -​ - -Fork a complete project +## Fork a complete project To build a shopping agent or a merchant agent with the Python SDK, start from the [Claude for commerce reference implementation](<https://platform.claude.com/docs/en/about-claude/use-case-guides/commerce-agents>). -## - -​ - -Work through a Python recipe +## Work through a Python recipe The Claude Cookbook’s Agent SDK series is a sequence of recipes, each a Python notebook, that progresses from a simple research agent to sophisticated multi-agent systems. Each notebook builds on the previous one, introducing new concepts and capabilities. Start with [the one-liner research agent](<https://platform.claude.com/cookbook/claude-agent-sdk-00-the-one-liner-research-agent>) and work forward. For recipes across Claude products, see the full [Claude Cookbook](<https://platform.claude.com/cookbook>).
modified Speed up responses with fast mode View current →
Show diff (226 lines)
--- a/fast-mode.md +++ b/fast-mode.md @@ -14,11 +14,7 @@ * Available to Claude Code users on subscription plans (Pro/Max/Ultra/Team/Enterprise), on Claude Console, and on Google Cloud’s Agent Platform with conditions. Team and Enterprise organizations need an Owner to enable it first, and Console organizations need access provisioned first to use it with Opus 5 or Opus 4.8. Requirements describes both. * For Claude Code users on subscription plans (Pro/Max/Ultra/Team/Enterprise), fast mode is available via usage credits only and not included in the subscription rate limits. -## - -​ - -Toggle fast mode +## Toggle fast mode On Agent Platform, `/fast` and the `fastMode` setting work differently, so follow Use fast mode on Agent Platform instead. In the CLI, toggle fast mode in either of these ways: @@ -35,11 +31,7 @@ On the Anthropic API, Opus 5.5 is the fast mode default in Claude Code v2.1.280 and later. Before v2.1.280, fast mode defaulted to Opus 5 from v2.1.219. When you disable fast mode with `/fast` again, you remain on your current model. To switch to a different model, use `/model`. -### - -​ - -Switch models while fast mode is on +### Switch models while fast mode is on Fast mode follows your model switches: @@ -49,19 +41,11 @@ Whenever a model switch turns fast mode on or off, Claude Code shows a `Fast mode ON` or `Fast mode OFF` confirmation, and the `↯` icon appears while fast mode is on. This holds whether you switch with `/model`, with [`/config model=<model>`](</docs/en/settings>), or from a device connected through [Remote Control](</docs/en/remote-control>). -### - -​ - -Use fast mode in cloud sessions +### Use fast mode in cloud sessions Fast mode works in [cloud sessions](</docs/en/claude-code-on-the-web>) when it’s available on your account, whether the session runs on Anthropic-managed infrastructure or a [self-hosted runner](</docs/en/self-hosted-environments>) on the Anthropic API. Requires Claude Code v2.1.271 or later in the session’s environment. Type `/fast on` in the session to turn fast mode on. It stays on for that session only and isn’t saved as your default. The requirements apply in cloud sessions too. In the browser at [claude.ai/code](<https://claude.ai/code>), you can also turn fast mode on and off from the model menu on the message box. The menu shows the switch when your plan includes fast mode and the selected model supports it. -## - -​ - -Understand the cost tradeoff +## Understand the cost tradeoff Fast mode has higher per-token pricing than standard speed. These are Anthropic’s rates: @@ -74,23 +58,15 @@ Fast mode pricing is flat across the full 1M token context window. For the standard rate to compare against, see the [Claude pricing reference](<https://platform.claude.com/docs/en/about-claude/pricing>). The first time you enable fast mode in a conversation, you pay the full fast mode uncached input token price for the entire conversation context. The deeper into a conversation you are, the more this costs, so the charge is smallest when you enable fast mode at the start. Fast mode and standard speed keep [separate caches](</docs/en/prompt-caching#turning-on-fast-mode>), so each later switch reads part or all of the conversation uncached again. -### - -​ - -See where fast mode spend appears +### See where fast mode spend appears You see fast mode spend in a different place depending on how you signed in, so first run [`/status`](</docs/en/commands>) to check. If it shows a `Login method` row such as `Claude Max account`, you signed in with a Claude subscription. If it shows an `API key` row instead, your requests bill to a Claude Console organization. * **Pro, Max, and Ultra** : you pay for fast mode from your usage credits. Go to [**Settings > Usage**](<https://claude.ai/settings/usage>) on claude.ai, where the **Usage credits** section shows how much you’ve spent in usage credits this month. That figure includes fast mode but doesn’t break it out separately. * **Team and Enterprise** : your organization pays for your fast mode usage from its usage credits. To see your own usage-credits spend, run [`/usage`](</docs/en/costs#check-your-usage-credits-spend>). For where your organization sees that spend, see [Claude for Teams and Enterprise](</docs/en/costs#claude-for-teams-and-enterprise>). - * **Claude Console** : your organization pays for fast mode with the rest of its API usage. On the Console [Usage](<https://platform.claude.com/usage>) and [Cost](<https://platform.claude.com/cost>) pages, select **Speed (research preview)** in the **Group by** menu to separate fast mode from standard-speed usage. You see that option only when the selected date range includes fast mode usage. - -## - -​ - -Decide when to use fast mode + * **Claude Console** : your organization pays for fast mode with the rest of its API usage. On the Console [Usage](<https://platform.claude.com/usage>) and [Cost](<https://platform.claude.com/cost>) pages, select **Speed** in the **Group by** menu to separate fast mode from standard-speed usage. You see that option only when the selected date range includes fast mode usage. + +## Decide when to use fast mode Fast mode is best for interactive work where response latency matters more than cost: @@ -104,11 +80,7 @@ * Batch processing or CI/CD pipelines * Cost-sensitive workloads -### - -​ - -Fast mode vs effort level +### Fast mode vs effort level Fast mode and effort level both affect response speed, but differently: @@ -119,11 +91,7 @@ You can combine both: use fast mode with a lower [effort level](</docs/en/model-config#adjust-effort-level>) for maximum speed on straightforward tasks. -## - -​ - -Requirements +## Requirements Fast mode requires all of the following: @@ -144,11 +112,7 @@ * **Per-session opt-in required** : managed settings that set `fastModePerSessionOptIn: true` refuse `/fast on` with the same message everywhere except an interactive terminal session. * **Fast-mode model not allowed** : if your organization’s [`availableModels`](</docs/en/model-config#restrict-model-selection>) allowlist excludes the model `/fast` switches to, turning it on is refused with “is not in your organization’s allowed models”. In a session already running on an allowed model that supports fast mode, `/fast` instead enables fast mode on your current model without switching models. -### - -​ - -Enable fast mode for your organization +### Enable fast mode for your organization Where you enable fast mode depends on which product your organization uses: @@ -157,11 +121,7 @@ Console organizations that use Claude Opus 5 or Claude Opus 4.8 also need provisioned access, as described in [fast mode on the Claude API](<https://platform.claude.com/docs/en/build-with-claude/fast-mode>). Without that access, fast mode requests on those models hit the fast mode rate limit and fall back to standard speed until access is provisioned. Another option to disable fast mode entirely is to set `CLAUDE_CODE_DISABLE_FAST_MODE=1`. See [Environment variables](</docs/en/env-vars>). -### - -​ - -Use fast mode on Agent Platform +### Use fast mode on Agent Platform On [Google Cloud’s Agent Platform](</docs/en/google-vertex-ai>), you can turn fast mode on for Fable 5.2, with `/fast` in an interactive session or with launch flags in [non-interactive mode](</docs/en/headless>). Requires Claude Code v2.1.322 or later. Fast mode needs the [region](</docs/en/google-vertex-ai#region-configuration>) for Fable 5.2 to be `global`, `us`, or `eu`. In another region, `/fast` reports `Fast mode needs Vertex region global, us or eu`, and `claude -p` runs at standard speed. Set the region in your shell before you start Claude Code, for example to `global`: @@ -177,27 +137,15 @@ * `Using standard speed on Fable 5.2 · fast mode wasn't available`: run `/fast on` to try fast mode again * `Fast mode was refused for this project · trying again in 30m`: Agent Platform answered a fast mode request with a 403 or 404 error. To try sooner, run `/fast on`. -### - -​ - -Use fast mode behind proxies and LLM gateways +### Use fast mode behind proxies and LLM gateways Before offering fast mode on the Anthropic API, Claude Code checks your organization’s fast mode availability with a request directly to `api.anthropic.com`. The check doesn’t follow [`ANTHROPIC_BASE_URL`](</docs/en/llm-gateway-connect#set-the-base-url-and-credential>), so on a network that routes Claude traffic through an [LLM gateway](</docs/en/llm-gateway>) and blocks direct egress to `api.anthropic.com`, the check fails even though inference requests work. The check does use a configured [HTTP proxy](</docs/en/network-config#proxy-configuration>), so a network block fails the check only where `api.anthropic.com` is unreachable even through the proxy. If your organization has fast mode enabled and `/fast` says otherwise, find the message it shows among these cases. -#### - -​ - -Fast mode unavailable due to network connectivity issues +#### Fast mode unavailable due to network connectivity issues The availability check failed, for example because your network blocks `api.anthropic.com`, and requests run at standard speed. A check that succeeded in the past keeps working from its cached result, so a blocked check mostly affects new installations. To restore fast mode, allowlist direct egress to `api.anthropic.com`, or set `CLAUDE_CODE_SKIP_FAST_MODE_NETWORK_ERRORS=1`, which treats a failed check as available and still honors a “disabled by your organization” response. -#### - -​ - -Fast mode is currently unavailable +#### Fast mode is currently unavailable Behind a gateway, check for these configurations, in which Claude Code doesn’t send the availability check and has no earlier successful check cached: @@ -206,11 +154,7 @@ To restore fast mode in either configuration, set `CLAUDE_CODE_SKIP_FAST_MODE_NETWORK_ERRORS=1`. -#### - -​ - -Fast mode has been disabled by your organization +#### Fast mode has been disabled by your organization Behind a gateway, you can see this message even when your organization has fast mode enabled, in either of these configurations: @@ -221,11 +165,7 @@ The skip variables change only the client-side check. When your organization has fast mode disabled, the API rejects fast mode requests whether or not they’re set. Claude Code then retries the request at standard speed, turns fast mode off, and `/fast` reports that your organization has disabled fast mode. -### - -​ - -Require per-session opt-in +### Require per-session opt-in By default on the Anthropic API, fast mode a user turns on in an interactive session persists across sessions on a supported model. On Fable 5.2, fast mode persists only if the user turned it on while using Fable 5.2. To make every session start with fast mode off, set `fastModePerSessionOptIn` to `true` in any [settings file](</docs/en/settings#where-settings-live>). Users then enable it with `/fast` in each session. Owners on [Team](<https://claude.com/pricing?utm_source=claude_code&utm_medium=docs&utm_content=fast_mode_teams#team-&-enterprise>) or [Enterprise](<https://anthropic.com/contact-sales?utm_source=claude_code&utm_medium=docs&utm_content=fast_mode_enterprise>) plans can deploy it organization-wide through [server-managed settings](</docs/en/server-managed-settings>). @@ -235,11 +175,7 @@ This is useful for controlling costs in organizations where users run multiple concurrent sessions. The user’s fast mode preference is still saved, so removing this setting restores the default persistent behavior. When managed settings set the key, `/fast on` works only in an interactive terminal session. Everywhere else, including [non-interactive mode](</docs/en/headless>), the [VS Code extension](</docs/en/vs-code>), and cloud sessions, it’s refused with a message that your organization has disabled fast mode. -## - -​ - -Handle rate limits +## Handle rate limits Fast mode has separate rate limits from standard speed; for Console organizations, the Claude Platform’s [rate limits](<https://platform.claude.com/docs/en/api/rate-limits>) page describes them. When you hit the fast mode rate limit: @@ -253,11 +189,7 @@ * In an interactive session, Claude Code shows a “Fast mode disabled · Out of usage credits” notification and turns fast mode off. Your saved fast mode preference doesn’t change; run `/fast` to turn fast mode back on. * In [non-interactive mode](</docs/en/headless>) with `--output-format stream-json`, and through the Agent SDK, Claude Code emits the same text on the message stream as a `system` message with subtype `notification`. The message arrives once per turn while you’re out of usage credits. Fast mode stays on. -## - -​ - -Research preview +## Research preview Fast mode for Claude Opus 5 and Claude Opus 4.8 is a research preview feature, which means: @@ -267,11 +199,7 @@ Report issues or feedback through your usual Anthropic support channels. -## - -​ - -See also +## See also * [Model configuration](</docs/en/model-config>): switch models and adjust effort levels * [Manage costs effectively](</docs/en/costs>): track token usage and reduce costs
modified Feature availability View current →
Show diff (123 lines)
--- a/feature-availability.md +++ b/feature-availability.md @@ -1,10 +1,6 @@ The Claude Code CLI and everything that runs locally work on every provider. For setup instructions per provider, see the [Enterprise deployment overview](</docs/en/third-party-integrations>). To skip straight to what is missing on your provider, see the summary by provider tabs. In the tables below, ✓ means available, ✗ means not available, and “See note” links to a footnote for partial support. A qualifier after ✓ narrows availability to that subset, and “Admin-enabled” means the feature is off until an organization admin turns it on. -## - -​ - -Availability by model provider +## Availability by model provider How you authenticate determines which features Claude Code can reach. For a single list of what is missing on your provider, see the summary by provider tabs. To find your column in the tables: @@ -15,11 +11,7 @@ * **Google Cloud’s Agent Platform** : Google-operated; you set `CLAUDE_CODE_USE_VERTEX` * **Microsoft Foundry** : Anthropic-operated; you set `CLAUDE_CODE_USE_FOUNDRY` -### - -​ - -Features available on every provider +### Features available on every provider These work on every provider: @@ -39,11 +31,7 @@ * `/voice` requires a claude.ai account * `/list-agents` and its alias `/peers` are available only in sessions where [cross-session messaging is enabled](</docs/en/cross-session-messaging#availability>) -### - -​ - -Features that require a Claude subscription +### Features that require a Claude subscription These require signing in with a claude.ai account and are not reachable with an Anthropic Console API key or from a third-party provider: @@ -61,11 +49,7 @@ Desktop is the partial exception: [gateway routing can be configured in the app or by an administrator](</docs/en/llm-gateway-connect#desktop-app>). [Claude Desktop on 3P](<https://claude.com/docs/third-party/claude-desktop/overview>) also runs the Code tab on Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, or a self-hosted LLM gateway. It also runs the Code tab on the [Claude API](<https://claude.com/docs/third-party/claude-desktop/claude-api>) with an Anthropic Console API key. For per-plan availability of these features, see Availability by subscription plan. -### - -​ - -CLI capabilities that vary by provider +### CLI capabilities that vary by provider These features work in the local CLI but depend on a server-side capability that not every provider exposes. Feature| Claude subscription| Anthropic Console| Amazon Bedrock| Claude Platform on AWS| Google Cloud’s Agent Platform| Microsoft Foundry ---|---|---|---|---|---|--- @@ -78,11 +62,7 @@ [GitHub Actions](</docs/en/github-actions>)| ✓| ✓| ✓| ✗| ✓| ✓ [GitLab CI/CD](</docs/en/gitlab-ci-cd>)| ✓| ✓| ✓| ✓| ✓| ✗ -### - -​ - -Admin and analytics +### Admin and analytics Organization-level controls and usage visibility. Feature| Claude subscription| Anthropic Console| Amazon Bedrock| Claude Platform on AWS| Google Cloud’s Agent Platform| Microsoft Foundry ---|---|---|---|---|---|--- @@ -97,11 +77,7 @@ If you authenticate through an [LLM gateway](</docs/en/llm-gateway>), feature availability matches the underlying provider the gateway forwards to, except for the features Claude Code itself turns off. Whenever `ANTHROPIC_BASE_URL` points at a host other than `api.anthropic.com`, Claude Code turns off features such as [Remote Control](</docs/en/remote-control#requirements>) and [server-managed settings](</docs/en/server-managed-settings#platform-availability>), whatever the gateway forwards. Some features, such as the [Advisor](</docs/en/advisor#requirements>), work only if the gateway forwards requests intact.For how the requests Claude Code sends differ between an Amazon Bedrock- or Agent Platform-format gateway, an `ANTHROPIC_BASE_URL` gateway, and a Claude apps gateway sign-in, see [client behavior by connection method](</docs/en/llm-gateway-protocol#how-the-connection-method-changes-client-behavior>). -### - -​ - -Summary by provider +### Summary by provider Each tab lists what is unavailable or partially supported on that provider, with alternatives where one exists. Everything not listed works the same as on a Claude subscription, apart from the provider-specific differences noted above. On Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, and Claude Platform on AWS, error reporting and telemetry to Anthropic are off by default. See [default behaviors by API provider](</docs/en/data-usage#default-behaviors-by-api-provider>) for what traffic still reaches Anthropic and how to opt out. @@ -154,11 +130,7 @@ * [Desktop](</docs/en/desktop>): via [Claude Desktop on 3P with the Claude API](<https://claude.com/docs/third-party/claude-desktop/claude-api>) -## - -​ - -Availability by subscription plan +## Availability by subscription plan If you authenticate through Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, or an Anthropic Console API key, this section does not apply to you. When you sign in with a claude.ai account, your plan determines which of the features below are available. In Enterprise organizations with the [HIPAA configuration](</docs/en/hipaa-setup>) applied, some features in this table are turned off. @@ -183,27 +155,15 @@ 6 On Enterprise, requires a premium seat or a Chat + Claude Code seat. See [Use Claude Code in the cloud](</docs/en/claude-code-on-the-web>). 7 Not included in the standard Enterprise plan. Requires separate enablement by Anthropic for qualified accounts. See [Zero Data Retention](</docs/en/zero-data-retention>). For pricing and the full plan comparison, see [Team plans](<https://support.claude.com/en/articles/9266767-what-is-the-team-plan>) and [Enterprise plans](<https://support.claude.com/en/articles/9797531-what-is-the-enterprise-plan>). -### - -​ - -Ultra plan +### Ultra plan Ultra is the new name for the Max 20x plan, and Max is the new name for Max 5x. To check which plan you’re on, see your subscription on claude.ai. In Claude Code, Max and Ultra have the same features, listed in the Max and Ultra columns of the availability table. For usage limits and pricing, see the [Claude pricing page](<https://claude.com/pricing>). -## - -​ - -Model availability +## Model availability For which Claude models and context-window sizes are available per provider and region, see [Model configuration](</docs/en/model-config>) and the [Models overview](<https://platform.claude.com/docs/en/about-claude/models/overview>). Vision, PDF input, and extended thinking are model capabilities rather than Claude Code features and work on every provider that offers the model. [Prompt caching](</docs/en/prompt-caching>) works the same way on most providers; on Amazon Bedrock, support varies by model. -## - -​ - -Related resources +## Related resources * [Enterprise deployment overview](</docs/en/third-party-integrations>): compare authentication, billing, and regions across providers * Provider setup guides: [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>)
modified Extend Claude Code View current →
Show diff (128 lines)
--- a/features-overview.md +++ b/features-overview.md @@ -4,11 +4,7 @@ **New to Claude Code?** Start with [CLAUDE.md](</docs/en/memory>) for project conventions, then add other extensions as specific triggers come up. -## - -​ - -Overview +## Overview Extensions plug into different parts of the agentic loop: @@ -25,11 +21,7 @@ [Skills](</docs/en/skills>) are the most flexible extension. A skill is a markdown file containing knowledge, workflows, or instructions. You can invoke skills with a command like `/deploy`, or Claude can load them automatically when relevant. Skills can run in your current conversation or in an isolated context via subagents. -## - -​ - -Match features to your goal +## Match features to your goal Features range from always-on context that Claude sees every session, to on-demand capabilities you or Claude can invoke, to background automation that runs on specific events. The table below shows what’s available and when each one makes sense. @@ -48,11 +40,7 @@ **[Plugins](</docs/en/plugins/overview>)** are the packaging layer. A plugin bundles skills, hooks, subagents, and MCP servers into a single installable unit. Plugin skills are namespaced (like `/my-plugin:review`) so multiple plugins can coexist. Use plugins when you want to reuse the same setup across multiple repositories or distribute to others via a **[marketplace](</docs/en/plugins/overview>)**. -### - -​ - -Build your setup over time +### Build your setup over time You don’t need to configure everything up front. Each feature has a recognizable trigger, and most teams add them in roughly this order: @@ -70,11 +58,7 @@ The same triggers tell you when to update what you already have. A repeated mistake or a recurring review comment is a CLAUDE.md edit, not a one-off correction in chat. A workflow you keep tweaking by hand is a skill that needs another revision. -### - -​ - -Compare similar features +### Compare similar features Some features can seem similar. For a deeper walkthrough of choosing between them, see [Steering Claude Code: when to use CLAUDE.md, skills, hooks, and subagents](<https://claude.com/blog/steering-claude-code-skills-hooks-rules-subagents-and-more>) on the blog. Here’s how to tell them apart. @@ -166,11 +150,7 @@ **Use a hook** when the action must happen the same way every time and doesn’t need Claude to think. For example: format on save, reject `rm -rf /`, post a Slack message when a session ends.**Use a skill** when Claude should decide how to apply the steps, or when the content is knowledge rather than a script. For example: a `/release` checklist, your API style guide, a debugging playbook.**Put guardrails in hooks.** An instruction like “never edit `.env`” in CLAUDE.md or a skill is a request, not a guarantee. A `PreToolUse` hook that blocks the edit is enforcement. If a rule must hold every time, make it a hook rather than a prompt instruction.**Hook output lands in context.** A `PostToolUse` hook that runs your linter feeds results back as text Claude reads; a `/fix-lint` skill tells Claude how to resolve them. -### - -​ - -Understand how features layer +### Understand how features layer Features can be defined at multiple levels: user-wide, per-project, via plugins, or through managed policies. You can also nest CLAUDE.md files in subdirectories or place skills in specific packages of a monorepo. When the same feature exists at multiple levels, here’s how they layer: @@ -179,11 +159,7 @@ * **MCP servers** override by name: local > project > user. See [MCP scope](</docs/en/mcp#scope-hierarchy-and-precedence>). * **Hooks** merge: all registered hooks fire for their matching events regardless of source. See [hooks](</docs/en/hooks>). -### - -​ - -Combine features +### Combine features Each extension solves a different problem: CLAUDE.md handles always-on context, skills handle on-demand knowledge and workflows, MCP handles external connections, subagents handle isolation, and hooks handle automation. Real setups combine them based on your workflow. For example, you might use CLAUDE.md for project conventions, a skill for your deployment workflow, MCP to connect to your database, and a hook to run linting after every edit. Each feature handles what it’s best at. @@ -194,19 +170,11 @@ **CLAUDE.md + Skills**| CLAUDE.md holds always-on rules; skills hold reference material loaded on demand| CLAUDE.md says “follow our API conventions,” a skill contains the full API style guide **Hook + MCP**| A hook triggers external actions through MCP| Post-edit hook sends a Slack notification when Claude modifies critical files -## - -​ - -Understand context costs +## Understand context costs Every feature you add consumes some of Claude’s context. Too much can fill up your context window, but it can also add noise that makes Claude less effective; skills may not trigger correctly, or Claude may lose track of your conventions. Understanding these trade-offs helps you build an effective setup. For an interactive view of how these features combine in a running session, see [Explore the context window](</docs/en/context-window>). -### - -​ - -Context cost by feature +### Context cost by feature Each feature has a different loading strategy and context cost: @@ -222,11 +190,7 @@ *Set [`disable-model-invocation: true`](</docs/en/skills#control-who-invokes-a-skill>) in a skill’s frontmatter to keep its description out of Claude’s context. For a skill you didn’t write, set [`skillOverrides`](</docs/en/skills#override-skill-visibility-from-settings>) in settings to do the same without editing its file. -### - -​ - -Understand how features load +### Understand how features load Each feature loads at different points in your session. The tabs below explain when each one loads and what goes into context. @@ -273,11 +237,7 @@ Hooks are ideal for side effects (linting, logging) that don’t need to affect Claude’s context. -## - -​ - -Learn more +## Learn more Each feature has its own guide with setup instructions, examples, and configuration options.
modified Rewind file changes with checkpointing View current →
Show diff (166 lines)
--- a/file-checkpointing.md +++ b/file-checkpointing.md @@ -2,11 +2,7 @@ `rewindFiles()` doesn’t undo what `sed -i` or another Bash command did to a file, unless a tool such as Write or Edit had modified that file in the main conversation. [Subagent](</docs/en/agent-sdk/subagents>) edits aren’t tracked, while edits from a [skill with `context: fork`](</docs/en/skills#run-skills-in-a-subagent>) running in the foreground are. -## - -​ - -How checkpointing works +## How checkpointing works When you enable file checkpointing, the SDK creates backups of files before modifying them through the Write, Edit, or NotebookEdit tools. User messages in the response stream include a checkpoint UUID that you can use as a restore point. @@ -14,11 +10,7 @@ When you rewind to a checkpoint, Claude Code deletes the files it created and restores the files it modified to their content at that point. Claude Code skips a tracked path that is a symlink, hard link, or other non-regular file. It also skips a tracked file whose parent directory no longer resolves to its checkpoint-time location, or whose backup it can’t read safely. [`RewindFilesResult`](</docs/en/agent-sdk/typescript#rewindfilesresult>) counts every skipped path in its `skippedLinks` field. Skipping requires Claude Code v2.1.216 or later; before v2.1.216, a rewind wrote and deleted through links at tracked paths. -## - -​ - -Implement checkpointing +## Implement checkpointing To use file checkpointing, enable it in your options, capture checkpoint UUIDs from the response stream, then call `rewindFiles()` (TypeScript) or `rewind_files()` (Python) when you need to restore. The examples in this section use the prompt “Refactor the authentication module”. Run them in a project that contains an authentication module, or change the prompt to name files that exist in your project, so you can watch files change and see the rewind restore them. This example enables checkpointing, captures the checkpoint UUID and session ID from the response stream, then resumes the session later to rewind files. The example’s numbered comments match the steps that follow. @@ -153,19 +145,11 @@ The `--rewind-files` flag doesn’t appear in `claude --help` output, but the CLI accepts it as shown. When the rewind succeeds, the command prints `Files rewound to state at message <checkpoint-uuid>` and exits without sending a prompt. -## - -​ - -Common patterns +## Common patterns These patterns show different ways to capture and use checkpoint UUIDs depending on your use case. -### - -​ - -Checkpoint before risky operations +### Checkpoint before risky operations This pattern keeps only the most recent checkpoint UUID, updating it before each agent turn. If something goes wrong during processing, you can immediately rewind to the last safe state and break out of the loop. Before running this example, replace `your_revert_condition` (Python) or `yourRevertCondition` (TypeScript) with your own check, such as error detection or a validation failure; the placeholder is not defined in the example. @@ -236,11 +220,7 @@ main(); -### - -​ - -Multiple restore points +### Multiple restore points If Claude makes changes across multiple turns, you might want to rewind to a specific point rather than all the way back. For example, if Claude refactors a file in turn one and adds tests in turn two, you might want to keep the refactor but undo the tests. This pattern stores all checkpoint UUIDs in an array with metadata. After the session completes, you can rewind to any previous checkpoint: @@ -367,11 +347,7 @@ main(); -## - -​ - -Try it out +## Try it out This complete example creates a small utility file, has the agent add documentation comments, shows you the changes, then asks if you want to rewind. Before you begin, make sure you have the [Claude Agent SDK installed](</docs/en/agent-sdk/quickstart>). @@ -585,11 +561,7 @@ You’ll see the agent add doc comments, then a prompt asking if you want to rewind. If you choose yes, the file is restored to its original state. -## - -​ - -Limitations +## Limitations File checkpointing has the following limitations: @@ -601,36 +573,20 @@ File content only| Creating, moving, or deleting directories is not undone by rewinding Local files| Remote or network files are not tracked -## - -​ - -Troubleshooting - -### - -​ - -Checkpointing options not recognized +## Troubleshooting + +### Checkpointing options not recognized If `enableFileCheckpointing` or `rewindFiles()` isn’t available, you may be on an older SDK version. **Solution** : Update to the latest SDK version: * **Python** : `pip install --upgrade claude-agent-sdk` * **TypeScript** : `npm install @anthropic-ai/claude-agent-sdk@latest` -### - -​ - -User messages don’t have UUIDs +### User messages don’t have UUIDs If `message.uuid` is `undefined` or missing, you’re not receiving checkpoint UUIDs. **Cause** : The `replay-user-messages` option isn’t set. **Solution** : Add `extra_args={"replay-user-messages": None}` (Python) or `extraArgs: { 'replay-user-messages': null }` (TypeScript) to your options. -### - -​ - -”No file checkpoint found for this message” error +### ”No file checkpoint found for this message” error This error occurs when the checkpoint data doesn’t exist for the specified user message UUID. **Common causes** : @@ -639,11 +595,7 @@ **Solution** : Ensure `enable_file_checkpointing=True` (Python) or `enableFileCheckpointing: true` (TypeScript) was set on the original session, then use the pattern shown in the examples: capture the first user message UUID, complete the session fully, then resume with an empty prompt and call `rewindFiles()` once. -### - -​ - -”File rewinding is not enabled” error +### ”File rewinding is not enabled” error This error occurs when you attempt a non-interactive rewind without checkpointing enabled: running bare `claude -p` with `--rewind-files`, or running an SDK session, including a resumed one, whose options don’t enable checkpointing. The SDK sets the `CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING` environment variable internally only when `enable_file_checkpointing` (Python) or `enableFileCheckpointing` (TypeScript) is enabled on the session performing the rewind; the bare CLI never sets it. **Solution** : For the bare CLI, set the environment variable when running the command: @@ -651,19 +603,11 @@ For the SDK, set `enable_file_checkpointing=True` (Python) or `enableFileCheckpointing: true` (TypeScript) on the resumed session, as the examples on this page do. -### - -​ - -”ProcessTransport is not ready for writing” error +### ”ProcessTransport is not ready for writing” error This error occurs when you call `rewindFiles()` or `rewind_files()` after you’ve finished iterating through the response. The connection to the CLI process closes when the loop completes. **Solution** : Resume the session with an empty prompt, then call rewind on the new query. The lead example under Implement checkpointing shows the resume-and-rewind call in both languages, at the comment marked Step 3. -## - -​ - -Next steps +## Next steps * **[Sessions](</docs/en/agent-sdk/sessions>)** : learn how to resume sessions, which is required for rewinding after the stream completes. Covers session IDs, resuming conversations, and session forking. * **[Permissions](</docs/en/agent-sdk/permissions>)** : configure which tools Claude can use and how file modifications are approved. Useful if you want more control over when edits happen.
modified Fullscreen rendering View current →
Show diff (213 lines)
--- a/fullscreen.md +++ b/fullscreen.md @@ -4,11 +4,7 @@ The term fullscreen describes how Claude Code takes over the terminal’s drawing surface, the way `vim` does. It has nothing to do with maximizing your terminal window, and works at any window size. -## - -​ - -Enable fullscreen rendering +## Enable fullscreen rendering Run `/tui fullscreen` inside any Claude Code conversation. The CLI saves the [`tui` setting](</docs/en/settings-reference#tui>) and relaunches into fullscreen with your conversation intact, so you can switch mid-session without losing context. Run `/tui default` to switch back to the classic renderer, or `/tui` with no argument to print which renderer is active. In [screen reader mode](</docs/en/accessibility>), Claude Code always uses the classic renderer except in attached [background sessions](</docs/en/agent-view>), which still render fullscreen. If you run `/tui fullscreen` in any other session, Claude Code prints an explanation instead of switching and doesn’t change the saved `tui` setting. Claude Code carries these into the relaunched session: @@ -31,11 +27,7 @@ For how the [`tui`](</docs/en/settings-reference#tui>) setting and the variable combine when both are set, see the setting’s entry. After a failed fullscreen start, Claude Code still honors the variable but not the setting. The `/tui` command clears `CLAUDE_CODE_NO_FLICKER` from the relaunched process so the setting it writes takes effect. -### - -​ - -Fullscreen by default +### Fullscreen by default Attached [background sessions](</docs/en/agent-view>) render fullscreen, and other sessions in [screen reader mode](</docs/en/accessibility>) use the classic renderer. Otherwise, Claude Code starts you in the renderer from the first row of this table that matches your setup: @@ -57,11 +49,7 @@ * If you choose **Not now** , Claude Code doesn’t offer again on this machine. * Claude Code stops offering after it has shown the dialog on three launches, answered or not. -## - -​ - -What changes +## What changes Fullscreen rendering changes how the CLI draws to your terminal. The input box stays fixed at the bottom of the screen instead of moving as output streams in. If the input doesn’t move while Claude is working, fullscreen rendering is active. Only visible messages are kept in the render tree, so memory stays constant regardless of conversation length. Because the conversation lives in the alternate screen buffer instead of your terminal’s scrollback, a few things work differently: @@ -73,11 +61,7 @@ If mouse capture interferes with your workflow, you can turn it off while keeping the flicker-free rendering. -## - -​ - -Use the mouse +## Use the mouse Fullscreen rendering captures mouse events and handles them inside Claude Code: @@ -110,11 +94,7 @@ In transcript mode, the navigation keys listed there also keep the selection. -## - -​ - -Scroll the conversation +## Scroll the conversation Fullscreen rendering handles scrolling inside the app. Use these shortcuts to navigate: @@ -133,19 +113,11 @@ These actions are rebindable. See [Scroll actions](</docs/en/keybindings#scroll-actions>) for the full list of action names, including half-page and full-page variants that have no default binding. While you’re scrolled up, a dim header row at the top of the conversation shows the most recent prompt that has scrolled above the view. Click the row to jump to that prompt. -### - -​ - -Auto-follow +### Auto-follow Scrolling up pauses auto-follow so new output doesn’t pull you back to the bottom. A `Jump to bottom` button floats over the bottom edge of the transcript while you’re scrolled up, and shows a count such as `3 new messages` when new output arrives. Click it, press `Ctrl+End`, or scroll to the bottom to resume following. While auto-follow is paused, the view also stays where you scrolled it when a response finishes streaming. The button’s keyboard hint reflects what your keyboard can send. On macOS it suggests clicking, or `Fn+↓` to scroll, because `Ctrl+End` doesn’t reach Claude Code from a Mac keyboard. Rebind [`scroll:bottom`](</docs/en/keybindings#scroll-actions>) and the button shows your chord on every platform. On a terminal too narrow for the full label, the button shortens the hint instead of wrapping onto the transcript row underneath. To turn auto-follow off entirely so the view stays where you leave it, open `/config` and set Auto-scroll to off. With auto-scroll disabled, the view never jumps to the bottom on its own. Permission prompts and other dialogs that need a response still scroll into view regardless of this setting. -### - -​ - -Mouse wheel scrolling +### Mouse wheel scrolling Mouse wheel scrolling requires your terminal to forward mouse events to Claude Code. Most terminals do this whenever an application requests it. iTerm2 makes it a per-profile setting: if the wheel does nothing but `PgUp` and `PgDn` work, open Settings → Profiles → Terminal and turn on Enable mouse reporting. The same setting is also required for click-to-expand and text selection to work. If mouse wheel scrolling feels slow, your terminal may be sending one scroll event per physical notch with no multiplier. Some terminals, like Ghostty and iTerm2 with faster scrolling enabled, already amplify wheel events. Others, including the VS Code integrated terminal, send exactly one event per notch. Claude Code can’t detect which. Set `CLAUDE_CODE_SCROLL_SPEED` to multiply the base scroll distance: @@ -153,19 +125,11 @@ A value of `3` matches the default in `vim` and similar applications. The setting accepts any positive value up to 20, including fractional values below 1 such as `0.25` to slow accelerated trackpad and wheel scrolling in terminals that already amplify wheel events. To adjust scroll speed interactively, run `/scroll-speed`. Scroll while the dialog is open to feel the change immediately. Press `←` and `→` to adjust the speed, `r` to reset to the auto-detected default, and `Enter` to save. The dialog steps in whole numbers up to 10, and on terminals that support finer control it also offers quarter steps down to 0.25. The command writes the same value the `CLAUDE_CODE_SCROLL_SPEED` environment variable sets, persisted to `~/.claude/settings.json`. The dialog’s maximum is 10: if you set a higher value through the environment variable, the dialog shows 10, and saving from the dialog persists 10. The command isn’t available in the JetBrains IDE terminal. Separately from the base speed, Claude Code accelerates the scroll rate when you spin the wheel quickly, so a fast spin covers more distance than the same number of slow notches. To turn acceleration off and keep a constant rate per notch, set `wheelScrollAccelerationEnabled` to `false` in [`settings.json`](</docs/en/settings-reference#all-settings>). This setting requires Claude Code v2.1.174 or later. -### - -​ - -Scroll in the JetBrains IDE terminal +### Scroll in the JetBrains IDE terminal In the JetBrains IDE terminal, Claude Code applies its own scroll handling and ignores `CLAUDE_CODE_SCROLL_SPEED`. The terminal sends scroll events at a much higher rate than other emulators, so a multiplier tuned elsewhere overshoots here. In 2025.2, the terminal also has scroll-wheel bugs that produce spurious arrow keys and wrong-direction events. Claude Code detects these at runtime and mitigates them automatically, so trackpad and mouse wheel scrolling work without configuration. For the best scroll experience, upgrade to 2025.3 or later. Claude Code shows a hint the first time you scroll if it detects the bug. -## - -​ - -Search and review the conversation +## Search and review the conversation `Ctrl+o` toggles between the normal prompt and transcript mode. For a quieter view that shows only your last prompt, a one-line summary of tool calls with edit diffstats, and the final response, run `/focus`. The setting persists across sessions. Run `/focus` again to turn it off. Transcript mode gains `less`-style navigation and search: @@ -185,27 +149,15 @@ * **`[`** : writes the full conversation into your terminal’s native scrollback buffer, with all tool output expanded. The conversation is now ordinary text in your terminal, so `Cmd+f`, tmux copy mode, and any other native tool can search or select it. Long sessions may pause for a moment while this happens. This lasts until you exit transcript mode with `Esc` or `q`, which returns you to fullscreen rendering. The next `Ctrl+o` starts fresh. * **`v`** : writes the conversation to a temporary file and opens it in `$VISUAL` or `$EDITOR`. -## - -​ - -Watch your changes in the diff panel +## Watch your changes in the diff panel In fullscreen rendering, [`/diff`](</docs/en/interactive-mode#review-changes-with-%2Fdiff>) opens a panel beside the conversation, so you can watch the changes accumulate while Claude works. [Diff panel](</docs/en/interactive-mode#diff-panel>) covers what it shows, when it opens on its own, how to keep it closed, and how to change what it compares against. -## - -​ - -Clear the conversation +## Clear the conversation Run `/clear` to start a new conversation. If the display looks garbled or partially blank, press `Ctrl+L` to redraw the screen. The redraw keeps the conversation and your input in place. `Cmd+K` does the same as `Ctrl+L` when your terminal passes it through to Claude Code. iTerm2 and Terminal.app handle `Cmd+K` themselves and clear their own screen, and Claude Code detects the cleared screen and repaints the conversation. Before v2.1.280, starting with v2.1.260, pressing `Ctrl+L`, or `Cmd+K` where it reaches Claude Code, cleared the screen in fullscreen rendering. Before v2.1.238, pressing `Ctrl+L` twice within two seconds ran `/clear`. -## - -​ - -Use with tmux +## Use with tmux Fullscreen rendering works inside tmux, with three caveats. Mouse wheel scrolling requires tmux’s mouse mode. If your `~/.tmux.conf` doesn’t already enable it, add this line and reload your config: @@ -213,11 +165,7 @@ Without mouse mode, wheel events go to tmux instead of Claude Code. Keyboard scrolling with `PgUp` and `PgDn` works either way. Claude Code prints a one-time hint at startup if it detects tmux with mouse mode off. Fullscreen rendering is incompatible with iTerm2’s tmux integration mode, which is the mode you enter with `tmux -CC`. In integration mode, iTerm2 renders each tmux pane as a native split rather than letting tmux draw to the terminal. The alternate screen buffer and mouse tracking don’t work correctly there: the mouse wheel does nothing, and double-click can corrupt the terminal state. Don’t enable fullscreen rendering in `tmux -CC` sessions. Regular tmux inside iTerm2, without `-CC`, works fine. tmux releases through the 3.6 series don’t implement synchronized output, so under those versions you may see more flicker during redraws than when running Claude Code directly in your terminal. Claude Code probes the terminal for synchronized-output support at startup and uses it when the terminal reports it. If you see flicker under tmux, upgrade to the newest tmux or run Claude Code in its own terminal tab outside tmux. -## - -​ - -Keep native text selection +## Keep native text selection Mouse capture is the most common friction point, especially over SSH or inside tmux. When Claude Code captures mouse events, your terminal’s native copy-on-select stops working. The selection you make with click-and-drag exists inside Claude Code, not in your terminal’s selection buffer, so tmux copy mode, Kitty hints, and similar tools don’t see it. Claude Code writes the selection to your system clipboard, and the path it uses depends on your setup. On a local session it runs a native clipboard tool: @@ -238,17 +186,9 @@ With mouse capture disabled, keyboard scrolling with `PgUp`, `PgDn`, `Ctrl+Home`, and `Ctrl+End` still works, and your terminal handles selection natively. You lose click-to-position-cursor, click-to-expand, URL clicking, and wheel scrolling inside Claude Code. To keep wheel scrolling but turn off click, drag, and hover handling, set `CLAUDE_CODE_DISABLE_MOUSE_CLICKS=1` instead. `CLAUDE_CODE_DISABLE_MOUSE` takes precedence when both variables are set. With clicks disabled, Claude Code still captures the mouse, so the wheel and touchpad scroll the conversation but left clicks do nothing inside Claude Code. You still need to hold your terminal’s key for native click-and-drag selection. Right-click and middle-click paste continue to work on terminals that support them. -## - -​ - -Troubleshooting - -### - -​ - -Stale or misplaced text on screen +## Troubleshooting + +### Stale or misplaced text on screen Fullscreen rendering sends only the cells that changed between frames. Some terminals, most commonly Windows Terminal and other ConPTY-backed hosts, coalesce these positioned writes incorrectly and leave fragments of earlier output on screen until you resize the window. Set [`CLAUDE_CODE_ALT_SCREEN_FULL_REPAINT=1`](</docs/en/env-vars>) to repaint every cell on every frame instead of sending incremental updates. On Windows PowerShell: @@ -261,11 +201,7 @@ On Windows, Claude Code already enables full repaint automatically for background sessions and [agent view](</docs/en/agent-view>), so you only need to set the variable for an interactive fullscreen session you launched directly. -### - -​ - -`Claude Code's fullscreen renderer didn't finish starting last time` appears at startup +### `Claude Code's fullscreen renderer didn't finish starting last time` appears at startup If a fullscreen session on this machine crashes before it has started successfully, Claude Code starts your next session in the classic renderer and prints one of two lines. A session has started successfully once it has drawn its first frame and then either stayed up for 10 seconds or you ended it with `/exit`, Ctrl+C, or Ctrl+D. The line you see tells you what Claude Code does after this session: @@ -274,21 +210,13 @@ To confirm that a failed start is why you’re in the classic renderer, run `/tui` with no argument. While a failed start is the reason, the `Current renderer` line says so. To keep the classic renderer, run `/tui default`, which saves the `tui` setting without relaunching. To try fullscreen rendering again, run `/tui fullscreen`. If that session doesn’t finish starting either, report the problem. Before v2.1.236, Claude Code kept starting sessions in fullscreen rendering after a failed start. -#### - -​ - -How Claude Code counts failed starts +#### How Claude Code counts failed starts * Sessions that count: only sessions that started in fullscreen rendering because your `tui` setting says so, because you accepted the startup dialog, or because Claude Code starts you in fullscreen by default * `CLAUDE_CODE_NO_FLICKER=1`: if you set it, Claude Code renders that session fullscreen even after a failed start, and doesn’t count it * Count reset: Claude Code counts failed starts per Claude Code version, and a successful fullscreen start resets the count * Startup dialog: if you accepted the dialog and the relaunched session crashed, Claude Code prints neither line and doesn’t show the dialog again on this Claude Code version -## - -​ - -Research preview +## Research preview Fullscreen rendering is a research preview feature. It has been tested on common terminal emulators, but you may encounter rendering issues on less common terminals or unusual configurations. If you encounter a problem, run `/feedback` inside Claude Code to report it, or open an issue on the [claude-code GitHub repo](<https://github.com/anthropics/claude-code/issues>). Include your terminal emulator name and version. To turn fullscreen rendering off, run `/tui default`, or unset `CLAUDE_CODE_NO_FLICKER` if you enabled it that way. When you switch back with `/tui default`, Claude Code may first show an optional feedback prompt asking what made you switch. Type a reason and press `Enter` to send it, or press `Esc` to skip. The CLI relaunches into the classic renderer either way. To force the classic renderer regardless of the saved `tui` setting, set `CLAUDE_CODE_DISABLE_ALTERNATE_SCREEN=1`. The classic renderer keeps the conversation in your terminal’s native scrollback so `Cmd+f` and tmux copy mode work as usual. Background sessions opened from [agent view](</docs/en/agent-view>) or `claude attach` always use fullscreen rendering. The attaching terminal enters the alternate screen buffer to show the session, and the classic renderer has no scrollback or mouse handling there, so the `tui` setting and `CLAUDE_CODE_DISABLE_ALTERNATE_SCREEN` don’t apply to them.
modified Interface gallery for mods View current →
Show diff (265 lines)
--- a/gallery.md +++ b/gallery.md @@ -1,10 +1,6 @@ A mod draws its interface from elements: text, boxes, buttons, fields, and a few that format content for you. The samples here show the code that draws an element, and most come with a screenshot of the result in a terminal pane, so you can pick an element by how it looks. To learn how drawing works, start with [Draw in the interface](</docs/en/plugins/mods/interface>). For the main props and which apps draw each element, see the [elements reference](</docs/en/plugins/mods/reference#elements>). The [type declarations](</docs/en/plugins/mods/create#get-the-types-for-your-build>) list every prop. -## - -​ - -Try a sample +## Try a sample The samples on this page are snippets, not whole mods. Each one is the code for one element and anything nested inside it. To see a sample in your own terminal, create the small mod in these steps and paste the sample into it. The mod adds a `/gallery` command that opens a pane and draws the sample there. A [pane](</docs/en/plugins/mods/interface#pick-where-to-draw>) is a sidebar beside the transcript in a wide fullscreen terminal, or a framed region above the prompt otherwise. @@ -82,11 +78,7 @@ Copy a sample from this page. In `register.js`, paste it over `Text({ children: ['Plain text'] })`, so that it follows `return`, and save the file. Claude Code reloads the module each time you save, so run `/gallery` again to see the new sample. -## - -​ - -Pick an element +## Pick an element The samples are grouped by what you want to put on screen: @@ -96,19 +88,11 @@ * **Take input** : `Button`, `Input`, and `Select` * **Draw pictures** : `Raster`, `Svg`, `Image`, and `Client` -## - -​ - -Show text +## Show text Three elements put words on screen: `Text` for your own styling, `Markdown` for content that’s already formatted, and `Link` for a URL. -### - -​ - -`Text` +### `Text` `Text` draws a string with the styles you give it. This sample shows plain text and eight styles, one on each line: @@ -129,11 +113,7 @@ `dimColor` draws the text in gray. `backgroundColor` fills only as wide as the text. -### - -​ - -`Markdown` +### `Markdown` `Markdown` formats text the way Claude’s replies are formatted. Pass the content in `text`, not in `children`: @@ -143,11 +123,7 @@ A heading draws in bold without its `#` marks. Inline code draws in color without its backticks. A quote draws in italics with a bar on its left. -### - -​ - -`Link` +### `Link` `Link` draws a label followed by its URL: @@ -155,19 +131,11 @@ The terminal draws the URL as text after the label. Whether a click opens it depends on the user’s terminal. -## - -​ - -Show code and changes +## Show code and changes `Code` draws source text with Claude Code’s own syntax colors, or a diff. In the VS Code extension, `Code` shows its `source` as plain text, with none of the colors, line numbers, or diff shading in these screenshots. -### - -​ - -`Code` +### `Code` Name the `language`, or pass a `path` for Claude Code to infer it from. With `startLine`, the lines are numbered from that number: @@ -179,11 +147,7 @@ The colors come from the user’s theme. -### - -​ - -`Code` as a diff +### `Code` as a diff With `format: 'diff'`, `source` is one or more unified diff hunks: @@ -194,17 +158,9 @@ Claude Code draws line numbers in place of the `@@` line. Where a removed line and an added line are alike, the words that changed get a stronger shade. -## - -​ - -Arrange elements - -### - -​ - -`Box` +## Arrange elements + +### `Box` `Box` lays out what’s inside it in a row or a column, and can draw a border. This sample puts a row of words above a bordered box: @@ -227,19 +183,11 @@ The border stretches to the width of the pane. -## - -​ - -Take input +## Take input `Button`, `Input`, and `Select` are controls: the user moves between them with Tab and uses the one that has the focus. [Keyboard focus and hotkeys](</docs/en/plugins/mods/interface#know-which-keys-your-mod-can-receive>) covers which keys reach them. Open a pane with `focus: true` to request keyboard focus for it. Typed letters reach an `Input` once it has the focus. To choose which field has the focus when the pane opens, see [Set a hotkey and the first focus](</docs/en/plugins/mods/interface#set-a-hotkey-and-the-first-focus>). -### - -​ - -`Button` +### `Button` A button runs `onPress`. This sample shows the default form, a `plain` button with a hotkey, and a dim one: @@ -254,11 +202,7 @@ A button that has the focus draws in inverse video. Here the user has pressed Tab twice: -### - -​ - -`Input` +### `Input` An `Input` is a text field that holds one line by default and runs `onSubmit` when the user presses Enter: @@ -287,11 +231,7 @@ * In the terminal, Up and Down move between the field’s rows. From its first and last row they move to the control before or after. * `onSubmit` and `onInput` receive the whole text with its lines joined by `\n`. -### - -​ - -`Select` +### `Select` A `Select` lets the user pick one of several options, and runs `onSelect` with the option’s `value`: @@ -311,17 +251,9 @@ Closed, it shows its label and the current option: Open, it lists its options and marks one: After the user picks an option, the list closes: -## - -​ - -Draw pictures - -### - -​ - -`Raster` +## Draw pictures + +### `Raster` A `Raster` is a grid of colored character cells, for a heat map, a sparkline, or a game board. The terminal draws it. This sample uses the `cellsOf` function in the starter module, which packs the cells into the string a `Raster` takes. [Draw a grid of colored cells](</docs/en/plugins/mods/interface#draw-a-grid-of-colored-cells>) explains it: @@ -337,11 +269,7 @@ A `Raster` rounds each color to a smaller palette, so `0x2e7d32` draws as `#337733`. -### - -​ - -`Svg` +### `Svg` An `Svg` draws an SVG document in the Desktop app and the VS Code extension: @@ -355,11 +283,7 @@ In the terminal, a pane that returns only an `Svg` opens empty. To draw something else there, check [`e.surface`](</docs/en/plugins/mods/interface#pick-where-to-draw>) and return a different tree. -### - -​ - -`Image` and `Client` +### `Image` and `Client` Two more elements have no sample here. `Image` draws a PNG or raw pixels in the terminal. `Client` is a region that a second file of yours draws, for animation and pointer input. The [elements reference](</docs/en/plugins/mods/reference#elements>) lists their props. An `Image` draws as a picture in these terminals: @@ -377,11 +301,7 @@ If your mod’s users see the dimmed text in a terminal that draws kitty graphics protocol images with Unicode placeholders, they can set [`CLAUDE_CODE_FORCE_TERMINAL_IMAGES`](</docs/en/env-vars>) to `1`. They shouldn’t set it inside GNU screen, inside tmux older than 3.3, in a tmux popup, or with tmux’s `allow-passthrough` off. There they see no picture and a box in place of the `alt` text. -#### - -​ - -Draw an `Image` inside tmux +#### Draw an `Image` inside tmux If an `Image` shows its `alt` text inside tmux, check these requirements along with the other `alt` text cases such as a background session: @@ -401,11 +321,7 @@ Then detach from tmux, attach again, and restart Claude Code. Restart it again whenever you attach tmux from a different terminal. To keep both options across tmux server restarts, [add both lines to `~/.tmux.conf`](</docs/en/terminal-config#configure-tmux>) too. -## - -​ - -See where a mod can draw +## See where a mod can draw The samples all draw in a pane. A mod can also draw in other places, and call Claude Code to show something for it: @@ -414,11 +330,7 @@ * **Toast, status line, and log line** : [Show something without starting a turn](</docs/en/plugins/mods/api#show-something-without-starting-a-turn>) * **Question dialog** : [Hold a tool call until the user decides](</docs/en/plugins/mods/events#hold-a-tool-call-until-the-user-decides>) -## - -​ - -Next steps +## Next steps * [Draw in the interface](</docs/en/plugins/mods/interface>): build a pane with tabs, step by step * [Test a drawing](</docs/en/plugins/mods/test#test-a-drawing>): press your buttons from a test
modified Run Claude Code through a gateway View current →
--- a/gateways.md +++ b/gateways.md @@ -5,11 +5,7 @@ * How gateways interact with claude.ai subscriptions * What’s configured separately from the gateway -## - -​ - -How a gateway works +## How a gateway works Each developer’s Claude Code sends its requests to the gateway’s address and authenticates with a gateway-issued credential. The gateway authenticates the developer, applies whatever access and budget rules you configure, and forwards the request to your provider with the organization’s credential. The provider can be Anthropic’s API or a [cloud provider](</docs/en/third-party-integrations>) such as Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry; the gateway’s configuration decides. With Claude apps gateway, or another gateway that exposes a single Anthropic-format endpoint, changing provider doesn’t require touching developer machines. @@ -18,43 +14,23 @@ * **Developer credential** : each developer holds their own, issued by the gateway. It authenticates them to the gateway and identifies them in usage tracking * **Provider credential** : the gateway holds one credential for your provider account, shared by all forwarded traffic -## - -​ - -Choose a gateway +## Choose a gateway Claude Code works with Anthropic’s own gateway or with a gateway your organization already runs. -### - -​ - -Claude apps gateway +### Claude apps gateway Claude apps gateway is Anthropic’s self-hosted gateway, included in the `claude` binary. It routes to Amazon Bedrock, Claude Platform on AWS, Google Cloud, Microsoft Foundry, or the Anthropic API as the upstream. Developers sign in with your corporate identity provider through `/login`, the gateway enforces model access and [managed settings](</docs/en/managed-settings>) by IdP group, and it emits [OpenTelemetry Protocol (OTLP)](</docs/en/monitoring-usage>) usage metrics to your own observability stack. Because it is built and tested alongside each Claude Code release, it forwards the `anthropic-beta` values and request fields Claude Code sends. A gateway maintained separately needs its [forwarding rules updated](</docs/en/llm-gateway-protocol#forward-as-open-lists>) as those change with each release; Claude apps gateway releases with the CLI, so there is no list to keep current. See [Availability and limitations](</docs/en/claude-apps-gateway#availability-and-limitations>) for the small set of features that behave differently on a gateway session. The gateway sign-in is a browser SSO step, and there is no service-token flow, so a CI pipeline with no developer to approve the sign-in can’t authenticate through it; configure those against your provider directly. Agent SDK sessions and `claude -p` runs on a machine where a developer has signed in use that machine’s gateway session and are governed by its policies. See [CI pipelines and remote machines](</docs/en/claude-apps-gateway#ci-pipelines-and-remote-machines>). See [Claude apps gateway](</docs/en/claude-apps-gateway>) to deploy it. -### - -​ - -Other gateways +### Other gateways If your organization already runs an LLM gateway or API gateway, you can use it instead. Anthropic doesn’t endorse, maintain, or audit other gateway products, and doesn’t support routing Claude Code to non-Claude models through any gateway. See [Other LLM gateways](</docs/en/llm-gateway>) for the admin rollout checklist, what a gateway must implement, and how to point Claude Code at it. -## - -​ - -Subscriptions and gateways +## Subscriptions and gateways When developers connect through a gateway with a gateway credential, usage is billed to your organization’s provider account at API rates, and their claude.ai subscriptions aren’t used or charged. Every request forwarded under that credential is charged to the account behind the gateway’s provider credential. The exception is setting only `ANTHROPIC_BASE_URL`, with no gateway credential. Requests still route through the gateway, but a saved claude.ai login stays the active credential, so the subscription’s usage limits and billing apply. [Other LLM gateways](</docs/en/llm-gateway#subscriptions-and-gateways>) covers that configuration and what the gateway has to forward for it to work. -## - -​ - -Configure separately from the gateway +## Configure separately from the gateway A gateway routes model API requests. A few things you might expect it to handle are configured elsewhere: @@ -63,13 +39,9 @@ * **Client telemetry** : Claude Code disables its Anthropic-bound client analytics when a session signs in to a Claude apps gateway. To keep pre-sign-in startup analytics off as well, deliver [`DISABLE_TELEMETRY`](</docs/en/managed-settings#turn-telemetry-off-for-your-organization>) in the [client-side managed settings](</docs/en/claude-apps-gateway-config#client-side-managed-settings>) on each device. * **Client telemetry on other gateways** : whether Claude Code sends the optional client telemetry stream depends on your provider, and the [telemetry defaults table](</docs/en/data-usage#default-behaviors-by-api-provider>) covers each case. * **Telemetry destinations** : where Claude Code sends a gateway session’s telemetry depends on how the session signed in, and [What’s enforced on developers](</docs/en/claude-apps-gateway#whats-enforced-on-developers>) says where each kind of session’s exports go. - * **Corporate HTTP proxies** : an `HTTPS_PROXY` sits between Claude Code and every server it talks to, including the gateway. If your network requires one, [configure the proxy](</docs/en/network-config>) in addition to the gateway. For a Claude apps gateway you host, [sign-in checks that the proxy host is also on a private network](</docs/en/claude-apps-gateway#prerequisites>); if it isn’t, add the gateway host to `NO_PROXY` so the CLI connects to it directly. + * **Corporate HTTP proxies** : Claude Code sends its requests, including those to the gateway, through the proxy in `HTTPS_PROXY`. If your network requires a proxy, [configure it](</docs/en/network-config>). If the proxy applies to a Claude apps gateway you host, [sign-in](</docs/en/claude-apps-gateway#prerequisites>) needs the proxy’s hostname to resolve to private addresses, or the gateway host in `NO_PROXY`. -## - -​ - -Next steps +## Next steps The next page depends on who runs the gateway. Anthropic’s gateway runs from the `claude` binary and has its own setup guide; a gateway your organization already runs has a compatibility guide to follow and an admin rollout checklist.
modified Claude Code GitHub Actions View current →
Show diff (309 lines)
--- a/github-actions.md +++ b/github-actions.md @@ -5,11 +5,7 @@ * [Claude Agent SDK](</docs/en/agent-sdk/overview>): custom automation outside GitHub Actions. The Claude Code GitHub Action is built on the SDK * [GitHub Enterprise Server](</docs/en/github-enterprise-server>): Claude Code with self-hosted GitHub -## - -​ - -Setup +## Setup You can set up the Claude Code GitHub Action in one of two ways: @@ -18,11 +14,7 @@ For either path, you need admin access to the repository. -### - -​ - -Quick setup +### Quick setup `/install-github-app` works only with github.com repositories. If your repository’s git remote is on gitlab.com or bitbucket.org, the command prints a notice and exits instead of starting setup. To run Claude Code from GitLab pipelines, see [Claude Code GitLab CI/CD](</docs/en/gitlab-ci-cd>). Before you start, install the [GitHub CLI](<https://cli.github.com>) and authenticate it with `gh auth login`. Claude Code checks for it and warns you if it’s missing. Open `claude` in the repository you want to connect, run `/install-github-app`, and follow the prompts. Claude Code installs the Claude GitHub App, then sets up an authentication secret for the workflows: @@ -39,11 +31,7 @@ * When you install the GitHub App, you grant it several permissions. See GitHub App permissions for the full set * Quick setup works with the Claude API and Claude subscriptions. If you use Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry, see [Use Claude Code GitHub Actions with cloud providers](</docs/en/github-actions-cloud-providers>) -### - -​ - -Manual setup +### Manual setup To configure the Claude Code GitHub Action without running `/install-github-app`, install the app, add a secret, and copy a workflow file yourself: @@ -78,11 +66,7 @@ After setup, test the Claude Code GitHub Action by tagging `@claude` in an issue or PR comment. -### - -​ - -Set up for an organization +### Set up for an organization With quick setup or manual setup, you configure one repository at a time. To roll the Claude Code GitHub Action out across an organization: @@ -99,11 +83,7 @@ Grant the workflow the `id-token: write` permission, which the Claude Code GitHub Action needs for the federation exchange even when you pass your own `github_token`. See the [Claude Code GitHub Action’s setup guide](<https://github.com/anthropics/claude-code-action/blob/main/docs/setup.md>) for the Console-side configuration. For data handling and retention questions in a security review, see [data usage](</docs/en/data-usage>) and [security](</docs/en/security>). -### - -​ - -Uninstall +### Uninstall To remove the Claude Code GitHub Action, undo each piece of the setup that applies to your installation: @@ -113,11 +93,7 @@ If you configured a [cloud provider](</docs/en/github-actions-cloud-providers>), also delete the provider secrets, such as `AWS_ROLE_TO_ASSUME`, the `GCP_*` secrets, or the `AZURE_*` secrets, and uninstall the custom GitHub App along with its `APP_ID` and `APP_PRIVATE_KEY` secrets. -### - -​ - -GitHub App permissions +### GitHub App permissions The [Claude GitHub App](<https://github.com/apps/claude>) is shared by every Claude feature that integrates with GitHub, including the Claude Code GitHub Action, [Code Review](</docs/en/code-review>), and [auto-fix for pull requests](</docs/en/claude-code-on-the-web#auto-fix-pull-requests>) in cloud sessions. A GitHub App has a single permission set covering all of its features, so the set includes some permissions that the Claude Code GitHub Action doesn’t use. When you install the app, you grant the following permissions: @@ -140,41 +116,25 @@ The permission set can also change ahead of the features that use it. When the app requests a permission it didn’t have before, GitHub prompts the account owner to approve it, an organization owner for an organization install, and the installation keeps its old permissions until they do. For example, when Actions access changes from read to write, the app can re-run workflows rather than only view runs and logs, so GitHub asks the owner to approve the change. When you install the app, you accept its full permission set. GitHub doesn’t let you accept a subset. If your organization requires only the permissions the Claude Code GitHub Action uses, create a custom GitHub App with Contents, Issues, and Pull requests instead, following the [Claude Code GitHub Action’s setup guide](<https://github.com/anthropics/claude-code-action/blob/main/docs/setup.md>). A custom app covers only the Claude Code GitHub Action. Code Review and web auto-fix still require the official app. For details on how the Claude Code GitHub Action limits what Claude can do with these permissions, see the [security documentation](<https://github.com/anthropics/claude-code-action/blob/main/docs/security.md>). -## - -​ - -Interactive and automation modes +## Interactive and automation modes The Claude Code GitHub Action detects how to run from your workflow configuration: * **Interactive mode** : when the workflow provides no `prompt` input, Claude waits for the trigger phrase, `@claude` by default, in an issue or pull request comment, in a pull request review, or in the body or title of a newly opened issue, then responds to that request. Progress and results appear as a comment on the triggering issue or PR. * **Automation mode** : when the workflow provides a `prompt` input, Claude runs without waiting for a mention, subject only to the checks on who can trigger runs. By default, results appear in the workflow run log rather than a comment. Claude can post to the issue or pull request when the prompt directs it to and it has a tool that can post, as in the code-review example. -### - -​ - -Who can trigger runs +### Who can trigger runs In both modes, the Claude Code GitHub Action runs two checks on the triggering actor before Claude starts, and the run fails when either check rejects it: * **Write access** : on issue and pull request events, the triggering user must have write access to the repository. To allow specific users without write access, set `allowed_non_write_users` and pass your own `github_token` input. Events that no user authors, such as a `schedule` trigger, skip this check. * **Human actor** : on every event, the Claude Code GitHub Action rejects a bot actor unless you list it in `allowed_bots`, which keeps bots from triggering Claude in a loop. This check also applies to scheduled runs, which GitHub attributes to a repository user, usually the one who last changed the workflow’s `cron` schedule. If that user is a bot, list it in `allowed_bots`. -## - -​ - -Example use cases +## Example use cases The [examples directory](<https://github.com/anthropics/claude-code-action/tree/main/examples>) contains ready-to-use workflows for different scenarios. The examples on this page show API key authentication. If you authenticate with a Claude subscription, replace the `anthropic_api_key` line in any example with `claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}`. -### - -​ - -Respond to @claude mentions +### Respond to @claude mentions This workflow runs the Claude Code GitHub Action in interactive mode, so Claude responds whenever someone mentions `@claude` in an issue or PR comment. @@ -217,11 +177,7 @@ Claude replies in a comment on the same issue or PR and updates it as it works. -### - -​ - -Run a skill +### Run a skill The `prompt` input accepts a [skill](</docs/en/skills>) invocation as well as plain text: @@ -261,11 +217,7 @@ Claude skips draft and closed pull requests, pull requests it judges not to need a review, such as automated or trivial ones, and pull requests that already have a comment from Claude. -### - -​ - -Run on a schedule +### Run on a schedule With a `prompt` input, the Claude Code GitHub Action runs in automation mode on any GitHub event, including a cron schedule. For a plain-text prompt, Claude has no shell or GitHub API access until you grant the tools the prompt needs, with `--allowedTools` in `claude_args` or a [`permissions.allow` rule](</docs/en/permissions#permission-rule-syntax>) in the `settings` input. If you invoke a skill instead, Claude can use the tools its [`allowed-tools` frontmatter](</docs/en/skills#pre-approve-tools-for-a-skill>) grants. GitHub runs scheduled workflows only from the default branch and, in public repositories, disables the schedule after 60 days without repository activity. This workflow generates a report in the workflow run log at 09:00 UTC each day. Its `claude_args` line passes CLI arguments that select the model and allow two GitHub MCP tools. Claude reads commits and issues through the GitHub API with those tools, so you can omit the checkout step: @@ -289,35 +241,19 @@ --model claude-opus-5-5 --allowedTools "mcp__github__list_commits,mcp__github__list_issues" -## - -​ - -Best practices - -### - -​ - -Define project standards in CLAUDE.md +## Best practices + +### Define project standards in CLAUDE.md Create a `CLAUDE.md` file in your repository root to define code style guidelines, review criteria, project-specific rules, and preferred patterns. Claude follows these guidelines when creating PRs and responding to requests. See the [memory documentation](</docs/en/memory>) for details. -### - -​ - -Protect your credentials +### Protect your credentials Never commit API keys or OAuth tokens directly to your repository. Always store them as GitHub Secrets and reference them in workflows, for example `anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}`. Grant the workflow only the permissions it needs, and review Claude’s changes before merging. For security guidance including permissions and authentication, see the [Claude Code Action security documentation](<https://github.com/anthropics/claude-code-action/blob/main/docs/security.md>). -### - -​ - -Manage costs +### Manage costs Each run consumes two kinds of resources: @@ -335,11 +271,7 @@ For usage tracking across your organization, see the [analytics dashboard](</docs/en/analytics>) and [monitoring](</docs/en/monitoring-usage>). For how usage is measured and billed, see [costs](</docs/en/costs>). -## - -​ - -Use a cloud provider +## Use a cloud provider By default, the Claude Code GitHub Action calls the Claude API directly with your API key or OAuth token. To route inference through your own cloud account instead, set the input for your provider and follow [Use Claude Code GitHub Actions with cloud providers](</docs/en/github-actions-cloud-providers>): @@ -349,17 +281,9 @@ With all three providers, you authenticate through OIDC identity federation instead of a Claude API key, so you store no static cloud credentials in your repository. -## - -​ - -Troubleshooting - -### - -​ - -Claude not responding to @claude commands +## Troubleshooting + +### Claude not responding to @claude commands * Verify the GitHub App is installed on the repository * Check that workflows are enabled for the repository @@ -367,37 +291,21 @@ * Confirm the comment contains `@claude` as a complete word, not `/claude` or `@claude-bot` * Confirm the commenting user has write access to the repository. See Who can trigger runs for the exceptions -### - -​ - -CI not running on Claude’s commits +### CI not running on Claude’s commits * GitHub doesn’t trigger workflows on commits made with the default `GITHUB_TOKEN`. If you pass `github_token: ${{ secrets.GITHUB_TOKEN }}` to the Claude Code GitHub Action, remove it so it authenticates as the Claude GitHub App, or pass a custom app token instead * Check that your CI workflow’s triggers include the events Claude’s pushes produce, such as `push` or `pull_request` -### - -​ - -Authentication errors +### Authentication errors * Confirm the API key or OAuth token is valid by testing it locally with `claude` before debugging the workflow * For Bedrock, Agent Platform, and Foundry, see the cloud provider page’s [troubleshooting section](</docs/en/github-actions-cloud-providers#troubleshooting>) For more solutions, see the Claude Code GitHub Action’s [FAQ](<https://github.com/anthropics/claude-code-action/blob/main/docs/faq.md>). -## - -​ - -Advanced configuration - -### - -​ - -Action parameters +## Advanced configuration + +### Action parameters These are the most commonly used inputs. Each maps to a `with:` key in the `anthropics/claude-code-action` step. @@ -418,11 +326,7 @@ For the full input list, see the Claude Code GitHub Action’s [configuration reference](<https://github.com/anthropics/claude-code-action/blob/main/docs/usage.md#inputs>). -### - -​ - -Pass CLI arguments +### Pass CLI arguments The `claude_args` parameter accepts any [Claude Code CLI argument](</docs/en/cli-reference>): @@ -436,11 +340,7 @@ * `--allowedTools`: comma-separated list of allowed tools. The `--allowed-tools` alias also works * `--debug`: enable debug output -## - -​ - -Upgrade from beta +## Upgrade from beta If your workflows still reference `anthropics/claude-code-action@beta`, update them to v1: @@ -451,11 +351,7 @@ For the full input mapping and before-and-after examples, see the [migration guide](<https://github.com/anthropics/claude-code-action/blob/main/docs/migration-guide.md>). -## - -​ - -What’s next +## What’s next * [Use Claude Code GitHub Actions with cloud providers](</docs/en/github-actions-cloud-providers>): route inference through Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry * [Configuration reference](<https://github.com/anthropics/claude-code-action/blob/main/docs/usage.md#inputs>): the full list of action inputs
modified Use Claude Code GitHub Actions with cloud providers View current →
--- a/github-actions-cloud-providers.md +++ b/github-actions-cloud-providers.md @@ -2,11 +2,7 @@ This page builds on the [GitHub Actions setup](</docs/en/github-actions#setup>). It assumes you already know the workflow file and the `anthropics/claude-code-action` step, and covers only what a cloud provider changes. -## - -​ - -Choose your provider +## Choose your provider The Claude Code GitHub Action supports three providers, and the setup steps below differ only in the cloud-side configuration. Use the one where your organization already has Claude model access. You tell the Claude Code GitHub Action which provider to use with one input in the `anthropics/claude-code-action` step’s `with:` block: @@ -16,11 +12,7 @@ The complete workflow examples under Set up the integration already include the input for each provider. -## - -​ - -Prerequisites +## Prerequisites Before you start, you need: @@ -31,11 +23,7 @@ * **Google Cloud’s Agent Platform** : a project with the Agent Platform API enabled and access to Claude models. See [Claude Code on Google Cloud’s Agent Platform](</docs/en/google-vertex-ai>) * **Microsoft Foundry** : a Foundry resource with a Claude model deployment. See [Claude Code on Microsoft Foundry](</docs/en/microsoft-foundry>) -## - -​ - -Set up the integration +## Set up the integration Beyond the prerequisites, you create a GitHub identity for the Claude Code GitHub Action, the cloud-side trust configuration, the repository secrets, and the workflow file. The steps below walk through each. @@ -88,7 +76,7 @@ Create a Microsoft Entra application with a federated credential for your repository, following [Microsoft’s guide to authenticating from GitHub Actions](<https://learn.microsoft.com/en-us/azure/developer/github/connect-from-azure-openid-connect>): * Register a Microsoft Entra application and add a federated identity credential that trusts tokens GitHub issues to your repository. A user-assigned managed identity works in place of an application. Both have the client ID you note below - * Assign the application the `Azure AI User` role on your Foundry resource. See [Azure RBAC configuration](</docs/en/microsoft-foundry#azure-rbac-configuration>) for a narrower custom role + * Assign the application the `Foundry User` role on your Foundry resource. See [Azure RBAC configuration](</docs/en/microsoft-foundry#azure-rbac-configuration>) for the other built-in role and custom roles Note the application’s client ID, your tenant ID, and your subscription ID. You add them as secrets in the next step. @@ -289,22 +277,14 @@ Mention `@claude` in an issue or PR comment, then watch the run in the repository’s Actions tab. Claude replies in a comment on the same issue or PR. -## - -​ - -Troubleshooting +## Troubleshooting A failing run usually breaks in one of two places: * **Authentication errors** : usually an OIDC misconfiguration. Check that the workflow includes the `id-token: write` permission, that the trust configuration’s repository condition matches your repository exactly, and that the secret names in your workflow match the ones you added * **Trigger and CI problems** : these behave the same as when the Claude Code GitHub Action calls the Claude API. See the main page’s [troubleshooting section](</docs/en/github-actions#troubleshooting>) and the Claude Code GitHub Action’s [FAQ](<https://github.com/anthropics/claude-code-action/blob/main/docs/faq.md>) -## - -​ - -What’s next +## What’s next * [Claude Code GitHub Actions](</docs/en/github-actions>) for examples, parameters, and best practices * [Claude Code on Amazon Bedrock](</docs/en/amazon-bedrock>) for Bedrock model IDs and regions
modified Claude Code with GitHub Enterprise Server View current →
Show diff (228 lines)
--- a/github-enterprise-server.md +++ b/github-enterprise-server.md @@ -2,11 +2,7 @@ GitHub Enterprise Server (GHES) support lets your organization use Claude Code with repositories hosted on your self-managed GitHub instance instead of github.com. Once an Owner connects your GHES instance, developers can run cloud sessions and get automated code reviews without any per-repository configuration. Plugin marketplaces hosted on your instance are also supported; credential requirements vary by surface, as described in Plugin marketplaces on GHES. For repositories on github.com, see [Use Claude Code in the cloud](</docs/en/claude-code-on-the-web>) and [Code Review](</docs/en/code-review>). To run Claude in your own CI infrastructure, see [GitHub Actions](</docs/en/github-actions>). -## - -​ - -What works with GitHub Enterprise Server +## What works with GitHub Enterprise Server The table below shows which Claude Code features support GHES and any differences from github.com behavior. @@ -21,11 +17,7 @@ GitHub Actions| ✅ Supported| Requires manual workflow setup; `/install-github-app` is github.com only GitHub MCP server| ❌ Not supported| The GitHub MCP server does not work with GHES instances -## - -​ - -Admin setup +## Admin setup An Owner connects your GHES instance to Claude Code once. You need the Owner or Primary Owner role in your Claude organization and permission to create GitHub Apps on your GHES instance. The guided setup generates a GitHub App manifest and redirects you to your GHES instance to create the app in one click. If your environment blocks the redirect flow, an alternative manual setup is available. @@ -59,11 +51,7 @@ Go to [claude.ai/admin-settings/claude-code](<https://claude.ai/admin-settings/claude-code>) and enable [Code Review](</docs/en/code-review-setup>) for your GHES repositories using the same configuration as github.com. -### - -​ - -GitHub App permissions +### GitHub App permissions The manifest configures the GitHub App with the permissions and webhook events below, which together cover cloud sessions, Code Review, Claude Security, and plugin marketplaces: @@ -81,27 +69,15 @@ The app subscribes to `pull_request`, `issue_comment`, `pull_request_review_comment`, `pull_request_review`, `check_run`, and `status` events. GitHub applies a manifest only when the app is created, so an app created from an earlier version of the manifest keeps the permissions and events it was created with. If your app is missing any of the permissions or events above, add them in the app’s settings on your GHES instance. GitHub then asks an owner of each installation to approve the new permissions, and the installation keeps its old permissions until they do. -### - -​ - -Manual setup +### Manual setup If the guided redirect flow is blocked by your network configuration, click **Connect** or **Add instance** , then select **Add manually** instead of **Set up automatically**. Create a GitHub App on your GHES instance with the permissions and events above, then enter the connection details in the form: a display name, your GHES hostname and optional port, and the app’s ID, client ID, client secret, webhook secret, and private key. The form also accepts an optional custom CA certificate and read replica hostnames. Claude generates the app’s webhook URL when you save the connection. After you click **Add configuration** , open the connection’s **More options** menu, select **Copy webhook URL** , and paste the URL into the app’s webhook settings on your GHES instance. Use the same webhook secret you entered in the form. -### - -​ - -Network requirements +### Network requirements For Anthropic-hosted sessions, your GHES instance must be reachable from Anthropic infrastructure so Claude can clone repositories and post review comments. If your GHES instance is behind a firewall, allowlist Anthropic’s [outbound IP addresses](<https://platform.claude.com/docs/en/api/ip-addresses#outbound-ip-addresses>). Sessions in a [self-hosted environment](</docs/en/self-hosted-environments-deploy#configure-git>) clone from inside your network instead, unless the runner opts into the [Anthropic git proxy](</docs/en/self-hosted-environments-deploy#use-the-anthropic-git-proxy>), which fetches from Anthropic’s side and needs the same reachability. Hosted pre-session flows, such as the repository picker, run on Anthropic’s side before a session starts. They need your GHES instance to be reachable from Anthropic infrastructure even when the session runs in a self-hosted environment. The [SCM connector](</docs/en/self-hosted-environments-reference#scm-connector-flags>) isn’t available, so those flows can’t reach a GHES host that’s only routable internally. -## - -​ - -Developer workflow +## Developer workflow Claude Code detects your GHES hostname automatically from the git remote in your working directory. Clone a repository from your GHES instance as you normally would, replacing `github.example.com` and the repository path with your GHES hostname and repository: @@ -114,19 +90,11 @@ The session clones your repository from GHES and pushes changes back to a branch. Monitor progress at [claude.ai/code](<https://claude.ai/code>). See [Use Claude Code in the cloud](</docs/en/claude-code-on-the-web>) for the full cloud session workflow including diff review, auto-fix, and cloud scheduled tasks. -### - -​ - -Teleport sessions to your terminal +### Teleport sessions to your terminal Pull a cloud session into your local terminal with `claude --teleport`. Teleport verifies you’re in a checkout of the same GHES repository before fetching the branch and loading the session history. See [teleport requirements](</docs/en/claude-code-on-the-web#teleport-requirements>) for details. -## - -​ - -Plugin marketplaces on GHES +## Plugin marketplaces on GHES Host plugin marketplaces on your GHES instance to distribute internal tooling across your organization. The marketplace structure is identical to github.com-hosted marketplaces, but installation works differently depending on where you add the marketplace, and credentials differ across surfaces: @@ -140,11 +108,7 @@ GitHub Enterprise connections on claude.ai are per user when a marketplace is added from user settings. The admin setup connects your GHES instance to your organization, but it does not connect individual user accounts: each user who adds a GHES marketplace from their own settings must first connect their own GitHub Enterprise account, and one user’s connection, including the Owner’s, does not cover anyone else. Marketplaces added by an Owner in the organization plugin settings do not put this requirement on users, because ongoing fetches use the organization’s GitHub App. The Owner adding the marketplace still needs their own GitHub Enterprise account connected at add time. -### - -​ - -Add a GHES marketplace +### Add a GHES marketplace The `owner/repo` shorthand always resolves to github.com. For GHES-hosted marketplaces, use the full git URL, replacing `github.example.com` and the repository path with your own. HTTPS URLs are recommended: @@ -156,11 +120,7 @@ Claude Code runs git non-interactively and rejects SSH connections to hosts that are not in the machine’s `known_hosts` file. An HTTPS URL with a git credential helper avoids the `known_hosts` requirement. See [Create and distribute a plugin marketplace](</docs/en/plugins/create-marketplace>) for the full guide to building marketplaces. -### - -​ - -Pre-register GHES marketplaces with managed settings +### Pre-register GHES marketplaces with managed settings The `extraKnownMarketplaces` setting pre-registers a marketplace so developers get it without manual setup. It works from [any settings file](</docs/en/settings-reference#extraknownmarketplaces>), including a repository’s `.claude/settings.json`; managed settings deliver it organization-wide: @@ -182,11 +142,7 @@ * **Confirm each machine can clone from your GHES host.** If a machine lacks credentials, the marketplace is registered but never installed, and its plugins report as not found instead of prompting for credentials. * **Confirm the setting reaches each machine.** A managed settings file only takes effect on machines it’s deployed to, for example through your device management system. See [Deploy managed settings](</docs/en/managed-settings#delivery-mechanisms>) for file locations. -### - -​ - -Allowlist GHES marketplaces in managed settings +### Allowlist GHES marketplaces in managed settings If your organization uses [managed settings](</docs/en/settings>) to restrict which marketplaces developers can add, use the `hostPattern` source type to allow all marketplaces from your GHES instance without enumerating each repository. See [Delivery mechanisms](</docs/en/managed-settings#delivery-mechanisms>) for file locations on each platform. Add the JSON to your `managed-settings.json` file or equivalent MDM policy: @@ -201,44 +157,24 @@ See the [strictKnownMarketplaces](</docs/en/settings-reference#strictknownmarketplaces>) and [extraKnownMarketplaces](</docs/en/settings-reference#extraknownmarketplaces>) settings reference for the complete schema. -## - -​ - -Limitations +## Limitations A few features behave differently on GHES than on github.com. The feature table summarizes support; this section covers the workarounds. * **`/install-github-app` command**: follow the admin setup flow on claude.ai instead. If you also want GitHub Actions workflows on GHES, adapt the [example workflow](<https://github.com/anthropics/claude-code-action/blob/main/examples/claude.yml>) manually. * **GitHub MCP server** : in a session on your own machine, use the `gh` CLI configured for your GHES host instead. Run `gh auth login --hostname github.example.com` to authenticate, then Claude can use `gh` commands there. -## - -​ - -Troubleshooting - -### - -​ - -Cloud session fails to clone repository +## Troubleshooting + +### Cloud session fails to clone repository If `claude --cloud` fails with a clone error, verify that an Owner has completed setup for your GHES instance and that the GitHub App is installed on the repository you’re working in. Ask the Owner who connected the instance to confirm that the hostname registered in Claude settings matches the hostname in your git remote. If the session stops with “Authentication failed while accessing the repository”, you may not have connected your own GitHub Enterprise account. Connect it from the repository picker on [claude.ai/code](<https://claude.ai/code>), then start a new session. -### - -​ - -Marketplace add fails with a policy error +### Marketplace add fails with a policy error If `/plugin marketplace add` is blocked for your GHES URL, your organization has restricted marketplace sources. Ask your admin to add a `hostPattern` entry for your GHES hostname in managed settings. -### - -​ - -Marketplace add on claude.ai fails with a GitHub access error +### Marketplace add on claude.ai fails with a GitHub access error If adding a GHES marketplace from your user settings fails with a generic error like “Marketplace couldn’t be added”, check your GitHub Enterprise connection first. This is what appears when your own GitHub Enterprise account is not connected to Claude, even if your organization’s GHES instance is configured and other users are connected. The dialog does not point to the GitHub Enterprise connect flow, and the “Connect to GitHub” option on the Browse tab signs in to github.com, which does not grant access to GHES repositories. Connect your GitHub Enterprise account in one of these places, then add the marketplace again: @@ -247,19 +183,11 @@ Alternatively, ask an Owner to add the marketplace in the organization plugin settings, which removes the per-user connection requirement. On other claude.ai surfaces, a “Repository not found. If it’s private, GitHub access is required” error on a GHES marketplace usually indicates the same missing connection. Connect your GitHub Enterprise account through one of the paths above, then try again. -### - -​ - -GHES instance not reachable +### GHES instance not reachable If reviews or Anthropic-hosted cloud sessions time out, your GHES instance may not be reachable from Anthropic infrastructure. Confirm your firewall allows inbound connections from Anthropic’s [outbound IP addresses](<https://platform.claude.com/docs/en/api/ip-addresses#outbound-ip-addresses>). Sessions in a [self-hosted environment](</docs/en/self-hosted-environments>) reach GHES from inside your network, so when one of them can’t clone, check the runner’s own network path instead. For the repository picker and other hosted pre-session flows, see Network requirements. -### - -​ - -Connection test passes but a second test fails +### Connection test passes but a second test fails The second test connects to your GHES instance the way Anthropic-hosted cloud sessions do. Find your message to see whether to check your firewall or try again: @@ -268,19 +196,11 @@ To test again, open the connection’s **More options** menu in [**Organization settings > Git providers**](<https://claude.ai/admin-settings/source-control#github-enterprise>) and select **Test connection**. -### - -​ - -Session start fails with `Unable to get organization UUID` +### Session start fails with `Unable to get organization UUID` Claude Code couldn’t read a claude.ai organization from your credentials. Sign in with `/login` using an account in your Team or Enterprise organization, since GitHub Enterprise Server support is limited to those plans. See [Unable to get organization UUID](</docs/en/claude-code-on-the-web#unable-to-get-organization-uuid>) for the causes and the other messages this state produces. -## - -​ - -Related resources +## Related resources These pages cover the features referenced throughout this guide in more depth:
modified Claude Code GitLab CI/CD View current →
Show diff (350 lines)
--- a/gitlab-ci-cd.md +++ b/gitlab-ci-cd.md @@ -2,11 +2,7 @@ This integration is built on top of the [Claude Code CLI and Agent SDK](</docs/en/agent-sdk/overview>), enabling programmatic use of Claude in your CI/CD jobs and custom automation workflows. -## - -​ - -Why use Claude Code with GitLab? +## Why use Claude Code with GitLab? * **Instant MR creation** : Describe what you need, and Claude proposes a complete MR with changes and explanation * **Automated implementation** : Turn issues into working code with a single command or mention @@ -15,11 +11,7 @@ * **Enterprise-ready** : Choose Claude API, Amazon Bedrock, or Google Cloud’s Agent Platform to meet data residency and procurement needs * **Secure by default** : Runs in your GitLab runners with your branch protection and approvals -## - -​ - -How it works +## How it works Claude Code uses GitLab CI/CD to run AI tasks in isolated jobs and commit results back via MRs: @@ -32,11 +24,7 @@ Pick regional endpoints to reduce latency and meet data-sovereignty requirements while using existing cloud agreements. -## - -​ - -What can Claude do? +## What can Claude do? In a GitLab pipeline, Claude Code can: @@ -46,17 +34,9 @@ * Fix bugs and regressions identified by tests or comments * Respond to follow-up comments to iterate on requested changes -## - -​ - -Setup - -### - -​ - -Quick setup +## Setup + +### Quick setup The fastest way to get started is to add a minimal job to your `.gitlab-ci.yml` and set your API key as a masked variable. @@ -102,11 +82,7 @@ To run on Amazon Bedrock or Google Cloud’s Agent Platform instead of the Claude API, see the Using with Amazon Bedrock and Google Cloud section below for authentication and environment setup. -### - -​ - -Manual setup (recommended for production) +### Manual setup (recommended for production) If you prefer a more controlled setup or need enterprise providers: @@ -122,17 +98,9 @@ * Add a project webhook for “Comments (notes)” to your event listener (if you use one) * Have the listener call the pipeline trigger API with variables like `AI_FLOW_INPUT` and `AI_FLOW_CONTEXT` when a comment contains `@claude` -## - -​ - -Example use cases - -### - -​ - -Turn issues into MRs +## Example use cases + +### Turn issues into MRs In an issue comment: @@ -140,11 +108,7 @@ Claude analyzes the issue and codebase, writes changes in a branch, and opens an MR for review. -### - -​ - -Get implementation help +### Get implementation help In an MR discussion: @@ -152,11 +116,7 @@ Claude proposes changes, adds code with appropriate caching, and updates the MR. -### - -​ - -Fix bugs quickly +### Fix bugs quickly In an issue or MR comment: @@ -164,11 +124,7 @@ Claude locates the bug, implements a fix, and updates the branch or opens a new MR. -## - -​ - -Using with Amazon Bedrock and Google Cloud +## Using with Amazon Bedrock and Google Cloud For enterprise environments, you can run Claude Code entirely on your cloud infrastructure with the same developer experience. @@ -176,11 +132,7 @@ * Google Cloud's Agent Platform -### - -​ - -Prerequisites +### Prerequisites Before setting up Claude Code with Amazon Bedrock, you need: @@ -191,11 +143,7 @@ * `AWS_ROLE_TO_ASSUME` (role ARN) * `AWS_REGION` (Amazon Bedrock region) -### - -​ - -Setup instructions +### Setup instructions Configure AWS to allow GitLab CI jobs to assume an IAM role via OIDC (no static keys).**Required setup:** @@ -206,11 +154,7 @@ Use the Amazon Bedrock job example to exchange the job’s OIDC token for temporary AWS credentials at runtime. -### - -​ - -Prerequisites +### Prerequisites Before setting up Claude Code with Google Cloud’s Agent Platform, you need: @@ -223,11 +167,7 @@ * `GCP_SERVICE_ACCOUNT` (service account email) * `GCP_PROJECT_ID` (Google Cloud project ID) -### - -​ - -Setup instructions +### Setup instructions Configure Google Cloud to allow GitLab CI jobs to impersonate a service account via Workload Identity Federation.**Required setup:** @@ -238,19 +178,11 @@ Use the Agent Platform job example to authenticate without storing keys. -## - -​ - -Configuration examples +## Configuration examples Below are ready-to-use snippets you can adapt to your pipeline. -### - -​ - -Amazon Bedrock job example (OIDC) +### Amazon Bedrock job example (OIDC) **Prerequisites:** @@ -307,11 +239,7 @@ Model IDs for Amazon Bedrock include region-specific prefixes (for example, `us.anthropic.claude-sonnet-4-6`). Pass the desired model via your job configuration or prompt if your workflow supports it. -### - -​ - -Agent Platform job example (Workload Identity Federation) +### Agent Platform job example (Workload Identity Federation) **Prerequisites:** @@ -381,25 +309,13 @@ With Workload Identity Federation, you do not need to store service account keys. Use repository-specific trust conditions and least-privilege service accounts. -## - -​ - -Best practices - -### - -​ - -CLAUDE.md configuration +## Best practices + +### CLAUDE.md configuration Create a `CLAUDE.md` file at the repository root to define coding standards, review criteria, and project-specific rules. Claude reads this file during runs and follows your conventions when proposing changes. -### - -​ - -Security considerations +### Security considerations **Never commit API keys or cloud credentials to your repository**. Always use GitLab CI/CD variables: @@ -408,21 +324,13 @@ * Limit job permissions and network egress * Review Claude’s MRs like any other contributor -### - -​ - -Optimizing performance +### Optimizing performance * Keep `CLAUDE.md` focused and concise * Provide clear issue/MR descriptions to reduce iterations * Cache npm and package installs in runners where possible -### - -​ - -CI costs +### CI costs When using Claude Code with GitLab CI/CD, be aware of associated costs: @@ -438,52 +346,28 @@ * Set appropriate `--max-turns` and job `timeout` values * Limit concurrency to control parallel runs -## - -​ - -Troubleshooting - -### - -​ - -Claude not responding to @claude commands +## Troubleshooting + +### Claude not responding to @claude commands * Verify your pipeline is being triggered (manually, MR event, or via a note event listener/webhook) * Ensure your `ANTHROPIC_API_KEY` or cloud provider variables are present * Check that the comment contains `@claude` (not `/claude`) and that your mention trigger is configured -### - -​ - -Job can’t write comments or open MRs +### Job can’t write comments or open MRs * Ensure `CI_JOB_TOKEN` has sufficient permissions for the project, or use a Project Access Token with `api` scope * Check the `mcp__gitlab` tool is enabled in `--allowedTools` * Confirm the job runs in the context of the MR or has enough context via `AI_FLOW_*` variables -### - -​ - -Authentication errors +### Authentication errors * **For Claude API** : Confirm `ANTHROPIC_API_KEY` is valid and unexpired * **For Amazon Bedrock or Google Cloud’s Agent Platform** : Verify OIDC/WIF configuration, role impersonation, and secret names; confirm region and model availability -## - -​ - -Advanced configuration - -### - -​ - -Common parameters and variables +## Advanced configuration + +### Common parameters and variables Control Claude Code runs in your jobs with these CLI flags, GitLab keywords, and variables: @@ -495,11 +379,7 @@ Exact flags and parameters may vary by version of `@anthropic-ai/claude-code`. Run `claude --help` in your job to see supported options. -### - -​ - -Customizing Claude’s behavior +### Customizing Claude’s behavior You can guide Claude in two primary ways:
modified Glossary View current →
Show diff (624 lines)
--- a/glossary.md +++ b/glossary.md @@ -1,72 +1,36 @@ This glossary defines Claude Code terminology. Each entry links to the page where the concept is covered in depth. For model-level concepts like tokens, temperature, and RAG, see the [platform glossary](<https://platform.claude.com/docs/en/about-claude/glossary>). For Claude Desktop terms such as desktop extension, MCPB, and DXT, see the [Claude Help Center](<https://support.claude.com/>). -## - -​ - -A - -### - -​ - -AGENTS.md +## A + +### AGENTS.md A markdown file of project instructions you write for AI coding agents. If your repository has one and no CLAUDE.md, Claude reads it as your project instructions without you adding a second file. You can change the **Project instructions** setting in `/config` to have Claude read both files or only `CLAUDE.md`. Reading `AGENTS.md` directly requires Claude Code v2.1.277 or later. In some sessions Claude [can’t read `AGENTS.md`](</docs/en/memory#when-agents-md-support-is-unavailable>), so [import it from a `CLAUDE.md`](</docs/en/memory#share-one-file-with-other-coding-tools>) there instead. Learn more: [AGENTS.md](</docs/en/memory#agents-md>) -### - -​ - -Agent teams +### Agent teams Multiple independent Claude Code sessions coordinated by a team lead, with a shared task list and peer-to-peer messaging. Unlike subagents, which run within a single session and report only to the parent, teammates each have their own context window and you can interact with any of them directly. Agent teams are experimental and disabled by default; see [Enable agent teams](</docs/en/agent-teams#enable-agent-teams>). Learn more: [Run agent teams](</docs/en/agent-teams>) -### - -​ - -Agentic coding +### Agentic coding A workflow where the AI can read files, run commands, and make changes autonomously while you watch, redirect, or step away, as opposed to chat-based assistants that only respond with text you must apply yourself. Claude Code is agentic because it has tools that let it act, not just advise. Learn more: [How Claude Code works](</docs/en/how-claude-code-works>) -### - -​ - -Agentic harness +### Agentic harness The tools, context management, and execution environment that turn a language model into a capable coding agent. Claude Code is the harness; Claude is the model inside it. The harness supplies file access, shell execution, permission gating, memory loading, and the loop that chains actions together. Learn more: [How Claude Code works](</docs/en/how-claude-code-works>) -### - -​ - -Agentic loop +### Agentic loop The cycle Claude works through for every task: gather context, take action, verify results, and repeat until done. Each tool use returns information that informs the next step. You can interrupt the loop at any point to redirect. Most extension points, including hooks, skills, and MCP, plug into specific phases of this loop. Learn more: [How Claude Code works](</docs/en/how-claude-code-works#the-agentic-loop>) -### - -​ - -Artifact +### Artifact A live, interactive web page Claude Code publishes from your session to a private URL on claude.ai, so you can see output visually or share it instead of reading terminal text. The page updates in place when the session republishes. Artifacts you create from Claude Code appear in the same gallery as artifacts created in claude.ai conversations. Sharing options depend on your plan: see [Share an artifact](</docs/en/artifacts#share-an-artifact>). Learn more: [Share session output as artifacts](</docs/en/artifacts>) -### - -​ - -Auto memory +### Auto memory Notes Claude writes for itself based on your corrections and preferences, stored per git repository under `~/.claude/projects/`. All worktrees of the same repository share one auto memory directory. The first 200 lines or 25 KB of the `MEMORY.md` index loads at the start of every session. Auto memory is the Claude-written counterpart to CLAUDE.md, which you write. Learn more: [Auto memory](</docs/en/memory#auto-memory>) -### - -​ - -Auto mode +### Auto mode A permission mode where a separate classifier model reviews actions instead of you, so Claude Code runs most of them without asking you. Claude Code still asks you before actions your explicit ask rules match. The classifier blocks scope escalation, untrusted infrastructure, and prompt injection. @@ -75,167 +39,79 @@ Learn more: [Eliminate prompts with auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) -## - -​ - -B - -### - -​ - -Bare mode +## B + +### Bare mode With `--bare`, Claude Code starts without loading hooks, skills, custom commands, subagents, installed plugins, MCP servers, auto memory, or CLAUDE.md, apart from skills in a directory you pass with `--add-dir`. Recommended for CI and scripted calls where you need the same result on every machine. Learn more: [Start faster with bare mode](</docs/en/headless#start-faster-with-bare-mode>) -### - -​ - -Bundled skills +### Bundled skills Prompt-based playbooks included with Claude Code, such as `/batch`, `/code-review`, `/debug`, and `/loop`. Unlike built-in commands, which execute fixed logic, bundled skills give Claude a detailed prompt and let it orchestrate the work, so they can spawn agents, read files, and adapt to your codebase. Learn more: [Bundled skills](</docs/en/skills#bundled-skills>) -## - -​ - -C - -### - -​ - -Channel +## C + +### Channel An MCP server that pushes events into your running session so Claude can react to things that happen while you’re away from the terminal. Channels can be two-way: Claude reads an inbound event and replies back through the same channel. Telegram, Discord, and iMessage are included in the research preview. Learn more: [Channels](</docs/en/channels>) -### - -​ - -Checkpoint +### Checkpoint A restore point created at each prompt you send that starts a turn. Claude Code snapshots files before every edit so a checkpoint can revert them. Press `Esc` twice or run `/rewind` to restore code, conversation, or both to an earlier point, or to summarize part of the conversation from a selected message. Checkpoints are saved with the conversation, so a resumed session can still `/rewind` to them. Rewinding doesn’t undo a Bash command’s changes to a file unless Claude had already used its file editing tools on that file in your conversation. Learn more: [Checkpointing](</docs/en/checkpointing>) -### - -​ - -`.claude` directory +### `.claude` directory The directory where Claude Code reads project-scoped configuration: settings, hooks, skills, subagents, rules, and auto memory. A project has `.claude/` at its root; your user-level defaults are at `~/.claude/`. Learn more: [The `.claude` directory](</docs/en/claude-directory>) -### - -​ - -CLAUDE.md +### CLAUDE.md A markdown file of persistent instructions you write for Claude, loaded at the start of every session as a user message after the system prompt. Put project conventions, architecture notes, and “always do X” rules here. Project-root CLAUDE.md survives compaction and is re-read fresh from disk afterward. You can place CLAUDE.md at project scope in `./CLAUDE.md` or `./.claude/CLAUDE.md`, at user scope in `~/.claude/CLAUDE.md`, or as managed policy for your organization. All discovered files are concatenated into context rather than overriding each other, ordered from broadest scope to most specific. Claude Code can also load a project’s AGENTS.md files in place of CLAUDE.md. Learn more: [CLAUDE.md files](</docs/en/memory#claude-md-files>) -### - -​ - -Cloud session +### Cloud session A Claude Code session that keeps running after you close your laptop, because it runs on cloud infrastructure instead of your machine. That infrastructure is Anthropic-managed by default, or a [self-hosted environment](</docs/en/self-hosted-environments>) your organization operates. You start one from claude.ai/code, the Claude mobile app, the Desktop app with **Cloud** selected, `claude --cloud`, or a [cloud scheduled task](</docs/en/routines>). A session in your terminal, IDE, or the Desktop app with **Local** selected is a local session; to reach a local session from another device, use Remote Control. Learn more: [Use Claude Code in the cloud](</docs/en/claude-code-on-the-web>) -### - -​ - -Command +### Command A reusable instruction you invoke by typing `/name` in the prompt. Built-in commands such as `/clear`, `/model`, and `/compact` control the session. You can define your own commands as files in `.claude/commands/`, or install them from a plugin. Skills are the recommended way to package multi-step commands. Two other uses of the word are unrelated: `claude` CLI subcommands such as `claude mcp add`, listed in the [CLI reference](</docs/en/cli-reference#cli-commands>), and the `command` field of a stdio MCP server entry, which specifies the executable Claude Code launches to start the server. Learn more: [Commands](</docs/en/commands>) · [Skills](</docs/en/skills>) -### - -​ - -Compaction +### Compaction Automatic summarization of your conversation when the context window approaches its limit. Project-root CLAUDE.md and auto memory survive compaction, but instructions given only in conversation may not. Run `/compact` to trigger manually, optionally with a focus like `/compact focus on the API changes`. Learn more: [What survives compaction](</docs/en/context-window#what-survives-compaction>) · [When context fills up](</docs/en/how-claude-code-works#when-context-fills-up>) · [When Claude Code compacts a conversation you leave idle](</docs/en/settings-reference#idlecompaction>) -### - -​ - -Connector +### Connector An MCP server added to your claude.ai account rather than configured in Claude Code. When you sign in to Claude Code with that account, your connectors appear in `/mcp` alongside the servers you added locally. Organizations can also provision connectors and set per-tool controls on them. Learn more: [Use MCP servers from claude.ai](</docs/en/mcp#use-mcp-servers-from-claude-ai>) -### - -​ - -Context window +### Context window The working memory for a session, holding conversation history, file contents, command outputs, CLAUDE.md, auto memory, loaded skills, and system instructions. As you work, context fills up until compaction summarizes it. Run `/context` to see what’s using space. For the underlying model concept, see the [platform glossary](<https://platform.claude.com/docs/en/about-claude/glossary#context-window>). Learn more: [Explore the context window](</docs/en/context-window>) -## - -​ - -D - -### - -​ - -Dispatch +## D + +### Dispatch A phone-initiated task router that spawns a Claude Code session in the Desktop app when you send a coding task from the Claude mobile app. Your prompt routes to the right tool automatically. Available on Pro, Max, and Ultra plans. Learn more: [Sessions from Dispatch](</docs/en/desktop#sessions-from-dispatch>) -## - -​ - -E - -### - -​ - -Effort level +## E + +### Effort level A setting that controls adaptive reasoning, which lets the model decide whether and how much to think on each step. Higher effort means more thinking tokens and deeper reasoning; lower effort is faster and cheaper. Effort is supported on Fable models, on Opus 4.6 and later, on Sonnet 4.6 and later, and on Haiku 5.5. Learn more: [Adjust effort level](</docs/en/model-config#adjust-effort-level>) -### - -​ - -Extended thinking +### Extended thinking Visible step-by-step reasoning the model performs before responding. You can adjust it with the effort level, or cap thinking tokens with `MAX_THINKING_TOKENS` on models with a fixed thinking budget. Thinking appears in gray italic text in the terminal. Learn more: [Use extended thinking](</docs/en/model-config#extended-thinking>) -## - -​ - -F - -### - -​ - -Frontmatter +## F + +### Frontmatter A block of YAML settings at the very top of a Markdown file, between an opening `---` line and a closing `---` line. Skills, subagents, output styles, and rules each read their configuration from frontmatter, such as a skill’s `description` or a subagent’s `tools`, and treat everything after the closing `---` as the instructions. The opening `---` must be the file’s first line. Each file type accepts its own set of fields. Learn more: [Skill frontmatter](</docs/en/skills#frontmatter-reference>), [Subagent frontmatter](</docs/en/sub-agents#supported-frontmatter-fields>), [Output style frontmatter](</docs/en/output-styles#frontmatter>), [Rule frontmatter](</docs/en/memory#rules-frontmatter-reference>) -## - -​ - -H - -### - -​ - -Hook +## H + +### Hook A user-defined handler that executes automatically at a specific point in Claude Code’s lifecycle, such as before a tool runs, after a file edit, or at session start. Handlers can be a shell command, HTTP endpoint, MCP tool, LLM prompt, or subagent. Hooks are deterministic: they fire at fixed lifecycle points rather than at the model’s discretion. A hook configuration has three levels: @@ -245,215 +121,103 @@ Learn more: [Get started with hooks](</docs/en/hooks-guide>) · [Hooks reference](</docs/en/hooks>) -## - -​ - -M - -### - -​ - -Managed settings +## M + +### Managed settings Settings enforced org-wide by IT or DevOps, delivered from Anthropic’s servers through the admin console or deployed to devices at an OS-level path outside `~/.claude`. User and project settings cannot override managed settings. Server-managed delivery applies on [eligible configurations](</docs/en/server-managed-settings#platform-availability>); see [Security considerations](</docs/en/server-managed-settings#security-considerations>). Use this for security policies, compliance requirements, or standardized tooling across a fleet. Learn more: [Server-managed settings](</docs/en/server-managed-settings>) · [Settings files](</docs/en/settings#where-settings-live>) -### - -​ - -MCP (Model Context Protocol) +### MCP (Model Context Protocol) An open standard for connecting AI tools to external data sources and services. MCP servers give Claude new tools for Slack, Jira, databases, browsers, and hundreds of other integrations. You connect servers via `/mcp` or by adding them to `.mcp.json`. For the protocol itself, see the [platform glossary](<https://platform.claude.com/docs/en/about-claude/glossary#mcp-model-context-protocol>). Learn more: [Model Context Protocol](</docs/en/mcp>) -### - -​ - -MCP server +### MCP server A program that gives Claude tools, prompts, or resources over MCP. You add servers with `claude mcp add`, in `.mcp.json`, through a plugin, or as a claude.ai connector. A local stdio server runs as a process Claude Code starts from the `command` and `args` fields of its configuration, which have nothing to do with the commands you type at the prompt. Learn more: [Model Context Protocol](</docs/en/mcp>) -### - -​ - -MCP Tool Search +### MCP Tool Search A context-saving mechanism that defers MCP tool schemas until needed. Only tool names and server instructions load at startup; Claude fetches the full schema on demand when it decides to use a specific tool. This keeps idle MCP servers from consuming much context. Learn more: [Scale with MCP Tool Search](</docs/en/mcp#scale-with-mcp-tool-search>) -## - -​ - -N - -### - -​ - -Non-interactive mode +## N + +### Non-interactive mode A mode that executes a single prompt and exits without an interactive prompt, invoked with `-p` or `--print`. Used for CI, scripts, and piping. The run is still saved as a resumable session unless you pass `--no-session-persistence`. The [Agent SDK](</docs/en/agent-sdk/overview>) is the Python and TypeScript equivalent. Formerly called headless mode. Learn more: [Run Claude Code programmatically](</docs/en/headless>) -## - -​ - -O - -### - -​ - -Output style +## O + +### Output style A configuration that changes the instructions Claude Code gives Claude, to set response behavior, tone, or format. Unlike CLAUDE.md, which adds project context alongside Claude Code’s default instructions, a custom output style adds its own instructions and can leave out the default software engineering instructions. Learn more: [Output styles](</docs/en/output-styles>) -## - -​ - -P - -### - -​ - -Permission mode +## P + +### Permission mode The baseline approval behavior for the session. Cycle with `Shift+Tab` in the CLI or use the mode selector in VS Code, Desktop, and claude.ai. Available modes are `default`, `acceptEdits`, `plan`, `auto`, `dontAsk`, and `bypassPermissions`. The `default` mode is labeled Manual in the CLI, in the VS Code and JetBrains extensions, and in the desktop app, and Claude Code accepts `manual` as an alias for the value. Learn more: [Choose a permission mode](</docs/en/permission-modes>) -### - -​ - -Permission rule +### Permission rule A settings entry that allows, asks about, or denies a tool invocation based on the tool name and argument pattern. Rules are evaluated deny→ask→allow, first match wins. Permission rules are fine-grained controls layered on top of the broader permission mode. Learn more: [Configure permissions](</docs/en/permissions>) -### - -​ - -Plan mode +### Plan mode A permission mode where Claude researches and proposes changes without editing your source files. It can read, search, and run exploration commands, then presents a plan for approval before touching anything. Enter plan mode with `/plan` or by pressing `Shift+Tab`. Learn more: [Analyze before you edit with plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>) -### - -​ - -Plugin +### Plugin A bundle of skills, hooks, subagents, and MCP servers packaged as a single installable unit. Plugin skills are namespaced as `plugin-name:skill-name` so multiple plugins coexist. Distribute plugins across teams via a [marketplace](</docs/en/plugins/overview>). Learn more: [Plugins](</docs/en/plugins/overview>) -### - -​ - -Project trust +### Project trust A dialog accepting a directory before Claude Code loads its configuration. Acceptance is saved per project directory, except your home directory, where trust is held for the current session only and the prompt reappears on each launch. Until you trust a directory, Claude Code holds back some of the content its repository supplies, such as project allow rules and marketplaces from `.claude/settings.json`. [What runs before you trust a folder](</docs/en/permissions#what-runs-before-you-trust-a-folder>) lists each kind of content, including what a `-p` session runs without a dialog. Learn more: [The `.claude` directory](</docs/en/claude-directory>) -### - -​ - -Prompt injection +### Prompt injection Hostile instructions embedded in a file, web page, or tool result that attempt to redirect Claude toward actions you didn’t ask for. Claude Code’s defenses include the permission system, command injection detection, and trust verification. In auto mode, a server-side probe scans tool results for suspicious content, and a classifier reviews actions. Learn more: [Protect against prompt injection](</docs/en/security#protect-against-prompt-injection>) -## - -​ - -R - -### - -​ - -Remote Control +## R + +### Remote Control A way to continue a local Claude Code session from your phone or browser via claude.ai. Your code execution and files stay on your machine; the interface is remote. Different from a [cloud session](</docs/en/claude-code-on-the-web>), which runs in a cloud sandbox. Learn more: [Remote Control](</docs/en/remote-control>) -### - -​ - -Rules +### Rules Modular instruction files in `.claude/rules/` that load alongside CLAUDE.md. A rule can be path-scoped with YAML `paths:` frontmatter so it only loads when Claude reads, writes, or edits a matching file, keeping context lean until it’s relevant. Learn more: [Organize rules with `.claude/rules/`](</docs/en/memory#organize-rules-with-claude/rules/>) -## - -​ - -S - -### - -​ - -Sandboxing +## S + +### Sandboxing OS-level filesystem and network isolation for the Bash tool. Commands run inside a boundary you define upfront, so Claude can work freely within it without per-command approval prompts. Sandboxing is a separate layer from permission rules. Learn more: [Sandboxing](</docs/en/sandboxing>) -### - -​ - -Session +### Session A conversation tied to your current directory, with its own independent context window. Sessions can be resumed with `claude -c`, forked with `--fork-session` to preserve history under a new session ID, or run in parallel across terminals. Running `/clear` starts a new session; the previous one stays stored and is available via `/resume`. Each session’s transcript is stored under `~/.claude/projects/`. Learn more: [Work with sessions](</docs/en/how-claude-code-works#work-with-sessions>) -### - -​ - -Settings layers +### Settings layers The hierarchy Claude Code reads configuration from, in precedence order from highest to lowest: managed policy, settings you pass with the `--settings` flag, local settings at `.claude/settings.local.json`, project settings at `.claude/settings.json`, then user settings at `~/.claude/settings.json`. Arrays merge across layers; scalars at a higher layer override lower ones. See [Settings precedence](</docs/en/settings#settings-precedence>). Learn more: [Settings files](</docs/en/settings#where-settings-live>) -### - -​ - -Skill +### Skill A `SKILL.md` file containing instructions, knowledge, or a workflow that Claude adds to its toolkit. Claude loads a skill automatically when relevant, or you invoke it directly with `/skill-name`. Skills follow the Agent Skills open standard; Claude Code extends it with invocation control and subagent execution. Skills are the recommended successor to custom commands. A file at `.claude/commands/deploy.md` and one at `.claude/skills/deploy/SKILL.md` both create `/deploy` and work the same way; existing command files continue to work. Learn more: [Extend Claude with skills](</docs/en/skills>) -### - -​ - -Subagent +### Subagent A specialized AI assistant that runs in its own context window with a custom system prompt, specific tool access, and independent permissions. It works on a delegated task and returns a summary to the main conversation. Use subagents to keep large explorations out of your primary context or to run parallel research. A subagent stays inside the session that spawned it. To pass findings between separate sessions you run yourself, use [cross-session messaging](</docs/en/cross-session-messaging>). Built-in subagents include Explore, Plan, and general-purpose. Learn more: [Create custom subagents](</docs/en/sub-agents>) -### - -​ - -Surface +### Surface Any place you access Claude Code: the CLI, VS Code, JetBrains, Desktop, or claude.ai. All surfaces share the same engine. Sessions on your machine read your local CLAUDE.md, settings, and skills; [cloud sessions](</docs/en/cloud-environments#what-carries-over-from-your-setup>) start from a fresh clone of your repository and don’t read `~/.claude/` on your machine. Slack and the Chrome extension are integrations that connect to a surface rather than surfaces themselves. Learn more: [Platforms and integrations](</docs/en/platforms>) -### - -​ - -System prompt +### System prompt The instructions Claude Code sends ahead of your conversation on every request, covering how Claude uses tools, behaves safely, and formats its responses. You can add to the system prompt with `--append-system-prompt` or replace it with `--system-prompt`. The system prompt is the first layer of the [prompt cache](</docs/en/prompt-caching#how-the-cache-is-organized>). Your CLAUDE.md files and the instructions of your output style aren’t part of the system prompt. Claude Code delivers them in the conversation as system reminders. Learn more: [System prompt flags](</docs/en/cli-reference#system-prompt-flags>) -### - -​ - -System reminder +### System reminder A message that Claude Code, as the harness, adds to the conversation to give Claude context. You don’t send system reminders yourself. Claude Code inserts them as a session runs, for example when the session starts, when a hook returns text, or when a file changes on disk. Claude reads them alongside your messages. The following all reach Claude as system reminders: @@ -466,79 +230,39 @@ In a logged API request, a system reminder appears wrapped in `<system-reminder>` tags inside a user message, or on some models as a separate message with the `system` role. Learn more: [Context Claude Code adds outside the system prompt](</docs/en/agent-sdk/modifying-system-prompts#context-claude-code-adds-outside-the-system-prompt>) -## - -​ - -T - -### - -​ - -Teleport +## T + +### 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: [Continue a cloud session in your terminal](</docs/en/claude-code-on-the-web#from-cloud-to-terminal>) -### - -​ - -Tool +### Tool An action Claude can take: read a file, edit code, run a shell command, search the web, spawn a subagent. Tools are what make Claude Code agentic. Without them, Claude can only respond with text. Each tool use returns a result that informs Claude’s next decision in the agentic loop. Learn more: [Tools available to Claude](</docs/en/tools-reference>) -### - -​ - -Transcript +### Transcript The stored record of a session. The conversation is what you and Claude exchange; the transcript is that conversation kept as a file, by default at `~/.claude/projects/<project>/<session-id>.jsonl`. Claude Code reads the file back when you resume, which is how a conversation continues after the session ends. For the on-screen view of the same conversation, see the [transcript viewer](</docs/en/interactive-mode#transcript-viewer>). Learn more: [Where transcripts are stored](</docs/en/sessions#where-transcripts-are-stored>) -### - -​ - -Turn +### Turn One complete response from Claude within a session. A turn begins when you send a message and ends when Claude finishes responding, with any number of tool calls in between. Stop hooks fire at the end of each turn. A session consists of many turns, and the agentic loop describes what happens inside one. Learn more: [How Claude Code works](</docs/en/how-claude-code-works#the-agentic-loop>) -## - -​ - -V - -### - -​ - -Verification loop +## V + +### Verification loop How a session knows the work is actually done instead of accepting a result that looks plausible. You give Claude a check it can run, such as a test suite, a build, or a screenshot comparison, and Claude iterates until the check passes instead of stopping after one attempt. A verification loop is the prerequisite for [`/goal`](</docs/en/goal>), unattended runs, and [dynamic workflows](</docs/en/workflows>): without one, the only thing deciding the agent is finished is the agent itself. Learn more: [Give Claude a check to run](</docs/en/best-practices#give-claude-a-check-to-run>) -## - -​ - -W - -### - -​ - -Worktree isolation +## W + +### Worktree isolation An isolation mode that runs Claude in a separate git worktree under `.claude/worktrees/`, enabled with the `-w` flag or `isolation: worktree` in subagent config. Changes stay on a separate branch in a separate directory, so parallel agents each edit their own copy of the files. Learn more: [Run parallel sessions with git worktrees](</docs/en/worktrees>) * * * -## - -​ - -Deprecated and renamed terms +## Deprecated and renamed terms These terms appear in older docs, blog posts, and community content. Use the current name when searching this site.
modified Keep Claude working toward a goal View current →
Show diff (194 lines)
--- a/goal.md +++ b/goal.md @@ -5,11 +5,7 @@ * Splitting a large file into focused modules until each is under a size budget * Working through a labeled issue backlog until the queue is empty -## - -​ - -Compare ways to keep a session running +## Compare ways to keep a session running Three approaches keep the current session running between prompts. Pick based on what should start the next turn: @@ -23,19 +19,11 @@ The approaches above keep the current session running. You can also schedule work that runs independent of any open session, such as nightly tests or morning triage. See [scheduling options](</docs/en/scheduled-tasks#compare-scheduling-options>) for cloud and Desktop scheduled tasks. -## - -​ - -Use `/goal` +## Use `/goal` One goal can be active per session. The same command sets, checks, and clears it depending on the argument. -### - -​ - -Set a goal +### Set a goal Run `/goal` followed by the condition you want satisfied. If a goal is already active, the new one replaces it. @@ -43,11 +31,7 @@ Setting a goal starts a turn immediately, with the condition itself as the directive. You don’t need to send a separate prompt. While the goal is active, a `◎ /goal active` indicator shows how long the goal has been running. A goal doesn’t change your permission mode. To let goal turns run unattended, run `/goal` in [auto mode](</docs/en/auto-mode-config>). In [Manual mode](</docs/en/permission-modes>), Claude still asks before tool calls that your settings don’t already allow, such as the test command above. While the goal is active, the transcript shows each verdict the evaluator returns, and you can press Ctrl+O to see the reason behind it. The status view also shows the most recent reason, so you can see what Claude is working toward next. -### - -​ - -Write an effective condition +### Write an effective condition The evaluator judges your condition against what Claude has surfaced in the conversation. It doesn’t run commands or read files independently, so write the condition as something Claude’s own output can demonstrate. “All tests in `test/auth` pass” works because Claude runs the tests and the result appears in the transcript for the evaluator to read. A condition that holds up across many turns usually has: @@ -57,11 +41,7 @@ The condition can be up to 4,000 characters. To bound how long a goal runs, include a turn or time clause in the condition, such as `or stop after 20 turns`. Claude reports progress against that clause each turn and the evaluator judges it from the conversation. -### - -​ - -Check status +### Check status Run `/goal` with no arguments to see the current state. @@ -77,11 +57,7 @@ The turn count and the most recent reason appear after the first evaluation has run. If no goal is active but one was achieved earlier in the session, the status shows the achieved condition along with its duration, turn count, and token spend. -### - -​ - -Clear a goal +### Clear a goal Run `/goal clear` to remove an active goal before it resolves. @@ -89,19 +65,11 @@ Claude prints `Goal cleared:` followed by the condition to confirm, or `No goal set` if nothing was active. `stop`, `off`, `reset`, `none`, and `cancel` are accepted as aliases for `clear`. Running `/clear` to start a new conversation also removes any active goal. -### - -​ - -Resume with an active goal +### Resume with an active goal When you resume a session, Claude Code restores a goal that was still active when the session ended. Claude Code restores it on every resume route: `--continue`, `--resume` with a session ID, name, or [transcript file path](</docs/en/sessions#resume-a-session>), and the [session picker](</docs/en/sessions#use-the-session-picker>). Before v2.1.239, Claude Code restored the goal on every route except the `claude --resume` picker. Claude Code carries the condition over but resets the turn count, timer, and token-spend baseline. It doesn’t restore a goal that was already achieved or cleared. -### - -​ - -Run non-interactively +### Run non-interactively `/goal` works in [non-interactive mode](</docs/en/headless>), in the [desktop app](</docs/en/desktop>), and through [Remote Control](</docs/en/remote-control>). Setting a goal with `-p` runs the loop to completion in a single invocation: @@ -109,11 +77,7 @@ With the default text output, Claude’s final response prints when the loop ends, so a goal that runs many turns can look stuck. Add `--output-format stream-json --verbose` to emit each message as the loop runs. Interrupt the process with Ctrl+C to stop a non-interactive goal before it resolves. -## - -​ - -How evaluation works +## How evaluation works `/goal` is a wrapper around a session-scoped [prompt-based Stop hook](</docs/en/hooks#prompt-based-hooks>). Each time Claude finishes a turn, Claude Code sends the condition and the conversation so far to your configured [small fast model](</docs/en/model-config>). The model returns one of three verdicts, each with a short reason: @@ -123,19 +87,11 @@ If Claude keeps answering the evaluator without making progress (no tool use for several turns in a row), Claude Code stops the loop, prints a warning, and returns control to you with the goal still set. Evaluation resumes after your next prompt. The [hooks guide](</docs/en/hooks-guide#stop-hook-hits-the-block-cap>) explains the underlying mechanism. -### - -​ - -When a turn fails +### When a turn fails When a turn fails, Claude Code clears the goal if the error is one you have to fix. After any other error the goal stays set. -#### - -​ - -Errors you have to fix clear the goal +#### Errors you have to fix clear the goal If a turn fails on an error that won’t clear until you fix it, Claude Code clears the goal and prints a warning naming the cause. The warning starts with `Goal cleared after an unrecoverable error` and ends with `Run /goal again to continue`. Fix the cause, then set the goal again with `/goal <condition>`. Failures that clear the goal include: @@ -145,11 +101,7 @@ * A context overflow that [auto-compaction](</docs/en/model-config#set-the-auto-compact-window>) couldn’t clear * A model that isn’t available -#### - -​ - -Other errors retry or pause the goal +#### Other errors retry or pause the goal After any other failure the goal stays set. In an interactive session on Claude Code v2.1.269 or later, Claude Code also prints a line naming the cause and either retries on its own or waits for you: @@ -158,11 +110,7 @@ Send a message at any time to start the next turn immediately. To turn automatic retries off, set [`CLAUDE_CODE_GOAL_CHECKIN_MINUTES`](</docs/en/env-vars>) to `0`, which also turns check-ins off. -### - -​ - -Background work defers evaluation +### Background work defers evaluation If a subagent or a background shell command is still running when a turn ends, Claude Code skips the evaluation for that turn. It evaluates at the end of the next turn that finishes with no background work running. When the background work finishes, Claude Code delivers the result to Claude as a new turn, so you don’t have to prompt. Once background work has kept the goal waiting for 30 minutes, a check-in is due. In the check-in, Claude Code lists the running tasks and asks Claude to read their output, keep waiting if they’re progressing, and fix or stop any that are stuck. After the first check-in, Claude Code waits twice as long before each later check-in, up to four times the first interval: with the default, 1 hour after the first check-in, then every 2 hours. Claude Code delivers a due check-in, the first one included, in one of two ways: @@ -171,11 +119,7 @@ Before v2.1.239, only idle check-ins backed off this way; a check-in delivered at a turn end recurred at the first interval. To change the first interval, set [`CLAUDE_CODE_GOAL_CHECKIN_MINUTES`](</docs/en/env-vars>). Claude Code uses your value in place of the 30-minute interval and scales the later intervals with it. Set it to `0` to turn off check-ins and automatic retries. Check-ins require Claude Code v2.1.234 or later. -### - -​ - -Evaluation model and cost +### Evaluation model and cost To evaluate on a different model, set [`ANTHROPIC_DEFAULT_HAIKU_MODEL`](</docs/en/model-config#environment-variables>). @@ -185,19 +129,11 @@ Evaluation tokens are billed on the small fast model configured for your provider and are typically negligible compared to main-turn spend. -## - -​ - -Requirements +## Requirements Claude Code makes `/goal` available under the same [workspace trust rule as hooks in settings files](</docs/en/permissions#what-runs-before-you-trust-a-folder>), because the evaluator is part of the hooks system. `/goal` is also unavailable when [`disableAllHooks`](</docs/en/hooks#disable-or-remove-hooks>) is `true` after settings precedence applies, or when [`allowManagedHooksOnly`](</docs/en/settings-reference#allowmanagedhooksonly>) is set in managed settings. -## - -​ - -See also +## See also * [Run a prompt repeatedly with `/loop`](</docs/en/scheduled-tasks#run-a-prompt-repeatedly-with-%2Floop>): re-run on a time interval instead of toward a condition * [Prompt-based hooks](</docs/en/hooks-guide#prompt-based-hooks>): write your own Stop hook when you need custom evaluation logic
modified Claude Code on Google Cloud's Agent Platform View current →
Show diff (239 lines)
--- a/google-vertex-ai.md +++ b/google-vertex-ai.md @@ -1,8 +1,4 @@ -## - -​ - -Prerequisites +## Prerequisites Before configuring Claude Code with Google Cloud’s Agent Platform, formerly Vertex AI, ensure you have: @@ -14,11 +10,7 @@ To sign in with your own Google Cloud’s Agent Platform credentials, follow Sign in with Google Cloud’s Agent Platform below. To deploy Claude Code across a team, use the manual setup steps and pin your model versions before rolling out. -## - -​ - -Sign in with Agent Platform +## Sign in with Agent Platform If you have Google Cloud credentials and want to start using Claude Code through Google Cloud’s Agent Platform, the login wizard walks you through it. You complete the GCP-side prerequisites once per project; the wizard handles the Claude Code side. @@ -42,29 +34,17 @@ After you’ve signed in, run `/setup-vertex` any time to reopen the wizard and change your credentials, project, region, or model pins. The model pin step starts from your currently pinned models. The wizard writes to `~/.claude/settings.json`, or to `$CLAUDE_CONFIG_DIR/settings.json` when [`CLAUDE_CONFIG_DIR`](</docs/en/env-vars#variables>) is set. -## - -​ - -Region configuration +## Region configuration Claude Code supports Google Cloud’s Agent Platform [global](<https://cloud.google.com/blog/products/ai-machine-learning/global-endpoint-for-claude-models-generally-available-on-vertex-ai>), multi-region, and regional endpoints. Set `CLOUD_ML_REGION` to `global`, a multi-region location such as `eu` or `us`, or a specific region such as `us-east5`. Claude Code selects the correct Google Cloud’s Agent Platform hostname for each form, including the `aiplatform.eu.rep.googleapis.com` and `aiplatform.us.rep.googleapis.com` hosts for multi-region locations. Google Cloud’s Agent Platform may not support the Claude Code default models on every endpoint type. Model availability varies across [specific regions](<https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations#genai-partner-models>), multi-region locations, and [global endpoints](<https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-partner-models#supported_models>). You may need to switch to a supported location or specify a supported model. -## - -​ - -Set up manually +## Set up manually To configure Google Cloud’s Agent Platform through environment variables instead of the wizard, for example in CI or a scripted enterprise rollout, follow the steps below. -### - -​ - -1\. Enable Agent Platform API +### 1\. Enable Agent Platform API Enable Google Cloud’s Agent Platform API in your GCP project. Replace `YOUR-PROJECT-ID` with your GCP project ID here and in the configuration step below: @@ -74,11 +54,7 @@ # Enable Agent Platform API gcloud services enable aiplatform.googleapis.com -### - -​ - -2\. Request model access +### 2\. Request model access Request access to Claude models in Google Cloud’s Agent Platform: @@ -87,21 +63,13 @@ 3. Request access to desired Claude models (for example, Claude Sonnet 4.6) 4. Wait for approval (may take 24-48 hours) -### - -​ - -3\. Configure GCP credentials +### 3\. Configure GCP credentials Claude Code uses standard Google Cloud authentication. For more information, see [Google Cloud authentication documentation](<https://cloud.google.com/docs/authentication>). Claude Code supports [X.509 certificate-based Workload Identity Federation](<https://cloud.google.com/iam/docs/workload-identity-federation-with-x509-certificates>) through the same Application Default Credentials chain. Set `GOOGLE_APPLICATION_CREDENTIALS` to the path of your credential configuration file. Claude Code addresses Google Cloud’s Agent Platform requests to the project in `ANTHROPIC_VERTEX_PROJECT_ID`, even when `GCLOUD_PROJECT`, `GOOGLE_CLOUD_PROJECT`, or the credential file referenced by `GOOGLE_APPLICATION_CREDENTIALS` carries a different project. -#### - -​ - -Advanced credential configuration +#### Advanced credential configuration Claude Code supports automatic credential refresh for GCP through the `gcpAuthRefresh` setting. Add it to your Claude Code [settings file](</docs/en/settings>), for example `~/.claude/settings.json`. When Claude Code detects that your GCP credentials are expired or cannot be loaded, it runs the configured command to obtain new credentials before retrying the request. @@ -114,11 +82,7 @@ Before running the command, Claude Code requests an access token with your current credentials to confirm they’re actually expired, and skips the command when they still work. If the check doesn’t finish within five seconds, Claude Code also skips the command and runs it only after a request fails with a credential error. Before v2.1.261, a check that timed out counted as an expired credential, so the command could open your browser at startup even though your credentials were still valid. Claude Code shows you the command’s output, but can’t send the command interactive input. This works well for browser-based authentication flows where the CLI shows a URL and you complete authentication in the browser. The refresh command times out after three minutes if authentication does not complete. If you set `gcpAuthRefresh` in project settings such as `.claude/settings.json`, Claude Code runs it under the same [workspace trust rule as hooks in settings files](</docs/en/permissions#what-runs-before-you-trust-a-folder>), which includes `-p` sessions in folders you’ve never trusted. -### - -​ - -4\. Configure Claude Code +### 4\. Configure Claude Code Set the following environment variables: @@ -146,11 +110,7 @@ Set `ENABLE_TOOL_SEARCH=false` to disable tool search on every model. -### - -​ - -5\. Pin model versions +### 5\. Pin model versions Pin specific model versions when deploying to multiple users. Without pinning, model aliases such as `sonnet` and `opus` resolve to Claude Code’s built-in default for Google Cloud’s Agent Platform, which can lag the newest release and may not yet be enabled in your project. Claude Code falls back to an earlier or lower-tier model at startup when the default is unavailable, but pinning lets you control when your users move to a new model. @@ -179,19 +139,11 @@ export ANTHROPIC_MODEL='claude-opus-4-8' export ANTHROPIC_DEFAULT_HAIKU_MODEL='claude-haiku-4-5@20251001' -### - -​ - -6\. Verify your configuration +### 6\. Verify your configuration Start Claude Code and run `/status` to confirm the setup. The `API provider` line shows `Google Vertex AI`, and the `GCP project`, `Default region`, and `Model` lines show your project ID, region, and resolved model. If the provider line is missing, the environment variables aren’t reaching the process. Confirm they are exported in the shell where you launched `claude`, or set them in the `env` block of your [settings file](</docs/en/settings>). -## - -​ - -Startup model checks +## Startup model checks When Claude Code starts with Google Cloud’s Agent Platform configured, it verifies that the models it intends to use are accessible in your project. You may have pinned a model version that is older than the current Claude Code default. If your project can invoke the newer version, Claude Code prompts you to update the pin: @@ -200,27 +152,15 @@ For a pin in the `env` block of [managed settings](</docs/en/managed-settings>), Claude Code runs no check and shows no prompt. If the update prompt still appears for this pin, update Claude Code to v2.1.314 or later. Before v2.1.314, the managed pin stayed in effect after you accepted, so the prompt came back at the next start. If you have not pinned a model and the current default is unavailable in your project, Claude Code falls back for the current session and shows a notice. It tries earlier versions of the default model first and, when the default is an Opus model and no Opus version is available, falls back to the default Sonnet model. The fallback is not persisted. Enable the newer model in [Model Garden](<https://console.cloud.google.com/vertex-ai/model-garden>) or pin a version to make the choice permanent. -### - -​ - -Start a session on a specific model +### Start a session on a specific model When you start the session on a specific Sonnet or Opus version, for example with `--model`, `ANTHROPIC_MODEL`, or the [`model` setting](</docs/en/settings-reference#model>), that version acts as the session’s pinned default for the matching `sonnet` or `opus` alias. Claude Code skips the availability check for the built-in default your model replaces and starts on the model you configured, with no fallback notice. When you start a session on a model alias such as `opus` or on a model ID Claude Code doesn’t recognize, that value doesn’t act as a pin. -### - -​ - -Remembered model refusals +### Remembered model refusals When the startup model checks find a model your project can’t invoke, Claude Code can remember the refusal on this machine for up to a day. Once ten minutes have passed since the last check, Claude Code checks a remembered refusal of a current default model again at launch. A default your administrator re-enables then comes back. To turn the memory off, set [`CLAUDE_CODE_SKIP_MODEL_ACCESS_MEMORY=1`](</docs/en/env-vars>). -### - -​ - -When your organization enforces a model allowlist +### When your organization enforces a model allowlist If you set [`enforceAvailableModels`](</docs/en/model-config#enforce-the-allowlist-for-the-default-model>) in managed settings, the startup model checks use only models your `availableModels` list permits. This requires Claude Code v2.1.287 or later. A list without `enforceAvailableModels` doesn’t restrict these checks. The checks compare each entry with the model ID they would send to Agent Platform, so write the list in those IDs. This example permits Opus 4.8 and Sonnet 4.5: @@ -231,19 +171,16 @@ For aliases, version prefixes, and `modelOverrides` entries, see [Pin models for third-party deployments](</docs/en/model-config#pin-models-for-third-party-deployments>). -### - -​ - -When a model is disabled mid-session - -If your project loses access to the model your session is running on, for example because an administrator disables it in [Model Garden](<https://console.cloud.google.com/vertex-ai/model-garden>), Claude Code switches the session to another model instead of failing each request, and shows `Switched to <fallback> because <model> is not available`. It tries the same models as the startup fallback: earlier versions of the same tier first and, for an Opus session with no Opus version available, the default Sonnet model. The switch applies only to a tier you haven’t pinned, the same condition as the startup fallback. A session on a specific version you picked keeps its model and, without a fallback model chain, the request fails instead. In [auto mode](</docs/en/permission-modes#enable-auto-mode-on-bedrock-agent-platform-or-foundry>), Claude Code switches only to a model auto mode supports on Agent Platform. If none of those models is available either, the request fails. A [fallback model chain](</docs/en/model-config#fallback-model-chains>) you configure replaces the tier switch: on these refusals Claude Code switches to your configured fallback instead. To have refused requests fail rather than switch, set [`CLAUDE_CODE_DISABLE_MODEL_ACCESS_FALLBACK=1`](</docs/en/env-vars>). A fallback chain you configured still switches on these refusals; remove the chain as well if you want every refused request to fail. - -## - -​ - -IAM configuration +### When a model is disabled mid-session + +When Agent Platform rejects your session’s model as unavailable in your project or region, Claude Code switches your session to another model, and you can keep working. You see a message that starts with `Switched to <fallback> because <model> is not available`. This happens, for example, when an administrator disables the model in [Model Garden](<https://console.cloud.google.com/vertex-ai/model-garden>) or it isn’t served in your region. If you configured a [fallback model chain](</docs/en/model-config#fallback-model-chains>), Claude Code switches to your configured fallback instead. Without a chain, the request fails in cases such as these: + + * Your session is on a pinned model or a specific version you picked + * None of the models Claude Code tries is available. In [auto mode](</docs/en/permission-modes#enable-auto-mode-on-bedrock-agent-platform-or-foundry>), Claude Code only switches to a model auto mode supports on Agent Platform. + +To keep working, run `/model` in the session and press `s` on a model available in your project and region, which leaves your default unchanged. To have rejected requests fail instead of switching, set [`CLAUDE_CODE_DISABLE_MODEL_ACCESS_FALLBACK=1`](</docs/en/env-vars>). If you configured a fallback model chain, remove it as well, because Claude Code still moves to that fallback. + +## IAM configuration Assign the `roles/aiplatform.user` role, which includes the required permissions: @@ -253,19 +190,11 @@ Create a dedicated GCP project for Claude Code to simplify cost tracking and access control. -## - -​ - -1M token context window +## 1M token context window Fable models, Sonnet 5 and later, and Opus 4.7 and later run with the [1M token context window](<https://platform.claude.com/docs/en/build-with-claude/context-windows#context-window-sizes-by-model>) by default on Google Cloud’s Agent Platform, with no `[1m]` suffix needed. To keep a 200K window instead, set [`CLAUDE_CODE_DISABLE_1M_CONTEXT=1`](</docs/en/model-config#turn-off-1m-context>). Opus 4.6 and Sonnet 4.6 reach the 1M window when you select their `[1m]` variant. The setup wizard offers a 1M context option when it pins models. To enable it for a manually pinned model instead, append `[1m]` to the model ID. See [Pin models for third-party deployments](</docs/en/model-config#pin-models-for-third-party-deployments>) for details, including how to use the 1M window without changing the pin. Before v2.1.287, the Fable models and Opus 4.7 and later ran with a 200K window by default on Google Cloud’s Agent Platform and reached the 1M window through a `[1m]` suffix. -## - -​ - -Troubleshooting +## Troubleshooting If you encounter “Could not load the default credentials” errors: @@ -290,11 +219,7 @@ * For regional endpoints, ensure the primary model and small/fast model are supported in your selected region * Consider switching to `CLOUD_ML_REGION=global` for better availability -## - -​ - -Additional resources +## Additional resources * [Google Cloud’s Agent Platform documentation](<https://cloud.google.com/vertex-ai/docs>) * [Google Cloud’s Agent Platform pricing](<https://cloud.google.com/vertex-ai/pricing>)
modified Run Claude Code programmatically View current →
Show diff (279 lines)
--- a/headless.md +++ b/headless.md @@ -4,11 +4,7 @@ This page covers using the Agent SDK via the CLI (`claude -p`). For the Python and TypeScript SDK packages with structured outputs, tool approval callbacks, and native message objects, see the [full Agent SDK documentation](</docs/en/agent-sdk/overview>). -## - -​ - -Basic usage +## Basic usage Add the `-p` (or `--print`) flag to any `claude` command to run it non-interactively. Not every [CLI option](</docs/en/cli-reference>) combines with `-p`. Claude Code rejects `--bg`, and rejects `--cloud` with a task description, with an error naming the conflict; `--cloud` with a session ID and `-p` instead [queues a message into that cloud session](</docs/en/claude-code-on-the-web#send-follow-ups-from-the-cli>) and exits. Options you’ll combine with `-p` often include: @@ -22,11 +18,7 @@ Claude Code exits with code 0 on success and a non-zero code when the run fails, so your scripts can branch on the exit status. If you pass an invalid flag, Claude Code reports the error to stderr before the run starts. When a failure happens inside the run, such as missing authentication, Claude Code prints the failure as the result on stdout. -### - -​ - -Start faster with bare mode +### Start faster with bare mode Add `--bare` to reduce startup time by skipping auto-discovery of hooks, skills, custom commands, [subagents](</docs/en/sub-agents>), installed plugins, MCP servers, auto memory, and CLAUDE.md. Without it, `claude -p` discovers and loads them as an interactive session would, including anything configured in the working directory or `~/.claude`. Bare mode is useful for CI and scripts where you need the same result on every machine. A hook in a teammate’s `~/.claude` or an MCP server in the project’s `.mcp.json` won’t run, because bare mode never reads them. A directory you name with `--add-dir` is a partial exception: bare mode loads skills from its `.claude/skills/` folder, but still skips its `.claude/commands/` and `.claude/agents/` folders. [Skills from additional directories](</docs/en/skills#skills-from-additional-directories>) covers what does and doesn’t load. Without `--bare`, a `-p` session runs the hooks in a project’s `.claude/settings.json` and connects the servers in its `.mcp.json`, even in a folder you’ve never trusted. A `-p` session shows no workspace trust dialog and no per-server approval prompt. [What runs before you trust a folder](</docs/en/permissions#what-runs-before-you-trust-a-folder>) covers each kind of repository content under `-p` and how to keep it out. This example runs a one-off summarize task in bare mode and pre-approves the Read tool so the call completes without a permission prompt. Set `ANTHROPIC_API_KEY` before running it, because bare mode doesn’t use your subscription login: @@ -52,11 +44,7 @@ `--bare` is the recommended mode for scripted and SDK calls, and will become the default for `-p` in a future release. -### - -​ - -Background tasks at exit +### Background tasks at exit After Claude finishes its turn and stdin has closed, a `claude -p` run can stay open to wait for background work that Claude started. Unless a background command that the main conversation started is still running, Claude Code stops whatever is still running after 10 minutes of continuous idle waiting by default and drops its partial result. To change the 10-minute cap, set [`CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS`](</docs/en/env-vars>), or set it to `0` to wait without one. The run waits for background work such as background commands, subagents and workflows, Monitor watches, and pending `/loop` wakeups: @@ -67,22 +55,14 @@ 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. -#### - -​ - -MCP work when a non-interactive run ends +#### MCP work when a non-interactive run ends A `claude -p` run doesn’t wait for MCP work in the background: * **[MCP tasks](</docs/en/mcp#mcp-tasks-that-run-on-the-server>)** : on a remote server the job goes on. To follow it again, [resume that session](</docs/en/mcp#exit-clear-or-resume-while-an-mcp-task-runs>), not as a one-shot `claude -p "<prompt>"` run. * **MCP calls that[automatic backgrounding](</docs/en/mcp#automatic-backgrounding-of-long-tool-calls>) moved**: the call’s result is lost. -### - -​ - -Stop a run with SIGTERM +### Stop a run with SIGTERM If you stop a `claude -p` run with SIGTERM, for example with `kill` or from a process supervisor, Claude Code exits with code 143. Claude Code leaves the turn that was in progress unfinished and records no result for it. To end the turn instead, send SIGINT, or call the Agent SDK’s `interrupt()`, before you stop the process. On SIGTERM, Claude Code terminates the process tree of any Bash command that is still running. Claude Code then runs [`SessionEnd` hooks](</docs/en/hooks#sessionend>) and exits. While exiting, Claude Code starts no new tool call, sends no new model request, and runs no hook other than `SessionEnd`. If the run was in the middle of a command or waiting on a permission prompt when the signal arrived, Claude Code handles that step as follows: @@ -91,27 +71,15 @@ When you resume the session, Claude Code leaves the interrupted turn as it is, and your next prompt drives the conversation. To have Claude Code continue the interrupted turn on resume instead, set [`CLAUDE_CODE_RESUME_INTERRUPTED_TURN=1`](</docs/en/env-vars>). -### - -​ - -If the working directory is deleted +### If the working directory is deleted If the working directory of a `claude -p` or Agent SDK session is deleted mid-session, the session keeps running. When a turn starts while the directory is missing, Claude Code emits a [warning message](</docs/en/agent-sdk/typescript#sdkinformationalmessage>) in `stream-json` output, and shell commands fail until the directory exists again. -## - -​ - -Examples +## Examples These examples highlight common CLI patterns. Where a command names a file such as `auth.py` or `build-error.txt`, substitute a file from your own project. In CI or other scripted environments, add `--bare` so Claude Code starts without loading the host’s hooks, plugins, auto memory, or `CLAUDE.md`. -### - -​ - -Pipe data through Claude +### Pipe data through Claude Non-interactive mode reads stdin, so you can pipe data in and redirect the response out like any other command-line tool. This example pipes a build log into Claude and writes the explanation to a file: @@ -123,11 +91,7 @@ If Claude Code can’t read stdin, for example because the process that started it disconnected its end, Claude Code prints a warning to stderr and continues with the prompt from the command line. -### - -​ - -Add Claude to a build script +### Add Claude to a build script You can wrap a non-interactive call in a script to use Claude as a project-specific linter or reviewer. This `package.json` script pipes the diff against `main` into Claude and asks it to report typos. Piping the diff means Claude doesn’t need Bash permission to read it, and the escaped double quotes keep the script portable to Windows: @@ -139,11 +103,7 @@ Run it with `npm run lint:claude`. -### - -​ - -Get structured output +### Get structured output Use `--output-format` to control how responses are returned: @@ -174,11 +134,7 @@ --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' \ | jq '.structured_output' -### - -​ - -Stream responses +### Stream responses Use `--output-format stream-json` with `--verbose` and `--include-partial-messages` to receive tokens as they’re generated. Each line is a JSON object representing an event: @@ -191,11 +147,7 @@ For programmatic streaming with callbacks and message objects, see [Stream responses in real-time](</docs/en/agent-sdk/streaming-output>) in the Agent SDK documentation. -#### - -​ - -Follow subagent messages +#### Follow subagent messages Messages from [subagents](</docs/en/sub-agents>) and from skills that [run in a subagent](</docs/en/skills#run-skills-in-a-subagent>) appear in the stream as `assistant` and `user` messages. Their `parent_tool_use_id` field says which run each one belongs to. Messages from the main conversation carry `null` in that field. The first message from a forked skill, or from a subagent running in the [foreground](</docs/en/sub-agents#run-subagents-in-foreground-or-background>), is a `user` message carrying the prompt or skill content that drives it. After that first message, Claude Code emits: @@ -216,11 +168,7 @@ * **Messages of subagents that a forked skill spawns, and of forked skills started inside a subagent or another forked skill** : v2.1.275 or later * **Messages of a forked skill you start by passing`/<skill-name>` as the prompt**: v2.1.287 or later -#### - -​ - -Handle API retries +#### Handle API retries When an API request fails with a retryable error, Claude Code emits a `system/api_retry` event before retrying. On v2.1.246 or later, when a `401` or `403` rejects an [`apiKeyHelper`](</docs/en/settings-reference#apikeyhelper>) credential, Claude Code makes the first two retries quietly with no event, then emits the event as usual from the third consecutive retry onward. The quiet retries still count toward `attempt`. You can use the event to show retry progress in your own interface. @@ -237,11 +185,7 @@ `uuid`| string| unique event identifier `session_id`| string| session the event belongs to -#### - -​ - -Read session metadata +#### Read session metadata The `system/init` event reports session metadata including the model, tools, MCP servers, and loaded plugins. It is the first event in the stream unless startup events precede it: @@ -250,11 +194,7 @@ The event also carries an optional `capabilities` array of strings naming the protocol behaviors this Claude Code version implements, such as `interrupt_receipt_v1` or `interrupt_cancel_queued_v1`. Check it to feature-detect instead of comparing version strings, and ignore values you don’t recognize. See [`SDKSystemMessage`](</docs/en/agent-sdk/typescript#sdksystemmessage>) for the capability list. -#### - -​ - -Fail CI when a plugin or MCP server doesn’t load +#### Fail CI when a plugin or MCP server doesn’t load Use the plugin fields in the `system/init` event to catch a plugin that didn’t load: @@ -272,11 +212,7 @@ When you run the command yourself in a terminal, Claude Code also prints a startup warning to stderr, such as `Warning: 1 MCP server skipped due to invalid config:`, followed by the reason for each skipped entry. When you redirect stderr, or when a program such as a CI runner or an SDK host captures it, Claude Code prints no warning. It reports the skipped entries only in the `mcp_server_errors` field. -#### - -​ - -Track plugin installs +#### Track plugin installs When [`CLAUDE_CODE_SYNC_PLUGIN_INSTALL`](</docs/en/env-vars>) is set, Claude Code emits `system/plugin_install` events while marketplace plugins install before the first turn. Use these to surface install progress in your own UI. @@ -290,11 +226,7 @@ `uuid`| string| unique event identifier `session_id`| string| session the event belongs to -### - -​ - -Auto-approve tools +### Auto-approve tools Use `--allowedTools` to let Claude use certain tools without prompting. Listing `Read` and `Edit` lets Claude read and edit files without asking for permission, apart from reads from [network paths](</docs/en/permissions#network-paths>). Listing `Bash` does the same for shell commands, except in a run that starts in [auto mode](</docs/en/permission-modes#how-auto-mode-evaluates-actions>), where Claude Code drops a bare `Bash` entry as a broad allow rule and auto mode evaluates each command instead. This example runs a test suite and fixes failures with those three tools listed: @@ -311,11 +243,7 @@ claude -p "Apply the lint fixes" --permission-mode acceptEdits -### - -​ - -Turn off permission prompts in unattended runs +### Turn off permission prompts in unattended runs Pass `--permission-prompts none` when nobody is available to answer permission prompts, for example in a scheduled job. The flag matters most when your run has a permission host: an Agent SDK app with a [`canUseTool` callback](</docs/en/agent-sdk/user-input>), or an MCP tool you pass with [`--permission-prompt-tool`](</docs/en/cli-reference#cli-flags>). Without the flag, your run waits for that host to answer each permission request. With the flag, your run doesn’t consult the host or wait on it. Anything that would prompt is denied unless a `PermissionRequest` hook allows it, Claude is told that nobody can approve the request and not to retry it, and the run continues. In a `-p` run with no host, these requests are denied either way, and the flag also tells Claude not to retry them. Permission rules, [`PermissionRequest` hooks](</docs/en/hooks#permissionrequest>), and the permission mode you set still decide every call first; Claude Code denies only the requests that nothing else resolves. This example runs an unattended task in [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>). The classifier reviews each action as usual, and Claude Code denies anything that would have fallen back to a prompt: @@ -325,11 +253,7 @@ The `--permission-prompts` flag requires Claude Code v2.1.259 or later. Earlier versions reject it with an unknown-option error. -### - -​ - -Create a commit +### Create a commit This example reviews staged changes and creates a commit with an appropriate message: @@ -346,11 +270,7 @@ * To change a setting, pass `key=value` to `/config`, for example `/config thinking=false`. * `/output-style <style>` switches [output styles](</docs/en/output-styles>) and `/output-style` alone lists them. Requires Claude Code v2.1.269 or later. -### - -​ - -Customize the system prompt +### Customize the system prompt Use `--append-system-prompt` to add instructions while keeping Claude Code’s default behavior. This example pipes a PR diff to Claude and instructs it to review for security vulnerabilities. Save it as a shell script, for example `review.sh`: @@ -360,11 +280,7 @@ In the script, `"$1"` stands for the first argument you pass on the command line. Run `bash review.sh 123` and the shell replaces `"$1"` with `123`, so the script fetches the diff for PR 123. Claude Code prints the review as JSON, with the text in the `result` field. See [system prompt flags](</docs/en/cli-reference#system-prompt-flags>) for more options including `--system-prompt` to fully replace the default prompt. If you replace it, the run also starts without the [git status snapshot](</docs/en/settings-reference#includegitinstructions>). -### - -​ - -Continue conversations +### Continue conversations Use `--continue` to continue the most recent conversation, or `--resume` with a session ID to continue a specific conversation. On Claude Code v2.1.257 or later, when you pass `--continue`, Claude Code opens a [background session](</docs/en/sessions#where-the-session-picker-looks>) that has finished, but not one that is still running. This example runs a review, then sends follow-up prompts: @@ -382,11 +298,7 @@ You can run the two commands from different directories: Claude Code [finds the session by its ID](</docs/en/sessions#where-the-session-picker-looks>) in any project on this machine. In place of the session ID, you can pass `--resume` the absolute path to a session’s `.jsonl` [transcript file](</docs/en/sessions#where-transcripts-are-stored>), and Claude Code continues the conversation stored in that file. -## - -​ - -Next steps +## Next steps * [Agent SDK quickstart](</docs/en/agent-sdk/quickstart>): build your first agent with Python or TypeScript * [CLI reference](</docs/en/cli-reference>): all CLI flags and options
modified Set up Claude Code (local mode) for a HIPAA-ready organization View current →
Show diff (243 lines)
--- a/hipaa-setup.md +++ b/hipaa-setup.md @@ -16,19 +16,11 @@ After it’s applied| The Code tab is off until an Owner turns it back on. Confirm the configuration on a computer Ongoing| Manage local session data -## - -​ - -Prepare computers before the HIPAA configuration is applied +## Prepare computers before the HIPAA configuration is applied We recommend you start with the tasks in this section and complete them before the configuration is applied. -### - -​ - -Check how developers sign in and connect +### Check how developers sign in and connect The HIPAA configuration takes effect only in sessions where a developer signs in with a Claude Enterprise account and Claude Code connects directly to the Claude API. On any other connection, developers can keep using Claude Code, but it doesn’t apply the HIPAA configuration. The table shows which connections are eligible. To find out whether your BAA covers a session in a “No” row, see [Use Claude Code (local mode) and Cowork (local mode) on a HIPAA-ready Enterprise plan](<https://support.claude.com/en/articles/17318731>). @@ -40,11 +32,7 @@ `ANTHROPIC_AUTH_TOKEN` or `apiKeyHelper`, on a computer with no Claude Enterprise sign-in| No A Claude Console API key or [federation credentials](</docs/en/authentication#anthropic-profiles-and-federation-credentials>)| No. These sessions belong to a Claude Console organization, which has its own agreement and settings -#### - -​ - -Check how a computer connects +#### Check how a computer connects Open a terminal on the computer, run `claude`, and enter `/status` at the prompt. The **Status** tab shows these lines: @@ -56,11 +44,7 @@ If a computer uses a connection that isn’t eligible for the HIPAA configuration, you can use managed settings to block cloud providers, gateways, and credentials set with `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, or `apiKeyHelper`. -### - -​ - -Update Claude Code and Claude Desktop +### Update Claude Code and Claude Desktop The HIPAA configuration requires Claude Code v2.1.285 or later and Claude Desktop v2.19675.0 or later. If your organization uses both the terminal and the [Claude Desktop app](</docs/en/desktop>), update both. To read the installed Claude Code version, run this command in a terminal. It’s the same in Bash, Zsh, and PowerShell: @@ -68,11 +52,7 @@ A supported installation prints `2.1.285 (Claude Code)` or a higher number. To read the installed Claude Desktop version, see [Check your version](</docs/en/desktop#check-your-version>). -#### - -​ - -What developers see on an older version +#### What developers see on an older version For organizations with the HIPAA configuration, Anthropic’s servers reject requests from versions older than the minimum version. Anthropic raises the minimum version over time, and there’s nothing for you to configure. @@ -83,11 +63,7 @@ To keep developers on a supported version, [keep Claude Code updated](</docs/en/setup#update-claude-code>). For Claude Desktop, see [Update Claude Desktop](<https://claude.com/docs/cowork/hipaa-setup#update-claude-desktop>). -### - -​ - -Allow network access +### Allow network access Allow the hosts in this table through your proxy and firewall, over HTTPS on port 443. Allow each whole host, not individual paths. @@ -107,11 +83,7 @@ Sessions that go through a corporate HTTPS proxy are still eligible for the HIPAA configuration, as long as the proxy can reach the hosts in the table. Claude Code learns that your organization has the HIPAA configuration by fetching your organization’s policy from `api.anthropic.com`, when it starts and again about every hour while the session is in use. The policy is a record of your organization’s HIPAA status and the feature restrictions that follow from it. To check whether one computer has fetched the policy, see Confirm the configuration on a computer. -### - -​ - -Deploy managed settings +### Deploy managed settings You can use [managed settings](</docs/en/managed-settings>) to direct developers to sign in with a Claude Enterprise account, to block cloud providers and gateways, and to set how many days every computer keeps local session data. The settings apply whether or not the HIPAA configuration is in effect. The settings in this section are a sample that we recommend as a starting point. Your organization is responsible for deciding what its own environment needs and for confirming that its configuration meets those needs. The following sample sets four keys that you could add to the [managed settings](</docs/en/managed-settings#choose-a-delivery-mechanism>) your organization deploys: @@ -124,11 +96,7 @@ 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>). -#### - -​ - -What each key does +#### What each key does The table shows what to set each key to and what Claude Code enforces for it. @@ -143,19 +111,11 @@ The HIPAA configuration doesn’t limit `cleanupPeriodDays`, so a developer can raise it in their own settings. When you set it in managed settings, Claude Code ignores the developer’s value. With `forceLoginMethod` or `forceLoginOrgUUID` set, Claude Code also refuses sessions that authenticate with `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, or `apiKeyHelper`. -#### - -​ - -Confirm the settings loaded +#### Confirm the settings loaded On a computer that has the settings, run `claude`, sign in with a Claude Enterprise account, and enter `/status`. The `Setting sources` line lists `Enterprise managed settings` followed by the source in parentheses, such as `(file)`, and the `Allowed providers` line reads `Anthropic API (managed allowedProviders)`. If `Setting sources` doesn’t list it, or the `Allowed providers` line is missing, see [Check that a policy is in force](</docs/en/managed-settings#check-that-a-policy-is-in-force>). -#### - -​ - -Sessions the managed settings keys don’t block +#### Sessions the managed settings keys don’t block Even with these keys deployed, some sessions can still run without the HIPAA configuration: @@ -165,19 +125,11 @@ To find out whether your BAA covers a session that runs without the HIPAA configuration, see [Use Claude Code (local mode) and Cowork (local mode) on a HIPAA-ready Enterprise plan](<https://support.claude.com/en/articles/17318731>). -### - -​ - -Restrict Claude Desktop sign-in +### Restrict Claude Desktop sign-in If developers use the Code tab of Claude Desktop, also set `forceLoginOrgUUID` in the Claude Desktop policy, as [Restrict sign-in to your organization](</docs/en/desktop#restrict-sign-in-to-your-organization>) describes. Deploying `forceLoginMethod` and `forceLoginOrgUUID` in managed settings doesn’t change the Claude Desktop sign-in screen. -## - -​ - -Confirm the configuration on a computer +## Confirm the configuration on a computer Run this check on one managed computer after the configuration is applied to your organization. @@ -217,11 +169,7 @@ 2. **A blocked policy fetch** : look for an `Organization policy` line in `/status`, which gives the cause. Outside a session, run `claude doctor` and read the same line, which says where Claude Code loaded the policy from or why the policy didn’t load. Allow `api.anthropic.com` through your proxy, then restart Claude Code. 3. **The configuration isn’t applied yet** : ask the Primary Owner whether they have applied the configuration. -## - -​ - -What developers see in Claude Code +## What developers see in Claude Code With the HIPAA configuration applied, some Claude Code features are off or behave differently in the terminal. The table lists the changes developers are most likely to ask you about. The [HIPAA feature availability table](<https://support.claude.com/en/articles/8114513-business-associate-agreements-baa-for-commercial-customers>) lists every Claude Code and Cowork feature, including the ones an Owner can turn back on. @@ -235,35 +183,19 @@ An MCP server or hook that reads `ANTHROPIC_API_KEY` stops authenticating| Claude Code removes Anthropic credentials from the processes it starts Restrictions remain after `/login` to a different organization| The HIPAA status lasts until Claude Code restarts -### - -​ - -Anthropic credentials in commands, hooks, and MCP servers +### Anthropic credentials in commands, hooks, and MCP servers With the HIPAA configuration applied, Claude Code removes the credentials it uses to reach Anthropic, such as `ANTHROPIC_API_KEY` and `ANTHROPIC_AUTH_TOKEN`, from the environment of the shell commands, hooks, and MCP servers it starts. The HIPAA configuration doesn’t remove cloud provider or GitHub credentials, so a command that pushes to GitHub or calls another service still works with that developer’s access. Your BAA with Anthropic doesn’t cover the data it sends there. See the [Implementation Guide](<https://trust.anthropic.com/resources?s=l1wrssd9hsbi4gak0tp5a6&name=%5Banthropic%5D-hipaa-ready-offering-implementation-guide>) for the full list of Eligible Services. To limit which commands and hosts Claude can use, see [permission rules](</docs/en/permissions>) and the [sandbox](</docs/en/sandboxing>). -## - -​ - -Manage local session data +## Manage local session data Claude Code (local mode) and Cowork (local mode) store session data on each developer’s computer. Securing and deleting that data is your organization’s responsibility. -### - -​ - -Claude Code data +### Claude Code data [Application data](</docs/en/claude-directory#application-data>) lists what Claude Code (local mode) stores on a computer, what its retention sweep deletes after `cleanupPeriodDays`, and what stays until someone deletes it. The same page states what differs in an organization with the HIPAA configuration applied. The retention sweep runs only when someone starts Claude Code, so a computer where nobody starts it keeps its data. -### - -​ - -Code tab data +### Code tab data The Code tab stores data in these places: @@ -274,19 +206,11 @@ On Windows, `~` means `%USERPROFILE%`. -### - -​ - -Cowork data +### Cowork data [Manage Cowork data on each computer](<https://claude.com/docs/cowork/hipaa-setup#manage-cowork-data-on-each-computer>) lists where Cowork (local mode) stores data and what Claude Desktop deletes. -### - -​ - -Delete session data right away +### Delete session data right away If your organization needs a developer’s session data removed before the retention sweep deletes it, you can remove most of it with one command. Sign in to the computer as that developer, open any shell, and run the command for the installed Claude Code version. On Claude Code v2.1.288 or later, run `claude purge`: @@ -298,19 +222,11 @@ Either command deletes every project’s transcripts and auto memory, the entries in `tasks/`, `debug/`, and `file-history/`, `history.jsonl`, and the project entries in `~/.claude.json`. Without `--yes`, it prints the plan and asks first. The purge leaves other paths that can hold session content, such as pasted text in `paste-cache/`. [Clear local data](</docs/en/claude-directory#clear-local-data>) lists the paths you can delete by hand. To clear a computer completely, for example before you reassign it, wipe it. -### - -​ - -Offboard a developer +### Offboard a developer Removing a developer’s seat or account deletes nothing on their computer, and `/logout` doesn’t delete session data either. To remove all of it, you can wipe the computer with your device management tool. -## - -​ - -Related resources +## Related resources * [Set up Cowork (local mode) for a HIPAA-ready organization](<https://claude.com/docs/cowork/hipaa-setup>) * [Deploy managed settings](</docs/en/managed-settings>)
modified Intercept and control agent behavior with hooks View current →
Show diff (379 lines)
--- a/hooks.md +++ b/hooks.md @@ -6,11 +6,7 @@ * **Require human approval** for sensitive actions like database writes or API calls * **Track session lifecycle** to manage state, clean up resources, or send notifications -## - -​ - -How hooks work +## How hooks work 1 @@ -141,11 +137,7 @@ The `Write|Edit` matcher limits this hook to the Write and Edit tools. If Claude writes `.env` with a Bash command, the hook doesn’t run. To block Bash writes to a file where [the sandbox runs](</docs/en/sandboxing>), see the sandbox configuration for [Python](</docs/en/agent-sdk/python#sandbox-configuration>) or [TypeScript](</docs/en/agent-sdk/typescript#sandbox-configuration>). -## - -​ - -Available hooks +## Available hooks The SDK provides hooks for different stages of agent execution. Some hooks are available in both SDKs, while others are TypeScript-only. @@ -185,11 +177,7 @@ `FileChanged`| No| Yes| A watched file is modified, created, or deleted| Reload configuration when project files change `DirectoryAdded`| No| Yes| A working directory is added during a session| Install dependencies for a repository added mid-session -## - -​ - -Configure hooks +## Configure hooks To configure a hook, pass it in the `hooks` field of your agent options (`ClaudeAgentOptions` in Python, the `options` object in TypeScript). This snippet assumes you have already defined a hook callback, like `protect_env_files` in Python or `protectEnvFiles` in TypeScript from the example above: @@ -222,11 +210,7 @@ * **Keys** : hook event names such as `'PreToolUse'`, `'PostToolUse'`, and `'Stop'` * **Values** : arrays of matchers, each containing an optional filter pattern and your callback functions -### - -​ - -Matchers +### Matchers Use matchers to filter when your callbacks fire. The `matcher` field matches against a different value depending on the hook event type. For example, tool-based hooks match against the tool name, while `Notification` hooks match against the notification type. SDK matchers follow the same rules as [matchers in settings files](</docs/en/hooks#matcher-patterns>). That section documents the exact-string and regular-expression evaluation paths, their version requirements, and the matcher values for each event type. @@ -239,17 +223,9 @@ Use the `matcher` pattern to target specific tools whenever possible. With a `'Bash'` matcher, your callbacks run for Bash commands. On Claude Code v2.1.314 or later, they also run on `PreToolUse` and `PermissionRequest` for Monitor commands, which they [can deny but not approve](</docs/en/hooks#match-monitor-commands>). With no matcher, they run for every occurrence of the event. -### - -​ - -Callback functions - -#### - -​ - -Inputs +### Callback functions + +#### Inputs Every hook callback receives three arguments: @@ -259,11 +235,7 @@ * **Tool use ID** (`str | None` / `string | undefined`): correlates `PreToolUse` and `PostToolUse` events for the same tool call. * **Context:** in TypeScript, contains a `signal` property (`AbortSignal`) for cancellation. In Python, this argument is reserved for future use. -#### - -​ - -Outputs +#### Outputs Your callback returns an object with two categories of fields: @@ -277,11 +249,7 @@ When multiple `PreToolUse` hooks return different [decisions](</docs/en/hooks#pretooluse-decision-control>), `deny` takes priority over `defer`, which takes priority over `ask`, which takes priority over `allow`. -#### - -​ - -Asynchronous output +#### Asynchronous output By default, the agent waits for your hook to return before proceeding. If your hook performs a side effect, such as logging or sending a webhook, and doesn’t need to influence the agent’s behavior, you can return an async output instead. This tells the agent to continue immediately without waiting for the hook to finish. In this snippet, `send_to_logging_service` in Python and `sendToLoggingService` in TypeScript stand in for any logging function you define: @@ -307,11 +275,7 @@ Async outputs can’t block, modify, or inject context into the operation since the agent has already moved on. Use them only for side effects like logging, metrics, or notifications. -### - -​ - -Block the action when a callback fails +### Block the action when a callback fails On most events, if a callback throws or returns output that fails validation, the action goes ahead and your app receives an [`SDKInformationalMessage`](</docs/en/agent-sdk/typescript#sdkinformationalmessage>) warning whose `tag` is `hook_callback_failed`. A `PreToolUse` guard that crashes then lets the tool call reach the normal permission flow. A callback that returns nothing, such as a path with no `return`, also counts as failing. In Python, read `tag` from `SystemMessage.data`. To block the action instead, set `onFailure: "block"` in TypeScript or `on_failure="block"` in Python on the matcher. Requires TypeScript Agent SDK v0.3.317 or later, or Python Agent SDK v0.2.177 or later. This example blocks a Bash call when `check_policy` in Python or `checkPolicy` in TypeScript fails: @@ -337,11 +301,7 @@ To test it, make the callback raise an error and ask Claude to run a Bash command. The tool result includes `failed; blocking because onFailure is "block"`, and Claude doesn’t see your error text. Return `{}` when the callback has no opinion. With `"block"` set, a path with no `return` blocks the action. A callback that catches its own error and returns `{}` isn’t failing, so let the error propagate from a guard. -#### - -​ - -Events that behave differently +#### Events that behave differently These events don’t always block with `"block"` set: @@ -351,30 +311,18 @@ A callback that exceeds its timeout follows Hook timeout. With `"block"` set, a timeout also blocks `PreCompact`, `Elicitation`, and `WorktreeCreate`. -#### - -​ - -Startup errors for `onFailure` +#### Startup errors for `onFailure` With `"block"` set, the query fails at startup and sends no prompt when it can’t honor the option: * **Claude Code doesn’t support the option** : the error includes `does not honor`. Update Claude Code, or remove the option. * **The session was already running and didn’t register your hooks** : the error includes `did not register your hooks`. Start a new session. -## - -​ - -Examples +## Examples Several examples in this section show only the callback function. To run one, register the callback under the matching event in the `hooks` field of your options, as shown in Configure hooks. -### - -​ - -Modify tool input +### Modify tool input This example intercepts Write tool calls and rewrites the `file_path` argument to prepend `/sandbox`. The callback returns `updatedInput` with the modified path and `permissionDecision: 'allow'` to auto-approve the rewritten operation: @@ -425,11 +373,7 @@ To confirm the redirect, set the prefix to a path you can write to, such as `./sandbox` or `/tmp/sandbox` (macOS doesn’t allow creating a root-level `/sandbox` directory), then ask the agent to write a file: the Write tool’s result in the message stream names the path with your sandbox prefix rather than the one Claude requested. -### - -​ - -Add context and block a tool +### Add context and block a tool This example denies tool calls whose `file_path` starts with `/etc` and explains why to both the model and the user: @@ -479,11 +423,7 @@ To confirm the block, register the callback under `PreToolUse` with a `Write|Edit` matcher and ask the agent to create a file under `/etc`: the Write tool’s result in the message stream contains `Writing to /etc is not allowed`, and no file is created. -### - -​ - -Auto-approve specific tools +### Auto-approve specific tools By default, the agent may prompt for permission before using certain tools. This example auto-approves read-only filesystem tools (Read, Glob, Grep) by returning `permissionDecision: 'allow'`, letting them run without user confirmation, apart from reads from [network paths](</docs/en/permissions#network-paths>), while leaving all other tools subject to normal permission checks: @@ -523,11 +463,7 @@ return {}; }; -### - -​ - -Register multiple hooks +### Register multiple hooks When an event fires, the matching hooks run in parallel. For permission decisions, the most restrictive result applies. One hook’s `deny` blocks the tool call. Because completion order is non-deterministic, write each hook to act independently rather than relying on another hook having run first. The example below registers three independent checks, each with an [omitted matcher](</docs/en/hooks#matcher-patterns>). The hook names in it, such as `audit_logger` in Python or `auditLogger` in TypeScript, stand in for callbacks you define: @@ -555,11 +491,7 @@ } }; -### - -​ - -Filter with multi-tool matchers +### Filter with multi-tool matchers Use multi-tool matchers to share one callback across related tools. This example registers three matchers with different scopes, and each hook it names stands in for a callback you define: @@ -599,11 +531,7 @@ } }; -### - -​ - -Track subagent activity +### Track subagent activity Use `SubagentStop` hooks to monitor when subagents finish their work. See the full input type in the [TypeScript](</docs/en/agent-sdk/typescript#hookinput>) and [Python](</docs/en/agent-sdk/python#hookinput>) SDK references. This example logs a summary each time a subagent completes: @@ -645,11 +573,7 @@ To confirm the hook fires, register the callback and ask the agent to delegate a small task to a subagent, such as listing the files in the current directory: when the subagent finishes, the callback prints the `[SUBAGENT] Completed:` lines with the subagent’s ID and transcript path. -### - -​ - -Make HTTP requests from hooks +### Make HTTP requests from hooks Hooks can perform asynchronous operations like HTTP requests. Catch errors inside your hook instead of letting them propagate. This example sends a webhook after each tool completes, logging which tool ran and when. The hook catches errors from a failed webhook: @@ -734,11 +658,7 @@ To confirm the hook fires, point the webhook URL at an endpoint you can watch and send a prompt that uses a tool: the hook sends a POST with the tool name and timestamp after each tool completes. -### - -​ - -Forward notifications to Slack +### Forward notifications to Slack Use `Notification` hooks to receive system notifications from the agent and forward them to external services. In SDK sessions, Claude Code runs this hook for the following notification types: @@ -838,17 +758,9 @@ When a `Notification` event fires, the hook posts the notification’s `message`, prefixed with `Agent status:`, to the channel your webhook targets. -## - -​ - -Fix common issues - -### - -​ - -Hook not firing +## Fix common issues + +### Hook not firing * Verify the hook event name is correct and case-sensitive (`PreToolUse`, not `preToolUse`) * Check that your matcher pattern matches the tool name exactly @@ -856,11 +768,7 @@ * For non-tool hooks that support matchers, like `Notification` and `SubagentStop`, matchers match against different fields, and `Stop` ignores matchers entirely (see [matcher patterns](</docs/en/hooks#matcher-patterns>)) * Hooks may not fire when the agent hits the [`max_turns`](</docs/en/agent-sdk/python#claudeagentoptions>) limit because the session ends before hooks can execute -### - -​ - -Matcher not filtering as expected +### Matcher not filtering as expected Matchers only match tool names, not file paths or other arguments. To filter by file path, check `tool_input.file_path` inside your hook: @@ -873,11 +781,7 @@ return {}; }; -### - -​ - -Hook timeout +### Hook timeout Claude Code runs each callback with a timeout, which you set in seconds with the `timeout` field on its `HookMatcher`. When you don’t set one, Claude Code uses the event’s default: 600 seconds for most events, 30 seconds for `UserPromptSubmit`, `PreModelSwitch`, and `PostModelSwitch`, and 10 seconds for `MessageDisplay`. Claude Code runs `SessionEnd` callbacks during shutdown under the shorter [SessionEnd timeout budget](</docs/en/hooks#sessionend-input>), 1.5 seconds by default. When a callback exceeds its timeout, Claude Code cancels it and discards its output, and the session continues rather than hanging. What happens next depends on the event: @@ -891,21 +795,13 @@ The first time a `Stop` or `SessionStart` callback times out in the main session, Claude Code also adds an [`SDKInformationalMessage`](</docs/en/agent-sdk/typescript#sdkinformationalmessage>) to the message stream saying the app driving the session didn’t respond. Later timeouts don’t repeat that message while your app stays unresponsive. If you interrupt the query while a callback is pending, Claude Code cancels the pending tool call. Before v2.1.208, the tool call could still proceed if you interrupted during a pending `PreToolUse` callback. If your callback needs more time, set a higher `timeout` on its `HookMatcher`. In TypeScript, use the `AbortSignal` from the third callback argument to handle cancellation gracefully when the timeout fires. -### - -​ - -Tool blocked unexpectedly +### Tool blocked unexpectedly * Check all `PreToolUse` hooks for `permissionDecision: 'deny'` returns * Add logging to your hooks to see what `permissionDecisionReason` they’re returning * Verify matcher patterns aren’t too broad: an empty matcher matches all tools -### - -​ - -Modified input not applied +### Modified input not applied * Ensure `updatedInput` is inside `hookSpecificOutput`, not at the top level: @@ -920,11 +816,7 @@ * Don’t pair `updatedInput` with `permissionDecision: 'defer'`, which drops the modified input. Omitting `permissionDecision` is fine: the modified input still applies through the normal permission evaluation. You can also return `'allow'` to auto-approve the modified input or `'ask'` to show it to the user for approval * Include `hookEventName` in `hookSpecificOutput` to identify which hook type the output is for -### - -​ - -Session hooks not available in Python +### Session hooks not available in Python `SessionStart` and `SessionEnd` can be registered as SDK callback hooks in TypeScript, but aren’t available in the Python SDK because its `HookEvent` type omits them. In Python, they are only available as [shell command hooks](</docs/en/hooks#hook-events>) defined in settings files such as `.claude/settings.json`. Which settings files your SDK application loads depends on [`setting_sources`](</docs/en/agent-sdk/python#settingsource>) or [`settingSources`](</docs/en/agent-sdk/typescript#settingsource>). If you set that option, include the source that holds the hooks: @@ -942,38 +834,22 @@ To run initialization logic as a Python SDK callback instead, use the first message from `client.receive_response()` as your trigger. -### - -​ - -Subagent permission prompts multiplying +### Subagent permission prompts multiplying When spawning multiple subagents, each one may request permissions separately for its own tool calls. To avoid repeated prompts, use `PreToolUse` hooks to auto-approve specific tools, or configure permission rules, which subagents [inherit from the parent conversation](</docs/en/sub-agents#permission-modes>). -### - -​ - -Recursive hook loops with subagents +### Recursive hook loops with subagents A `UserPromptSubmit` hook that spawns subagents can create infinite loops if those subagents trigger the same hook. To prevent this: * Use a shared variable or session state to track whether you’re already inside a subagent * Scope hooks to only run for the top-level agent session -### - -​ - -systemMessage not appearing in output +### systemMessage not appearing in output The `systemMessage` field shows a message to the user, not the model. On Claude Code v2.1.227 or later, a hook’s `systemMessage` can surface in the message stream as an [`SDKInformationalMessage`](</docs/en/agent-sdk/typescript#sdkinformationalmessage>). Whether it does depends on the event. Each [event’s section](</docs/en/hooks#hook-events>) on the hooks page says how output surfaces. To pass context to the model instead, return [`additionalContext`](</docs/en/hooks#add-context-for-claude>). Before v2.1.227, the SDK surfaced hook output in the message stream only for `SessionStart` and `Setup` hooks. For any other event, the output appeared only in the lifecycle events that [`includeHookEvents`](</docs/en/agent-sdk/typescript#options>) (`include_hook_events` in Python) adds. That option’s entry covers which lifecycle events each hook event produces. If you need to surface hook decisions to your application reliably, log them separately or use a dedicated output channel. -## - -​ - -Related resources +## Related resources * [Claude Code hooks reference](</docs/en/hooks>): full JSON input/output schemas, event documentation, and matcher patterns * [Claude Code hooks guide](</docs/en/hooks-guide>): shell command hook examples and walkthroughs
modified Automate actions with hooks View current →
Show diff (435 lines)
--- a/hooks-guide.md +++ b/hooks-guide.md @@ -2,11 +2,7 @@ This guide covers common use cases and how to get started. For full event schemas, JSON input/output formats, and advanced features like async hooks and MCP tool hooks, see the [Hooks reference](</docs/en/hooks>). -## - -​ - -Set up your first hook +## Set up your first hook To create a hook, add a `hooks` block to a settings file. This walkthrough creates a desktop notification hook, so you get alerted whenever Claude is waiting for your input instead of watching the terminal. @@ -39,7 +35,7 @@ "PostToolUse": [ { "matcher": "Edit|Write", - "hooks": [{ "type": "command", "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write" }] + "hooks": [{ "type": "command", "command": "f=$(jq -r '.tool_input.file_path') && npx prettier --write --ignore-unknown \"$f\"" }] } ], "Notification": [ @@ -65,19 +61,11 @@ Press `Esc` to return to the CLI. Press `Shift+Tab` until the status bar shows `⏸ manual mode on`, ask Claude to do something that requires permission, then switch away from the terminal. You should receive a desktop notification. -## - -​ - -What you can automate +## What you can automate Hooks let you run code at key points in Claude Code’s lifecycle: format files after edits, block commands before they execute, send notifications when Claude needs input, inject context at session start, and more. For the full list of hook events, see the [Hooks reference](</docs/en/hooks#hook-lifecycle>). Each example includes a ready-to-use configuration block that you add to a settings file. For a production example of hooks that run a separate model review and feed findings back into the session, see [how the `security-guidance` plugin integrates with Claude Code](</docs/en/security-guidance#how-the-plugin-integrates-with-claude-code>). -### - -​ - -Get notified when Claude needs input +### Get notified when Claude needs input Get a desktop notification whenever Claude finishes working and needs your input, so you can switch to other tasks without checking the terminal. This hook uses the `Notification` event, which Claude Code fires when Claude is waiting for input or permission. See [when each notification type fires](</docs/en/hooks#notification>) for the exact timing. Each tab below uses the platform’s native notification command. Add this to `~/.claude/settings.json`: @@ -176,11 +164,7 @@ Claude Code times `permission_prompt` differently in a terminal and in Claude Desktop, the VS Code extension, and other hosts that answer permission requests through the Agent SDK. See [when each notification type fires](</docs/en/hooks#notification>) for both timings. The `quota_auto_resume_fired`, `quota_auto_resume_stale`, and `quota_auto_resume_disabled` matchers require Claude Code v2.1.234 or later. The `auth_storage_failure` matcher requires v2.1.288 or later. In terminal sessions, `permission_prompt` for a sandboxed command’s network request requires Claude Code v2.1.246 or later. `agent_needs_input` for a teammate’s terminal setup question requires Claude Code v2.1.248 or later. Type `/hooks` at the Claude Code prompt and confirm the hook appears under `Notification`. -### - -​ - -Auto-format code after edits +### Auto-format code after edits Automatically run [Prettier](<https://prettier.io/>) on every file Claude edits, so formatting stays consistent without manual intervention. This hook uses the `PostToolUse` event with an `Edit|Write` matcher, so it runs only after file-editing tools. The command extracts the edited file path with [`jq`](<https://jqlang.org/>) and passes it to Prettier. Add this to `.claude/settings.json` in your project root: @@ -192,7 +176,7 @@ "hooks": [ { "type": "command", - "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write" + "command": "f=$(jq -r '.tool_input.file_path') && npx prettier --write --ignore-unknown \"$f\"" } ] } @@ -204,11 +188,7 @@ 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/>). -### - -​ - -Block edits to protected files +### Block edits to protected files Prevent Claude from modifying sensitive files like `.env`, `package-lock.json`, or anything in `.git/`. Claude receives feedback explaining why the edit was blocked, so it can adjust its approach. This example uses a separate script file that the hook calls. The script checks the target file path against a list of protected patterns and exits with code 2 to block the edit. @@ -274,11 +254,7 @@ Ask Claude to add a comment to your `.env` file. Claude Code blocks the edit before it runs and passes the script’s `Blocked:` message to Claude as feedback. -### - -​ - -Re-inject context after compaction +### Re-inject context after compaction When Claude’s context window fills up, compaction summarizes the conversation to free space. This can lose important details. Use a `SessionStart` hook with a `compact` matcher to re-inject critical context after every compaction. Claude Code adds plain text your command writes to stdout to Claude’s context. This example reminds Claude of project conventions and recent work. Add this to `.claude/settings.json` in your project root: @@ -300,13 +276,9 @@ You can replace the `echo` with any command that produces dynamic output, like `git log --oneline -5` to show recent commits. For injecting context on every session start, consider using [CLAUDE.md](</docs/en/memory>) instead. For environment variables, see [`CLAUDE_ENV_FILE`](</docs/en/hooks#persist-environment-variables>) in the reference. -### - -​ - -Audit configuration changes - -Track when settings or skills files change during a session. The `ConfigChange` event fires when an external process or editor modifies a configuration file, so you can log changes for compliance or block unauthorized modifications. This example appends each change to an audit log. Add this to `~/.claude/settings.json`: +### Audit configuration changes + +Track when settings or skills files change during a session. The `ConfigChange` event fires when an external process or editor modifies a configuration file, so you can log changes for compliance or block unauthorized modifications. This example appends each event to an audit log. Add this to `~/.claude/settings.json`: { "hooks": { @@ -326,11 +298,7 @@ The matcher filters by configuration type: `user_settings`, `project_settings`, `local_settings`, `policy_settings`, or `skills`. To block a change from taking effect, exit with code 2 or return `{"decision": "block"}`. See the [ConfigChange reference](</docs/en/hooks#configchange>) for the full input schema. To confirm the hook records changes, edit a settings file in another editor while a session is running, then open `~/claude-config-audit.log`: the hook appends one JSON line per change with the timestamp, source, and file path. -### - -​ - -Reload environment when directory or files change +### Reload environment when directory or files change Some projects set different environment variables depending on which directory you are in. Tools like [direnv](<https://direnv.net/>) do this automatically in your shell, but Claude’s Bash tool doesn’t pick up those changes on its own. Pairing a `SessionStart` hook with a `CwdChanged` hook fixes this. `SessionStart` loads the variables for the directory you launch in, and `CwdChanged` reloads them each time Claude changes directory. Both write to `CLAUDE_ENV_FILE`, which Claude Code runs as a script preamble before each Bash command. Add this to `~/.claude/settings.json`: @@ -379,11 +347,7 @@ See the [CwdChanged](</docs/en/hooks#cwdchanged>) and [FileChanged](</docs/en/hooks#filechanged>) reference entries for input schemas, `watchPaths` output, and `CLAUDE_ENV_FILE` details. -### - -​ - -Auto-approve specific permission prompts +### Auto-approve specific permission prompts Skip the approval dialog for tool calls you always allow. This example auto-approves `ExitPlanMode`, the tool Claude calls when it finishes presenting a plan and asks to proceed, so you aren’t prompted every time a plan is ready. Unlike the exit-code examples above, auto-approval requires your hook to write a JSON decision to stdout. Claude Code runs `PermissionRequest` hooks when it’s about to ask you for permission, and if your hook returns `"behavior": "allow"`, Claude Code answers the request on your behalf. For a tool that [requires user interaction](</docs/en/hooks#allow-with-updatedinput>), such as `ExitPlanMode`, the allow also needs `updatedInput`, or Claude Code ignores it and still shows the prompt. The matcher scopes the hook to `ExitPlanMode` only, so no other prompts are affected. Add this to `~/.claude/settings.json`: @@ -413,11 +377,7 @@ Keep the matcher as narrow as possible. Matching on `.*` or leaving the matcher empty would auto-approve every tool permission prompt, including file writes and shell commands. See the [PermissionRequest reference](</docs/en/hooks#permissionrequest-decision-control>) for the full set of decision fields. -## - -​ - -How hooks work +## How hooks work Claude Code fires hook events at specific points in its lifecycle. When an event fires, Claude Code runs the matching hooks in parallel; see [Hook handler fields](</docs/en/hooks#hook-handler-fields>) for how duplicate handlers are treated. The table below shows each event and when it triggers: @@ -464,11 +424,7 @@ * `"type": "prompt"`: single-turn LLM evaluation. See Prompt-based hooks. * `"type": "agent"`: multi-turn verification with tool access. Agent hooks are experimental and may change. See Agent-based hooks. -### - -​ - -Combine results from multiple hooks +### Combine results from multiple hooks When multiple hooks match the same event, every hook’s command runs to completion before Claude Code merges the results. One hook returning `deny` doesn’t stop sibling hooks from executing. Don’t rely on one hook’s `deny` to suppress side effects in another hook. After all matching hooks finish, Claude Code combines their outputs. For `PreToolUse` permission decisions, the most restrictive answer applies, in the order `deny`, `defer`, `ask`, `allow`. Text from `additionalContext` is kept from every hook and passed to Claude together. The example below registers two `PreToolUse` hooks on `Bash`. The first appends every command to a log file and exits 0. The second runs a script that exits 2 to deny when the command contains `rm -rf`: @@ -494,19 +450,11 @@ When Claude tries to run `rm -rf /tmp/build`, both hooks execute in parallel. The logging hook writes the command to `~/.claude/bash.log` and exits 0, which reports no decision. The guardrail hook exits 2, which denies the tool call. The deny takes precedence, so Claude Code blocks the command and shows Claude the guardrail’s stderr. The log entry is still written because the logging hook already ran. -### - -​ - -Read input and return output +### Read input and return output Hooks communicate with Claude Code through stdin, stdout, stderr, and exit codes. When an event fires, Claude Code passes event-specific data as JSON to your script’s stdin. Your script reads that data, does its work, and tells Claude Code what to do next via the exit code. -#### - -​ - -Hook input +#### Hook input Every event includes common fields like `session_id`, a unique ID for the session, and `cwd`, the working directory when the event fired, but each event type adds different data. When Claude runs a Bash command, a `PreToolUse` hook receives these fields on stdin: @@ -528,11 +476,7 @@ Your script can parse that JSON and act on any of those fields. `UserPromptSubmit` hooks get the `prompt` text instead, `SessionStart` hooks get a `source` of `startup`, `resume`, `clear`, `compact`, or `fork`, and so on. See [Common input fields](</docs/en/hooks#common-input-fields>) in the reference for shared fields, and each event’s section for event-specific schemas. -#### - -​ - -Hook output +#### Hook output Your script tells Claude Code what to do next by writing to stdout or stderr and exiting with a specific code. The following `PreToolUse` hook blocks a command: @@ -556,11 +500,7 @@ * A parsed object that fails schema validation, or stdout that Claude Code [tries to parse as JSON](</docs/en/hooks#exit-code-0>) but that isn’t valid JSON: the action proceeds as a non-blocking error. Check the `<hook name> hook error` notice for the validation or parse message. * Stdout that Claude Code [treats as plain text](</docs/en/hooks#exit-code-0>), or empty stdout: the action proceeds as a non-blocking error. The transcript shows a `<hook name> hook error` notice, then the first line of stderr prefixed with `Failed with non-blocking status code:`. To capture the full stderr, enable [debug logging](</docs/en/hooks#debug-hooks>) with `claude --debug` or by running `/debug` mid-session. -#### - -​ - -Structured JSON output +#### Structured JSON output Exit codes only let you block or stay silent. For more control, exit 0 and print a JSON object to stdout instead. @@ -594,11 +534,7 @@ See [UserPromptSubmit decision control](</docs/en/hooks#userpromptsubmit-decision-control>) for the full output shape, including blocking prompts and setting the session title. Hooks with `type: "prompt"` handle output differently: see Prompt-based hooks. -### - -​ - -Filter hooks with matchers +### Filter hooks with matchers Without a matcher, a hook fires on every occurrence of its event. Matchers let you narrow that down. For example, if you want to run a formatter only after file edits, not after every tool call, add a matcher to your `PostToolUse` hook: @@ -704,11 +640,7 @@ } } -#### - -​ - -Filter by tool name and arguments with the `if` field +#### Filter by tool name and arguments with the `if` field The `if` field uses [permission rule syntax](</docs/en/permissions>) to filter hooks by tool name and arguments together, so the hook process only spawns when the tool call matches. This goes beyond `matcher`, which filters at the group level by tool name only. For example, this configuration runs a hook only when Claude uses `git` commands rather than all Bash commands: @@ -741,11 +673,7 @@ When Claude Code can’t determine which commands the Bash input runs, it runs your hook regardless of the pattern. The [Bash matching table](</docs/en/hooks#bash-if-matching>) covers the command shapes Claude Code can and can’t narrow by subcommand. Because the filter is best-effort, use the [permission system](</docs/en/permissions>) rather than a hook to enforce a hard allow or deny. The `if` field accepts the same patterns as permission rules: `"Bash(git *)"`, `"Edit(*.ts)"`, and so on. To match multiple tool names, use separate handlers each with its own `if` value, or match at the `matcher` level where pipe alternation is supported. `if` only works on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. Adding it to any other event prevents the hook from running. -### - -​ - -Configure hook location +### Configure hook location Where you add a hook determines its scope: @@ -761,11 +689,7 @@ Run [`/hooks`](</docs/en/hooks#the-%2Fhooks-menu>) in Claude Code to browse all configured hooks grouped by event. To disable hooks, set `"disableAllHooks": true` in your settings file. Claude Code reads the value left after [settings precedence](</docs/en/hooks#disable-or-remove-hooks>) applies, so a project’s settings file can override yours. Hooks configured in managed settings still run unless `disableAllHooks` is also set there. For the full reach of each level, see [`disableAllHooks`](</docs/en/settings-reference#disableallhooks>). If you edit settings files directly while Claude Code is running, the file watcher normally picks up hook changes automatically. -## - -​ - -Prompt-based hooks +## Prompt-based hooks For decisions that require judgment rather than deterministic rules, use `type: "prompt"` hooks. Instead of running a shell command, Claude Code sends your prompt and the hook’s input data to a Claude model to make the decision. You can specify a different model with the `model` field if you need more capability. The model’s only job is to return its decision as JSON: @@ -795,11 +719,7 @@ For full configuration options, see [Prompt-based hooks](</docs/en/hooks#prompt-based-hooks>) in the reference. -## - -​ - -Agent-based hooks +## Agent-based hooks Agent hooks are experimental. Behavior and configuration may change in future releases. For production workflows, prefer [command hooks](</docs/en/hooks#command-hook-fields>). @@ -823,11 +743,7 @@ Use prompt hooks when the hook input data alone is enough to make a decision. Use agent hooks when you need to verify something against the actual state of the codebase. For full configuration options, see [Agent-based hooks](</docs/en/hooks#agent-based-hooks>) in the reference. -## - -​ - -HTTP hooks +## HTTP hooks Use `type: "http"` hooks to POST event data to an HTTP endpoint instead of running a shell command. The endpoint receives the same JSON that a command hook would receive on stdin, and returns results through the HTTP response body using the same JSON format. HTTP hooks are useful when you want a web server, cloud function, or external service to handle hook logic: for example, a shared audit service that logs tool use events across a team. This example posts every tool use to a local logging service: @@ -857,17 +773,9 @@ 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. -## - -​ - -Limitations and troubleshooting - -### - -​ - -Limitations +## Limitations and troubleshooting + +### Limitations Keep these constraints in mind when designing hooks: @@ -882,11 +790,7 @@ * `Stop` hooks fire whenever Claude finishes responding, not only at task completion. They don’t fire on user interrupts. API errors fire [StopFailure](</docs/en/hooks#stopfailure>) instead. * When multiple `PreToolUse` hooks return [`updatedInput`](</docs/en/hooks#pretooluse>) to rewrite a tool’s input, Claude Code doesn’t merge the rewrites or guarantee which rewrite the tool runs with. Avoid having more than one hook rewrite the same tool’s input. -### - -​ - -Hooks and permission modes +### Hooks and permission modes With a hook in a settings file or a plugin’s `hooks/hooks.json` you can’t loosen restrictions past what permission rules allow, and a hook’s `"deny"` holds in every permission mode: @@ -900,11 +804,7 @@ Your machine might lack [managed settings](</docs/en/settings#check-what-your-organization-enforces>) and a [`managed-mcp.json` file](</docs/en/managed-mcp#deploy-managed-mcp-json>), and your session might not use [`/login` credentials](</docs/en/authentication#authentication-precedence>) for a Team or Enterprise plan. In that setup, a [mod](</docs/en/plugins/mods/overview>) can approve a call your `PreToolUse` hook blocked. A session that runs on an API key or a long-lived [`CLAUDE_CODE_OAUTH_TOKEN`](</docs/en/authentication#generate-a-long-lived-token>) instead isn’t using that login, even when that login is stored.In plan mode, a mod can approve such a blocked call only when it’s read-only, so not a file edit. For the cases where a mod’s approval doesn’t get past your rules and hooks, see [Extend permissions with hooks](</docs/en/permissions#precedence-among-rules-hooks-and-mods>). -### - -​ - -Hook not firing +### Hook not firing The hook is configured but never executes. @@ -913,11 +813,7 @@ * Check that the matcher pattern matches the tool name exactly. Matchers are case-sensitive * Verify you’re triggering the right event type: `PreToolUse` fires before tool execution, `PostToolUse` fires after. A `PermissionRequest` hook fires when Claude Code is about to ask you for permission; see the limitations for the non-interactive cases -### - -​ - -Hook error in output +### Hook error in output You see a message like “PreToolUse hook error: …” in the transcript. @@ -932,11 +828,7 @@ * If the notice shows a JSON validation message, your hook’s stdout parsed as JSON but failed schema validation. If it shows a JSON parse message, the stdout looked like a JSON object but wasn’t valid JSON. Both happen even on exit 0. To fix a parse failure, build the payload with a JSON encoder such as `jq` instead of string concatenation, so quotes and backslashes inside values are escaped. The reference’s [Exit code output](</docs/en/hooks#exit-code-output>) section covers the exit-code and JSON combinations * If the script isn’t running at all, make it executable: `chmod +x ./my-hook.sh` -### - -​ - -`/hooks` shows no hooks configured +### `/hooks` shows no hooks configured You edited a settings file but the hooks don’t appear in the menu. @@ -945,11 +837,7 @@ * Confirm the settings file is in the correct location: `.claude/settings.json` for project hooks, `~/.claude/settings.json` for global hooks * If the menu shows `Only hooks from managed settings run here`, your organization has set [`allowManagedHooksOnly`](</docs/en/settings-reference#allowmanagedhooksonly>). Hooks in your user, project, and local settings files don’t run and aren’t listed -### - -​ - -Stop hook hits the block cap +### Stop hook hits the block cap Claude keeps working instead of stopping, then ends the turn with a warning that the Stop hook blocked too many consecutive times. Claude Code overrides a Stop hook after it blocks eight times in a row with no tool call from Claude in between. Your hook script needs to check whether it already triggered a continuation. Parse the `stop_hook_active` field from the JSON input and exit early if it’s `true`: @@ -962,22 +850,14 @@ If your hook legitimately needs more than eight iterations to converge, raise the cap with [`CLAUDE_CODE_STOP_HOOK_BLOCK_CAP`](</docs/en/env-vars>). -### - -​ - -Hook JSON has no effect +### Hook JSON has no effect Your hook prints valid JSON, but the decision doesn’t take effect and no error appears in the transcript. Check which cause applies: * **Extra output before the JSON** : something else writes to stdout first, usually an unconditional `echo` in your shell profile, so the output no longer starts with `{`. See Shell profile output before the JSON. * **A field at the wrong level** : compare each field’s placement against the [JSON output](</docs/en/hooks#json-output>) format. For example, `permissionDecision` belongs inside `hookSpecificOutput`, not at the top level. See Fields at the wrong level. -#### - -​ - -Shell profile output before the JSON +#### Shell profile output before the JSON Hooks run in non-interactive shells, but Git Bash and some configurations, such as `BASH_ENV` pointing at `~/.bashrc`, still source your profile, and anything the profile prints reaches stdout ahead of your hook’s JSON: @@ -993,19 +873,11 @@ The `$-` variable contains shell flags, and `i` means interactive. Hooks run in non-interactive shells, so the echo is skipped. -#### - -​ - -Fields at the wrong level +#### Fields at the wrong level When your hook returns `permissionDecision` or `additionalContext` at the top level instead of inside `hookSpecificOutput`, the JSON still parses, and Claude Code ignores the misplaced fields without reporting an error. To see which fields it ignored, start Claude Code with `claude --debug` and search the [debug log](</docs/en/hooks#debug-hooks>) for `Hook JSON output had unrecognized keys`. -### - -​ - -Check what a hook did +### Check what a hook did Press `Ctrl+O` to open the transcript view and look for the hook’s outcome: @@ -1016,11 +888,7 @@ 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](</docs/en/hooks#debug-hooks>). 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. -## - -​ - -Learn more +## Learn more * [Hooks reference](</docs/en/hooks>): full event schemas, JSON output format, async hooks, and MCP tool hooks * [Security considerations](</docs/en/hooks#security-considerations>): review before deploying hooks in shared or production environments
modified Host and maintain a marketplace View current →
Show diff (380 lines)
--- a/host-marketplace.md +++ b/host-marketplace.md @@ -7,11 +7,7 @@ Start with Host your marketplace to pick a host and the command your users run. Read Keep users up to date before your first release. Read Rename or remove a plugin before you change a plugin’s `name`. -## - -​ - -Host your marketplace +## Host your marketplace You can host the marketplace on GitHub, on another git host, as a hosted `marketplace.json` URL, or in a directory on a shared filesystem. Send your users the add command for your host and tell them what they need on their machine: @@ -24,27 +20,15 @@ To pin a branch or tag of a GitHub or git-URL marketplace, tell users to append `#<ref>`, as in `your-org/your-marketplace#stable`. The [plugin commands reference](</docs/en/plugins/cli-reference#plugin-marketplace-add>) lists every form the command accepts. A successful add prints `Successfully added marketplace: your-marketplace`. Claude Code takes that name from the `name` field in your `marketplace.json`, not from the repository name. Users then install a plugin by its entry’s `name` and the marketplace’s `name`, as in `/plugin install code-formatter@your-marketplace`. -### - -​ - -Register the marketplace for everyone in a repository +### Register the marketplace for everyone in a repository To share the marketplace with everyone who works in one repository, run `claude plugin marketplace add your-org/your-marketplace --scope project` there once from your shell and commit the `.claude/settings.json` it writes. Claude Code then registers the marketplace for each teammate who [trusts the folder](</docs/en/plugins/org#require-plugins-per-repository>). -### - -​ - -Avoid relative-path entries in a URL-hosted marketplace +### Avoid relative-path entries in a URL-hosted marketplace When users add your marketplace as a bare `marketplace.json` URL, Claude Code downloads only that file. An entry in your `plugins` array whose `source` is a relative path such as `./plugins/formatter` then fails at install with [`its marketplace entry path does not stay inside the marketplace directory`](</docs/en/plugins/troubleshooting#plugins-with-relative-paths-fail-in-url-based-marketplaces>). Give every entry a source that can be fetched on its own, such as a `github` repository or an `archive` URL, or host the marketplace in a git repository so Claude Code clones the whole tree. -### - -​ - -Stay within the download limits for hosted files +### Stay within the download limits for hosted files When users add your marketplace as a `marketplace.json` URL, or install an entry with an [`archive`](</docs/en/plugins/marketplace-reference#archive-plugin-source>) source, Claude Code downloads the file from your server. The download fails past the limits in this table, so size your files and configure your server to stay inside them. @@ -60,27 +44,15 @@ * **Total size** : 1 GiB uncompressed * **Compression ratio** : uncompressed content 50 times the size of the zip -### - -​ - -Edit plugins in place on a shared directory +### Edit plugins in place on a shared directory When users add your marketplace from a shared directory, Claude Code reads plugins with relative-path sources directly from that directory instead of copying them. Users see your edits when they next start a session or run `/reload-plugins`, without an update step or a version bump. -### - -​ - -Keep plugin files out of Git LFS +### Keep plugin files out of Git LFS Keep the files your plugins need out of [Git LFS](<https://git-lfs.com>). When users add a marketplace hosted in a git repository, or install a git-based plugin it lists, Claude Code clones that marketplace or plugin repository onto their machine. The clone never downloads LFS content, so LFS-tracked files arrive as pointer files. -### - -​ - -Share files within a marketplace with symlinks +### Share files within a marketplace with symlinks To share files between your plugin and other parts of the same marketplace, create symbolic links inside your plugin directory. When Claude Code copies the plugin into its cache, it handles each symlink by where the target resolves: @@ -92,11 +64,7 @@ ln -s ../../shared-plugin/skills/foo ./skills/foo -## - -​ - -Distribute through organization settings +## Distribute through organization settings On a Team or Enterprise plan, you can also distribute the marketplace through [**Organization settings > Plugins & skills**](<https://claude.ai/admin-settings/skills?tab=inventory>) on claude.ai instead of hosting it somewhere users add it themselves. Organization sync reads the repository through your organization’s GitHub or GitLab connection on claude.ai, so your users’ git credentials aren’t involved. Organization sync is stricter about the repository than `/plugin marketplace add` is: @@ -106,11 +74,7 @@ [Sync your organization’s plugins from a repository](<https://claude.com/docs/plugins/org-sync>) on claude.com lists the accepted sources, the GitLab setup, and the `bin/` error, and [Manage plugins for your organization](<https://claude.com/docs/plugins/admin>) covers the admin workflow. -## - -​ - -Grant access to a private marketplace +## Grant access to a private marketplace When a user adds, installs from, or updates your marketplace, Claude Code runs `git` on their machine with interactive prompts turned off and relies on whatever credentials that machine already holds. Claude Code has no git token of its own, and `marketplace.json` has no field for one. You choose whether the clone runs over SSH or HTTPS by the form of the add command you send users: @@ -125,11 +89,7 @@ For a GitHub Enterprise Server host, users need git access to that host from their machine. See [Plugin marketplaces on GHES](</docs/en/github-enterprise-server#plugin-marketplaces-on-ghes>) for what each Claude Code surface needs to reach a GHES-hosted marketplace. If you distribute through **Organization settings > Plugins & skills** on claude.ai instead, your users’ git credentials aren’t involved. See Distribute through organization settings. -### - -​ - -Serve users who have no git-host account +### Serve users who have no git-host account Users without a git-host account can add a marketplace you serve as a `marketplace.json` URL or from a shared directory, but they can install only the plugins whose entry sources they can also reach. An entry that points at a private `github` repository still fails at install for them, because Claude Code fetches it with the same non-interactive `git` it uses for a git-hosted marketplace. These entry sources need no git account: @@ -138,11 +98,7 @@ Keep `CLAUDE_CODE_PLUGIN_PREFER_HTTPS=1` in your instructions even if `claude plugin install` succeeds without it from the shell on a machine with no SSH key. For a `github` source, that command can fall back to HTTPS on its own, printing `SSH not configured, cloning via HTTPS`. Installs from `/plugin` inside a session and plugin updates don’t fall back, so without the variable they fail for users who have no GitHub SSH key. For a team on one network, a `directory` marketplace on a shared filesystem also works without git accounts. Users need only read access to the path. -### - -​ - -What background auto-update does with credentials +### What background auto-update does with credentials Background auto-update is Claude Code’s unattended refresh of marketplaces and installed plugins after a session starts. It’s off for your marketplace until a user or admin turns it on, as covered under Keep users up to date. When it’s on for a private marketplace, the background check for new commits uses the user’s configured git credential helpers and never prompts. Each kind of remote and helper gives a different result: @@ -162,11 +118,7 @@ If a user sets `GITHUB_TOKEN` or another provider token in the environment, that alone doesn’t authenticate the background check. A token takes effect through a credential helper, such as the `gh` CLI’s helper, which reads `GH_TOKEN` and `GITHUB_TOKEN`. -## - -​ - -Roll out to a whole company +## Roll out to a whole company Rolling a plugin out to a company involves you as the marketplace owner, an administrator who controls managed settings, and each person who uses Claude Code. You can run the rollout without the administrator, in which case each person adds the marketplace and installs the plugin themselves. @@ -182,19 +134,11 @@ * **A pre-populated plugins directory** : [Seed containers and CI](</docs/en/plugins/org#seed-containers-and-ci>), which also serves users who have no git-host account * **claude.ai organization settings** : Distribute through organization settings, where your users’ git credentials aren’t involved -## - -​ - -Keep users up to date +## Keep users up to date Your changes reach users through background auto-update, once it’s turned on for your marketplace, or when users update the plugin themselves. In both cases a user gets a new copy of a plugin only when its computed version changes, as described under Release a new version. -### - -​ - -Turn on auto-update +### Turn on auto-update Background auto-update is off for your marketplace by default, and `marketplace.json` has no field to turn it on. A user or an admin turns it on: @@ -203,11 +147,7 @@ Without auto-update, users receive your changes when they run `/plugin marketplace update <name>` in a session or `claude plugin update <plugin>@<name>` in the shell. For what users see when an update reaches them, see [When auto-update runs](</docs/en/plugins/loading#when-auto-update-runs>). -### - -​ - -Release a new version +### Release a new version To release a new version to users, change the plugin’s `version`. Users get a new copy only when the plugin’s computed version differs from the one they have. That version comes from `plugin.json` first, then from the marketplace entry, per [Versions and updates](</docs/en/plugins/loading#versions-and-updates>). A plugin that users [load in place](</docs/en/plugins/loading#find-plugins-on-disk>) from a marketplace they added from a local path isn’t controlled by `version`. It loads your current files at every session start, whatever its version string says. For every install other than an in-place load or one from a `command` source, either increase `version` on each release or omit it: @@ -216,11 +156,7 @@ Don’t set `version` in both `plugin.json` and the marketplace entry. If you do, Claude Code uses the `plugin.json` value without warning, and `claude plugin validate` reports the mismatch as `Entry declares version "<a>" but <path>/plugin.json says "<b>"`. -### - -​ - -Hold users on one version +### Hold users on one version One marketplace serves one version of each plugin at a time, so you hold users on a version by choosing what each entry points at: @@ -230,11 +166,7 @@ Release a new version says when a changed entry reaches users. -### - -​ - -Change the command of a command source +### Change the command of a command source If you change the `command` of a [`command` source](</docs/en/plugins/marketplace-reference#command-plugin-source>), or switch its `mode`, each user has to accept the new command before Claude Code runs it. Claude Code runs only the exact command a user accepted when they installed or last updated the plugin. After a user’s copy of your marketplace picks up the change, that user sees the following: @@ -243,11 +175,7 @@ Tell users to run the `claude plugin update` command that entry shows, in a terminal. Claude Code shows them the new command and asks them to accept it. -## - -​ - -Run release channels +## Run release channels To offer stable and early-access tracks, host two marketplaces whose entries point at different refs of the same plugin, and let each user add the one they want. Claude Code has no release-channel concept, and one marketplace serves one version of each plugin at a time. Give the two `marketplace.json` files different `name` values. Claude Code identifies a marketplace by its `name`, so a user can’t have two marketplaces with the same name registered at once. With these two catalogs, users who add `stable-tools` install `code-formatter` from the `stable` branch, and users who add `latest-tools` install it from `latest`: @@ -269,19 +197,11 @@ Give the two refs different `plugin.json` versions, or omit `version` so the commit SHA distinguishes them. Updates are detected by comparing versions, so a ref that moves without a version change leaves users on the cached copy. To assign the channels to user groups instead of letting users choose, an admin gives each group the matching `extraKnownMarketplaces` entry, as described under [Set update policy](</docs/en/plugins/org#set-update-policy>). -## - -​ - -Rename or remove a plugin +## Rename or remove a plugin A plugin’s `name` is its identifier. Users reference it in the `enabledPlugins` and `pluginConfigs` settings keys and in `/plugin install`, so changing it breaks every existing install. To change the label users see in `/plugin` without breaking anything, set `displayName` in `plugin.json` and keep `name` unchanged. -### - -​ - -Migrate users with a renames map +### Migrate users with a renames map When you must change a `name`, add a top-level `renames` map to `marketplace.json` so Claude Code migrates existing users instead of reporting [`Plugin "<name>" not found in marketplace`](</docs/en/plugins/troubleshooting#plugin-not-found-in-marketplace>). Do the same when you remove an entry from `plugins`. Map each former name to its current name, or to `null` when the plugin is gone. This marketplace renames `formatter` to `code-formatter` and records that `legacy-linter` was removed: @@ -305,11 +225,7 @@ For a marketplace users added from a git repository or URL, a renamed plugin reports [`Plugin "<name>" not cached at <path>`](</docs/en/plugins/troubleshooting#plugin-not-cached-at>) until the user runs `/plugin install code-formatter@your-marketplace` once in a session. Treat `renames` as append-only history. Keep old entries after everyone has migrated. When you rename again, add a second entry rather than editing the first, because Claude Code follows the chain from the oldest name. In your shell, run `claude plugin validate .` after editing the map. It rejects a chain that cycles or that ends anywhere other than `null` or a name in `plugins`, with `renames.<name>: chain does not resolve`. -### - -​ - -Uninstall removed plugins from users’ machines +### Uninstall removed plugins from users’ machines To uninstall a removed plugin from users’ machines rather than leave a copy behind, set `"forceRemoveDeletedPlugins": true` at the top level of `marketplace.json`. Without the field, a removed plugin stays installed and reports `Plugin "<name>" not found in marketplace` when a session loads it. With it, Claude Code does the following at each session start: @@ -317,11 +233,7 @@ 2. Uninstalls each removed plugin from the user, project, and local scopes. Plugins that only managed settings installed stay in place. 3. Lists each removed plugin under a **Flagged** heading in `/plugin` with the status `Removed from marketplace`. -## - -​ - -Authenticate archive downloads +## Authenticate archive downloads To authenticate an [`archive`](</docs/en/plugins/marketplace-reference#archive-plugin-source>) download, such as a download from a private registry, set the HTTP headers Claude Code sends with it. You can set `headers` in either of these places: @@ -337,11 +249,7 @@ Where both places set a header of the same name, Claude Code sends the entry’s value. Within one place, a header the command prints overrides a header of the same name listed in `headers`. -### - -​ - -Add a headersHelper to a plugin entry +### Add a headersHelper to a plugin entry This entry sets `headersHelper` beside `source`. It also sets [`"strict": false`](</docs/en/plugins/marketplace-reference#strict-mode>), which Claude Code requires of a `marketplace.json` entry that sets `headersHelper`: @@ -358,11 +266,7 @@ To check the entry, run `claude plugin install my-plugin@your-marketplace` in your shell. Claude Code shows you the command and the archive URL, and downloads the zip after you accept. -### - -​ - -Write the headersHelper command +### Write the headersHelper command Whether you set `headersHelper` on a marketplace’s `url` source or on a plugin entry, write the command to meet these requirements: @@ -376,11 +280,7 @@ {"Authorization": "Bearer eyJhbGciOiJSUzI1NiJ9"} -### - -​ - -When Claude Code skips a headersHelper command or drops its output +### When Claude Code skips a headersHelper command or drops its output A `headersHelper` command doesn’t run, or headers from `headers` or from the command’s output are dropped, when one of the following applies: @@ -391,11 +291,7 @@ * **Command set in an`--add-dir` directory’s settings**: the command is ignored, on a `url` source and on an [inline plugin entry](</docs/en/settings-reference#extraknownmarketplaces>) alike, and only that file’s `headers` are sent. * **Managed settings block the command** : setting [`disableCommandPluginSources`](</docs/en/settings-reference#disablecommandpluginsources>) to `true` blocks `headersHelper` commands, and [`allowManagedHooksOnly`](</docs/en/settings-reference#allowmanagedhooksonly>) blocks them too unless `disableCommandPluginSources` is explicitly `false`. Under either block, Claude Code still runs the command for a marketplace that managed settings themselves declare. -### - -​ - -How users accept a headersHelper command +### 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. 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: @@ -405,22 +301,14 @@ 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`. -### - -​ - -Installs and updates that refuse a command instead of asking +### Installs and updates that refuse a command instead of asking On any operation other than a single-plugin install or update, Claude Code neither runs an entry’s command nor downloads its archive. The plugin stays at its installed version or stays uninstalled, and the user sees one of these results: * **Installing several plugins at once, from a plugin suggestion, or as another plugin’s dependency** : Claude Code refuses the plugin that has the command and directs the user to that plugin’s own view in `/plugin`. The other plugins in a bulk install still install. A plugin that depends on the refused plugin fails to install until the user installs the refused plugin by itself. * **Background auto-update, or session start for a plugin whose archive was never downloaded** : Claude Code lists the plugin in the `/plugin` Errors tab so the user knows to install or update it themselves. -### - -​ - -When a marketplace `url` source’s command runs +### When a marketplace `url` source’s command runs You declare a marketplace `url` source’s `headersHelper` in a settings file, such as an [`extraKnownMarketplaces`](</docs/en/settings-reference#extraknownmarketplaces>) entry, rather than in the catalog the marketplace publishes. Claude Code therefore doesn’t ask the user to accept it on each install or update. Instead, the settings file that declares it decides when Claude Code runs it: @@ -432,11 +320,7 @@ For an [inline plugin entry](</docs/en/settings-reference#extraknownmarketplaces>) in one of these files, Claude Code requires the same folder trust or settings approval as for a marketplace-level command in that file, and the user also accepts the entry’s command on each install or update. -## - -​ - -Depend on and recommend other plugins +## Depend on and recommend other plugins An entry can declare dependencies on other plugins. @@ -445,11 +329,7 @@ For version ranges, the `<plugin>--v<version>` git-tag convention they resolve against, and cross-marketplace trust, see [Plugin dependencies](</docs/en/plugins/dependencies>). To have Claude Code suggest a plugin when a project matches it, add a `relevance` block to the entry with the signals that identify the project. Users see these suggestions only when an admin lists your marketplace in `pluginSuggestionMarketplaces`. For the signals and the enablement step, see [Plugin relevance](</docs/en/plugins/relevance>). -## - -​ - -Work around what a marketplace can’t do +## Work around what a marketplace can’t do Some things owners ask for have no field in `marketplace.json`. Here is the nearest option for each: @@ -460,11 +340,7 @@ * **Turn on auto-update for your users** : each user turns it on under **Marketplaces** in `/plugin`, or an admin sets `autoUpdate` in managed settings. See Turn on auto-update. * **Carry git credentials** : no marketplace field holds a git token. Access to a git-hosted marketplace or plugin follows the user’s git setup, per Grant access to a private marketplace. For `archive` sources, an entry can set `headers` or `headersHelper` instead. -## - -​ - -Next steps +## Next steps * [Marketplace reference](</docs/en/plugins/marketplace-reference>): `marketplace.json` fields, source types, and validation messages * [Manage plugins for your organization](</docs/en/plugins/org>): require, restrict, or seed your marketplace across your organization’s machines
modified Hosting the Agent SDK View current →
Show diff (258 lines)
--- a/hosting.md +++ b/hosting.md @@ -1,10 +1,6 @@ The Agent SDK spawns and supervises a `claude` CLI subprocess that owns a shell, a working directory, and session files on disk. Hosting it is not like hosting a stateless API wrapper. Every running agent is a long-lived process tied to local state, which shapes how you allocate resources, persist sessions, and scale across tenants. This page covers self-hosting on your own infrastructure. For deployable Dockerfiles and Kubernetes manifests, see the [hosting cookbook](<https://github.com/anthropics/claude-cookbooks/tree/main/claude_agent_sdk/hosting>). If you don’t need to run the agent loop itself on your own infrastructure, consider [Managed Agents](<https://platform.claude.com/docs/en/managed-agents/overview>) instead. Anthropic hosts the agent loop, and your application sends events and receives streamed results through the client SDKs or the REST API. Tool execution runs in an Anthropic-managed cloud sandbox or a [self-hosted sandbox](<https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes>) on your own infrastructure. -## - -​ - -The subprocess model +## The subprocess model Every hosting decision on this page follows from how the SDK runs the agent. When your code calls `query()`, the SDK spawns a separate `claude` CLI process and talks to it over stdio. That subprocess owns the shell, the working directory, and the JSONL session transcripts on local disk. One agent session maps to one subprocess. Running N concurrent sessions means N subprocesses, each with its own process tree and transcript file. By default they all inherit your application’s working directory. When sessions need separate filesystems, pass a distinct `cwd` in the options of each session’s `query()` call: @@ -36,11 +32,7 @@ The TypeScript examples on this page use top-level `await`, so save them as `.mts` files or set `"type": "module"` in `package.json`. -### - -​ - -State that lives on local disk +### State that lives on local disk Three kinds of agent state live on the container’s filesystem by default. None of them survive a container restart, a scale-down, or a move to a different node. @@ -52,19 +44,11 @@ To persist transcripts across hosts, configure a [`SessionStore` adapter](</docs/en/agent-sdk/session-storage>). Memory files and other working-directory artifacts need their own storage strategy, such as a mounted volume or an object-store sync. For how sessions, resumption, and forking work at the API level, see [Sessions](</docs/en/agent-sdk/sessions>). -## - -​ - -Choose a session pattern +## Choose a session pattern These four patterns cover session lifecycle: how long a container lives relative to the sessions it serves. For where the container runs, the [hosting cookbook](<https://github.com/anthropics/claude-cookbooks/blob/main/claude_agent_sdk/07_Hosting_the_agent.ipynb>) has [deployable code](<https://github.com/anthropics/claude-cookbooks/tree/main/claude_agent_sdk/hosting>) for local Docker, Modal, and Kubernetes. Choose a session pattern here and a deployment target from the cookbook. -### - -​ - -Ephemeral sessions +### Ephemeral sessions Create a container for each user task and destroy it when the task completes. Best for one-off tasks. The user may still interact with the AI while the task is completing, but once completed the container is destroyed. Example workloads include bug investigation and fix, invoice and receipt extraction, document translation, and media transformation. The container runs a one-shot entrypoint that reads the task from the `TASK_PROMPT` environment variable, calls the SDK, and exits. @@ -95,11 +79,7 @@ The script prints each message as it arrives, including a result message whose `subtype` is `success` when the task completes within the turn limit. If the task hits the 20-turn limit instead, the result message’s `subtype` is `error_max_turns` and the `query()` call raises an error after yielding it, so wrap the loop in a try block if the container needs to exit cleanly. See [Handle the result](</docs/en/agent-sdk/agent-loop#handle-the-result>) for the error subtypes. -### - -​ - -Long-running sessions +### Long-running sessions Run persistent container instances, often hosting multiple SDK processes per container, to serve ongoing work. Best for agents that take autonomous action, serve content, or handle high-volume message streams. Example workloads include an email agent that triages and responds to incoming mail, a site builder that hosts a per-user editable site through container ports, and a chat bot that handles continuous traffic from a platform like Slack. The container exposes an HTTP or WebSocket endpoint and maps each active session to a long-lived query and the subprocess behind it. The calls that keep sessions open and warm differ between the SDKs: @@ -108,11 +88,7 @@ Size the container so it can hold the maximum number of concurrent sessions in memory. -### - -​ - -Hybrid sessions +### Hybrid sessions Ephemeral containers that hydrate from a [`SessionStore`](</docs/en/agent-sdk/session-storage>) on startup and persist updates back. Best for sessions that span many interactions but sit idle between them. The container spins down during idle periods and spins back up when the user returns. Example workloads include a personal project manager with intermittent check-ins, deep research that pauses and resumes over hours, and a customer support agent that loads ticket history across interactions. Tune your provider’s idle timeout to how frequently you expect users to return. Shutting a container down without a `SessionStore` configured loses the transcript with it, so the store is required for this pattern, not optional. The pattern hinges on resuming a session by ID with a shared store attached: @@ -152,25 +128,13 @@ asyncio.run(main()) -### - -​ - -Multi-agent container +### Multi-agent container Run multiple SDK subprocesses inside one container. Best for agents that must collaborate closely, for example multi-agent simulations where the agents interact with each other in a shared environment. Give each agent its own working directory so they do not overwrite each other’s files, and isolate settings loading so per-agent `CLAUDE.md` files do not leak across agents. See Multi-tenant isolation for the specific options. -## - -​ - -Provision the container - -### - -​ - -Container-based sandboxing +## Provision the container + +### Container-based sandboxing Run the SDK inside a sandboxed container for process isolation, resource limits, network control, and an ephemeral filesystem. Questions to answer when choosing a provider: @@ -182,11 +146,7 @@ For self-hosted options such as Docker, gVisor, and Firecracker, and detailed isolation configuration, see [Isolation Technologies](</docs/en/agent-sdk/secure-deployment#isolation-technologies>). -### - -​ - -Runtime dependencies +### Runtime dependencies The container needs your SDK’s language runtime: @@ -195,35 +155,19 @@ The bundled binary is pinned to the SDK package version, so updating the SDK is how you update the CLI. The SDK follows semver: take patch releases continuously and review the [TypeScript](<https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/CHANGELOG.md>) or [Python](<https://github.com/anthropics/claude-agent-sdk-python/blob/main/CHANGELOG.md>) changelog before taking a minor. -### - -​ - -Resources +### Resources 1 GiB RAM, 5 GiB disk, and 1 CPU per agent is a reasonable starting point for a freshly started instance. Memory usage grows with session length and tool activity, so size for the session lengths and concurrency you actually need rather than the idle baseline. See Scaling and concurrency for how to work out agents per host. -### - -​ - -Network +### Network The SDK needs outbound HTTPS to `api.anthropic.com`, or to your provider’s regional endpoint when running on Amazon Bedrock or Google Cloud’s Agent Platform. If your agents use [MCP servers](</docs/en/agent-sdk/mcp>) or external tools, they need outbound access to those endpoints as well. For production, route outbound traffic through an egress proxy that enforces domain allowlists, injects credentials, and logs requests. See [Secure Deployment](</docs/en/agent-sdk/secure-deployment>) for the full pattern. For inbound traffic, expose an HTTP or WebSocket port on the container. Your application handles client requests on that port and calls the SDK internally; the subprocess itself does not listen on the network. -## - -​ - -Handle production concerns +## Handle production concerns Work through these decisions before shipping a self-hosted agent. -### - -​ - -Session and state persistence +### Session and state persistence Default local disk is lost on restart, scale-down, or a move to a different node. For any session a user expects to resume, mirror the transcript to durable storage with a [`SessionStore` adapter](</docs/en/agent-sdk/session-storage>). See [Reference implementations](</docs/en/agent-sdk/session-storage#reference-implementations>) for example adapters for an object store, a key-value store, and a database, and a conformance suite for your own. Three things to know about how `SessionStore` behaves: @@ -231,11 +175,7 @@ * **Mirror, not replacement** : the subprocess writes to local disk first, and the SDK forwards a copy of each batch to the store. A fresh session’s local transcript outlives the run; a run resumed from the store deletes its local copy at the end, so the store holds the only durable copy. See [Dual-write architecture](</docs/en/agent-sdk/session-storage#dual-write-architecture>). * **`mirror_error` messages**: when the SDK can’t deliver a batch to the store, it drops the batch, emits a `{ type: "system", subtype: "mirror_error" }` message, and continues the query. Alert on these if store durability matters. See [Mirror writes are best-effort](</docs/en/agent-sdk/session-storage#mirror-writes-are-best-effort>) for the retry and timeout behavior. -### - -​ - -Observability +### Observability Agent SDK agents are long-lived processes that spawn tool calls across many API round-trips. Without telemetry you cannot see which tools ran, how long they took, or where a session stalled. The SDK inherits OpenTelemetry configuration from the environment. Set the OTEL environment variables at the container or orchestrator level so every `query()` call exports spans, metrics, and log events to your collector. The example below enables OTLP export for all three signals. `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA` is required only for traces; omit it if you export metrics and logs alone. @@ -251,11 +191,7 @@ Prompt text and tool inputs are not included in exports by default. See [Control sensitive data in exports](</docs/en/agent-sdk/observability#control-sensitive-data-in-exports>) for the opt-in flags, and [Observability](</docs/en/agent-sdk/observability>) for the full signal catalog. -### - -​ - -Auth and secrets +### Auth and secrets Three auth concerns matter at hosting time: @@ -263,11 +199,7 @@ * **Inbound** : put authentication at a gateway in front of the agent container. The agent should receive pre-authenticated requests and should not be the component that validates user tokens. * **Outbound tools** : keep tool credentials out of the agent environment. Route outbound calls through a proxy that injects API keys after the request leaves the container. The agent makes the call; the proxy adds the credential. -### - -​ - -Scaling and concurrency +### Scaling and concurrency Each session runs in its own subprocess, so concurrency on a host is bounded by how many subprocesses its RAM can hold. Size each host with this formula: @@ -275,19 +207,11 @@ Measure the per-session ceiling by running a representative session to your target length under your expected tool load and recording peak RSS. The 1 GiB starting point in Resources is a floor, not the ceiling. Horizontal-scale routing depends on your pattern. For long-running sessions, where containers hold many sessions, run a pool of containers behind a load balancer and pin each session to one container using consistent hashing on `sessionId`. A pinned session keeps hitting the same container, and therefore the same running subprocess, until it is evicted or the container restarts. -### - -​ - -Cost +### Cost Anthropic token cost typically dominates container infrastructure cost by an order of magnitude or more. A minimally provisioned container runs roughly $0.05 per hour, while a single long agent session can spend dollars in tokens. See [Cost tracking](</docs/en/agent-sdk/cost-tracking>) for per-session token accounting. -### - -​ - -Multi-tenant isolation +### Multi-tenant isolation Default SDK behavior reads settings and `CLAUDE.md` memory files from the filesystem. In a shared container that serves multiple tenants, those files can leak one tenant’s context into another tenant’s session. To isolate tenants inside a shared container: @@ -347,11 +271,7 @@ asyncio.run(main()) -## - -​ - -Known limitations +## Known limitations Plan around these in your deployment design. @@ -362,11 +282,7 @@ Large parallel-subagent fanouts can hit rate limits| Break work into smaller batches rather than issuing one wide dispatch. No per-subagent wall-clock deadline| Cap each [subagent](</docs/en/agent-sdk/subagents>) with `maxTurns` in its `AgentDefinition`. `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS` sets a stall watchdog that fires when a subagent stops producing output; it isn’t a total-runtime deadline. -## - -​ - -Troubleshoot deployment failures +## Troubleshoot deployment failures Use this section when an agent that works on your machine fails in a deployed service. Each item below names a failure and links the entry that covers it: @@ -374,11 +290,7 @@ * **CLI present in the image but won’t launch** : Claude Code can’t start from a binary that doesn’t match the container’s architecture or libc, or from a file that lost its execute permission in the image build. See [Failed to start Claude Code](</docs/en/agent-sdk/troubleshooting#cliconnectionerror-failed-to-start-claude-code>). * **Claude Code process exits mid-run** : the error your application receives depends on the SDK language and on whether the CLI reported an error result first. The entries under [CLI process exit](</docs/en/agent-sdk/troubleshooting#cli-process-exit>) cover each message. -## - -​ - -Next steps +## Next steps * [Hosting cookbook](<https://github.com/anthropics/claude-cookbooks/blob/main/claude_agent_sdk/07_Hosting_the_agent.ipynb>): notebook walkthrough with [deployable code](<https://github.com/anthropics/claude-cookbooks/tree/main/claude_agent_sdk/hosting>) for Docker, Modal, and Kubernetes. * [Session storage](</docs/en/agent-sdk/session-storage>): persist transcripts across hosts with a `SessionStore` adapter.
modified How Claude Code works View current →
Show diff (246 lines)
--- a/how-claude-code-works.md +++ b/how-claude-code-works.md @@ -1,26 +1,14 @@ Claude Code is an agentic assistant that runs in your terminal. While it excels at coding, it can help with anything you can do from the command line: writing docs, running builds, searching files, researching topics, and more. This guide covers the core architecture, built-in capabilities, and tips for working effectively. For step-by-step walkthroughs, see [Common workflows](</docs/en/common-workflows>). For extensibility features like skills, MCP, and hooks, see [Extend Claude Code](</docs/en/features-overview>). -## - -​ - -The agentic loop +## The agentic loop When you give Claude a task, it works through three phases: **gather context** , **take action** , and **verify results**. These phases blend together. Claude uses tools throughout, whether searching files to understand your code, editing to make changes, or running tests to check its work. The loop adapts to what you ask. A question about your codebase might only need context gathering. A bug fix cycles through all three phases repeatedly. A refactor might involve extensive verification. Claude decides what each step requires based on what it learned from the previous step, chaining dozens of actions together and course-correcting along the way. You’re part of this loop too. You can interrupt at any point to steer Claude in a different direction, provide additional context, or ask it to try a different approach. Claude works autonomously but stays responsive to your input. The agentic loop is powered by two components: models that reason and tools that act. Claude Code is the layer around the model that provides the tools and manages the context the model sees. This surrounding layer is what the term agentic harness refers to. -### - -​ - -Models +### Models Claude Code uses Claude models to understand your code and reason about tasks. Claude can read code in any language, understand how components connect, and figure out what needs to change to accomplish your goal. For complex tasks, it breaks work into steps, executes them, and adjusts based on what it learns. [Multiple models](</docs/en/model-config>) are available with different tradeoffs. Sonnet handles most coding tasks well. Opus provides stronger reasoning for complex architectural decisions. Switch with `/model` during a session or start with `claude --model <name>`. When this guide says “Claude chooses” or “Claude decides,” it’s the model doing the reasoning. -### - -​ - -Tools +### Tools Tools are what make Claude Code agentic. Without tools, Claude can only respond with text. With tools, Claude can act: read your code, edit files, run commands, search the web, and interact with external services. Each tool use returns information that feeds back into the loop, informing Claude’s next decision. The built-in tools generally fall into five categories, each representing a different kind of agency. @@ -43,11 +31,7 @@ Each tool use gives Claude new information that informs the next step. This is the agentic loop in action. **Extending the base capabilities:** The built-in tools are the foundation. You can extend what Claude knows with [skills](</docs/en/skills>), connect to external services with [MCP](</docs/en/mcp>), automate workflows with [hooks](</docs/en/hooks>), and offload tasks to [subagents](</docs/en/sub-agents>). These extensions form a layer on top of the core agentic loop. See [Extend Claude Code](</docs/en/features-overview>) for guidance on choosing the right extension for your needs. -## - -​ - -What Claude can access +## What Claude can access When you run `claude` in a directory, Claude Code gains access to: @@ -60,19 +44,11 @@ Because Claude sees your whole project, it can work across it. When you ask Claude to “fix the authentication bug,” it searches for relevant files, reads multiple files to understand context, makes coordinated edits across them, runs tests to verify the fix, and commits the changes if you ask. This is different from inline code assistants that only see the current file. -## - -​ - -Environments and interfaces +## Environments and interfaces The agentic loop, tools, and capabilities are the same everywhere you use Claude Code. What changes is where the code executes and how you interact with it. -### - -​ - -Execution environments +### Execution environments Claude Code runs in three environments, each with different tradeoffs for where your code executes. @@ -82,51 +58,27 @@ **Cloud**| Anthropic-managed VMs, or [self-hosted environments](</docs/en/self-hosted-environments>) your organization operates| Offload tasks, work on repos you don’t have locally **Remote Control**| Your machine, controlled from a browser| Use the web UI while execution and your files stay local -### - -​ - -Interfaces +### Interfaces You can access Claude Code through the terminal, the [desktop app](</docs/en/desktop>), [IDE extensions](</docs/en/vs-code>), [claude.ai/code](<https://claude.ai/code>), [Remote Control](</docs/en/remote-control>), [Slack](</docs/en/slack>), and [CI/CD pipelines](</docs/en/github-actions>). The interface determines how you see and interact with Claude, but the underlying agentic loop is identical. See [Use Claude Code everywhere](</docs/en/overview#use-claude-code-everywhere>) for the full list. -## - -​ - -Work with sessions +## Work with sessions Claude Code saves your conversation locally as you work. Each message, tool use, and result is written to a plaintext JSONL file under `~/.claude/projects/`, which enables rewinding, resuming, and forking sessions. Before Claude makes code changes, it also snapshots the affected files so you can revert if needed. For paths, retention, and how to clear this data, see [application data in `~/.claude`](</docs/en/claude-directory#application-data>). **Sessions are independent.** Each new session starts with a fresh context window, without the conversation history from previous sessions. Claude can persist learnings across sessions using [auto memory](</docs/en/memory#auto-memory>), and you can add your own persistent instructions in [CLAUDE.md](</docs/en/memory>). -### - -​ - -Work across branches +### Work across branches Each Claude Code conversation is a session tied to your current directory. The `/resume` picker shows sessions from the current worktree by default, with keyboard shortcuts to widen the list to other worktrees or projects. See [Manage sessions](</docs/en/sessions#use-the-session-picker>) for the full list of picker shortcuts and how name resolution works. Claude sees your current branch’s files. When you switch branches, Claude sees the new branch’s files, but your conversation history stays the same. Claude remembers what you discussed even after switching. Since sessions are tied to directories, you can run parallel Claude sessions by using [git worktrees](</docs/en/worktrees>), which create separate directories for individual branches. -### - -​ - -Resume or fork sessions +### Resume or fork sessions Resuming a session with `claude --continue` or `claude --resume` reopens it under the same session ID and appends new messages to the existing conversation. Forking with `--fork-session` or `/branch` copies the history into a new session ID, leaving the original unchanged. For the resume flags, the `/resume` picker, naming, and what happens when the same session is open in two terminals, see [Manage sessions](</docs/en/sessions>). -### - -​ - -The context window +### The context window Claude’s context window holds your conversation history, file contents, command outputs, [CLAUDE.md](</docs/en/memory>), [auto memory](</docs/en/memory#auto-memory>), loaded skills, and system instructions. As you work, context fills up. Claude compacts automatically, but instructions from early in the conversation can get lost. Put persistent rules in CLAUDE.md, and run `/context` to see what’s using space. For an interactive walkthrough of what loads and when, see [Explore the context window](</docs/en/context-window>). -#### - -​ - -Context Claude Code adds on its own +#### Context Claude Code adds on its own If Claude follows a rule you didn’t write, such as adding a `Co-Authored-By` trailer to a commit, the rule may have come from a [system reminder](</docs/en/glossary#system-reminder>). As you work, Claude Code adds its own context to the conversation alongside your messages: @@ -137,43 +89,23 @@ To change or remove the attribution lines, set [`attribution`](</docs/en/settings-reference#attribution>). To remove Claude Code’s built-in commit and pull request instructions, set [`includeGitInstructions`](</docs/en/settings-reference#includegitinstructions>) to `false`. For the other switches, see [Turn off the context your agent replaces](</docs/en/agent-sdk/modifying-system-prompts#turn-off-the-context-your-agent-replaces>). -#### - -​ - -When context fills up +#### When context fills up Claude Code manages context automatically as you approach the limit. It compacts the conversation into a summary. The summary keeps your requests and key code snippets, but detailed instructions from early in the conversation may be lost. Put persistent rules in CLAUDE.md rather than relying on conversation history. To control what’s preserved during compaction, add a “Compact Instructions” section to CLAUDE.md or run `/compact` with a focus (like `/compact focus on the API changes`). If a single file or tool output is so large that context refills immediately after each summary, Claude Code stops auto-compacting after a few attempts and shows an error instead of looping. See [Auto-compaction stops with a thrashing error](</docs/en/troubleshooting#auto-compaction-stops-with-a-thrashing-error>) for recovery steps. Run `/context` to see what’s using space. MCP tool definitions are deferred by default and loaded on demand via [tool search](</docs/en/mcp#scale-with-mcp-tool-search>), so only tool names and server instructions consume context until Claude uses a specific tool. -#### - -​ - -Manage context with skills and subagents +#### Manage context with skills and subagents Beyond compaction, you can use other features to control what loads into context. [Skills](</docs/en/skills>) load on demand. Claude sees skill descriptions at session start, but the full content only loads when a skill is used. For skills you invoke manually, set `disable-model-invocation: true` to keep descriptions out of context until you need them. For skills you didn’t write, use [`skillOverrides`](</docs/en/skills#override-skill-visibility-from-settings>) to do the same from settings. [Subagents](</docs/en/sub-agents>) work in their own context window. A subagent starts fresh unless it’s a [fork](</docs/en/sub-agents#fork-the-current-conversation>), which starts with a copy of your conversation so far. Either way, the subagent’s tool calls stay out of your context, and Claude gets back a summary when the subagent finishes. See [context costs](</docs/en/features-overview#understand-context-costs>) for what each feature costs, and [reduce token usage](</docs/en/costs#reduce-token-usage>) for tips on managing context. -## - -​ - -Stay safe with checkpoints and permissions +## Stay safe with checkpoints and permissions Claude has two safety mechanisms: checkpoints let you undo file changes, and permissions control what Claude can do without asking. -### - -​ - -Undo changes with checkpoints +### Undo changes with checkpoints **File edits are reversible.** Before Claude edits a file, it snapshots the current contents. If something goes wrong, press `Esc` twice to rewind to a previous state, or ask Claude to undo. Checkpoints are separate from git and remain available when you resume a conversation. They only cover file changes, and a restore [skips symlinked and hard-linked files](</docs/en/checkpointing#symlinked-and-hard-linked-paths-not-restored>). Actions that affect remote systems (databases, APIs, deployments) can’t be checkpointed. You control those with your permission mode and permission rules. -### - -​ - -Control what Claude can do +### Control what Claude can do Choose a permission mode to set what Claude can do without asking you. Press `Shift+Tab` to cycle through the permission modes: @@ -186,30 +118,18 @@ * * * -## - -​ - -Work effectively with Claude Code +## Work effectively with Claude Code These tips help you get better results from Claude Code. For more on specific prompts, verification, and the rules worth enforcing rather than prompting for, see [Best practices](</docs/en/best-practices>). -### - -​ - -Ask Claude Code for help +### Ask Claude Code for help Claude Code can teach you how to use it. Ask questions like “how do I set up hooks?” or “what’s the best way to structure my CLAUDE.md?” and Claude will explain. Built-in commands also guide you through setup: * `/init` generates a starter CLAUDE.md for your project * `/doctor` runs a setup checkup that diagnoses installation and configuration issues and can fix them -### - -​ - -It’s a conversation +### It’s a conversation Claude Code is conversational. You don’t need perfect prompts. Start with what you want, then refine: @@ -221,22 +141,14 @@ [Claude adjusts approach] When the first attempt isn’t right, you don’t start over. You iterate. -#### - -​ - -Interrupt and steer +#### Interrupt and steer You can redirect Claude at any point without starting over. Do either of these: * **Press`Esc`** to stop Claude immediately. The running tool call is canceled and Claude waits for your next instruction. If you have messages queued, Claude Code [sends them next](</docs/en/interactive-mode#queue-messages-while-claude-works>). * **Type a correction and press`Enter`** without stopping Claude. The message shows as queued in the conversation. If Claude is running tool calls, it reads the message as soon as those calls finish, within the same turn, and adjusts before its next step. [Queue messages while Claude works](</docs/en/interactive-mode#queue-messages-while-claude-works>) covers when other queued entries are sent. -### - -​ - -Delegate, don’t dictate +### Delegate, don’t dictate Think of delegating to a capable colleague. Give context and direction, then trust Claude to figure out the details: @@ -245,11 +157,7 @@ You don’t need to specify which files to read or what commands to run. Claude figures that out. -## - -​ - -What’s next +## What’s next ## Extend with features
modified Install and manage plugins View current →
Show diff (289 lines)
--- a/install.md +++ b/install.md @@ -7,11 +7,7 @@ Start with Install a plugin. If someone sent you an install command whose `@` name isn’t `claude-plugins-official`, add that marketplace first. -## - -​ - -Install a plugin +## Install a plugin As an example, this section installs [`commit-commands`](<https://github.com/anthropics/claude-plugins-official/tree/main/plugins/commit-commands>) from [Anthropic’s official marketplace](</docs/en/plugins/anthropic-marketplaces>), which adds commands for committing, pushing, and opening pull requests. The same steps install any other plugin: substitute its name and its marketplace’s name wherever `commit-commands` and `claude-plugins-official` appear. If that plugin comes from a different marketplace, add the marketplace first. Pick the tab for where you run Claude Code. @@ -129,11 +125,7 @@ A [cloud session](</docs/en/cloud-environments>), including [the browser at claude.ai/code](</docs/en/claude-code-on-the-web>), has no plugin browser and doesn’t load the plugins you installed on your own machine or the ones your repository’s `.claude/settings.json` turns on. For plugins your organization distributes through managed settings, see [Manage plugins for your organization](</docs/en/plugins/org>).See [which parts of your setup are also available in a cloud session](</docs/en/cloud-environments#what-carries-over-from-your-setup>) for the rest of your setup. -### - -​ - -Choose an install scope +### Choose an install scope A plugin’s install scope decides who gets the plugin and which settings file records it as enabled: @@ -143,11 +135,7 @@ Some plugins are set by their author to start turned off, through the [`defaultEnabled`](</docs/en/plugins/manifest-reference#defaultenabled>) field. Such a plugin is installed but stays off until you turn it on with `claude plugin enable <name>` in your shell, or from the **Installed** tab of `/plugin` in a session. When the same plugin is set at several scopes, the local setting overrides the project setting, and the project setting overrides the user setting. See [Find where a plugin is enabled](</docs/en/plugins/loading#find-where-a-plugin-is-enabled>) for the full rule. The terminal, the desktop app’s local sessions, and the VS Code extension on one computer read the same settings files, so a plugin you install at user scope in any of them is available in the other two. -### - -​ - -JetBrains, non-interactive runs, and the Agent SDK +### JetBrains, non-interactive runs, and the Agent SDK Some places you run Claude Code have no plugin browser of their own: @@ -159,11 +147,7 @@ If you’re a plugin author testing a copy of your plugin on disk, start Claude Code from your shell with `--plugin-dir` to load it for one session instead of installing it. See [Flags that load a plugin for one session](</docs/en/plugins/cli-reference#flags-that-load-a-plugin-for-one-session>). -### - -​ - -Plugins from your claude.ai account +### Plugins from your claude.ai account Your claude.ai account is a separate source of plugins, alongside the marketplaces you install from: @@ -173,11 +157,7 @@ For sync timing, sign-in requirements, and turning sync off, see [Plugins synced from claude.ai](</docs/en/plugins/loading#synced-plugins>). -### - -​ - -Install from your shell +### Install from your shell Run `claude plugin install` in your shell to install a plugin without starting a Claude Code session, for example from a setup script. @@ -189,11 +169,7 @@ The command prints `Successfully installed plugin: formatter@your-org (scope: project)` when it finishes. Some plugins install by running a command that their marketplace names, called a [`command` source](</docs/en/plugins/marketplace-reference#command-plugin-source>). Claude Code shows you that command and asks you to accept it before it runs. A script has no one to answer that prompt, so pass `--yes` there to accept it. For the other `claude plugin install` flags, see [plugin install](</docs/en/plugins/cli-reference#plugin-install>). -## - -​ - -Add a marketplace +## Add a marketplace You only need this section when the plugin you want isn’t in Anthropic’s official marketplace, for example one a coworker published or one from Anthropic’s community marketplace. A marketplace is a catalog of plugins, and Claude Code has to know about a marketplace before you can install from it. You add a marketplace once. After that, its plugins appear on the **Discover** tab and install with `/plugin install <plugin>@<marketplace>` in a session or `claude plugin install <plugin>@<marketplace>` in your shell, where `<marketplace>` is the name the marketplace registered under. To do both in one step, see Add a marketplace and install in one command. In a Claude Code session, run `/plugin marketplace add` followed by the marketplace’s source: a GitHub repository, a git repository on any host, a local directory or file, or a hosted `marketplace.json`. @@ -210,19 +186,11 @@ Include the `https://` prefix on every URL, or use the `git@host:path` form for SSH. If you type a bare `gitlab.example.com/your-group/your-marketplace.git`, Claude Code reads it as GitHub `owner/repo` shorthand and rejects it. When the command succeeds, it prints `Successfully added marketplace: <name>`, and the marketplace’s plugins appear on the **Discover** tab the next time you open `/plugin`, with no reload needed. If it fails, match the error message in [Troubleshoot plugins](</docs/en/plugins/troubleshooting#add-a-marketplace>). -### - -​ - -Add a marketplace and install in one command +### Add a marketplace and install in one command To install a plugin from a marketplace you haven’t added yet, name the marketplace source with `--marketplace` on the install command, in a session or from your shell. The source takes the same forms as `/plugin marketplace add`, such as GitHub `owner/repo`, a git URL, or a local path. Give the plugin name by itself, without an `@marketplace` suffix. -#### - -​ - -Add and install in a session +#### Add and install in a session Run `/plugin install` in a Claude Code session with the plugin and the source. Requires Claude Code v2.1.275 or later. In a session, the source can’t contain spaces. @@ -230,11 +198,7 @@ If you haven’t added that marketplace yet, Claude Code shows the source it resolved and asks you to confirm before adding it. Once the marketplace is added, the plugin’s details open and you choose an installation scope. If the source matches a marketplace you’ve already added, Claude Code skips the confirmation and opens the plugin’s details in that marketplace. -#### - -​ - -Add and install from your shell +#### Add and install from your shell In your shell, without starting a session, run `claude plugin install` with the plugin and the source. Requires Claude Code v2.1.292 or later. @@ -242,11 +206,7 @@ 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. -### - -​ - -Add a private marketplace +### Add a private marketplace A private marketplace is one in a repository you need credentials to clone, on GitHub or any other git host. You add it with the same `/plugin marketplace add` or `claude plugin marketplace add` command as a public one. Claude Code clones it with the git credentials already on your machine and never prompts, so each way of connecting has a requirement: @@ -256,11 +216,7 @@ The same credentials apply when you run `/plugin install`, `/plugin marketplace update`, and `claude plugin update`. On a GitHub Enterprise Server host, see [Plugin marketplaces on GHES](</docs/en/github-enterprise-server#plugin-marketplaces-on-ghes>) for the credentials each operation needs. If your organization registers the marketplace for you through managed settings, you don’t add it yourself. See [Pre-install and require plugins](</docs/en/plugins/org#pre-install-and-require-plugins>). -### - -​ - -Add a marketplace from claude.ai +### Add a marketplace from claude.ai In terminal sessions where [plugins sync from your claude.ai account](</docs/en/plugins/loading#synced-plugins>), claude.ai can also list plugin marketplaces for you, such as your organization’s plugin library and your own claude.ai uploads. You add one of these by its name rather than by a source. Adding a marketplace from claude.ai requires Claude Code v2.1.273 or later. Add a claude.ai marketplace from the `/plugin` panel or from your shell: @@ -273,11 +229,7 @@ Claude Code registers the marketplace under a local name that starts with `claudeai-`, derived from the name that claude.ai lists it under. For example, a marketplace listed as “Organization library” becomes `claudeai-organization-library`. Install its plugins by that name, for example with `claude plugin install <plugin>@claudeai-organization-library`. If you sign out, or sign in to a different claude.ai organization, the marketplace stays configured but shows no plugins, and the plugins you already installed from it keep loading. The `From claude.ai:` section can also list git-based marketplaces shared through claude.ai, and it prints a source for each of those. Add them by that source as in Add a marketplace, not with `--claudeai`. -## - -​ - -Manage installed plugins +## Manage installed plugins The **Installed** tab in `/plugin` lists your plugins with actions to enable, disable, update, or uninstall each one. In a Claude Code session, run `/plugin` and press **Tab** to reach it, or run `/plugin enable`, `/plugin disable`, or `/plugin uninstall` to open the panel and make that change there. Disabled plugins are grouped under a collapsed header at the bottom of the list. Use these keys on the list: @@ -292,11 +244,7 @@ The tab can also show plugins at **Managed** scope. Your organization installed those through [managed settings](</docs/en/settings#settings-files>), and you can’t enable, disable, or uninstall them here. For a synced plugin that your organization requires on claude.ai, see Manage plugins synced from claude.ai. When you close the `/plugin` panel with pending changes you made in it, Claude Code runs `/reload-plugins` for you to apply them. If the reload would [invalidate the prompt cache](</docs/en/prompt-caching#enabling-or-disabling-a-plugin>), it warns and leaves the changes pending instead. Run `/reload-plugins --force` to apply them anyway. -### - -​ - -Manage plugins synced from claude.ai +### Manage plugins synced from claude.ai The **Installed** tab in `/plugin` also lists the [plugins synced from your claude.ai account](</docs/en/plugins/loading#synced-plugins>), with `synced` as their source. Synced plugins appear in terminal sessions on Claude Code v2.1.273 or later. @@ -305,38 +253,22 @@ When Claude Code syncs an added, updated, or removed plugin into an interactive session, you see `Plugins changed. Run /reload-plugins to activate.` Run `/reload-plugins` to load the change in that session, or leave it for the next time you start Claude Code. -### - -​ - -Uninstall a plugin the project enables +### Uninstall a plugin the project enables When you choose **Uninstall** for a plugin that this repository’s `.claude/settings.json` enables, whether from the **Installed** tab or with `/plugin uninstall`, Claude Code asks whether to disable it for you or uninstall it for everyone: * **Disable for me** : press **y**. Claude Code writes `false` for the plugin in your `.claude/settings.local.json` and leaves it installed for the project. * **Uninstall for everyone** : press **u**. Claude Code removes the plugin from the shared `.claude/settings.json`. -### - -​ - -See what an installed plugin adds to your sessions +### See what an installed plugin adds to your sessions In your shell, run `claude plugin details <name>` for an installed plugin. The `Always-on` line is the number of tokens the plugin adds to every session where it’s enabled, and the per-component rows show which skill or agent contributes most. For the full output and what each figure means, see [Measure what a plugin costs](</docs/en/plugins/measure#measure-what-a-plugin-costs>). -### - -​ - -Find plugins you no longer use +### Find plugins you no longer use On the **Installed** tab in `/plugin`, plugins you installed yourself and haven’t used recently appear under a **Not used recently** header, and each plugin’s details show a **Last used** line. Use that header and that line to find plugins that still add startup and context cost, then disable or uninstall them. -### - -​ - -Plugins with dependencies +### Plugins with dependencies A plugin can declare other plugins that it depends on. When you install, disable, or uninstall such a plugin from a marketplace, Claude Code acts on those dependencies too: @@ -347,11 +279,7 @@ If you loaded the plugin with `--plugin-dir` instead, see [Test a plugin and its dependency locally](</docs/en/plugins/dependencies#test-a-plugin-and-its-dependency-locally>). -### - -​ - -Manage plugins from your shell +### Manage plugins from your shell You can also manage plugins without starting a Claude Code session. In your shell, run `claude plugin install`, `enable`, `disable`, or `uninstall` as ordinary terminal commands; they change the same settings the `/plugin` panel does. Each takes `--scope` to target one scope, and uses a default scope when you omit it: @@ -364,11 +292,7 @@ claude plugin enable formatter@your-org claude plugin uninstall formatter@your-org --scope project -## - -​ - -Keep plugins updated +## Keep plugins updated Plugins update automatically when the marketplace they came from has auto-update turned on. After a session starts, Claude Code refreshes those marketplaces and updates the on-disk copies of the plugins you installed from them. The running session keeps the versions it already loaded. After an update, you see `Plugin updated: <name> · Run /reload-plugins to apply`, and the next session loads the new versions automatically. These are the auto-update defaults for each kind of marketplace: @@ -377,35 +301,19 @@ For when auto-update runs, which plugins it skips, and the environment variables that turn it off, see [When auto-update runs](</docs/en/plugins/loading#when-auto-update-runs>). -### - -​ - -Turn auto-update on or off for a marketplace +### Turn auto-update on or off for a marketplace In a Claude Code session, run `/plugin` and go to the **Marketplaces** tab. Select the marketplace, then select **Enable auto-update** or **Disable auto-update**. -### - -​ - -Update plugins now +### Update plugins now To update one plugin, open it on the **Installed** tab in `/plugin` during a session and select **Update now** , or run `claude plugin update <plugin>@<marketplace>` in your shell. There’s no command that updates every plugin at once. To update the plugins you installed from one marketplace at once, go to the **Marketplaces** tab in `/plugin`, select the marketplace, and choose **Update marketplace**. That refreshes the marketplace’s listing, updates the plugins you installed from it, and reports any plugin it left for you to update yourself. A plugin with a [`command` source](</docs/en/plugins/marketplace-reference#command-plugin-source>) or with a marketplace entry that sets a `headersHelper` command isn’t updated this way, so you update it from its view on the **Installed** tab or with `claude plugin update <plugin>@<marketplace>`. If you run `claude plugin marketplace update` in your shell with no name, it refreshes every marketplace’s listing but leaves your installed plugins at their current versions. -### - -​ - -Auto-update from a private marketplace +### Auto-update from a private marketplace For a private marketplace, see [What background auto-update does with credentials](</docs/en/plugins/host-marketplace#what-background-auto-update-does-with-credentials>) for how background auto-updates authenticate over SSH and HTTPS, and [Troubleshoot plugins](</docs/en/plugins/troubleshooting#add-a-marketplace>) for the messages you see when they fail. -## - -​ - -Manage marketplaces +## Manage marketplaces The **Marketplaces** tab in `/plugin` lists every marketplace you registered, along with its source. Select one to browse its plugins, update its listing, turn auto-update on or off, or remove it. You can also list, update, and remove marketplaces with commands, from your shell or inside a session: @@ -417,11 +325,7 @@ When you remove a marketplace, Claude Code uninstalls every plugin you installed from it and removes their `enabledPlugins` entries from your settings files. The **Marketplaces** tab names those plugins before it asks you to confirm. -## - -​ - -Next steps +## Next steps * [Anthropic’s marketplaces](</docs/en/plugins/anthropic-marketplaces>): how the official and community marketplaces differ and where to browse each one * [Plugin loading reference](</docs/en/plugins/loading>): why a plugin loaded, didn’t load, or didn’t change after an update
modified Interactive mode View current →
Show diff (706 lines)
--- a/interactive-mode.md +++ b/interactive-mode.md @@ -1,16 +1,8 @@ -## - -​ - -Keyboard shortcuts +## Keyboard shortcuts Keyboard shortcuts may vary by platform and terminal. In [fullscreen rendering](</docs/en/fullscreen>), press `?` in the transcript viewer to see available shortcuts there.**macOS users** : Option/Alt key shortcuts (`Alt+B`, `Alt+F`, `Alt+D`, `Alt+Y`, `Alt+P`) require configuring Option as Meta in your terminal. See [Enable Option key shortcuts on macOS](</docs/en/terminal-config#enable-option-key-shortcuts-on-macos>) for the setting in each terminal. -### - -​ - -General controls +### General controls Shortcut| Description| Context ---|---|--- @@ -32,16 +24,12 @@ `Esc`| Interrupt Claude, or close a dialog| Stop the current response or tool call mid-turn so you can redirect. Claude keeps the work done so far. If you have messages queued, Claude Code sends them next. When a dialog is open, `Esc` closes the dialog. While a footer item is selected, such as a row in the [subagent panel](</docs/en/sub-agents#run-subagents-in-foreground-or-background>) below the prompt, `Esc` [deselects it](</docs/en/keybindings#footer-actions>) instead of interrupting. On a permission prompt, `Esc` declines the action, the same as [**No** without a comment](</docs/en/permissions#add-a-comment-when-you-answer-a-permission-prompt>) `Esc` \+ `Esc`| Clear input draft, or rewind| When the prompt input contains text, double `Esc` clears it and saves the draft to history so `Up` recalls it. When the input is empty, double `Esc` opens the [rewind menu](</docs/en/checkpointing>) to restore or summarize code and conversation from a previous point `Ctrl+Enter` or `Ctrl+X Ctrl+S`| Send queued messages now| Sends your queued messages, and your draft with them, right away. When Claude Code sends what you queued covers what happens to the turn Claude is working on. In shell mode, the key only queues your command. In terminals that don’t report extended keys, `Ctrl+Enter` arrives as plain `Enter`; `Ctrl+X Ctrl+S` works in any terminal. Requires Claude Code v2.1.275 or later -`Shift+Tab`, or `Alt+M` on Windows when the Node or Bun runtime doesn’t enable VT input mode| Cycle permission modes| Cycle through `default` (labeled Manual in the mode indicator), `acceptEdits`, `plan`, and, when available, `bypassPermissions` and then `auto`. From `auto`, the first press switches to `default`. See [permission modes](</docs/en/permission-modes>). On a file permission prompt, the same key closes an open [comment field](</docs/en/permissions#add-a-comment-when-you-answer-a-permission-prompt>). With no field open, it selects the option that allows the action for the rest of the session, when the prompt offers that option +`Shift+Tab`, or `Alt+M` on Windows when the Node or Bun runtime doesn’t enable VT input mode| Cycle permission modes| Cycle through `default` (labeled Manual in the mode indicator), `acceptEdits`, and `plan`, then `bypassPermissions` and `auto` where available. See [permission modes](</docs/en/permission-modes>). On a file permission prompt, the same key closes an open [comment field](</docs/en/permissions#add-a-comment-when-you-answer-a-permission-prompt>). With no field open, it selects the option that allows the action for the rest of the session, when the prompt offers that option. At the plan approval prompt, it approves the plan `Option+P` (macOS) or `Alt+P` (Windows/Linux)| Switch model| Switch models without clearing your prompt `Option+T` (macOS) or `Alt+T` (Windows/Linux)| Toggle extended thinking| Enable or disable extended thinking mode. Has no effect on Opus 5.5, Sonnet 5.5, Haiku 5.5, or the Fable models, which always use extended thinking. Works on macOS without configuring Option as Meta `Option+O` (macOS) or `Alt+O` (Windows/Linux)| Toggle fast mode| Enable or disable [fast mode](</docs/en/fast-mode>) -### - -​ - -Text editing +### Text editing Shortcut| Description| Context ---|---|--- @@ -57,43 +45,27 @@ `Alt+D`| Delete to end of word| Deletes to the end of the current word, or to the end of the next word when the cursor is between words. Stores deleted text for pasting. Requires Option as Meta on macOS `Ctrl+_` or `Ctrl+Shift+-`| Undo last input edit| Restores the previous input text and cursor position -### - -​ - -Word boundaries in editing shortcuts +### Word boundaries in editing shortcuts The word shortcuts `Alt+B`, `Alt+F`, `Alt+D`, `Option+Delete`, and `Ctrl+Backspace` treat a word as a run of letters and digits, so punctuation such as `_`, `.`, and `/` separates words. With `src/utils/foo.ts` in the prompt, repeated presses of `Alt+B` stop at the start of `ts`, `foo`, `utils`, and `src`. `Ctrl+W` is different: it ignores punctuation and deletes back to the previous whitespace, so one press removes all of `src/utils/foo.ts`. In text written without spaces, such as Chinese or Japanese, the word shortcuts still move or delete one word at a time. These readline conventions apply in Claude Code v2.1.261 and later. The [`keybindingFlavor`](</docs/en/settings-reference#keybindingflavor>) setting that turned them on in earlier versions is deprecated and has no effect. You can’t remap these shortcuts in the [keybindings configuration file](</docs/en/keybindings>), which has no actions for them. -### - -​ - -Theme and display +### Theme and display Shortcut| Description| Context ---|---|--- `Ctrl+T`| Toggle syntax highlighting for code blocks| Only works inside the `/theme` picker menu. Controls whether code in Claude’s responses uses syntax coloring -### - -​ - -Multiline input +### Multiline input Method| Shortcut| Context ---|---|--- Quick escape| `\` \+ `Enter`| Works in all terminals Option key| `Option+Enter`| After enabling [Option as Meta](</docs/en/terminal-config#enable-option-key-shortcuts-on-macos>) on macOS -Shift+Enter| `Shift+Enter`| Native in iTerm2, WezTerm, Ghostty, Kitty, Warp, Apple Terminal, Windows Terminal. For other terminals, see [Enter multiline prompts](</docs/en/terminal-config#enter-multiline-prompts>) +Shift+Enter| `Shift+Enter`| Native in iTerm2, WezTerm, Ghostty, Kitty, Warp, Windows Terminal. For other terminals, see [Enter multiline prompts](</docs/en/terminal-config#enter-multiline-prompts>) Control sequence| `Ctrl+J`| Works in any terminal without configuration Paste mode| Paste directly| For code blocks, logs -### - -​ - -Quick commands +### Quick commands Shortcut| Description| Notes ---|---|--- @@ -103,11 +75,7 @@ `:`| Emoji shortcode| Type a full `:name:` to insert the emoji, or two or more characters for suggestions. See Emoji shortcodes `?` on empty input| Toggle the shortcut help panel| Typing `?` when the input already contains text inserts the character -### - -​ - -Transcript viewer +### Transcript viewer When the transcript viewer is open (toggled with `Ctrl+O`), these shortcuts are available. Run `/tui` with no argument to check which renderer is active. `Ctrl+E` can be rebound via [`transcript:toggleShowAll`](</docs/en/keybindings>). @@ -120,29 +88,17 @@ `v`| Write the conversation to a temporary file and open it in `$VISUAL` or `$EDITOR`. Requires [fullscreen rendering](</docs/en/fullscreen>) `q`, `Ctrl+C`, `Esc`| Exit transcript view. All three can be rebound via [`transcript:exit`](</docs/en/keybindings>) -### - -​ - -Voice input +### Voice input Shortcut| Description| Notes ---|---|--- Hold or tap `Space`| Voice dictation| Requires [voice dictation](</docs/en/voice-dictation>) to be enabled. Hold to record, or run `/voice tap` for tap-to-toggle. [Rebindable](</docs/en/voice-dictation#rebind-the-dictation-key>) -## - -​ - -Commands +## Commands Type `/` in Claude Code to see the commands available to you, or type `/` followed by any letters to filter. The `/` menu lists built-in commands, bundled and user-authored [skills](</docs/en/skills>), and commands contributed by [plugins](</docs/en/plugins/overview>) and [MCP servers](</docs/en/mcp#use-mcp-prompts-as-commands>). Not all built-in commands are visible to every user since some depend on your platform or plan, and [a few available commands are hidden from the menu by design](</docs/en/commands#how-the-command-menu-matches-what-you-type>) and run when you type their full name. In [fullscreen rendering](</docs/en/fullscreen#use-the-mouse>), the `/` command and `@` file suggestion lists also respond to the mouse: hovering highlights a row and clicking accepts it. See the [commands reference](</docs/en/commands>) for the full list of commands included in Claude Code. -### - -​ - -Complete a command mid-prompt +### Complete a command mid-prompt Command completion also works partway through a prompt: type `/` after a space, then the first letters of a name, as in `run the tests, then /com`. Only commands whose names start with those letters match, so a file path such as `/tmp/notes.md` doesn’t keep a list open. Claude Code runs a command itself only when the command [starts your message](</docs/en/commands>). @@ -151,19 +107,11 @@ In both renderers, press `Tab` on a bare mid-prompt `/` to list every command. A plugin skill matches on its bare name too, so `/deploy` finds a skill named `myplugin:deploy-app`. When you insert the match, Claude Code writes the full `/myplugin:deploy-app`. -## - -​ - -Vim editor mode - -Enable vim-style editing via `/config` → Editor mode. Claude Code keeps your vim mode and cursor position when you toggle the transcript viewer with `Ctrl+O` or open and close a panel such as `/config`. If you leave the prompt in NORMAL mode, it’s still in NORMAL mode when you return, with the cursor where you left it. - -### - -​ - -Mode switching +## Vim editor mode + +Enable vim-style editing via `/config` → Editor mode. + +### Mode switching Command| Action| From mode ---|---|--- @@ -177,11 +125,7 @@ `v`| Start character-wise visual selection| NORMAL `V`| Start line-wise visual selection| NORMAL -### - -​ - -Remap INSERT-mode key sequences +### Remap INSERT-mode key sequences The [`vimInsertModeRemaps`](</docs/en/settings-reference#viminsertmoderemaps>) setting maps a two-key INSERT-mode sequence to Escape, so a mapping like `jj` returns you to NORMAL mode. The following `~/.claude/settings.json` example turns on vim mode and maps `jj` to Escape: @@ -192,11 +136,7 @@ Each key is exactly two printable characters typed in sequence, and `"<Esc>"` is the only supported target. Entries with a different length or target are ignored. Typing the first character of a sequence inserts it normally. Pressing the second character within one second removes that pending character and switches to NORMAL mode, leaving neither character in your input. After the one-second window, or if a different key follows, both characters stay as literal text, so you can still type a word containing the sequence by pausing between the two keys. Claude Code reads this setting from your user settings file, the `--settings` flag, and [managed settings](</docs/en/managed-settings>) only. Entries in a project’s `.claude/settings.json` or `.claude/settings.local.json` are ignored, so a checked-out repository can’t remap your keystrokes. -### - -​ - -Navigation (NORMAL mode) +### Navigation (NORMAL mode) Command| Action ---|--- @@ -221,11 +161,7 @@ In vim NORMAL mode, if the cursor is at the beginning or end of input and can’t move further, `j`/`k` and `↑`/`↓` navigate command history instead. `←` on an empty prompt opens [agent view](</docs/en/agent-view>) from NORMAL mode as well as INSERT. -### - -​ - -Editing (NORMAL mode) +### Editing (NORMAL mode) Command| Action ---|--- @@ -254,11 +190,7 @@ `u`| Undo `.`| Repeat last change -### - -​ - -Text objects (NORMAL mode) +### Text objects (NORMAL mode) Text objects work with operators like `d`, `c`, and `y`: @@ -272,11 +204,7 @@ `i[`/`a[`| Inner/around brackets `i{`/`a{`| Inner/around braces -### - -​ - -Visual mode +### Visual mode Press `v` for character-wise selection or `V` for line-wise selection. Motions extend the selection, and operators act on it directly. @@ -296,19 +224,11 @@ Block-wise visual mode with `Ctrl+V` is not supported. -### - -​ - -Cancel a question in vim mode +### Cancel a question in vim mode When you’re typing your own answer in the `Other` row of a [question Claude asks](</docs/en/tools-reference#askuserquestion-tool-behavior>), press `Esc` twice to cancel the question. To cancel with a single key press instead, [bind another key to cancel the question](</docs/en/keybindings#cancel-a-question-with-one-key-press>). -## - -​ - -Command history +## Command history Claude Code keeps a history of the prompts you type, and Up-arrow recall reaches prompts from past sessions of the same project: @@ -318,22 +238,14 @@ * When you recall a prompt that included pasted text, Claude Code sends the full pasted content again when you resubmit. If the content has since been [cleaned up](</docs/en/claude-directory#cleaned-up-automatically>), Claude Code doesn’t send the literal `[Pasted text #N]` string; see [Paste large content](</docs/en/terminal-config#paste-large-content>) for what happens to the prompt * History expansion with `!` is disabled by default -### - -​ - -Bring back a cleared draft +### Bring back a cleared draft To get back a draft you cleared with `Ctrl+C`, press `Up`, either right away or after you’ve sent a message or command: * **Right after clearing the draft** : press `Up` once while the prompt is still empty. Requires Claude Code v2.1.288 or later. * **After sending a message or command** : press `Up` to step back to the draft. Claude Code keeps the ten most recent cleared drafts for the current session, with their pasted text and images, and discards them when you exit. Requires Claude Code v2.1.292 or later. -### - -​ - -Reverse search with Ctrl+R +### Reverse search with Ctrl+R Press `Ctrl+R` to interactively search through your command history. In [fullscreen rendering](</docs/en/fullscreen>), `Ctrl+R` opens a search dialog instead. Type to filter in the dialog, and press `Up` and `Down` to move through the list of matches, with a preview pane showing the start of the highlighted match. In the dialog, press `Ctrl+S` to cycle the scope through this session, this project, and all projects. Press `Enter` or `Tab` to place a match in the prompt input, or `Esc` to cancel. The steps below describe the classic renderer’s inline search: @@ -348,21 +260,13 @@ * Press `Ctrl+C` to cancel and restore your original input * Press `Backspace` on empty search to cancel -Accepting a match or canceling the search takes effect immediately, even while Claude Code is still loading the history. To find an earlier prompt when all you remember is something long you pasted into it, such as an error log, press `Ctrl+R` and type a word from the paste. Requires Claude Code v2.1.314 or later. - -## - -​ - -Background Bash commands +To find an earlier prompt when all you remember is something long you pasted into it, such as an error log, press `Ctrl+R` and type a word from the paste. Requires Claude Code v2.1.314 or later. + +## Background Bash commands Claude Code supports running Bash commands in the background, allowing you to continue working while long-running processes execute. -### - -​ - -How backgrounding works +### How backgrounding works When Claude Code runs a command in the background, it runs the command asynchronously and immediately returns a background task ID. Claude Code can respond to new prompts while the command continues executing in the background. To run commands in the background, you can either: @@ -390,11 +294,7 @@ * Development servers * Long-running processes (docker, terraform) -### - -​ - -Shell mode with `!` prefix +### Shell mode with `!` prefix Run shell commands directly without going through Claude by prefixing your input with `!`: @@ -415,19 +315,11 @@ Unless your session is one of those listed under [strict sandbox mode](</docs/en/sandboxing#turn-off-the-retry-with-strict-sandbox-mode>), commands you type in shell mode run outside the [sandbox](</docs/en/sandboxing>) even when you’ve enabled sandboxing, because the sandbox applies to the commands Claude runs. Claude responds to the command output automatically once it lands in the transcript, so you can run `! npm test` and get an explanation of the failures without a second prompt. The response costs the same as sending a normal prompt. To add the output to context without a response instead, set [`respondToBashCommands`](</docs/en/settings-reference#respondtobashcommands>) to `false` in `settings.json`. -## - -​ - -Queue messages while Claude works +## Queue messages while Claude works Type a message and press `Enter` while Claude is working. Claude Code queues the message instead of interrupting the turn, and lists the queued entries in the conversation until it sends them. You can queue `!` shell commands and most [commands](</docs/en/commands>) the same way, apart from the commands, such as `/status`, that Claude Code runs as soon as you send them. Sent and queued messages show in gray until Claude starts responding to them, so you can tell which messages Claude hasn’t started on yet. If you queue a message with a selection attached from a [connected IDE](</docs/en/vs-code#the-built-in-ide-mcp-server>), it keeps the selection you had when you pressed `Enter`, whatever you select afterward. -### - -​ - -When Claude Code sends what you queued +### When Claude Code sends what you queued When a queued entry reaches Claude depends on what you queued. @@ -445,30 +337,18 @@ * `/effort`: the next message you send runs at the new level. To [start it in the turn Claude is already working on](</docs/en/model-config#when-a-new-effort-level-starts>), queue a message while Claude is running tool calls * [`/fast`](</docs/en/fast-mode#toggle-fast-mode>): Claude Code keeps the fast mode setting that was active when the turn started, so your speed change applies from your next turn. If your current model doesn’t support fast mode, turning it on also [switches your model](</docs/en/prompt-caching#turning-on-fast-mode>), and Claude Code uses the new model from its next request in that turn -### - -​ - -Background a session with messages queued +### Background a session with messages queued When the session moves to the background after you [press `←`](</docs/en/agent-view#switch-sessions-without-leaving-the-terminal>), the messages you had queued move with it. Claude reads them there in the order you sent them. Commands and `!` shell commands can’t move, and neither can some messages, such as one with an [IDE selection](</docs/en/vs-code#the-built-in-ide-mcp-server>) attached. If you press `←` while one of them is queued, the session stays in the foreground and a notice that begins `Cannot open agents` appears. To background the session, get the entry out of the queue and then press `←` again: * **Commands and`!` shell commands**: wait for them to run at the end of the turn, or take them back and clear the input box. While anything else is queued, you can’t take `!` shell commands back, so wait for them to run. * **Messages that can’t move** : wait until Claude has read them -### - -​ - -Take back what you queued +### Take back what you queued Press `Up` from the first line of the input box to take back the queued messages and commands. Claude Code removes them from the queue and puts them in the input box, one per line, ahead of any text you had typed. Edit the text and press `Enter` to queue it again as one entry, or clear the input box to drop it. Claude Code takes back queued shell commands only when the input box is empty and you have nothing else queued, and it switches the input box to shell mode when it does. Otherwise it leaves them in the queue, listed with their `!` prefix, and runs them after the turn ends. If you take back queued text while `←` [waits to background the session](</docs/en/agent-view#switch-sessions-without-leaving-the-terminal>), the text stays in the input box and Claude Code cancels the switch. If you take it back at the moment the session moves, the text disappears with the foreground screen: it wasn’t sent. Each message you took back is saved as its own entry in command history. To recover one, reopen the session and press `Up` on an empty prompt with nothing queued. -## - -​ - -Prompt suggestions +## Prompt suggestions When you first open a session, Claude Code shows a grayed-out example command in the prompt input to help you get started. It picks this from your project’s git history, so the example reflects files you’ve been working on recently. After Claude responds, Claude Code can suggest your next prompt based on your conversation history, such as a follow-up step from a multi-part request or a natural continuation of your workflow. @@ -477,11 +357,7 @@ Claude Code generates each of these next-prompt suggestions with a short background request to the same model your session is using. The request counts toward your plan’s usage limits or your API costs. Because it reuses the conversation’s prompt cache, it is mostly cache reads plus a few output tokens, so the added cost is small. -### - -​ - -When Claude Code skips suggestions +### When Claude Code skips suggestions In interactive mode, Claude Code leaves prompt suggestions off by default and hides the **Prompt suggestions** toggle in `/config` in a [session that doesn’t fetch feature flags](</docs/en/env-vars#features-that-need-feature-flag-fetching>), such as one on a third-party provider or through a Claude apps gateway, and in a [first session after an install or upgrade](</docs/en/env-vars#first-session-after-an-install-or-upgrade>) whose flags haven’t arrived yet. Claude Code also skips individual suggestions in several situations, including: @@ -494,11 +370,7 @@ The notice `Showing fewer prompt suggestions · use one to bring them back` means Claude Code is showing suggestions less often because you left many in a row unused. To return to the usual frequency, use a suggestion or set [`CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION`](</docs/en/env-vars>) to `true`. In print mode, Claude Code doesn’t generate suggestions by default. Pass [`--prompt-suggestions`](</docs/en/cli-reference#cli-flags>) with `-p "<prompt>" --output-format stream-json --verbose` to have Claude Code emit a `prompt_suggestion` message after each turn that generates one. The generator skips very short conversations and cold prompt caches here too, so a single short `-p` query can emit none. -### - -​ - -Turn prompt suggestions off +### Turn prompt suggestions off To disable prompt suggestions entirely, use any of the following: @@ -510,11 +382,7 @@ To turn prompt suggestions off across an organization, set `promptSuggestionEnabled` to `false` in [managed settings](</docs/en/managed-settings>). Also set `CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION` to `false` under the managed [`env`](</docs/en/settings-reference#env>) key so that users can’t re-enable them with their own environment variable. -## - -​ - -You should know suggestions +## You should know suggestions “You should know” looks for one thing you should know but might have missed, such as a tradeoff Claude chose without calling it out or a result that may be off. When it finds one, it shows a short note above the prompt input: @@ -532,19 +400,11 @@ Where `/plugin` doesn’t list the mod, the enable command answers `Plugin "cc-plugin-you-should-know@builtin" is not installed in this project`. -### - -​ - -Cost of checks +### Cost of checks While the mod is on, checks are background requests to the same model your session is using, and they count toward your plan’s usage limits or your API costs. Each check sends what’s already in Claude’s context, meaning the conversation so far with its tool results, followed by the mod’s own instructions and the text of your recent notes. The conversation part is read from the session’s [prompt cache](</docs/en/prompt-caching>) on the same terms as Claude’s own next request. The instructions, several thousand tokens of them, and the side agent’s reply are billed in full on every check. To watch the checks happen, set [`CLAUDE_CODE_YOU_SHOULD_KNOW_DEBUG=1`](</docs/en/env-vars>) in your shell before you start Claude Code. -### - -​ - -Answer a note +### Answer a note Type the choice’s digit on its own into an empty prompt input. A note offers these choices: @@ -557,22 +417,14 @@ The main agent doesn’t see a note unless you send it with **Chat in main session**. Claude Code keeps your recent notes and the topics you marked as known in a file whose name starts with `cc-plugin-you-should-know` under `~/.claude/plugins/store/`. Each check, in this session and later ones, lists them to the side agent as ones not to repeat. Claude Code deletes the file once it has gone [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>) without a session reading or writing it. To clear them sooner, delete that file while no session is running. -### - -​ - -Turn off You should know +### Turn off You should know To turn off You should know, use either of the following: * At the Claude Code prompt, run `/plugin disable cc-plugin-you-should-know@builtin`, or turn it off from the **Installed** tab of `/plugin` * After you choose **Dismiss** on a note without opening **Learn more** first, choose **Turn off suggestions** on the `Dismissed.` line, which clears after 20 seconds -## - -​ - -Emoji shortcodes +## Emoji shortcodes Type a `:` followed by an emoji shortcode in the prompt input to insert the emoji. @@ -581,28 +433,16 @@ The shortcode must start the input or follow a space, so a `:` inside a word or URL doesn’t open suggestions. To turn the feature off, set [`emojiCompletionEnabled`](</docs/en/settings-reference#emojicompletionenabled>) to `false` in `settings.json`. This disables both the suggestion popup and the inline replacement. -## - -​ - -Check spelling as you type +## Check spelling as you type Claude Code can underline misspelled words in the prompt input while you type. It checks only the text in the input box, never Claude’s replies or your files. It also checks nothing while the input box is in shell mode, `Ctrl+R` history search, or [voice dictation](</docs/en/voice-dictation>). Spell checking is off by default, and Claude Code checks nothing in [screen reader mode](</docs/en/accessibility>). Requires Claude Code v2.1.235 or later. -### - -​ - -Prerequisites +### Prerequisites * Install [aspell](<https://github.com/GNUAspell/aspell>), [hunspell](<https://github.com/hunspell/hunspell>), or [ispell](<https://en.wikipedia.org/wiki/Ispell>) and make sure it’s on your `PATH`. Claude Code runs the first of the three it finds, in that order, on every platform, including a `.cmd` shim a package manager installs on Windows. * To check that the program is on your `PATH`, run `aspell --version`, `hunspell --version`, or `ispell -v` in your terminal. A “command not found” error means it isn’t on your `PATH` yet. -### - -​ - -Turn spell checking on or off +### Turn spell checking on or off Claude Code reads the [`spellcheck`](</docs/en/settings-reference#spellcheck>) setting from three places, and ignores it in a project’s `.claude/settings.json` and `.claude/settings.local.json`. Turn it on from whichever one you use: @@ -653,24 +493,16 @@ If more than one of the three places has a `spellcheck` setting, Claude Code uses only one of them: managed settings first, then `--settings`, then user settings. It doesn’t combine fields from two places. For example, when `--settings` sets `spellcheck`, a `language` in your user settings has no effect. -### - -​ - -What Claude Code underlines - -Shortly after you pause typing, Claude Code underlines the words the dictionary doesn’t know. It leaves the word you’re still typing alone until you move past it, and it never changes your text. It also skips text that looks like code: +### What Claude Code underlines + +Shortly after you pause typing, Claude Code underlines the words the dictionary doesn’t know. It leaves the word you’re still typing alone until you move past it. It also skips text that looks like code: * Commands such as `/help`, `@` mentions, URLs, file paths, and flags such as `--verbose` * Words with digits, underscores, or a capital letter after the first, and text in backticks Claude Code also skips Chinese, Japanese, Korean, Thai, Lao, Khmer, and Myanmar text. Claude Code has no word list of its own: a word is misspelled when your checker says so. To stop Claude Code from underlining a word, add the word to your checker’s personal dictionary, following the checker’s own documentation. Claude Code picks up the new word after you restart it. -### - -​ - -When Claude Code underlines nothing +### When Claude Code underlines nothing Claude Code underlines nothing when it can’t keep a checker running: @@ -680,19 +512,11 @@ To find out which of these happened, start `claude --debug` with spell checking on and type a word. Then look for the `[spellcheck]` lines in the debug log at `~/.claude/debug/<session-id>.txt`. One line names the program Claude Code started, or lists the ones it looked for and didn’t find. Later lines say why it stopped. A missing-dictionary error there means the checker has no dictionary for your `language` value, or no default one when `language` is unset. Install one, or set `language` to a dictionary you have. -## - -​ - -Invisible characters in prompts +## Invisible characters in prompts Pasted text can carry Unicode characters that a terminal draws as nothing at all, such as tag characters, bidirectional controls, and zero-width spaces, so a prompt can contain text you never see. To keep copied text from carrying instructions your terminal doesn’t draw, Claude Code removes those characters when you press Enter, before sending anything. It cleans both the prompt and the contents of any collapsed [pasted-text reference](</docs/en/terminal-config#paste-large-content>) the prompt includes. Claude Code keeps the joiners that Persian and Indic scripts write and the selectors inside emoji sequences. If Claude Code removed anything, that Enter sends nothing. The cleaned prompt goes back into the input box with a notice such as `Removed 3 invisible characters · review and press Enter to send`, and pressing Enter again sends the text as shown. When you pass a prompt on the command line, as in `claude "fix the login bug"`, Claude Code doesn’t wait for a second Enter. It removes the characters, shows a notice, and sends the cleaned prompt. If the cleaned prompt would begin with `/`, Claude Code puts it in the input box for you to review and send instead. -## - -​ - -Review changes with /diff +## Review changes with /diff Run `/diff` to look over the changes in your working tree without leaving Claude Code. You see the edits Claude has made so far alongside anything else you haven’t committed. What `/diff` opens depends on which renderer is active: @@ -701,11 +525,7 @@ The panel and the dialog both come from `cc-plugin-diff`, one of the [mods built into Claude Code](</docs/en/plugins/mods/overview#mods-built-into-claude-code>). If you disable that mod in `/plugin`, `/diff` opens Claude Code’s earlier panel and [diff viewer](</docs/en/keybindings#diff-actions>) instead. In the changes `/diff` reads from git, a submodule appears as a single entry, and only when the commit it points to changes; edits to files inside the submodule don’t appear there. The panel and the dialog also offer a view of each turn’s edits once Claude has edited files. These turn views come from Claude’s file edits rather than from git, so a change Claude makes through a shell command appears only under `Current`, the working-tree view. -### - -​ - -Diff panel +### Diff panel The diff panel lists the changed files with their added and removed line counts, and shows each file’s diff under the list. Claude Code refreshes it each time Claude edits a file or runs a shell command. To close the panel, run `/diff` again or click the `✕` in its header. To use the panel you need: @@ -724,11 +544,7 @@ To rebind the keys that scroll the file list or change the comparison, see [Diff panel actions](</docs/en/keybindings#diff-panel-actions>). During an unfinished merge, rebase, cherry-pick, or revert, the panel keeps showing the changes it last read from git, so it doesn’t fill with the operation’s incoming changes. It updates at its first refresh after the operation ends, for example when Claude next edits a file. -### - -​ - -Diff dialog +### Diff dialog The diff dialog opens as a bordered block above the prompt and lists your changed files with their added and removed line counts. It compares them against `HEAD`, or against whatever you last chose in the diff panel for this repository. Once Claude has edited files, a `source` picker appears above the list. It offers one turn view, labeled `T1`, `T2`, and so on, for each of your prompts that led Claude to edit files. A turn view shows only that turn’s edits, and `Current` returns you to the working tree. Use these keys in the dialog: @@ -737,11 +553,7 @@ * **Esc** : return from a file’s diff to the list, or close the dialog from the list. * **Tab** : move to the `source` picker, then choose `Current` or a turn view with Up and Down and press Enter. In a file’s diff, Tab moves to the `ask` button. Press Enter to attach that file’s diff to your next prompt. -## - -​ - -Side questions with /btw +## Side questions with /btw Use `/btw` to ask a question about your current work without adding to the conversation history. @@ -767,19 +579,11 @@ In an attached [background session](</docs/en/agent-view#attach-to-a-session>), `Left` detaches and returns you to agent view, even while the answer is still arriving. The side question keeps running while you’re away. The next time you attach to the session, the overlay reopens with the side question, or with its answer. Before v2.1.257, `Left` didn’t detach there. `/btw` sees your full conversation, or the subagent transcript you have open, but has no tools. A [subagent](</docs/en/sub-agents>) has tools and starts from the prompt it receives. A [fork](</docs/en/sub-agents#fork-the-current-conversation>) starts from a copy of this conversation. Use `/btw` to ask about what Claude already knows from this session; use a subagent to go find out something new. -### - -​ - -Ask /btw about a subagent +### Ask /btw about a subagent With a [subagent’s transcript open](</docs/en/sub-agents#observe-and-steer-running-forks>), Claude answers `/btw` from that transcript instead of the main conversation, so you can ask what the subagent did. A later `/btw` from that transcript sees only the side questions you asked from it. Requires Claude Code v2.1.314 or later. From an [agent team](</docs/en/agent-teams>) teammate’s transcript, Claude answers from the main conversation. -## - -​ - -Task list +## Task list The task list is Claude’s to-do checklist: items Claude created to plan multi-step work, with indicators showing what’s pending, in progress, or complete. It’s separate from the background-task view. To see running shells and subagents, use [`/tasks`](</docs/en/commands>) instead. The list fills only in sessions that have the task-tracking tools, which Claude Code provides by default on [Opus 4.7, Sonnet 4.6, Haiku 4.5, and earlier models](</docs/en/tools-reference#task-tool-availability>). On any other model, including a model ID Claude Code doesn’t recognize, the list stays empty unless you opt in with `CLAUDE_CODE_ENABLE_TODO_TOOLS=1` or one of the other ways under [Task tool availability](</docs/en/tools-reference#task-tool-availability>). When the session has the tools, the task list works as follows: @@ -789,19 +593,11 @@ * Tasks persist across context compactions, helping Claude stay organized on larger projects * To share a task list across sessions, set `CLAUDE_CODE_TASK_LIST_ID` to use a named directory in `~/.claude/tasks/`: `CLAUDE_CODE_TASK_LIST_ID=my-project claude` -## - -​ - -Session recap +## Session recap When you return to the terminal after stepping away, Claude Code shows a one-line recap of what happened in the session so far. The recap generates in the background once at least three minutes have passed since the last completed turn and the terminal is unfocused, so it’s ready when you switch back. Recaps only appear once the session has at least three turns, and never twice in a row. Run `/recap` to generate a summary on demand. It runs only when you ask for it yourself. When it arrives in a message relayed from a Slack, Teams, or project thread, you get a [notice](</docs/en/errors#recap-only-runs-when-you-ask-for-it-yourself>) instead of a recap. You also get the notice when `/recap` arrives in a prompt a cloud scheduled task sent. Session recap is on by default for every plan and provider. To turn automatic recaps off, open `/config` and turn off **Session recap**. The automatic recap never appears in non-interactive mode. Claude Code caps both automatic recaps and `/recap` output at 400 characters. -## - -​ - -Wait for a usage limit to reset +## Wait for a usage limit to reset When a claude.ai [usage limit](</docs/en/errors#youve-hit-your-session-limit>) stops Claude mid-task, Claude Code waits in the open session and continues the task on its own after the limit resets. Automatic continue is on by default in interactive sessions signed in with a claude.ai subscription. Requires Claude Code v2.1.234 or later. While Claude Code waits, the lines at the bottom of the session show when your limit resets and when Claude will continue: @@ -816,11 +612,7 @@ In the continued task, Claude Code still asks for [permissions](</docs/en/permissions>) as usual, so the task can stop on a prompt while you’re away. If the task hits the limit again, the wait starts again. After three automatic continuations, automatic continue stops and the `Automatic continue stopped after repeated usage-limit hits` notification appears. Run `/rate-limit-options` to choose what to do next. When you send another prompt, or pick a wait from that menu, the count starts over. Automatic continue also stops after three continuations for a [`/goal`](</docs/en/goal>) or [session-scoped scheduled task](</docs/en/scheduled-tasks>) that runs through several reset windows. -### - -​ - -Cancel the wait +### Cancel the wait Press `Esc` at an empty prompt, or `Ctrl+C`, while the lines show, or run [`/rate-limit-options`](</docs/en/commands#all-commands>) and pick **Don’t continue automatically**. Claude Code confirms with a line that starts `Automatic continue cancelled`. After a cancel, nothing continues until you send a prompt or pick the row that starts **Wait here, then continue automatically** from `/rate-limit-options` again. Claude Code doesn’t start a wait on its own again for that reset window; the next reset window starts fresh. The wait also ends without continuing the task in these cases: @@ -830,11 +622,7 @@ * **The setting turns off, or the reset moves past 24 hours** : this ends only a wait Claude Code started on its own. A wait you picked from `/rate-limit-options` keeps counting down. * **The continuation is blocked** : a [`UserPromptSubmit` hook](</docs/en/hooks#userpromptsubmit>) that blocks the continuation prompt, or a failure before it reaches the model, ends the wait. Claude Code tells you the continuation didn’t run. Send a prompt to continue. -### - -​ - -Start a wait yourself +### Start a wait yourself Claude Code doesn’t start the wait on its own in these cases: @@ -848,19 +636,11 @@ * **API keys, cloud providers, and usage-based billing** : usage there is metered per request, so there is no reset to wait for. * **An[LLM gateway](</docs/en/llm-gateway#subscriptions-and-gateways>) without a saved claude.ai login**: Claude Code offers the wait only while a saved claude.ai login is the active credential. -### - -​ - -Turn automatic continue off +### Turn automatic continue off In `/config`, turn off **Continue automatically at usage limit** , or set [`autoContinueAtUsageLimit`](</docs/en/settings-reference#autocontinueatusagelimit>) to `false` in your user settings. `/config autoContinueAtUsageLimit=false` also works, including with `-p`, but the `key=value` form can’t turn it back on, because the setting grants unattended execution. Which settings files Claude Code reads for this key is in the [settings reference](</docs/en/settings-reference#autocontinueatusagelimit>). -## - -​ - -PR review status +## PR review status When working on a branch with an open pull request, Claude Code displays a clickable PR link in the footer, such as “PR #446”. The link has a colored underline indicating the review state: @@ -877,11 +657,7 @@ * **A GitHub Enterprise host set as`GH_HOST`**: `GH_ENTERPRISE_TOKEN` or `GITHUB_ENTERPRISE_TOKEN`, or the token saved by `gh auth login --hostname <host>`. Without one, the footer shows the same hints * **Any other GitHub host** : the token saved by `gh auth login --hostname <host>`. Without one, Claude Code shows no badge and no hint -### - -​ - -GitLab merge requests +### GitLab merge requests When you work on a branch with an open GitLab merge request, Claude Code shows a clickable `MR !N` badge in the footer slot that otherwise holds the GitHub PR link. `!N` is GitLab’s own reference syntax for merge request number N. The colored underline shows the merge request’s state: @@ -897,11 +673,7 @@ Claude Code ignores `glab`’s token environment variables, such as `GITLAB_TOKEN`, when it checks status, so you get no badge from an exported token alone. Claude Code also looks for `glab` and for its login once per session, so restart Claude Code after you install `glab` or run `glab auth login`. -## - -​ - -Issue reference links +## Issue reference links When Claude mentions an issue as `owner/repo#123`, you can click the reference to open it, as long as your terminal supports hyperlinks. If Claude Code doesn’t detect hyperlink support in your terminal, set [`FORCE_HYPERLINK`](</docs/en/env-vars>) to `1` to turn the links on, or to `0` to keep references as plain text. You get a link only for the two-part `owner/repo#123` form. These stay plain text: @@ -918,11 +690,7 @@ gitlab.com| `https://gitlab.com/owner/repo/-/issues/123` bitbucket.org, codeberg.org, or gitea.com| No link; the reference stays plain text -## - -​ - -See also +## See also * [Skills](</docs/en/skills>) \- Custom prompts and workflows * [Checkpointing](</docs/en/checkpointing>) \- Rewind Claude’s edits and restore previous states
modified Draw in the interface with a mod View current →
Show diff (429 lines)
--- a/interface.md +++ b/interface.md @@ -2,11 +2,7 @@ To look up one prop or limit, see the [reference](</docs/en/plugins/mods/reference#render-sites>). -## - -​ - -Build a pane with tabs +## Build a pane with tabs In this section you build a mod that adds a `/hello-tabs` command, and the command opens a pane. A pane is a sidebar beside the transcript in a wide fullscreen terminal, or a framed region above the prompt otherwise. This pane shows two tabs, and the second tab has a button that adds one to a counter. The count is still there after you restart Claude Code. The finished mod looks like this. The recording opens the pane, switches to the second tab, presses the button a few times, and returns to the first tab: @@ -159,11 +155,7 @@ Press Esc to close the pane, then exit the session. In your shell, start Claude Code again with the same `claude --plugin-dir ./hello-tabs` command, and at the Claude Code prompt run `/hello-tabs`. The count is where you left it.To clear the count, have the mod call `$.store.delete('count')`. Keep state covers how long each kind of value lasts. -## - -​ - -Pick where to draw +## Pick where to draw A `ui.render` hook runs for every render site unless you narrow it to the one you want to draw in. To choose the render site, pass a filter, called a [matcher](</docs/en/plugins/mods/events#filter-which-events-a-hook-handles>), as the second argument to `on`. `{ component: 'Pane' }` runs the hook only for panes. In the hook, `e.component` names the site, `e.surface` says which app is drawing, and `e.props` holds the site’s own data. For a pane, `e.requestId` is the `id` you opened it with. The pane and the band are empty until a mod fills them. Select a tab to see what each one is and how to draw in it: @@ -177,11 +169,7 @@ A mod can also place a row of its own in the transcript. -### - -​ - -Change what Claude Code already draws +### Change what Claude Code already draws Claude Code draws most of its interface itself: messages, tool call rows, the spinner, and more. Each of those parts is a render site too, so a mod can restyle or replace it. To change one, filter your `ui.render` hook on its name from this table: @@ -247,11 +235,7 @@ While Claude works, the spinner animates as before, and `under the spinner` appears below it. The permission prompt isn’t a render site, so a mod can’t change what it shows. The question dialog, `AskUserQuestion`, is one, so a mod can change that. A tree for the dialog has to hold the reference exactly once, with your elements above it. Otherwise, Claude Code draws its own dialog. -### - -​ - -Open a pane at the right time +### Open a pane at the right time A pane appears only when your mod opens it. How and when you open it decides whether it takes keyboard focus, how much room it asks for, and whether it shows at all in a narrow terminal. To open a pane, call [`$.ui.open`](</docs/en/plugins/mods/reference#mods-api-methods>) with an `id` you choose. The `id` is the pane’s name: your `ui.render` hook checks for it, and you pass it again to close the pane. @@ -279,19 +263,11 @@ To let a command open the pane while Claude is working, add `immediate: true` when you [register the command](</docs/en/plugins/mods/api#add-a-command>). Without it, a command typed during a turn waits for the turn to end. -#### - -​ - -Hold toasts behind a dialog +#### Hold toasts behind a dialog Pass `holdToasts: true` to `$.ui.open` when the pane is a dialog the user answers and leaves, so toasts don’t appear while they decide. In the terminal, the hold lasts while that pane is the one showing, and a toast raised in that time waits until the hold ends. Claude Code holds other mods’ toasts and its own short-lived notifications as well as the ones your mod raises with [`$.ui.toast`](</docs/en/plugins/mods/api#show-something-without-starting-a-turn>). Leave the field off a pane that stays open, so the user keeps seeing them. -#### - -​ - -When a pane waits for a wider terminal +#### When a pane waits for a wider terminal A pane your mod opens without being asked doesn’t appear in a narrow terminal, so it can’t take over a small screen. Whether it appears depends on what opened it: @@ -300,11 +276,7 @@ When the pane appears, `$.ui.open` resolves to `{ isPlaced: true }`. When the pane is waiting, `isPlaced` is `false` and `reason` is a string that says why. A waiting pane appears when the user opens it or widens the terminal. To say something is available without opening a pane, call `$.ui.toast('Your message')`, which shows a toast notification. -### - -​ - -Draw in the VS Code extension +### Draw in the VS Code extension In the VS Code extension, what a mod draws appears in the chat panel with extension version 2.1.299 or later. A session that [doesn’t fetch feature flags](</docs/en/env-vars#features-that-need-feature-flag-fetching>), such as one on Amazon Bedrock, needs 2.1.304 or later. In a `ui.render` hook for the panel, `e.surface` is `vscode`. To check which sites and elements the panel draws, and which props it ignores, see the [render sites](</docs/en/plugins/mods/reference#render-sites>) and [elements](</docs/en/plugins/mods/reference#elements>) tables. To make a mod work in the panel as well as the terminal, account for these differences: @@ -317,11 +289,7 @@ * **Prompt suggestions** : `$.prompt.suggest` resolves with `isShown: false` and shows nothing, because the panel keeps the prompt box’s dim suggestion text for Claude’s own suggestions. * **Text limits** : the panel cuts a status line at 200 characters or two rows, and a toast at 500 characters. -### - -​ - -Place a row in the transcript +### Place a row in the transcript A row is a line your mod adds to the transcript in the terminal, after the latest message. It stays at that spot as the conversation goes on, and Claude doesn’t see it. `$.ui.place` requires Claude Code v2.1.314 or later. @@ -365,11 +333,7 @@ * **A second call with the same`id`**: while the first row is still in the transcript, the call adds no row and resolves with that row’s `requestId`. To change what the row shows, redraw the row. * **When the row goes away** : when the conversation ends, when the user rewinds past the row, or, outside [fullscreen rendering](</docs/en/fullscreen>), when the conversation is compacted. `--resume` doesn’t bring the row back. To show the row again, call `$.ui.place` again. -### - -​ - -Put a backdrop behind the conversation +### Put a backdrop behind the conversation `$.theme.set` and `$.theme.clear` replace `$.ui.backdrop`, which Claude Code v2.1.319 removed. Change `$.ui.backdrop({ id: 'your-backdrop' })` to `$.theme.set({ backdrop: { id: 'your-backdrop' } })`, and `$.ui.backdrop(undefined)` to `$.theme.clear()`, which removes any mod’s backdrop. @@ -402,11 +366,7 @@ * **Whether the backdrop is drawn** : `$.theme.set` resolves with `isDrawn: true` when a Desktop or mobile app connected to the session says it draws backdrops. Otherwise `isDrawn` is `false` and `reason` says why. * **One backdrop for each session** : a `$.theme.set` call replaces the session’s backdrop and `$.theme.clear()` removes that backdrop, whichever mod set it. Call `$.theme.clear()` only when the user asks for it. -## - -​ - -Build a tree from elements +## Build a tree from elements What a `ui.render` hook returns is an element tree: a description of what to draw, made of boxes, text, and controls nested inside each other. You describe the drawing, and Claude Code renders it in whichever app the user has open: the terminal, the Desktop app, or the VS Code extension. To get the elements, call `$.ui.resolve(e)` in your hook, as in `const { Box, Text, Button } = $.ui.resolve(e)`. Each element is a function. You pass it props, and you put the elements and strings that go inside it in `children`. Select a tab to see each of the most common elements and how the terminal draws it: @@ -477,11 +437,7 @@ my-mod: ui.render hook skipped: returned the wrong shape (a tree Pane refuses: Text prop "bogusProp" is not allowed) -### - -​ - -`Link` in the Desktop app and VS Code +### `Link` in the Desktop app and VS Code In the Desktop app and the VS Code extension, a `Link` draws as plain text unless its `href` meets these requirements: @@ -491,19 +447,11 @@ In the terminal, these requirements don’t apply. -### - -​ - -When a `Client` fails +### When a `Client` fails In the terminal, when the file a `Client` runs fails, a dimmed line such as `my-mod: Client client/spinner.js: boom` takes the `Client`’s place, and the rest of your drawing still shows. If your mod handles [`ui.fault`](</docs/en/plugins/mods/reference#interface>), Claude Code then draws the site again. -### - -​ - -Draw a grid of colored cells +### Draw a grid of colored cells For a heat map, a sparkline, or a game board in the terminal, draw one `Raster` and not a `Box` for each cell. A `Raster` takes a `key`, its size in `columns` and `rows`, and `cells`, a base64 string that packs every cell. Each cell is three numbers: the character’s code point, its color, and its background color. A color is a 24-bit RGB value in hexadecimal, such as `0xc62828` for a red. The value `0x01000000`, one above that range, means the terminal’s default. Apps other than the terminal have no `Raster`, so check `e.surface` and draw text there. This pane body draws a three by two heat map: @@ -537,11 +485,7 @@ In the terminal, the pane shows the grid: The `rows` array is the part you’d change, and `cellsOf` turns it into the packed string. The hook draws only in a pane whose `id` is `heat`, so open one with `$.ui.open({ id: 'heat' })` from a command, as the `hello-tabs` example opens its pane. Each character has to be one cell wide. To animate a `Raster` that’s already on screen, call `$.ui.blit` with the pane’s `id` as `requestId`, the `Raster`’s `key`, the same size, and new cells. For this example, that’s `$.ui.blit({ requestId: 'heat', key: 'grid', columns: 3, rows: 2, cells: cellsOf(newRows) })`. It repaints that one element without running your `ui.render` hook again. -## - -​ - -Respond to presses and typing +## Respond to presses and typing When the user presses a button, types into a field, or picks from a list your mod drew, Claude Code calls that control’s callback, which runs in your module. Each control takes its own callbacks: @@ -549,11 +493,7 @@ * **`Input`** : takes `onSubmit(value)` and `onInput(value)` * **`Select`** : takes `onSelect(value)` with its choices in `options`, a list of at least one choice with unique values, such as `[{ value: 'sm', label: 'Small' }, { value: 'lg', label: 'Large' }]` -### - -​ - -Which controls need a `key` +### Which controls need a `key` Give every `Input` and `Select` a `key` prop, such as `key: 'size'`. A `Button` can go without a `key` when it has a `label` prop or a single string child. Its key is then the `label` value or that string. Tests and other mods identify a control by its key: @@ -562,19 +502,11 @@ If a message says `needs a key` or `is drawn twice`, [find the cause by that message](</docs/en/plugins/mods/troubleshoot#needs-a-key>). -### - -​ - -Keyboard focus and hotkeys +### Keyboard focus and hotkeys Your mod never reads the keyboard itself. The user presses a key, Claude Code decides which of your controls it’s for, and that control’s callback runs. Apart from a [digit hotkey on the band or an `action` binding](</docs/en/plugins/mods/reference#elements>), that happens only while your pane or band has keyboard focus. The rest of the time, keys go to the prompt. In the VS Code extension, buttons have no hotkeys: the user clicks a button or presses Enter on it, and types into fields. -#### - -​ - -How a pane gets keyboard focus +#### How a pane gets keyboard focus A pane gets keyboard focus when: @@ -584,11 +516,7 @@ Claude Code grants `focus: true` only while the prompt is empty and nothing else has keyboard focus. A pane that opens while the user is typing doesn’t take their keystrokes. -#### - -​ - -What each key does +#### What each key does This table lists what a key does while your pane or band has keyboard focus: @@ -606,11 +534,7 @@ A mod can’t bind Tab or the arrow keys to anything else, so a game steers with `w`, `a`, `s`, and `d`. -#### - -​ - -Set a hotkey and the first focus +#### Set a hotkey and the first focus * **`hotkey`** : to let the user press a `Button` with one key, give it a `hotkey` of one digit or one lowercase letter, as in `hotkey: 'a'` * **`autoFocus`** : to choose which control has the focus when the pane opens, add `autoFocus: true` to it. In the VS Code extension, `autoFocus` does nothing: the control draws as if you had left it out, and you don’t need to change anything. The prop accepts only `true`, so omit it on the other controls. @@ -624,11 +548,7 @@ In the terminal, name the key in a bracketed button’s label, or use `plain: true`, so the user can see what to press. The [elements reference](</docs/en/plugins/mods/reference#elements>) has the other `Button` rules: `action`, digit hotkeys on the band, and two buttons on one hotkey. -#### - -​ - -When the user collapses the band +#### When the user collapses the band In the terminal, while a mod draws in the band, the user can collapse the band to one row to get it out of the way: @@ -641,11 +561,7 @@ The same keys, or in fullscreen rendering a click on the row, expand the band again. Until then, nothing presses a button in it: no hotkey, no digit typed into an empty prompt, and no keybinding for a button’s [`action`](</docs/en/plugins/mods/reference#elements>). If the band has keyboard focus when the user collapses it, the focus returns to the prompt, and Ctrl+X then Tab skips the band while it’s collapsed. The band stays collapsed until the user expands it, even after `/clear`, and is expanded again the next time Claude Code starts. Your mod can’t expand it or tell that it’s collapsed: the `ui.render` hook keeps running, and nothing in `e.props` says so. Don’t make the band the only place your mod shows something the user has to answer. -### - -​ - -Take typed input and draw a row for each item +### Take typed input and draw a row for each item Many panes are a text field with a list under it. The example in this section is a notes pane: you type a note and press Enter to add it, and each note has an `x` button that deletes it. With two notes added, the terminal draws the pane this way: @@ -732,27 +648,15 @@ Submitting an `Input` doesn’t start a turn unless your callback calls [`$.prompt.submit`](</docs/en/plugins/mods/api#start-a-turn-from-a-background-job>). -## - -​ - -Redraw a site +## Redraw a site A drawing is a snapshot: it shows what your `ui.render` hook returned the last time the hook ran. To show something new, the hook has to run again. Claude Code runs it again for some changes, and your mod asks for the rest. -### - -​ - -When Claude Code redraws without being asked +### When Claude Code redraws without being asked Claude Code runs your `ui.render` hook again when the site’s props change or the terminal’s width changes. When a `Client` in the site fails and your mod handles [`ui.fault`](</docs/en/plugins/mods/reference#interface>), Claude Code runs the hook once more after your `ui.fault` hooks return, so your `ui.render` hook can leave the `Client` out. It doesn’t run the hook on a timer, and it can’t tell when a variable in your module changes. -### - -​ - -Redraw when your data changes +### Redraw when your data changes To have your sites drawn again after your own data changes, call `$.ui.invalidate('ui.render')`. This pane counts presses. The button’s callback changes `count`, then asks for a redraw: @@ -781,11 +685,7 @@ Each press raises the number in the pane. The `hello-tabs` example wraps the same call in its `redraw` function. A value you keep in `$.state` doesn’t need the call, because writing the value redraws the sites that read it. -### - -​ - -Redraw on a timer +### Redraw on a timer To keep a clock, a countdown, or a value from outside the session current, redraw on a schedule. Start a timer in the module’s `session.start` hook. If the module already has one, as `hello-tabs` does, add the [`$.clock.every`](</docs/en/plugins/mods/api#run-work-in-the-background>) line to it: @@ -797,19 +697,11 @@ Claude Code now runs your `ui.render` hook once a second. The timer stops after the module reloads, and the new instance of the module starts its own. -### - -​ - -How often a site can redraw +### How often a site can redraw Claude Code throttles redraws of a site, so your mod can call `$.ui.invalidate` as often as its data changes. For how often each site can redraw, see the [limits table](</docs/en/plugins/mods/reference#limits>). Calls that come faster than the limit are coalesced into one redraw. That redraw runs your hook once, and the hook reads your data as it is at that moment, so the latest value shows and the values in between don’t. An animation can’t run faster than the limit. -## - -​ - -Keep state +## Keep state Where a mod keeps a value decides how long the value lasts: until the module reloads, until the session ends, or from one session to the next. Choose by how long the value has to last: @@ -821,19 +713,11 @@ `$.store.get(key)` resolves to the value or `undefined`, and `$.store.set(key, value)` takes any JSON value. -### - -​ - -Keep a value in `$.state` +### Keep a value in `$.state` `$.state` holds values for the length of a session, and it redraws for you. It’s reactive state: a `ui.render` hook that reads a value subscribes to it, so Claude Code redraws that site each time you write the value, and you don’t call `$.ui.invalidate`. A value in `$.state` also survives a reload of the module, which a variable doesn’t. To set it up, declare your values, point your manifest at the declaration, then define and use each value. The examples move the `count` from `hello-tabs` into `$.state`. -#### - -​ - -Declare the values +#### Declare the values Declare the values in a type declaration file. The outer key is your plugin’s name, and each entry under it is a value and its type. Save this as `hello-tabs/types/index.d.ts`: @@ -848,11 +732,7 @@ } } -#### - -​ - -Point the manifest at the declaration +#### Point the manifest at the declaration To let `claude plugin validate` check your code against that file, add a `types` field to the manifest with its path: @@ -866,11 +746,7 @@ "types": "./types/index.d.ts" } -#### - -​ - -Define, read, and write a value +#### Define, read, and write a value In your module, define each value with a default, read it while drawing, and write it from a callback. `atom` names a value and its default, `read` returns it, and `update` writes it. The three helpers call `$.state.get` and `$.state.set` for you: @@ -892,11 +768,7 @@ * **Declare every value in the type declaration file** : otherwise validation fails with `hello-tabs.count is not declared` * **Write from a callback or another event’s hook** : a `ui.render` hook can read state and can’t write it, so write from `onPress`, `onSubmit`, or a hook for another event -#### - -​ - -Change `hello-tabs` to use `$.state` +#### Change `hello-tabs` to use `$.state` To move `count` in `hello-tabs` into `$.state`, change every line that uses it: @@ -907,11 +779,7 @@ Keep `redraw` for the tab buttons, because `tab` is still a variable. -### - -​ - -Load a saved value again after `/clear` +### Load a saved value again after `/clear` If your mod copies a saved value from `$.store` into `$.state` at `session.start`, it has to copy it again after `/clear`, `/resume`, or `/branch`. Those commands reset every `$.state` value to its default, and `session.start` doesn’t fire again. [`classic.SessionStart`](</docs/en/plugins/mods/events#hook-the-settings-hook-events>) does fire after each of them, with `e.source` set to `clear`, `resume`, or `fork`, so copy the value again in a hook on it. Otherwise your drawing shows the default, and a callback that saves the `$.state` value writes the default over what you stored. This code loads `count` from both hooks. It builds on the `$.state` version of `hello-tabs`, where `count` is an atom and `update` is imported. Put `loadCount` above `register`, and add the `loadCount` call to the `session.start` hook you already have. `classic.SessionStart` also fires at startup and after compaction, which doesn’t reset `$.state`, so the filter on `source` keeps the hook to the three resets: @@ -935,11 +803,7 @@ With both hooks in place, the pane shows the saved count after `/clear` and not `0`, and the next press of **Add one** adds to the saved count. `loadCount` writes the stored value over the one in `$.state`, and `session.start` fires again each time the module reloads. To keep the store from falling behind, save on every change, as the **Add one** button does. To check the reload without a session, [test the drawing after `/clear`](</docs/en/plugins/mods/test#test-a-drawing-after-clear>). -### - -​ - -Save from more than one session +### Save from more than one session Every session on your machine that runs your mod shares one `$.store`. A `get` followed by a `set` isn’t atomic. When two sessions each read a value, change it, and write it back, they race, and the second write replaces the first. To make that less likely: @@ -958,11 +822,7 @@ If a second session has pressed its own button three times since this session started, this press shows and saves a count that includes those three. -## - -​ - -Next steps +## Next steps * [React to events](</docs/en/plugins/mods/events>): feed your drawing from tool calls and turns * [Use the mods API](</docs/en/plugins/mods/api>): feed your drawing from timers and model calls
modified JetBrains IDEs View current →
Show diff (247 lines)
--- a/jetbrains.md +++ b/jetbrains.md @@ -1,10 +1,6 @@ Claude Code integrates with JetBrains IDEs through a dedicated plugin, providing features like interactive diff viewing, selection context sharing, and more. -## - -​ - -Supported IDEs +## Supported IDEs The Claude Code plugin works with most JetBrains IDEs, including: @@ -15,11 +11,7 @@ * PhpStorm * GoLand -## - -​ - -Features +## Features * **Quick launch** : use `Cmd+Esc` (Mac) or `Ctrl+Esc` (Windows/Linux) to open Claude Code directly from your editor, or click the Claude Code button in the UI * **Diff viewing** : Claude Code opens code changes in the IDE diff viewer instead of the terminal; change this with the **Diff tool** setting in `/config` @@ -27,11 +19,7 @@ * **File reference shortcuts** : use `Cmd+Option+K` (Mac) or `Alt+Ctrl+K` (Linux/Windows) to insert file references such as `@src/auth.ts#L1-99` * **Diagnostic sharing** : Claude reads the IDE’s inspection diagnostics, such as lint and syntax errors, by calling the `getDiagnostics` tool; Claude Code doesn’t request diagnostics from the plugin on its own after edits -## - -​ - -Installation +## Installation The plugin runs the `claude` command in your IDE’s integrated terminal and connects to it. It does not bundle its own copy of the CLI, so install both pieces: @@ -51,25 +39,13 @@ If `claude` is installed somewhere your IDE can’t find, set the full path in the plugin’s Claude command setting. Claude Code works with any paid Claude subscription (Pro, Max, Ultra, Team, or Enterprise) or a Claude Console account, and no API key is required. You’ll be prompted to [log in](</docs/en/authentication#log-in-to-claude-code>) the first time you run `claude`. -## +## Usage -​ - -Usage - -### - -​ - -Run Claude Code from your IDE +### Run Claude Code from your IDE Run `claude` from your IDE’s integrated terminal, and all integration features will be active. -### - -​ - -Connect from an external terminal +### 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: @@ -79,17 +55,9 @@ When the connection succeeds, Claude Code confirms with a message like `Connected to IntelliJ IDEA.` If you want Claude to have access to the same files as your IDE, start Claude Code from the same directory as your IDE project root. -## +## Configuration -​ - -Configuration - -### - -​ - -Claude Code settings +### Claude Code settings Configure IDE integration through Claude Code’s settings: @@ -99,19 +67,11 @@ The **Diff tool** entry appears in `/config` only when Claude Code is connected to the IDE, so run `claude` from the JetBrains terminal or run [`/ide`](</docs/en/commands>) first from an external terminal. See [`diffTool`](</docs/en/settings-reference#difftool>) for the underlying setting. -### - -​ - -Plugin settings +### Plugin settings Configure the Claude Code plugin by going to **Settings → Tools → Claude Code [Beta]** : -#### - -​ - -General settings +#### General settings * **Claude command** : specify a custom command to run Claude, for example `claude`, `/usr/local/bin/claude`, or `npx @anthropic-ai/claude-code` * **Suppress notification for when Claude Command is not found** : skip notifications about not finding the Claude command @@ -120,11 +80,7 @@ For WSL users: Set `wsl -d Ubuntu -- bash -lic "claude"` as your Claude command (replace `Ubuntu` with your WSL distribution name) -#### - -​ - -ESC key configuration +#### ESC key configuration If the ESC key doesn’t interrupt Claude Code operations in JetBrains terminals: @@ -136,33 +92,17 @@ This allows the ESC key to properly interrupt Claude Code operations. -## +## Special configurations -​ - -Special configurations - -### - -​ - -Remote development +### Remote development When using JetBrains Remote Development, you must install the plugin on the remote host via **Settings → Plugin (Host)** , not on your local client machine. -### - -​ - -WSL configuration +### WSL configuration If you’re using Claude Code on WSL2 with a JetBrains IDE and see “No available IDEs detected”, the cause is usually WSL2’s NAT networking or Windows Firewall blocking the connection between WSL2 and the IDE running on the Windows host. WSL1 uses the host’s network directly and isn’t affected. -#### - -​ - -Allow WSL2 traffic through Windows Firewall +#### Allow WSL2 traffic through Windows Firewall This is the recommended fix because it keeps your existing WSL2 networking mode. @@ -190,11 +130,7 @@ Close and reopen both so the new rule takes effect. -#### - -​ - -Switch WSL2 to mirrored networking +#### Switch WSL2 to mirrored networking Mirrored networking requires Windows 11 22H2 or later. If you’re on Windows 10, use the firewall rule above instead. Add this to `.wslconfig` in your Windows user directory: @@ -203,17 +139,9 @@ Then restart WSL with `wsl --shutdown` from PowerShell. -## +## Troubleshooting -​ - -Troubleshooting - -### - -​ - -Plugin not working +### Plugin not working If the plugin is installed but Claude Code features don’t appear in your IDE: @@ -222,11 +150,7 @@ * Completely restart the IDE (you may need to do this multiple times) * For Remote Development, ensure the plugin is installed in the remote host -### - -​ - -IDE not detected +### IDE not detected If the `/ide` command shows “No available IDEs detected”: @@ -235,11 +159,7 @@ * If you expected an automatic connection without running `/ide`, check that you launched `claude` from the IDE’s integrated terminal * For WSL users, see WSL configuration above -### - -​ - -Command not found +### Command not found If clicking the Claude icon shows “command not found”: @@ -247,11 +167,7 @@ 2. Configure the Claude command path in plugin settings 3. For WSL users, use the WSL command format mentioned in the configuration section -## - -​ - -Security considerations +## Security considerations When Claude Code runs in a JetBrains IDE in [`acceptEdits` permission mode](</docs/en/permission-modes#auto-approve-file-edits-with-acceptedits-mode>), it may be able to modify IDE configuration files that can be automatically executed by your IDE. This may increase the risk of running Claude Code in `acceptEdits` mode and allow bypassing Claude Code’s permission prompts for Bash execution. When running in JetBrains IDEs, consider: @@ -261,11 +177,7 @@ For Claude Code installation or login problems outside the IDE, see [Troubleshoot installation and login](</docs/en/troubleshoot-install>). -### - -​ - -The built-in IDE MCP server +### The built-in IDE MCP server When the plugin is active, it runs a local MCP server that the CLI connects to automatically. This is how the CLI opens diffs in the IDE’s native diff viewer, reads your current selection for `@`-mentions, and lets Claude read inspection diagnostics. The server is named `ide` and is hidden from `/mcp` because there’s nothing to configure. If your organization uses a [`PreToolUse` hook](</docs/en/hooks#pretooluse>) to allowlist MCP tools, though, you’ll need to know it exists. **Selection and open-file context.** While connected, the CLI includes your current editor selection and the path of the active file as context on each prompt you send. The transcript shows a `⧉ Selected N lines from <file>` line when this happens. If you [queue a message while Claude works](</docs/en/interactive-mode#queue-messages-while-claude-works>), it keeps the selection you had when you pressed `Enter`, whatever you select afterward. To exclude a sensitive file such as `.env`, add a [`Read` deny rule](</docs/en/permissions#read-and-edit>) for its path. A matching deny rule prevents both the selected text and the open-file notice for that file from reaching Claude. **Transport and authentication.** The server listens on an OS-assigned ephemeral port, and the port is not configurable. The transport is unencrypted `ws://`; on loopback, any process that could capture the traffic can also read the token from the lock file, so TLS would not add protection against a local attacker. Each IDE start generates a fresh random auth token, writes it to a lock file at `~/.claude/ide/<port>.lock`, and the CLI must present it as the `X-Claude-Code-Ide-Authorization` header to connect. If `CLAUDE_CONFIG_DIR` is set, the lock file is written to `$CLAUDE_CONFIG_DIR/ide/` instead. **Tools exposed to the model.** The server hosts several tools, but only one is visible to the model. The rest are internal RPC the CLI uses for its own UI, such as opening diffs and reading selections, and are filtered out before the tool list reaches Claude.
modified Customize keyboard shortcuts View current →
Show diff (567 lines)
--- a/keybindings.md +++ b/keybindings.md @@ -1,10 +1,6 @@ Claude Code supports customizable keyboard shortcuts. Run `/keybindings` to create or open your configuration file at `~/.claude/keybindings.json`. -## - -​ - -Configuration file +## Configuration file The keybindings configuration file is an object with a `bindings` array. Each block specifies a context and a map of keystrokes to actions. @@ -32,11 +28,7 @@ ] } -## - -​ - -Contexts +## Contexts Each binding block specifies a **context** where the bindings apply: @@ -72,19 +64,11 @@ Before v2.1.205, a `Doctor` context and a `doctor:fix` action existed for the `/doctor` diagnostics screen. -## - -​ - -Available actions +## Available actions Actions follow a `namespace:action` format, such as `chat:submit` to send a message or `app:toggleTodos` to show the task list. Each context has specific actions available. -### - -​ - -App actions +### App actions Actions available in the `Global` context: @@ -96,11 +80,7 @@ `app:toggleTodos`| Ctrl+T| Toggle visibility of Claude’s to-do checklist. This is not the [`/tasks`](</docs/en/commands>) background-task view `app:toggleTranscript`| Ctrl+O| Toggle verbose transcript -### - -​ - -History actions +### History actions Actions for navigating command history: @@ -110,11 +90,7 @@ `history:previous`| Up| Previous history item `history:next`| Down| Next history item -### - -​ - -Chat actions +### Chat actions Actions available in the `Chat` context: @@ -140,11 +116,7 @@ *On Windows without VT mode (Node <24.2.0/<22.17.0, Bun <1.2.23), defaults to Meta+M. -### - -​ - -Autocomplete actions +### Autocomplete actions Actions available in the `Autocomplete` context: @@ -155,11 +127,7 @@ `autocomplete:previous`| Up| Previous suggestion `autocomplete:next`| Down| Next suggestion -### - -​ - -Confirmation actions +### Confirmation actions Actions available in the `Confirmation` context: @@ -190,11 +158,7 @@ With these bindings, `y` and `n` still type as letters while a text field has focus. Before v2.1.280, `y` was also bound to `confirm:yes` and `n` to `confirm:no` by default. If you created your `keybindings.json` with `/keybindings` before v2.1.280, the file lists both bindings and they stay in effect until you delete those two lines. -### - -​ - -Permission actions +### Permission actions Actions available in the `Confirmation` context for permission dialogs: @@ -202,11 +166,7 @@ ---|---|--- `permission:toggleDebug`| (unbound)| Claude Code doesn’t respond to this action, and a `keybindings.json` that names it remains valid -### - -​ - -Transcript actions +### Transcript actions Actions available in the `Transcript` context: @@ -217,11 +177,7 @@ `transcript:toggleShowAll` applies in the classic renderer only; in [fullscreen rendering](</docs/en/fullscreen>), the transcript viewer doesn’t offer a show-all toggle. -### - -​ - -History search actions +### History search actions Actions available in the `HistorySearch` context: @@ -235,11 +191,7 @@ The `historySearch:next`, `historySearch:accept`, `historySearch:cancel`, and `historySearch:execute` defaults apply to the inline history search in the classic renderer, which always searches prompts from all projects. `historySearch:cycleScope` takes effect only in [fullscreen rendering](</docs/en/fullscreen>), where `Ctrl+R` opens a search dialog instead and `Ctrl+S` cycles its scope. The dialog’s other keys are fixed and can’t be rebound: `Enter` or `Tab` places the highlighted match in the prompt input and `Esc` cancels. -### - -​ - -Task actions +### Task actions Actions available in the `Task` context: @@ -247,11 +199,7 @@ ---|---|--- `task:background`| Ctrl+B, Ctrl+X Ctrl+B| Background current task -### - -​ - -Theme actions +### Theme actions Actions available in the `ThemePicker` context: @@ -259,11 +207,7 @@ ---|---|--- `theme:toggleSyntaxHighlighting`| Ctrl+T| Toggle syntax highlighting -### - -​ - -Help actions +### Help actions Actions available in the `Help` context: @@ -271,11 +215,7 @@ ---|---|--- `help:dismiss`| Escape| Close help menu -### - -​ - -Tabs actions +### Tabs actions Actions available in the `Tabs` context: @@ -286,11 +226,7 @@ In a tabbed dialog, `tabs:next` and `tabs:previous` switch tabs while the tab row has focus. In some dialogs, such as `/help` and `/sandbox`, the tab-switching keys also work from inside the tab’s content. `Up` and `Down` move focus between the tab row and the tab’s content, and a list in the content responds to keys only while it has focus. -### - -​ - -Attachments actions +### Attachments actions Actions available in the `Attachments` context: @@ -301,11 +237,7 @@ `attachments:remove`| Backspace, Delete| Remove selected attachment `attachments:exit`| Down, Escape| Exit attachment navigation -### - -​ - -Footer actions +### Footer actions Actions available in the `Footer` context: @@ -322,11 +254,7 @@ While a footer item is selected, such as a row in the agent panel below the prompt, `Enter` opens it even when you rebind `Enter` in the `Chat` context to `chat:queueSubmit` or `chat:newline`. `Chat` bindings on keys the `Footer` context doesn’t bind, such as `Shift+Tab` for `chat:cycleMode`, keep working while an item is selected. -### - -​ - -Message selector actions +### Message selector actions In the message list of the [rewind menu](</docs/en/checkpointing>), you move through messages and pick one with the Select actions and their default keys. Your `Select` bindings for those actions apply there too. The `MessageSelector` context has no actions or default bindings of its own. Use it to change a key for this list alone, by binding a Select action such as `select:accept` in a `MessageSelector` block. This example binds `o` to pick the highlighted message in the rewind menu, without changing any other list: @@ -343,11 +271,7 @@ Before v2.1.283, this list ignored `Select` bindings and had its own actions: `messageSelector:up`, `messageSelector:down`, `messageSelector:top`, `messageSelector:bottom`, and `messageSelector:select`. If your `keybindings.json` binds one of those names, the binding keeps working in this list as the Select action that does the same thing. `Home` and `End` jump to either end of the list; before v2.1.283, keys such as `Shift+K` and `Shift+J` did that by default. -### - -​ - -Diff actions +### Diff actions These actions reach only Claude Code’s earlier diff viewer, which `/diff` opens outside [fullscreen rendering](</docs/en/fullscreen>) after you disable the [`cc-plugin-diff` mod](</docs/en/plugins/mods/overview#mods-built-into-claude-code>) in `/plugin`. While that mod is enabled, `/diff` opens the [diff dialog](</docs/en/interactive-mode#diff-dialog>) instead. Actions available in the `DiffDialog` context: @@ -371,11 +295,7 @@ `scroll:top`| G, Home| Jump to the top `scroll:bottom`| Shift+G, End| Jump to the bottom -### - -​ - -Diff panel actions +### Diff panel actions Actions for the [diff panel](</docs/en/interactive-mode#diff-panel>) that `/diff` opens in fullscreen rendering. `app:cycleDiffBase` is in the `DiffPanel` context, which is active while the panel is open; the others are `Global`. The built-in [`cc-plugin-diff` mod](</docs/en/plugins/mods/overview#mods-built-into-claude-code>) draws this panel and handles `app:cycleDiffBase`, `app:diffFileListUp`, and `app:diffFileListDown`. `app:toggleReplTab`, `app:toggleDiffNoiseFilter`, and `app:toggleDiffPreSession` reach only Claude Code’s earlier panel, which `/diff` opens after you disable `cc-plugin-diff` in `/plugin`. @@ -388,11 +308,7 @@ `app:toggleDiffNoiseFilter`| (unbound)| Show or hide test and generated files in the panel `app:toggleDiffPreSession`| (unbound)| Expand or collapse the changes from before this session -### - -​ - -Model picker actions +### Model picker actions Actions available in the `ModelPicker` context: @@ -402,11 +318,7 @@ `modelPicker:increaseEffort`| Right| Increase effort level `modelPicker:thisSessionOnly`| s| Apply highlighted model to this session only -### - -​ - -Effort slider actions +### Effort slider actions Actions available in the `EffortSlider` context, the slider that opens when you run `/effort` with no arguments. The slider’s Enter and Escape keys can’t be rebound. @@ -417,11 +329,7 @@ `effortSlider:toggleUltracode`| Tab| Turn [ultracode](</docs/en/workflows#let-claude-decide-with-ultracode>) on or off for this session, when the slider [offers it](</docs/en/model-config#when-ultracode-is-available>). Requires v2.1.284 or later `effortSlider:thisSessionOnly`| s| Apply the focused [effort level](</docs/en/model-config#adjust-effort-level>) to this session only. Requires v2.1.257 or later -### - -​ - -Select actions +### Select actions Actions available in the `Select` context: @@ -438,11 +346,7 @@ In list panels such as `/skills`, `/mcp`, and `/tasks`, Claude Code applies your `select:pageUp`, `select:pageDown`, `select:first`, and `select:last` bindings. In most other lists, such as the `/model` picker, your `select:first` and `select:last` bindings apply. PageUp and PageDown page through the options in those lists regardless of your bindings. Before v2.1.280, those other lists ignored Home, End, and your `select:first` and `select:last` bindings. Before v2.1.283, the `/mcp` tool list paged with fixed PageUp and PageDown keys regardless of your bindings. -### - -​ - -Plugin actions +### Plugin actions Actions available in the `Plugin` context: @@ -452,11 +356,7 @@ `plugin:install`| I| Install selected plugins `plugin:favorite`| F| Favorite the selected plugin so it sorts near the top of the Installed tab -### - -​ - -Above-prompt actions +### Above-prompt actions Actions for the band above the prompt, the shared strip where [mods](</docs/en/plugins/mods/interface#pick-where-to-draw>) draw buttons, input fields, and selects. `abovePrompt:toggle` and `abovePrompt:focus` apply in the `Chat` context. The other actions apply in the context of whatever has keyboard focus in the band or a pane. @@ -473,11 +373,7 @@ In the `AbovePrompt` context, Right and Left also run `abovePrompt:next` and `abovePrompt:previous` by default, and Space also runs `abovePrompt:press`. The `AbovePrompt` context also binds Up, Down, PageUp, PageDown, Home, and End to the pane scroll actions `pane:scrollUp` through `pane:bottom`, so to change one of those keys for the band, bind the scroll action in an `AbovePrompt` block. -### - -​ - -Pane actions +### Pane actions Actions for a pane drawn by a [mod](</docs/en/plugins/mods/interface#know-which-keys-your-mod-can-receive>). The scroll, resize, and close actions apply in the `Pane` context. `pane:close` also applies in the `PaneField` context, so it works while one of the pane’s fields has focus. `pane:next` and `pane:previous` apply in the `Global` context while more than one pane is open. @@ -497,11 +393,7 @@ The `Pane` context also binds Tab, Shift+Tab, Enter, and Escape to the same above-prompt actions as the band, and a pane’s input fields and selects use the `AbovePromptInput` and `AbovePromptSelect` contexts. [Keyboard focus and hotkeys](</docs/en/plugins/mods/interface#know-which-keys-your-mod-can-receive>) lists what each key does in a pane. -### - -​ - -Settings actions +### Settings actions Actions available in the `Settings` context. The `select:accept` and `confirm:no` actions are reused from the Select and Confirmation contexts with Settings-specific behavior: changes apply to each setting as soon as you change it, so Escape closes the panel with your changes saved rather than declining. @@ -513,11 +405,7 @@ `select:accept`| Enter, Space| Change the selected setting or open its submenu `confirm:no`| Escape| Close the panel. Changes are already saved -### - -​ - -Agents actions +### Agents actions Actions available in the `Agents` context, which applies in [agent view](</docs/en/agent-view>), opened with `claude agents`. Requires v2.1.257 or later. @@ -532,11 +420,7 @@ While agent view is open, Claude Code uses the `Agents` binding for any key the `Agents` context binds, and it ignores a `Chat` or `Global` binding on the same key. For example, pressing Ctrl+S in agent view switches the session grouping rather than triggering the default `chat:stash`. The dispatch input’s external-editor shortcut isn’t an `Agents` action. Agent view follows the `Chat` context’s `chat:externalEditor` binding, Ctrl+G by default. Bindings fire on single keystrokes in agent view, so the Ctrl+X Ctrl+E chord bound to `chat:externalEditor` doesn’t open the editor there. -### - -​ - -Voice actions +### Voice actions Actions available in the `Chat` context when [voice dictation](</docs/en/voice-dictation>) is enabled: @@ -544,11 +428,7 @@ ---|---|--- `voice:pushToTalk`| Space| Dictate a prompt. Hold or tap depending on `/voice` mode -### - -​ - -Scroll actions +### Scroll actions Actions available in the `Scroll` context when [fullscreen rendering](</docs/en/fullscreen>) is enabled: @@ -573,17 +453,9 @@ `selection:extendLineStart`| Shift+Home| Extend the active selection to the start of the line `selection:extendLineEnd`| Shift+End| Extend the active selection to the end of the line -## - -​ - -Keystroke syntax - -### - -​ - -Modifiers +## Keystroke syntax + +### Modifiers Use modifier keys with the `+` separator: @@ -599,30 +471,18 @@ meta+p Option + P on macOS, Alt + P elsewhere ctrl+shift+c Multiple modifiers -### - -​ - -Uppercase letters +### Uppercase letters Claude Code parses key names case-insensitively, so `K` is the same binding as `k` and `ctrl+K` is the same as `ctrl+k`. To bind Shift and a letter, write `shift+k`. -### - -​ - -Non-US keyboard layouts +### Non-US keyboard layouts Write the key names of Ctrl shortcuts as Latin characters even when your active keyboard layout types other characters. How Claude Code matches the key you press to a binding depends on the kind of layout: * Under a non-Latin layout such as Cyrillic, Claude Code matches Ctrl shortcuts by the key’s US-layout position when the terminal uses the Kitty keyboard protocol and reports that position. In such a terminal, with a Russian layout active, pressing Ctrl and the physical W key triggers `ctrl+w`. In a terminal that doesn’t report the position, Claude Code matches whatever the terminal sends for the keypress: an ASCII control code triggers the Latin shortcut, and a keypress that arrives as the Cyrillic character matches no binding * Under layouts that rearrange Latin letters, such as AZERTY, Claude Code matches the letter that the key types, so pressing Ctrl and the key labeled A triggers `ctrl+a` -### - -​ - -Chords +### Chords Chords are sequences of keystrokes separated by spaces: @@ -630,11 +490,7 @@ Press each keystroke within 3 seconds of the one before it. If you wait longer, Claude Code cancels the chord and shows a brief notice saying so. -### - -​ - -Special keys +### Special keys * `escape` or `esc` \- Escape key * `enter` or `return` \- Enter key @@ -646,11 +502,7 @@ * `backspace`, `delete` \- Delete keys * `wheelup`, `wheeldown` \- Mouse wheel scroll events -## - -​ - -Unbind default shortcuts +## Unbind default shortcuts Set an action to `null` to unbind a default shortcut: @@ -667,7 +519,7 @@ This also works for chord bindings. Unbinding every chord that shares a prefix frees that prefix for use as a single-key binding. A chord in any active context keeps its prefix reserved, so you must unbind each chord in the context that defines it. Claude Code binds these default chords on the `ctrl+x` prefix, by context: - * `Chat`: `ctrl+x ctrl+k`, `ctrl+x ctrl+e`, `ctrl+x enter`, `ctrl+x ctrl+a`, `ctrl+x ctrl+s`, and `ctrl+x tab` + * `Chat`: `ctrl+x ctrl+k`, `ctrl+x ctrl+e`, `ctrl+x enter`, `ctrl+x ctrl+a`, `ctrl+x ctrl+s`, `ctrl+x tab`, `ctrl+x ctrl+=`, `ctrl+x ctrl+-`, `ctrl+x ctrl+_`, `ctrl+x =`, and `ctrl+x -` * `Task`: `ctrl+x ctrl+b` * `DiffPanel`: `ctrl+x b` * `Pane`: `ctrl+x left`, `ctrl+x right`, `ctrl+x up`, `ctrl+x down`, and `ctrl+x x` @@ -714,6 +566,11 @@ "ctrl+x ctrl+a": null, "ctrl+x ctrl+s": null, "ctrl+x tab": null, + "ctrl+x ctrl+=": null, + "ctrl+x ctrl+-": null, + "ctrl+x ctrl+_": null, + "ctrl+x =": null, + "ctrl+x -": null, "ctrl+x": "chat:newline" } } @@ -722,11 +579,7 @@ If you unbind some but not all chords on a prefix, pressing the prefix still enters chord-wait mode for the remaining bindings. -## - -​ - -Reserved shortcuts +## Reserved shortcuts These shortcuts cannot be rebound: @@ -740,11 +593,7 @@ Ctrl+H| Sends the ASCII backspace byte. [How Claude Code reads it on Windows](</docs/en/terminal-config#fix-backspace-deleting-a-whole-word-on-windows>) depends on your terminal and the [`CLAUDE_CODE_BS_AS_CTRL_BACKSPACE`](</docs/en/env-vars>) environment variable Caps Lock| Not delivered to terminal applications -## - -​ - -Terminal conflicts +## Terminal conflicts Some shortcuts may conflict with terminal multiplexers: @@ -754,11 +603,7 @@ Ctrl+A| GNU screen prefix Ctrl+Z| Unix process suspend (SIGTSTP) -## - -​ - -Text fields +## Text fields If you bind a bare letter, digit, or Space, you can still type that character in a text field inside a dialog or panel. One such field is the `Other` answer to a question Claude asks. While the field has focus, a printable key you press without Ctrl, Alt, or Cmd goes to the field, and Claude Code doesn’t match it against your bindings. These keys still run their bindings while the field has focus: @@ -768,11 +613,7 @@ At the main prompt, Claude Code matches every key against the active contexts, such as `Chat`, and types the key only when no binding takes it. -## - -​ - -Vim mode interaction +## Vim mode interaction When you enable vim mode with the Editor mode setting in `/config`, keybindings and vim mode operate independently: @@ -786,11 +627,7 @@ In the `Other` row of a question Claude asks, Escape doesn’t cancel the question right away in vim mode. Except in [screen reader mode](</docs/en/accessibility>), the row starts in INSERT mode each time you focus it. When you press Escape in the `Other` row, the row switches to NORMAL mode or drops a half-typed vim command, and the question stays open. Press Escape again in NORMAL mode to cancel the question. -### - -​ - -Cancel a question with one key press +### Cancel a question with one key press To cancel a question with one key press in vim mode, bind another key to `select:cancel` in the `Select` context. You can cancel this way from the `Other` row of a question where you select one option. In [screen reader mode](</docs/en/accessibility>) or in a question where you can select several options, the bound key doesn’t cancel, so cancel with Escape instead. Pick a key that you press with Ctrl or Alt. A bare letter or digit goes to the `Other` row instead and doesn’t reach your bindings. For example, to bind `Ctrl+Q`, add this to `~/.claude/keybindings.json`: @@ -807,11 +644,7 @@ After you save the file, press `Ctrl+Q` in the `Other` row of a question where you select one option. The question closes whether the row is in INSERT or NORMAL mode. -## - -​ - -Validation +## Validation Claude Code validates your keybindings and writes a warning to the debug log for:
modified Set up Claude Code in a monorepo or large codebase View current →
Show diff (244 lines)
--- a/large-codebases.md +++ b/large-codebases.md @@ -1,18 +1,10 @@ A large codebase can be one repository with millions of lines or a monorepo with many packages. Claude Code works at any size, but as the codebase grows, the defaults tuned for smaller projects can fill the context window with instructions and file reads unrelated to the task, costing tokens and degrading Claude’s performance. This guide shows individual developers and engineering teams how to scope Claude to the part of the codebase a task touches. Each section notes whether a setting is personal to your machine or committed to the repository. -## - -​ - -What this guide covers +## What this guide covers The table below lists each setting and what it accomplishes. The file tree after it is the example monorepo every code sample on this page refers to. -### - -​ - -Settings on this page +### Settings on this page Each setting below is independent. They layer rather than replace each other, so apply whichever fit your repository. Choose where to start Claude determines where your settings files live, so read it first. Put it together shows all of them combined. @@ -29,11 +21,7 @@ For workflow techniques that keep context small in any repository, see [Best practices for Claude Code](</docs/en/best-practices>). One example is [running exploration in a subagent](</docs/en/best-practices#know-what-subagents-cost>) so file reads stay out of the main conversation. To roll out a baseline configuration to every developer in your organization, see [Set up Claude Code for your organization](</docs/en/admin-setup>). -### - -​ - -The example monorepo +### The example monorepo The examples throughout this page refer to a monorepo with three packages. The same patterns work in a large single-tree codebase: where an example uses `packages/api/`, substitute your own subsystem directory such as `src/backend/` or `lib/core/`. @@ -52,11 +40,7 @@ CLAUDE.md # shared library instructions src/ -## - -​ - -Choose where to start Claude +## Choose where to start Claude Where you launch `claude` determines which files Claude can read and edit without an additional permission grant, which CLAUDE.md files load into context at startup, and which project settings apply. @@ -67,11 +51,7 @@ Project settings in `.claude/settings.json` aren’t inherited from parent directories the way CLAUDE.md files are. For which directory’s `.claude/settings.json` a session reads, see [where Claude Code looks for each file](</docs/en/settings#where-claude-code-looks-for-each-file>). Each section below states whether its settings file belongs at the repository root or in the subdirectory you start from, and whether it is committed or kept local. -## - -​ - -Layer CLAUDE.md files by directory +## Layer CLAUDE.md files by directory In a large codebase, a single CLAUDE.md at the repository root tends to either grow to cover every subsystem’s conventions, costing context on instructions unrelated to the current task, or stay too generic to be useful. Splitting instructions across per-directory files means Claude loads repository-wide rules plus only the conventions for the code you’re working in. Claude Code loads every [CLAUDE.md](</docs/en/memory>) file from your working directory and every parent directory at launch, then loads each subdirectory’s file [on demand](</docs/en/memory#how-claude-md-files-load>). A root file sets repository-wide rules and each subdirectory adds its own. A common split is two levels: @@ -102,11 +82,7 @@ For more on how CLAUDE.md files load and interact, see [Memory and project instructions](</docs/en/memory>). -### - -​ - -Choose between per-directory CLAUDE.md and path-scoped rules +### Choose between per-directory CLAUDE.md and path-scoped rules Per-directory `CLAUDE.md` files and [path-scoped rules](</docs/en/memory#path-specific-rules>) under `.claude/rules/` both let you target instructions to part of the tree. They differ in where the file lives and when it loads. @@ -117,11 +93,7 @@ For a comparison that also covers skills, see [Compare similar features](</docs/en/features-overview#compare-similar-features>). -### - -​ - -Exclude irrelevant CLAUDE.md files +### Exclude irrelevant CLAUDE.md files When you start Claude from the repository root, each subdirectory’s CLAUDE.md can [load on demand](</docs/en/memory#how-claude-md-files-load>) during the session. The `claudeMdExcludes` setting skips specific files by path or glob pattern so they never load. Use this for directories you never work in, such as other teams’ packages, legacy code, or vendored subtrees. The exclusion list is static, not a per-task switch. To focus on one package today and another tomorrow, start Claude from that package’s directory instead of editing exclusions. If you only want these exclusions for yourself, put the setting in `.claude/settings.local.json`. Claude Code adds that file to your global gitignore when it saves a setting there. Since you are creating it by hand here, add it to your gitignore yourself. Patterns use glob syntax matched against absolute file paths, so start relative-style patterns with `**/` to match anywhere in the tree. The example below excludes a package owned by another team: @@ -141,19 +113,11 @@ You can set `claudeMdExcludes` at any [settings scope](</docs/en/settings#where-settings-live>): user, project, local, or managed. Arrays merge across scopes, so a team can set project-level defaults while individuals add local overrides. If your organization deploys a [managed CLAUDE.md file](</docs/en/memory#deploy-organization-wide-claude-md>), a pattern that matches it doesn’t skip it, whichever scope sets the pattern. For the full exclusion documentation, see [Exclude specific CLAUDE.md files](</docs/en/memory#exclude-specific-claude-md-files>). -## - -​ - -Reduce what Claude reads +## Reduce what Claude reads Instructions are only part of what ends up in Claude’s context. File reads are another cost that grows with the codebase. The settings below block reads of irrelevant paths and replace exhaustive file scans with language-server lookups. -### - -​ - -Block reads of generated and vendored code +### Block reads of generated and vendored code Claude’s content searches respect `.gitignore` by default, so paths already listed there, such as `node_modules/`, `dist/`, and `build/`, stay out of search results without additional configuration. For paths that are checked in, such as a vendored SDK or committed generated code, add `Read` deny rules in `permissions.deny` to block Claude from opening those files. The deny rules can cover everyone working in the repository, only you, or every session on the machine, depending on which settings file you put them in: @@ -178,11 +142,7 @@ Deny rules cover Claude’s built-in file tools. In Bash, they cover the file commands Claude Code recognizes, such as `cat`, `head`, `grep`, and `find`, when a denied path appears as an argument, and the target of a [redirection](</docs/en/permissions#redirections>) such as `< file`. Claude Code also makes a best-effort attempt to leave denied paths out of the results of the built-in Grep and Glob tools. A Bash search such as `grep -r` or `find` over a directory that contains denied files still includes them in its output. Deny rules don’t cover subprocesses that open files themselves. For the full pattern syntax, see [Read and Edit permission rules](</docs/en/permissions#read-and-edit>). -### - -​ - -Reduce file reads with code intelligence +### Reduce file reads with code intelligence In a large codebase, finding where a symbol is defined or used can cost many file reads and grep calls. [Code intelligence plugins](</docs/en/plugins/code-intelligence>) connect Claude to a language server so it can jump to definitions, find references, and surface type errors directly instead of scanning the tree. The official marketplace has plugins for TypeScript, Python, Go, Rust, and other common languages. In the VS Code extension or the desktop app, install one by following [Install a plugin](</docs/en/plugins/install#install-a-plugin>). In a terminal, start Claude Code by running `claude`, then enter this at its prompt to install the TypeScript plugin: @@ -195,19 +155,11 @@ To turn a plugin on for everyone in the repository, add it to the [`enabledPlugins` project setting](</docs/en/settings-reference#plugin-settings>). Each person still [installs it](</docs/en/plugins/loading#enabled-in-project-settings-but-not-installed>). Code intelligence plugins require the language’s language server binary on each developer’s machine. See [which binary each language requires](</docs/en/plugins/code-intelligence>). Installing from the official marketplace requires network access to GitHub, where the marketplace is hosted. On a restricted network, [add the marketplace from an internal Git host or local path](</docs/en/plugins/install#add-a-marketplace>) instead. This pairs well with `claudeMdExcludes` and the `Read` deny rules above. Those keep irrelevant content out of context, and code intelligence keeps Claude from reading through what remains to locate a definition. -## - -​ - -Scope worktrees and file access +## Scope worktrees and file access These settings control what’s on disk in worktrees and which directories Claude can read and write beyond your starting point. -### - -​ - -Check out only the directories you need +### Check out only the directories you need The `--worktree` flag starts a session in a new git worktree so changes stay isolated from your main checkout. By default it checks out the entire repository. In a large repository, the `worktree.sparsePaths` setting uses git sparse-checkout to write only the listed directories plus root-level files to disk, so worktrees start faster and use less space. If everyone working in this directory needs the same paths, commit the setting to `.claude/settings.json`. To add paths for yourself, use `.claude/settings.local.json`: the lists merge across scopes, so a local file can add paths to the committed list but not remove them. The JSON examples on this page show one setting at a time. If your `.claude/settings.json` already contains other keys, such as the `permissions.deny` rules above, add the `worktree` key alongside them rather than replacing the file. Put it together shows the combined result. The example below shows the committed file: @@ -250,11 +202,7 @@ For the full worktree settings reference, see [Worktree settings](</docs/en/settings-reference#worktree>). -### - -​ - -Grant access across packages or repositories +### Grant access across packages or repositories This section applies when you start Claude from a subdirectory, or when a task spans multiple checkouts. If you start from the repository root in a single large tree, Claude already has access to every file and you can skip this. When you start Claude from `packages/api/`, it can read and write files within that directory. If a task requires changes across packages, such as updating a shared type that both `api` and `web` import, you need to grant access to the sibling directory. The same mechanism grants access to a separately checked-out repository. The `additionalDirectories` setting in `.claude/settings.json` gives Claude access to directories outside the working directory. The example below grants access to two sibling packages: @@ -286,11 +234,7 @@ The environment variable has no effect on directories listed in the `additionalDirectories` setting. See [Load from additional directories](</docs/en/memory#load-from-additional-directories>) for details. For sibling directories that everyone in this area needs, commit `additionalDirectories` to `.claude/settings.json`. For a personal selection or one-off access, use `.claude/settings.local.json` or pass `--add-dir` at launch. -## - -​ - -Add per-directory skills +## Add per-directory skills Any subdirectory can define [skills](</docs/en/skills>) scoped to its own stack. A skill loads on demand when Claude determines it’s relevant. Skills live under `.claude/skills/` inside the directory. Commit them alongside that area’s code so anyone who clones the repository gets them. In a monorepo this can be one set of skills per package. In a large single-tree codebase it’s one set per subsystem such as `src/db/.claude/skills/`. Create a skill directory inside the subdirectory: @@ -329,11 +273,7 @@ A different subdirectory holds different skills the same way: `packages/web/.claude/skills/component-patterns/` describes the frontend’s component conventions instead of testing. When Claude works on a file in `packages/api/`, it loads the api-testing skill. When it works in `packages/web/`, it loads component-patterns. You can also scope a skill by file pattern instead of by placement. The [`paths` frontmatter field](</docs/en/skills#frontmatter-reference>) takes glob patterns, and Claude loads the skill automatically only when it works with matching files. Use this for a skill that lives in the repository root’s `.claude/skills/` but applies only to certain files, such as a database-migration skill scoped to `**/migrations/**`. For more on creating and organizing skills, see [Skills](</docs/en/skills>). -### - -​ - -Keep skills discoverable +### Keep skills discoverable With skills spread across many directories, the list Claude chooses from can grow large. Claude picks a skill by reading every discovered skill’s name and description, and only the chosen skill’s full content loads into context. This section covers how to keep that list small. Which skills are in scope depends on where you start Claude: @@ -343,11 +283,7 @@ Names always load, but [when there are many, some skills lose their descriptions entirely](</docs/en/skills#skill-descriptions-are-cut-short>), which can strip the keywords Claude uses to decide whether a skill applies. Keep descriptions short and lead with words a request would contain, like “writing or modifying tests in `packages/api/`”. For skills that many directories share, such as PR conventions or a deploy checklist, place them in the repository root’s `.claude/skills/` so they load from any starting directory. When shared skills need their own version history or must work across repositories, package them as a [plugin](</docs/en/plugins/overview>) instead. Plugin skills use a `plugin-name:skill-name` namespace, so they never collide with per-directory skills. A platform team can version and update them in one place. To find which skills go unused, enable the OpenTelemetry [logs exporter](</docs/en/monitoring-usage>) and set `OTEL_LOG_TOOL_DETAILS=1` so skill names are recorded verbatim instead of redacted. The [`skill_activated` event](</docs/en/monitoring-usage#skill-activated-event>) records every invocation in its `skill.name` attribute, and `invocation_trigger` records whether a command, Claude, or a nested skill invoked it, which tells you what to consolidate or retire. -## - -​ - -Centralize conventions when layering stops scaling +## Centralize conventions when layering stops scaling Per-directory CLAUDE.md files can become hard to govern as the codebase grows. Conventions drift, files go stale, and no one owns the root. Solving that typically falls to the team that maintains the repository’s Claude Code setup rather than to each developer working in their own area. Move conventions and reference content out of always-loaded CLAUDE.md and into mechanisms that load on demand: @@ -357,19 +293,11 @@ See [server-managed or endpoint-managed settings](</docs/en/server-managed-settings#choose-between-server-managed-and-endpoint-managed-settings>) for how platform teams can enforce these centrally. -### - -​ - -Recommend the right plugin at session start +### Recommend the right plugin at session start Once conventions live in plugins, a teammate starting Claude in an unfamiliar part of the tree has no signal about which plugin that area’s owners maintain. A [`SessionStart` hook](</docs/en/hooks#sessionstart>) can close that gap, since Claude Code adds plain text the hook prints to stdout to Claude’s context before the first prompt. For example, you can write a script that reads the launch directory from the [hook input](</docs/en/hooks#common-input-fields>), looks it up in a path-to-plugin map committed to the repository, and prints the recommendation for Claude to relay in its first reply. See [Automate actions with hooks](</docs/en/hooks-guide>) to write and register the hook. -## - -​ - -Put it together +## Put it together The combined configuration below uses the monorepo layout. The same files work for any subdirectory in a large single tree. Each subdirectory’s `.claude/settings.json` must be self-contained rather than layered on a root file. The example commits `worktree`, `additionalDirectories`, and the `Read` deny rules in `.claude/settings.json` so every developer in `packages/api/` gets the same sibling access, sparse paths, and exclusions. The file below is the committed per-area settings for `packages/api/`: @@ -434,22 +362,14 @@ * Has the api-testing skill available on demand * Creates worktrees containing `.claude/`, `packages/api/`, `packages/shared/`, and root-level files, with the deny rules applied across the worktree from the root settings file -## - -​ - -Scope and plan changes that span packages +## Scope and plan changes that span packages The configuration above controls what Claude sees. When a single change touches several packages, such as updating a shared type along with every call site that uses it, how you scope and sequence the task also affects the result. Two techniques help keep a cross-package change consistent: * **Give Claude the whole change in one session** : handing over the shared edit and its call sites together keeps the decisions behind each edit consistent, rather than re-deriving them per package * **Plan before editing** : plan first in [plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>), and Claude writes the plan to a file. A long cross-package session [compacts its context](</docs/en/context-window#what-survives-compaction>) as it goes. Claude Code re-injects the plan file after each compaction, so the plan survives where conversation history may not -## - -​ - -Next steps +## Next steps Once this configuration is in place, you can refine it:
modified Legal and compliance View current →
Show diff (118 lines)
--- a/legal-and-compliance.md +++ b/legal-and-compliance.md @@ -1,33 +1,17 @@ -## +## Legal agreements -​ - -Legal agreements - -### - -​ - -License +### License Your use of Claude Code is subject to: * [Commercial Terms of Service](<https://www.anthropic.com/legal/commercial-terms>) \- for Team, Enterprise, and Claude API users * [Consumer Terms of Service](<https://www.anthropic.com/legal/consumer-terms>) \- for Free, Pro, Max, and Ultra users -### - -​ - -Commercial agreements +### Commercial agreements Whether you’re using the Claude API directly (1P) or accessing it through Amazon Bedrock or Google Cloud’s Agent Platform (3P), your existing commercial agreement will apply to Claude Code usage, unless we’ve mutually agreed otherwise. -### - -​ - -Can customers offer Claude Code in their products? +### Can customers offer Claude Code in their products? Unless we’ve mutually agreed otherwise, preinstalling or running Claude Code in your products or services (e.g. in hosted sandboxes or other agent infrastructure) requires agreeing to our [Commercial Terms of Service](<https://www.anthropic.com/legal/commercial-terms>) and complying with the conditions below: @@ -36,17 +20,9 @@ **Using the Claude Code name and logo.** You can accurately say, in plain text, that your product has Claude Code preinstalled or that it runs Claude Code. But you can’t use the Claude Code or Anthropic names or logos as part of your own product, feature, or company name, in your own logo, or in a way that suggests Anthropic built, endorses, or is partnered with your product. Any other use of Anthropic’s names or logos is governed by our [Trademark Guidelines](<https://www.anthropic.com/legal/trademark-guidelines>) and requires our written permission. Claude Code remains governed by Anthropic’s standard terms (see the License and Commercial agreements sections above) regardless of the platform through which it is accessed. -## +## Compliance -​ - -Compliance - -### - -​ - -Healthcare compliance (BAA) +### Healthcare compliance (BAA) If a customer has executed a Business Associate Agreement (BAA) with Anthropic, that BAA extends to Claude Code in two configurations, depending on what is available for your organization: @@ -55,25 +31,13 @@ Under the HIPAA configuration, cloud sessions, Remote Control, Claude Code in the Claude mobile app, and Claude Code routed through a third-party cloud provider or a gateway aren’t covered. Review the [Implementation Guide](<https://trust.anthropic.com/resources?s=l1wrssd9hsbi4gak0tp5a6&name=%5Banthropic%5D-hipaa-ready-offering-implementation-guide>) for a full list of Eligible Services. -## +## Usage policy -​ - -Usage policy - -### - -​ - -Acceptable use +### Acceptable use Claude Code usage is subject to the [Anthropic Usage Policy](<https://www.anthropic.com/legal/aup>). Advertised usage limits for Pro, Max, and Ultra plans assume ordinary, individual usage of Claude Code and the Agent SDK. -### - -​ - -Authentication and credential use +### Authentication and credential use Claude Code authenticates with Anthropic’s servers using OAuth tokens or API keys. These authentication methods serve different purposes: @@ -82,25 +46,13 @@ This does not restrict how customers provision and manage their own API keys or third-party inference provider credentials — for example, configuring an API key in a development environment, secrets manager, or machine image for use by the customer’s own authorized users — provided the resulting usage is billed to the key owner under their agreement with Anthropic (or the applicable provider) and is not resold or intermediated as described above. Nor does it prevent an end user from signing in to the unmodified Claude Code binary with their own Claude subscription, including where a platform hosts Claude Code as described under _Can customers offer Claude Code in their products?_ above. Anthropic reserves the right to take measures to enforce these restrictions and may do so without prior notice. For questions about permitted authentication methods for your use case, please [contact sales](<https://www.anthropic.com/contact-sales?utm_source=claude_code&utm_medium=docs&utm_content=legal_compliance_contact_sales>). -## +## Security and trust -​ - -Security and trust - -### - -​ - -Trust and safety +### Trust and safety You can find more information in the [Anthropic Trust Center](<https://trust.anthropic.com>) and [Transparency Hub](<https://www.anthropic.com/transparency>). -### - -​ - -Security vulnerability reporting +### Security vulnerability reporting Anthropic manages our security program through HackerOne. [Use this form to report vulnerabilities](<https://hackerone.com/4f1f16ba-10d3-4d09-9ecc-c721aad90f24/embedded_submissions/new>).
modified Other LLM gateways View current →
--- a/llm-gateway.md +++ b/llm-gateway.md @@ -6,11 +6,7 @@ Any gateway that exposes a [supported API format](</docs/en/llm-gateway-protocol#api-formats>) works. Anthropic doesn’t endorse, maintain, or audit third-party gateway products, and doesn’t support routing Claude Code to non-Claude models through any gateway. Deploy the gateway following its own documentation, then complete the Claude Code side with the rollout steps below. -## - -​ - -What a gateway provides +## What a gateway provides A gateway gives your organization one place to manage: @@ -22,11 +18,7 @@ All of these except provider switching apply whether the upstream is Anthropic’s API or a [cloud provider](</docs/en/third-party-integrations>). Provider switching without reconfiguring developer machines also depends on the gateway exposing a single [Anthropic-format endpoint](</docs/en/llm-gateway-protocol#api-formats>) regardless of upstream. A gateway that exposes a provider’s own format ties the client configuration to that provider and changes [what Claude Code sends and which defaults it applies](</docs/en/llm-gateway-protocol#how-the-connection-method-changes-client-behavior>). The tradeoff is that the gateway becomes infrastructure your organization operates. Claude Code adds capabilities with each release, and a gateway that doesn’t forward them breaks the corresponding features, so the gateway product needs to be kept updated as Claude Code evolves. The [gateway compatibility guide](</docs/en/llm-gateway-protocol>) covers what to forward. -## - -​ - -Roll out a gateway +## Roll out a gateway When you’re ready to roll out an LLM gateway to your organization, the sequence is the same whichever gateway product you choose: @@ -37,19 +29,11 @@ [Roll out an LLM gateway for your organization](</docs/en/llm-gateway-rollout>) walks each step and shows the configuration files to distribute at each one. The gateway is one part of organization setup; for policy enforcement, usage visibility, and data handling decisions, see [Set up Claude Code for your organization](</docs/en/admin-setup>). To make a gateway reached through `ANTHROPIC_BASE_URL` the only destination a managed machine may use, set [`allowedProviders`](</docs/en/settings-reference#allowedproviders>) to `["customEndpoint"]` in the same managed settings file and put the gateway’s `ANTHROPIC_BASE_URL` in that file’s `env` block. Claude Code then refuses a session pointed anywhere else, including at Anthropic directly or at a developer’s own proxy, and accepts `ANTHROPIC_BASE_URL` only with the value you set there. For a gateway reached through a provider-specific endpoint variable such as `ANTHROPIC_BEDROCK_BASE_URL`, the `allowedProviders` entry says which variable to pin. Requires Claude Code v2.1.285 or later. -## - -​ - -Subscriptions and gateways +## Subscriptions and gateways While a [gateway credential variable](</docs/en/llm-gateway-connect#set-the-credential-variable>) or `apiKeyHelper` is active, requests carry that credential in place of a developer’s claude.ai subscription login, and the subscription’s usage limits don’t apply to them. Claude Code keeps a saved claude.ai login on the machine but doesn’t send it with those requests. That traffic is billed per token to whoever owns the credential the gateway forwards, such as your organization’s Anthropic Console account, or your Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry account when the gateway routes there. [`ANTHROPIC_BASE_URL`](</docs/en/llm-gateway-connect#set-the-base-url-and-credential>) is the variable that points Claude Code at the gateway. Setting only that variable, without a gateway credential, doesn’t replace the subscription. Requests still route through the gateway, but a saved claude.ai login remains the active credential, so its usage limits and billing apply. Gateways that pass this traffic on to Anthropic must forward `Authorization` and the OAuth capability in `anthropic-beta`; see the [request headers reference](</docs/en/llm-gateway-protocol#request-headers>). -## - -​ - -Related pages +## Related pages * [Gateway overview](</docs/en/gateways>): how a gateway works and how to choose between Claude apps gateway and another product * [Claude apps gateway](</docs/en/claude-apps-gateway>): Anthropic’s self-hosted gateway with SSO sign-in and OTLP telemetry
modified Connect Claude Code to an LLM gateway View current →
Show diff (367 lines)
--- a/llm-gateway-connect.md +++ b/llm-gateway-connect.md @@ -3,11 +3,7 @@ * To deploy a gateway for your organization, see [Roll out an LLM gateway](</docs/en/llm-gateway-rollout>) * For what Claude Code sends to a gateway, see the [gateway compatibility guide](</docs/en/llm-gateway-protocol>) -## - -​ - -Check for an existing configuration +## Check for an existing configuration Administrators can distribute the gateway address and credential through [managed settings](</docs/en/managed-settings>), device management, or an `apiKeyHelper`, so Claude Code picks them up at startup with nothing for you to set. To check whether your organization already did this: @@ -34,11 +30,7 @@ If both lines in the `/status` menu look right but the message to Claude fails, see the troubleshooting table. -## - -​ - -Configure Claude Code yourself +## Configure Claude Code yourself To configure Claude Code for the gateway yourself, you need from your gateway team: @@ -53,11 +45,7 @@ * Configure each surface: if you are using a surface besides the Claude Code CLI, such as VS Code, see how to configure it with your gateway credentials * Additional configuration: variables some gateways need beyond the base URL and credential, such as a custom header, a credential helper, model discovery, a provider-format base URL, or turning off traffic outside the gateway path. Set these only if your administrator named them or your network restricts egress -### - -​ - -Set the credential variable +### Set the credential variable To authenticate Claude Code to the gateway, set your credential in an environment variable. Which variable depends on what your gateway team told you: @@ -69,19 +57,11 @@ If you weren’t told which kind, use `ANTHROPIC_AUTH_TOKEN`; the verification request below shows how to tell if you need to switch. -### - -​ - -Set the base URL and credential +### Set the base URL and credential Set the gateway’s base URL and the credential variable you picked above as environment variables. The examples use `ANTHROPIC_AUTH_TOKEN`; swap it for `ANTHROPIC_API_KEY` if that’s the variable you picked. You can set them in your shell, which lasts for one terminal session, or in a Claude Code settings file, which persists everywhere Claude Code runs. For your first connection, start with shell exports and run the verification request before moving the values to a settings file. -#### - -​ - -Set as shell environment variables +#### Set as shell environment variables Replace the values with the ones your gateway team gave you: @@ -97,11 +77,7 @@ Shell exports apply only to that terminal session and programs started from it. An editor launched from the dock or Start menu won’t see them. To make the values persist across new terminals, add the same lines to your shell profile, such as `~/.zshrc`, `~/.bashrc`, or your PowerShell `$PROFILE`. If you export the gateway only in your shell, it doesn’t reliably reach background agents hosted by the [supervisor](</docs/en/agent-view#how-background-sessions-are-hosted>); see [how each background session sources its gateway](</docs/en/agent-view#llm-gateway>). Use a settings file for any gateway that background agents must always route through. -#### - -​ - -Set in a settings file +#### Set in a settings file To make the configuration apply everywhere Claude Code runs, including [background agents](</docs/en/agent-view#how-background-sessions-are-hosted>), set the variables in the `env` block of a [settings file](</docs/en/settings>) instead of relying on your shell. Settings files have different scopes: @@ -121,11 +97,7 @@ When both a shell export and a settings-file `env` block set the same variable, the settings-file value applies. Run `/status` to see which base URL and credential source Claude Code is using. -### - -​ - -Verify the connection +### Verify the connection With the variables exported in your shell, send a one-token request to the gateway directly. This confirms the URL and credential work before you open Claude Code, so a failure points at the gateway rather than your configuration. The commands below read the shell variables, so they need the shell exports even if you also put the values in a settings file. @@ -146,43 +118,23 @@ If your gateway expects keys in the `x-api-key` header, replace the `Authorization` header with `x-api-key: $ANTHROPIC_API_KEY` in the Bash command, or the `"Authorization"` hashtable entry with `"x-api-key" = "$env:ANTHROPIC_API_KEY"` in the PowerShell command. A JSON response that starts with `{"id":"msg_` and includes a `"content":[...]` field means the gateway is reachable and the credential works. An error naming an unknown model still proves the URL and credential work, since the gateway authenticated the request before rejecting the model name; you don’t need to find a model your gateway serves for this test. A `401` means the credential was rejected: if you guessed the variable, switch to the other one and re-export. -#### - -​ - -Confirm in Claude Code +#### Confirm in Claude Code Start `claude` from the same shell so it inherits the exports, send a message, and run `/status`. On the **Status** tab, the `Anthropic base URL` line should show your gateway address, which confirms requests are routing there; if the line isn’t there, the variable didn’t reach the session. An `Auth token` or `API key` line naming the variable you set confirms the gateway credential is active rather than a saved claude.ai login. If the message fails, or `/status` doesn’t show the gateway URL, see the troubleshooting table below. -### - -​ - -How the credential variable maps to a header +### How the credential variable maps to a header Each variable sends the credential in a different HTTP header: `ANTHROPIC_AUTH_TOKEN` in `Authorization: Bearer`, `ANTHROPIC_API_KEY` in `x-api-key`, and `apiKeyHelper` in both. A credential in the wrong variable reaches the gateway in a header it doesn’t read, and the request fails with `401`. If the verification request returned `401`, switch to the other variable and try again. -### - -​ - -Conflicts with an existing login - -A gateway credential variable takes precedence over a saved claude.ai login or Console key. With `ANTHROPIC_AUTH_TOKEN`, the variable takes precedence immediately. With `ANTHROPIC_API_KEY`, you are prompted once in interactive mode to approve the key before it takes over. Run `/status` to confirm which credential source is active. If startup shows an auth-conflict warning naming two sources, see the first row of the troubleshooting table for which one to drop. To clear a saved login so only the gateway credential remains, run `/logout`. - -## - -​ - -Configure each surface +### Conflicts with an existing login + +Your requests use a gateway credential variable rather than a saved claude.ai login. With `ANTHROPIC_AUTH_TOKEN`, the variable takes precedence immediately. With `ANTHROPIC_API_KEY`, you are prompted once in interactive mode to approve the key before it takes over. Run `/status` to confirm which credential source is active. If startup shows an auth-conflict warning naming two sources, see the first row of the troubleshooting table for which one to drop. To clear a saved login so only the gateway credential remains, run `/logout`. + +## Configure each surface The CLI reads the environment variables and settings files above. The other surfaces are the VS Code extension, the desktop app, GitHub Actions, the Agent SDK, and the cloud surfaces such as Slack and the web; the sections below cover whether those settings reach each one. -### - -​ - -VS Code extension +### VS Code extension Set the gateway variables for the [VS Code extension](</docs/en/vs-code>) in `claudeCode.environmentVariables`, in VS Code’s own user settings opened with the **Preferences: Open User Settings (JSON)** command. The extension checks credentials from this setting before launching, so it’s the reliable place for the gateway credential; values in `~/.claude/settings.json` reach the spawned process but not the extension’s own login check. @@ -193,11 +145,7 @@ ] } -### - -​ - -Desktop app +### Desktop app The desktop app reads gateway routing from its [third-party inference configuration](<https://claude.com/docs/third-party/claude-desktop/gateway>), not from `ANTHROPIC_BASE_URL` or `settings.json`. That configuration can come from your organization or from a form in the app itself: @@ -211,11 +159,7 @@ See [SSH remote sessions in Claude Desktop on 3P](<https://claude.com/docs/third-party/claude-desktop/ssh-remote-sessions>). You can also run the CLI on the remote host with `ANTHROPIC_BASE_URL` and the gateway credential set there. If the desktop app shows `Gateway was unreachable`, the app couldn’t reach the configured base URL at startup; check the URL and network path with the curl test above. -### - -​ - -GitHub Actions +### GitHub Actions [Claude Code GitHub Actions](</docs/en/github-actions>) reads `ANTHROPIC_BASE_URL` and `ANTHROPIC_CUSTOM_HEADERS` from the workflow’s `env` block. Pass the credential as the action’s `anthropic_api_key` input; the action sets it as `ANTHROPIC_API_KEY`, so it reaches the gateway in the `x-api-key` header. For an `x-api-key` gateway, set the base URL in `env` and pass the gateway key as the input: @@ -240,11 +184,7 @@ For the action’s other authentication options, including `CLAUDE_CODE_OAUTH_TOKEN` and workload identity federation, see [Claude Code GitHub Actions](</docs/en/github-actions>) and the action’s [README](<https://github.com/anthropics/claude-code-action#readme>). -### - -​ - -Agent SDK +### Agent SDK The [Agent SDK](</docs/en/agent-sdk/overview>) has no gateway-specific options; it passes environment variables to the Claude Code process it spawns. Each SDK accepts an `env` option that sets the spawned process’s environment, and the TypeScript and Python SDKs treat it differently: @@ -273,30 +213,18 @@ } ) -### - -​ - -Slack, cloud sessions, and Remote Control +### Slack, cloud sessions, and Remote Control [Claude Code in Slack](</docs/en/slack>) and [cloud sessions](</docs/en/claude-code-on-the-web>) aren’t part of a gateway deployment. Gateway variables set in a cloud session’s environment configuration are not applied. If your traffic must stay on the gateway, don’t enable these surfaces for those users. [Remote Control](</docs/en/remote-control>) and [voice dictation](</docs/en/voice-dictation>) both rely on a claude.ai identity: Remote Control to pair a live session with your account, and voice dictation to reach the claude.ai transcription endpoint. They are unavailable while `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, or an `apiKeyHelper` is active. Remote Control is also disabled while `ANTHROPIC_BASE_URL` points at a non-Anthropic host, so signing in with claude.ai isn’t enough on its own. To restore either feature, log in with claude.ai and unset the gateway variables that feature checks. The Remote Control section of `claude doctor` names what is currently blocking Remote Control. * Voice dictation: unset the gateway credential * Remote Control: unset the gateway credential and `ANTHROPIC_BASE_URL` -## - -​ - -Additional configuration +## Additional configuration These settings cover cases beyond the base URL and credential. Set them only if your administrator’s instructions, your network’s egress rules, or the troubleshooting table call for one. -### - -​ - -Send additional headers +### Send additional headers Some gateways route or tag requests using a custom header in addition to the credential, for example a tenant identifier or a routing key. To send one, set [`ANTHROPIC_CUSTOM_HEADERS`](</docs/en/env-vars>) with one `Name: Value` pair per line. The example below adds a routing header named `X-Org-Route`: @@ -318,19 +246,11 @@ Routing and tenant header names like these count as [headers that need approval](</docs/en/server-managed-settings#environment-variables-and-the-approval-dialog>). When the headers come from a project settings file, Claude Code applies them under the [rules for when it applies `env` values](</docs/en/settings-reference#when-claude-code-applies-env-values>). -### - -​ - -Add gateway models to the model picker +### Add gateway models to the model picker With model discovery enabled, Claude Code queries the gateway for its model list at startup and adds those names to the `/model` picker alongside the built-in entries. If you or your administrator set `replaceBuiltInOptions` in a [`modelPicker`](</docs/en/settings-reference#modelpicker>) lineup, Claude Code hides the discovered names too. It keeps a row for the model the session is already using. Enable it if your gateway serves model names that aren’t in Claude Code’s built-in list and you want to select them from the picker. If the built-in models are what you use, you don’t need discovery; your administrator may also have already enabled it through managed settings. To enable it, set `CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1` in your shell or in the `env` block of `~/.claude/settings.json`. Discovered models appear as additional `/model` entries. Each entry shows the description your gateway supplies for the model, or `From gateway` when it doesn’t supply one. To confirm discovery ran, start `claude --debug` and look for the `[gatewayDiscovery]` lines in the debug log at `~/.claude/debug/<session-id>.txt`. The first time discovery succeeds, Claude Code logs how many models it cached, and it logs again only when the gateway’s list changes. A `404`, timeout, or redirect appears there too. For when discovery runs, what it filters, and the response format gateways serve, see the [model discovery reference](</docs/en/llm-gateway-protocol#model-discovery>). -### - -​ - -Rotate credentials with apiKeyHelper +### Rotate credentials with apiKeyHelper An `apiKeyHelper` is a command Claude Code runs to fetch your gateway credential, instead of reading it from a static environment variable. Use a helper when the credential expires on a schedule, comes from a vault or SSO command, or your administrator told you to configure one. If your credential is a fixed string you set once, the credential variable is all you need and you can skip this section. The helper is any shell command that prints the current credential to stdout. Claude Code runs it through your system shell, so on Windows it can be an executable or a PowerShell invocation. Make the command print nothing but the credential. On Claude Code v2.1.227 or later, a banner or a log line printed alongside the key makes the [helper fail](</docs/en/errors#your-apikeyhelper-script-is-failing>). Write the script, make it executable, and reference it from `apiKeyHelper` in your [settings file](</docs/en/settings>): @@ -361,11 +281,7 @@ Claude Code caches the helper’s output for five minutes by default and re-runs the helper after the cache lifetime elapses. To change the lifetime, set `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` in milliseconds, for example `CLAUDE_CODE_API_KEY_HELPER_TTL_MS=900000` for 15 minutes. See [`apiKeyHelper`](</docs/en/settings-reference#apikeyhelper>) for the other cases in which Claude Code re-runs the helper. The helper’s value is sent in both the `Authorization` and `x-api-key` headers, so it works whichever header your gateway reads. -### - -​ - -Turn off traffic outside the gateway path +### Turn off traffic outside the gateway path The gateway carries model requests, but Claude Code also sends nonessential background traffic outside the gateway path, to Anthropic and to third-party services such as GitHub: version checks, telemetry, release notes, and similar requests. On a network that only allows egress to the gateway, these requests fail and can appear as blocked connections in your egress monitoring. To turn that traffic off, set `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1` alongside the gateway variables, in the same shell exports or settings-file `env` block: @@ -385,22 +301,14 @@ * The WebFetch tool’s [domain safety check](</docs/en/data-usage#webfetch-domain-safety-check>) isn’t affected and still calls `api.anthropic.com`. Turn it off separately with `skipWebFetchPreflight: true` in [settings](</docs/en/settings>) if your network blocks that host. * For each telemetry stream and the variable that controls it, see [telemetry services](</docs/en/data-usage#telemetry-services>). -### - -​ - -Route to a cloud provider through a gateway +### Route to a cloud provider through a gateway These configurations point Claude Code at a gateway through a provider-specific base URL variable in place of `ANTHROPIC_BASE_URL`. Amazon Bedrock and Google Cloud’s Agent Platform gateways accept those providers’ native request formats; Microsoft Foundry and Claude Platform on AWS gateways accept the Anthropic Messages format. On the Amazon Bedrock and Google Cloud’s Agent Platform routes, Claude Code also limits the beta headers and request fields it sends to the set that provider accepts. For what your gateway receives on each route, see the [gateway compatibility guide](</docs/en/llm-gateway-protocol>). Use one only if your gateway team specifically named Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, or the Claude Platform on AWS. If the verification request above returned JSON, you can skip this section. Set the block for the provider your gateway team named. The skip-auth variables in the Amazon Bedrock, Google Cloud’s Agent Platform, and Claude Platform on AWS blocks tell Claude Code not to sign requests with the cloud provider’s credentials, since the gateway holds those. If the gateway also needs its own token, where you put it depends on the provider: * **Amazon Bedrock, Google Cloud’s Agent Platform, or Claude Platform on AWS** : add `ANTHROPIC_AUTH_TOKEN` after the block. Claude Code sends it to the gateway as an `Authorization: Bearer` header. For a credential in a different scheme or header, use `ANTHROPIC_CUSTOM_HEADERS` instead. Keep the skip-auth variable set either way, since without it Claude Code removes any `Authorization` header that `ANTHROPIC_AUTH_TOKEN`, an `apiKeyHelper`, or `ANTHROPIC_CUSTOM_HEADERS` would add. * **Microsoft Foundry** : use `ANTHROPIC_FOUNDRY_API_KEY` as its block shows -#### - -​ - -Amazon Bedrock +#### Amazon Bedrock Leave `AWS_BEARER_TOKEN_BEDROCK` unset when the gateway issues its own credential. If you set it, Claude Code sends that [Amazon Bedrock API key](</docs/en/amazon-bedrock#2-configure-aws-credentials>) as the `Authorization` header instead of your gateway token, even with `CLAUDE_CODE_SKIP_BEDROCK_AUTH` set. @@ -416,11 +324,7 @@ $env:CLAUDE_CODE_SKIP_BEDROCK_AUTH = "1" $env:CLAUDE_CODE_USE_BEDROCK = "1" -#### - -​ - -Google Cloud’s Agent Platform +#### Google Cloud’s Agent Platform Replace the project ID and region with your own values. Claude Code includes both in the path of each request it sends to the gateway: @@ -446,11 +350,7 @@ * **Model versions** : pin `ANTHROPIC_DEFAULT_OPUS_MODEL`, `ANTHROPIC_DEFAULT_SONNET_MODEL`, and `ANTHROPIC_DEFAULT_HAIKU_MODEL` as in [Pin model versions](</docs/en/google-vertex-ai#5-pin-model-versions>). Setting `ANTHROPIC_DEFAULT_HAIKU_MODEL` also moves background tasks such as session titles to that model, and that section explains which model runs them otherwise. * **Model capabilities** : if you pin a model ID that your Claude Code version doesn’t recognize, features such as effort levels or extended thinking can stay disabled on it. Declare what the model supports with [`ANTHROPIC_DEFAULT_OPUS_MODEL_SUPPORTED_CAPABILITIES`](</docs/en/model-config#customize-pinned-model-display-and-capabilities>) and its Sonnet and Haiku counterparts. -#### - -​ - -Microsoft Foundry +#### Microsoft Foundry Put the gateway’s credential in `ANTHROPIC_FOUNDRY_API_KEY`; it is sent to the gateway as the `x-api-key` header. A gateway that expects a bearer token can take [`ANTHROPIC_FOUNDRY_AUTH_TOKEN`](</docs/en/env-vars>) instead. Claude Code sends that value as the `Authorization: Bearer` header, and it takes precedence over `ANTHROPIC_FOUNDRY_API_KEY` when both are set. Requires Claude Code v2.1.203 or later. For a gateway that injects its own `Authorization` header, set `CLAUDE_CODE_SKIP_FOUNDRY_AUTH=1` and leave both credential variables unset. Claude Code then sends requests without an Azure credential and preserves the `Authorization` header you supply, for example through `ANTHROPIC_CUSTOM_HEADERS`. @@ -466,11 +366,7 @@ $env:ANTHROPIC_FOUNDRY_API_KEY = "sk-gateway-key" $env:CLAUDE_CODE_USE_FOUNDRY = "1" -#### - -​ - -Claude Platform on AWS +#### Claude Platform on AWS See [Claude Platform on AWS](</docs/en/claude-platform-on-aws>) for the workspace ID. @@ -488,11 +384,7 @@ $env:CLAUDE_CODE_SKIP_ANTHROPIC_AWS_AUTH = "1" $env:CLAUDE_CODE_USE_ANTHROPIC_AWS = "1" -#### - -​ - -Confirm the provider route +#### Confirm the provider route Start `claude` from the shell where you set the block and run `/status`. With the Amazon Bedrock block, the **Status** tab shows rows like these: @@ -502,17 +394,13 @@ The other blocks produce the same rows under their provider’s names, for example `Vertex base URL` and `GCP auth skipped` for Google Cloud’s Agent Platform; the Microsoft Foundry block shows an auth skipped row only if you set `CLAUDE_CODE_SKIP_FOUNDRY_AUTH`. If you also route through a corporate proxy, a `Proxy` row shows the proxy URL. If the base URL row is missing, the variable didn’t reach the session. -## - -​ - -Troubleshoot gateway errors +## Troubleshoot gateway errors These are the most common errors when running Claude Code through a gateway, with the gateway-side cause and the fix: Error| Cause| Fix ---|---|--- -A startup warning naming two credential sources and ending in `auth may not work as expected`. Older versions show `Auth conflict: Both a token (SOURCE) and an API key (SOURCE) are set` instead.| A gateway credential and a saved login are both active; the variable is used for requests, but the stale login can cause unexpected auth behavior| Unset the variable to use the saved login, or run `/logout` to use the gateway credential +A startup warning naming two credential sources and ending in `auth may not work as expected`. Older versions show `Auth conflict: Both a token (SOURCE) and an API key (SOURCE) are set` instead.| A gateway credential and a saved login are both active| Unset the variable to use the saved login, or run `/logout` to use the gateway credential `401` errors naming an invalid or unrecognized token| The credential isn’t one the gateway issued, or it’s in a header the gateway doesn’t read| Confirm the variable matches your credential kind in the credential table, and regenerate the key at the gateway if it was revoked `Your apiKeyHelper script is failing`, or `apiKeyHelper failed:` on stderr in non-interactive mode| The command in the [`apiKeyHelper`](</docs/en/settings-reference#apikeyhelper>) setting didn’t produce a usable key, so requests carry a placeholder key| Run the command directly to see why it fails, and re-authenticate with your credential provider if it reports an expired session; see [the error reference](</docs/en/errors#your-apikeyhelper-script-is-failing>) `Connection refused — a firewall or proxy may be blocking it (ConnectionRefused)` when nothing answers at the address, or `Can't reach the API server — check your internet or DNS (ENOTFOUND)` when the hostname doesn’t resolve, often after a silent pause while Claude Code [retries with backoff](</docs/en/errors#automatic-retries>). The code in parentheses varies; [Unable to connect to API](</docs/en/errors#unable-to-connect-to-api>) covers the code spellings and the earlier wording| Nothing answered at the base URL: the address is wrong, or a VPN or firewall blocks the path to the gateway| Run the curl test above, which fails immediately with the same cause, and confirm the URL and network path with your gateway team @@ -526,6 +414,7 @@ `/fast` reports `Fast mode unavailable due to network connectivity issues` while inference requests work| The [fast mode](</docs/en/fast-mode>) availability check goes directly to `api.anthropic.com` and doesn’t follow `ANTHROPIC_BASE_URL`, so blocked direct egress fails the check| Allowlist `api.anthropic.com` if egress is blocked, or set a skip variable. See [use fast mode behind proxies and LLM gateways](</docs/en/fast-mode#use-fast-mode-behind-proxies-and-llm-gateways>) `/fast` reports `Fast mode is currently unavailable` in a session that authenticates with a gateway-issued key in `ANTHROPIC_API_KEY`| While `ANTHROPIC_BASE_URL` points at your gateway and the key isn’t in the format of an Anthropic API key, Claude Code doesn’t send the [fast mode](</docs/en/fast-mode>) availability check. Without an earlier successful check cached, it treats fast mode as unavailable| Set `CLAUDE_CODE_SKIP_FAST_MODE_NETWORK_ERRORS=1`; see [use fast mode behind proxies and LLM gateways](</docs/en/fast-mode#use-fast-mode-behind-proxies-and-llm-gateways>) `/fast` reports `Fast mode has been disabled by your organization` in a session authenticated with `ANTHROPIC_AUTH_TOKEN`, even though the organization has fast mode enabled| The availability check requires a claude.ai login or an API key; with only a bearer token, Claude Code treats fast mode as disabled without sending the check| Set `CLAUDE_CODE_SKIP_FAST_MODE_ORG_CHECK=1`; see [use fast mode behind proxies and LLM gateways](</docs/en/fast-mode#use-fast-mode-behind-proxies-and-llm-gateways>) +`/feedback` saves a local file in a session that uses `ANTHROPIC_BASE_URL`| Behind a gateway, `ANTHROPIC_AUTH_TOKEN` and a key that isn’t in the format of an Anthropic API key aren’t Anthropic credentials. Without one, Claude Code writes the report to a local archive under `~/.claude/feedback-bundles/` instead of sending it| Send the file to your Anthropic account representative or attach it to a support request. See [telemetry services](</docs/en/data-usage#telemetry-services>) Claude Code asks you to log in even though the curl test succeeds| The CLI has no credential of its own: a reachable base URL isn’t one, and in an interactive session an `env` block in a project’s `.claude/settings.json` or `.claude/settings.local.json` applies only after the first-run wizard and [trust prompt](</docs/en/permissions#what-runs-before-you-trust-a-folder>)| Set `ANTHROPIC_AUTH_TOKEN` somewhere Claude Code reads before first-run setup: a shell export, the `env` block in `~/.claude/settings.json`, or managed settings `ANTHROPIC_API_KEY` is set but ignored, with no prompt| The key needs a one-time approval in interactive sessions, and a previously declined key is ignored without asking again| Enable it under `/config` with the `Use custom API key` option `This machine's managed settings require a first-party login`, or [`Administrator policy requires a Cloud gateway sign-in`](</docs/en/errors#administrator-policy-requires-a-cloud-gateway-sign-in>) when managed settings set `forceLoginMethod` to `"gateway"` or also set `forceLoginGatewayUrl`| Managed settings include `forceLoginMethod` or `forceLoginOrgUUID`, which cannot coexist with `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, or `apiKeyHelper`| Your administrator must remove `forceLoginMethod`, `forceLoginOrgUUID`, and `forceLoginGatewayUrl` from managed settings to use gateway credentials, or remove the gateway credential and use the sign-in the managed settings require. The two cannot be combined @@ -534,11 +423,7 @@ If Claude Code prompts you to log in repeatedly after removing gateway configuration, the cause is usually credential storage rather than the gateway; see [authentication errors](</docs/en/errors#authentication-errors>). -## - -​ - -Related resources +## Related resources * [LLM gateways overview](</docs/en/llm-gateway>): what a gateway is and how it interacts with claude.ai subscriptions * [Roll out an LLM gateway for your organization](</docs/en/llm-gateway-rollout>): the admin-facing checklist for deploying and distributing gateway configuration
modified Claude Code gateway compatibility guide View current →
Show diff (306 lines)
--- a/llm-gateway-protocol.md +++ b/llm-gateway-protocol.md @@ -20,11 +20,7 @@ Anything not marked forward unchanged is yours to consume or ignore. -## - -​ - -API formats +## API formats A gateway must expose at least one of the following API formats to Claude Code clients. A client picks a format and points Claude Code at your gateway with the variables in the Selected by column of the table below. Google Cloud’s Agent Platform is Google Cloud’s Claude endpoint, formerly Vertex AI; its variable names keep the `VERTEX` spelling. @@ -34,19 +30,11 @@ Amazon Bedrock InvokeModel| `ANTHROPIC_BEDROCK_BASE_URL` with `CLAUDE_CODE_USE_BEDROCK=1`| `/model/{model}/invoke`, `/model/{model}/invoke-with-response-stream`, `/model/{model}/count-tokens` (optional)| `anthropic_beta` and `anthropic_version` request body fields Google Cloud’s Agent Platform rawPredict| `ANTHROPIC_VERTEX_BASE_URL` with `CLAUDE_CODE_USE_VERTEX=1`| `:rawPredict`, `:streamRawPredict`, `count-tokens:rawPredict` (optional)| `anthropic-beta` and `anthropic-version` request headers, and the `anthropic_version` request body field -### - -​ - -Foundry and Claude Platform on AWS +### Foundry and Claude Platform on AWS Microsoft Foundry and the [Claude Platform on AWS](</docs/en/claude-platform-on-aws>) implement the Anthropic Messages format. Claude Code routes to them through their own variables, `ANTHROPIC_FOUNDRY_BASE_URL` and `ANTHROPIC_AWS_BASE_URL`, but a gateway fronting either implements the Anthropic Messages row above. A gateway fronting the Claude Platform on AWS must also forward the `anthropic-workspace-id` header, which [that platform requires on every request](</docs/en/claude-platform-on-aws>). -### - -​ - -Optional endpoints and startup traffic +### Optional endpoints and startup traffic Token-counting endpoints are the only optional ones: when they’re absent, Claude Code falls back to a character-based estimate of context usage. Match on the path, not the full URL: @@ -55,11 +43,7 @@ A gateway also sees best-effort startup traffic it can reject without breaking anything. An Anthropic Messages-format gateway receives a `HEAD /api/hello` connection-warming probe, which Claude Code skips when an HTTP proxy or client certificate is configured. An Amazon Bedrock-format gateway receives a `GET /inference-profiles?type=SYSTEM_DEFINED` request and, when the configured model is an inference profile, `GET /inference-profiles/{profile}` lookups. Sessions that go through a gateway aren’t eligible for the HIPAA configuration. [Check how developers sign in and connect](</docs/en/hipaa-setup#check-how-developers-sign-in-and-connect>) lists which sign-in and connection methods are. See [The HIPAA configuration behind a gateway](</docs/en/llm-gateway-rollout#the-hipaa-configuration-behind-a-gateway>). The [fast mode](</docs/en/fast-mode>) availability check never appears in gateway logs: it calls `api.anthropic.com` directly rather than following `ANTHROPIC_BASE_URL`, so on a network that blocks direct egress to `api.anthropic.com`, fast mode can report a connectivity error while inference through the gateway keeps working. The [WebFetch domain safety check](</docs/en/data-usage#webfetch-domain-safety-check>) also calls `api.anthropic.com` directly. [Use fast mode behind proxies and LLM gateways](</docs/en/fast-mode#use-fast-mode-behind-proxies-and-llm-gateways>) covers the variables that restore it. -### - -​ - -Streaming +### Streaming Claude Code reads each streaming inference response event by event as it arrives, so the way your gateway relays the stream affects what the user sees: @@ -69,11 +53,7 @@ * Claude Code aborts a streaming response once no bytes reach it for longer than its [streaming idle timeout](</docs/en/network-config#streaming-idle-watchdogs>). During a long thinking pause, the upstream’s SSE `ping` events can be the only bytes on the stream, so a gateway that strips or buffers them can trip that timeout partway through a response. A gateway that translates from an upstream without pings, such as Amazon Bedrock’s binary event stream, has the same gap unless it emits its own `ping` events. * On the Amazon Bedrock InvokeModel format, Claude Code reads the `/model/{model}/invoke-with-response-stream` response as the binary `application/vnd.amazon.eventstream` body Bedrock returns, and can’t parse it once a gateway converts it to server-sent events or rewrites that `Content-Type` header. [Streaming errors behind a gateway or proxy](</docs/en/amazon-bedrock#streaming-errors-behind-a-gateway-or-proxy>) describes what the user sees then. -### - -​ - -Format mismatch with the upstream +### Format mismatch with the upstream Which format the client speaks determines what your gateway receives. The common failure mode is a mismatch between the format the client sends to your gateway and the format the upstream provider behind it accepts. @@ -82,11 +62,7 @@ Bridging that difference is your gateway’s job. Feature pass-through describes what breaks when it doesn’t. If your upstream is Amazon Bedrock or Google Cloud’s Agent Platform, you can avoid the bridging by exposing that provider’s format instead. [Route to a cloud provider through a gateway](</docs/en/llm-gateway-connect#route-to-a-cloud-provider-through-a-gateway>) shows the client configuration for that format. -## - -​ - -How the connection method changes client behavior +## How the connection method changes client behavior The way a developer connects to your gateway determines which model IDs, `anthropic-beta` values, and request fields Claude Code sends, and which defaults it applies. Your gateway sees one of three client behaviors: @@ -94,11 +70,7 @@ * **Anthropic Messages format** : the developer sets `ANTHROPIC_BASE_URL` to your gateway. Claude Code treats the gateway as the Claude API and can’t tell which upstream you forward to. * **Claude apps gateway sign-in** : the developer signs in to a [Claude apps gateway](</docs/en/claude-apps-gateway>). That gateway speaks the Anthropic Messages format but can route to any upstream, so Claude Code sends only the `anthropic-beta` values and model-capability assumptions that Amazon Bedrock and Agent Platform also accept. -### - -​ - -Requests and defaults by connection method +### Requests and defaults by connection method The table below compares the three connection methods, one behavior per row. It leaves out Microsoft Foundry and Claude Platform on AWS, which also use the Anthropic Messages format but which Claude Code reaches through their own variables. For those, see the [Microsoft Foundry](</docs/en/microsoft-foundry>) and [Claude Platform on AWS](</docs/en/claude-platform-on-aws>) pages. @@ -112,22 +84,14 @@ For the features each connection supports and the telemetry it sends to Anthropic by default, see [Feature availability](</docs/en/feature-availability#availability-by-model-provider>) and [Default behaviors by API provider](</docs/en/data-usage#default-behaviors-by-api-provider>). -### - -​ - -Settings for unrecognized model IDs +### Settings for unrecognized model IDs Two client-side settings change what Claude Code assumes for a model ID it doesn’t recognize, whichever connection method the developer uses: * **Context window** : Claude Code assumes 200K, or 1M when the ID carries `[1m]`. To declare the real window, see [Correct the window for a gateway or custom model ID](</docs/en/model-config#correct-the-window-for-a-gateway-or-custom-model-id>) * **Capabilities** : to give a gateway alias the capabilities of the model behind it, map that model’s Anthropic ID to your alias with a [`modelOverrides`](</docs/en/errors#unrecognized-model-id-on-a-request>) entry in the settings you distribute. For where the `ANTHROPIC_DEFAULT_*_MODEL_SUPPORTED_CAPABILITIES` variables apply, see feature pass-through -## - -​ - -Request headers +## Request headers Claude Code includes these headers on API requests. Header names are case-insensitive on the wire. Forward `anthropic-version` and `anthropic-beta` unchanged, plus `anthropic-workspace-id` when the upstream is the [Claude Platform on AWS](</docs/en/claude-platform-on-aws>). Also forward `Authorization` when your gateway authenticates to Anthropic with the developer’s claude.ai login and not a key of its own. The rest the gateway may consume for routing, attribution, and tracing, and need not forward. @@ -142,11 +106,7 @@ Subagent IDs are generated fresh each time Claude Code spawns a subagent. Teammate agents, the named members of an [agent team](</docs/en/agent-teams>), reuse a stable name-based ID across reconnections. In both cases the ID identifies an agent, not a person or a device, so don’t treat the agent ID header as a user identifier. If your developers set `ANTHROPIC_CUSTOM_HEADERS`, those headers appear on requests as well. -### - -​ - -Gateway hint headers +### Gateway hint headers Claude Code can also send routing hints: per-request facts a gateway or router can use to schedule, cache, or attribute a request. Requires Claude Code v2.1.273 or later. Whether a request carries them depends on where Claude Code sends it: @@ -174,19 +134,11 @@ * Absence: compaction calls, side requests, and the first request of a new prompt never carry it. Don’t read a missing header as a turn that ran no tools * Times: each one excludes permission prompts and hooks, and parallel tool calls each report their own time, so the entries don’t add up to the gap between requests -### - -​ - -Forward as open lists +### Forward as open lists Treat the headers and body fields as open lists, not closed ones. Claude Code gains capabilities over releases, and they arrive as new `anthropic-beta` values, new request body fields, and occasionally new `anthropic-*` or `x-claude-code-*` headers. When forwarding to an Anthropic-format upstream, pass `anthropic-*` request headers and request body fields through unchanged rather than allowlisting the ones you see today. A gateway pinned to an observed list strips the next capability’s header or field and breaks it on the release that introduces it. The exception is a non-Anthropic upstream such as Amazon Bedrock or Google Cloud’s Agent Platform, where bridging the schema difference is the gateway’s job; see feature pass-through. -## - -​ - -Response headers +## Response headers Claude Code reads these response headers to detect stalled streams, to decide whether and when to retry, and to show usage limits. The table lists what to return for each. Also forward error response bodies unmodified, so Claude Code’s capability-rejection recovery can match the upstream’s error wording. @@ -197,11 +149,7 @@ `x-should-retry`| Pass the upstream’s value through unchanged. Claude Code reads this header as one input when deciding whether to retry a failed request: `true` marks the response retryable and `false` marks it not retryable. For retry counts, backoff, and which failures Claude Code retries, see [automatic retries](</docs/en/errors#automatic-retries>) `anthropic-ratelimit-unified-*`| Forward the upstream’s values unchanged on every response. Claude Code reads them on successful responses to show usage against plan limits to developers signed in with claude.ai, and on a `429` to tell a plan limit or spend cap from a temporary throttle; see [usage limits](</docs/en/errors#usage-limits>) -## - -​ - -System prompt attribution block +## System prompt attribution block Claude Code prepends a short attribution block to the system prompt containing the client version and a fingerprint derived from the conversation. The `api.anthropic.com` endpoint strips the block before processing when it arrives unchanged as the first system block, so it doesn’t affect first-party prompt caching. Any other upstream receives it as part of the prompt. The strip is positional, so it only works when the gateway forwards the `system` array unchanged. To keep the block out of the prompt without losing other system content: @@ -219,19 +167,11 @@ * Implements a prompt cache keyed on the request body. * Forwards requests to a third-party provider such as Amazon Bedrock, Microsoft Foundry, or Google Cloud’s Agent Platform, in the Anthropic Messages format or the provider’s own, where the changing prefix reduces prompt-cache reuse on that provider. -## - -​ - -Feature pass-through +## Feature pass-through Claude Code treats an `ANTHROPIC_BASE_URL` gateway as an Anthropic-format endpoint and sends it the beta headers and request body fields it sends to `api.anthropic.com`, except a small set of diagnostics and defaults reserved for direct connections, such as the fine-grained tool streaming default covered below. That set varies by release, so don’t depend on its contents. Fine-grained tool streaming is one of the direct-connection defaults: it is off by default whenever requests route through a custom base URL, and a gateway receives it when developers set [`CLAUDE_CODE_ENABLE_FINE_GRAINED_TOOL_STREAMING=1`](</docs/en/env-vars>). -### - -​ - -Beta header and body field pairs +### Beta header and body field pairs Capabilities that add body fields pair them with a beta header, and the pair travels together. A gateway that strips the header while passing the body, or forwards an Anthropic-format body to an upstream with a different schema, produces `400` errors. When both halves are absent together, the feature turns off quietly. A gateway that rewrites or redacts request bodies for content inspection breaks the pairing the same way stripping does, so inspect without modifying. The table notes where a feature deviates from the pairing. @@ -249,11 +189,7 @@ The `ANTHROPIC_DEFAULT_*_MODEL_SUPPORTED_CAPABILITIES` [variables](</docs/en/model-config>) declare model capabilities only in the provider configurations: `CLAUDE_CODE_USE_BEDROCK`, `CLAUDE_CODE_USE_VERTEX`, `CLAUDE_CODE_USE_FOUNDRY`, and [`CLAUDE_CODE_USE_MANTLE`](</docs/en/amazon-bedrock#use-the-mantle-endpoint>). They have no effect behind an `ANTHROPIC_BASE_URL` gateway. -### - -​ - -Automatic retry and error forwarding +### Automatic retry and error forwarding When the upstream rejects one of these capabilities, Claude Code can retry the request on its own with the rejected part removed or changed: @@ -272,11 +208,7 @@ The `bound to a different conversation` rejection comes from the API’s [preserved thinking](<https://platform.claude.com/docs/en/build-with-claude/preserved-thinking>) check, which fails when `system`, `tools`, or earlier `messages` content differs from the request that produced the thinking. A gateway that rewrites any of that content can cause the rejection itself; [Libraries, proxies, and gateways](<https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#libraries-proxies-gateways>) covers what to pass through unchanged. Most of this retry logic matches on the upstream’s error wording, so forward error response bodies unmodified. A gateway that wraps upstream errors in its own envelope breaks the recovery path, even when it preserves the status code, unless the envelope’s message carries a stable `capability_rejected:` token. [Claude apps gateway substitutes those tokens for cloud providers’ error wording](</docs/en/claude-apps-gateway-config#upstream-error-messages>), for example `capability_rejected: prompt_too_long`. -#### - -​ - -Retry without a rejected beta value +#### Retry without a rejected beta value When a `400` rejects by name an `anthropic-beta` value that this retry covers, the gateway sees the request once more without it. Later requests omit the value. Most values it covers require v2.1.314 or later. Your gateway needs no change if the message of the `400` it returns carries the value in either of these forms: @@ -289,11 +221,7 @@ * **A value Claude Code doesn’t recognize** : a value that a developer set through `ANTHROPIC_BETAS` stays on each request, so the developer’s requests keep failing with the `400`. Have the developer remove the entry * **A bare`invalid beta flag`**: Claude Code guesses which value the upstream rejected. If the request carried a value it guesses at, the gateway sees the request again without that value. If the `400` still reaches the developer, have your gateway name the rejected value in one of those forms -#### - -​ - -How long a rejected beta value stays out +#### How long a rejected beta value stays out Upstream rejected| Requests that omit it| Until ---|---|--- @@ -302,19 +230,11 @@ `context_management` or another `anthropic-beta` value the retry by name covers| Requests in the same conversation| The conversation ends or Claude Code rebuilds its prompt, such as when the main conversation compacts `context_management` or another value that retry covers, when the error message opens with the API’s own sentence for the rejection, such as `Unexpected value(s)`, or carries a `beta_header:` token| Also new conversations on the model the rejected request named, including after `/clear`| Claude Code exits -#### - -​ - -Retry without tool search +#### Retry without tool search On v2.1.305 or later, Claude Code resends a request without [`defer_loading` fields and `tool_reference` blocks](</docs/en/mcp#tool-search-through-a-gateway>) after a `400` or `422` that names tool search or whose cause it doesn’t recognize. After a successful retry, later requests in that conversation omit them too. The developer’s requests keep working without any change on the gateway, with their MCP tools loaded upfront. When Claude Code tries tool search again, the gateway can see another rejected request followed by its retry. For tool search itself, Claude Code expects the gateway to forward the `defer_loading` fields and `tool_reference` blocks with their `anthropic-beta` value. -### - -​ - -Disable pre-release capabilities +### Disable pre-release capabilities When your gateway or its upstream rejects pre-release `anthropic-beta` values or the body fields that pair with them, and you can’t forward both halves, have developers set `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1`. With the variable set, Claude Code stops sending pre-release capabilities and the `anthropic-beta` values that pair with them, including: @@ -341,19 +261,11 @@ The set of capabilities Claude Code sends grows over releases. For current beta header strings, see the [beta headers reference](<https://platform.claude.com/docs/en/api/beta-headers>); test your gateway against new Claude Code releases rather than pinning to an observed list. -## - -​ - -Model discovery +## Model discovery When `ANTHROPIC_BASE_URL` points at a gateway that exposes the Anthropic Messages format, Claude Code can query the gateway’s `/v1/models` endpoint at startup and add the returned models to the `/model` picker. If you or your administrator set `replaceBuiltInOptions` in a [`modelPicker`](</docs/en/settings-reference#modelpicker>) lineup, Claude Code hides the discovered models from the picker. Developers enable it by setting [`CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1`](</docs/en/env-vars>), in their own environment or through managed settings. Discovery is off by default so that gateways backed by a shared API key don’t surface every model the key can access to every user. -### - -​ - -When discovery runs +### When discovery runs Discovery applies only to the Anthropic Messages format. It doesn’t run when: @@ -362,11 +274,7 @@ Discovery still runs when [nonessential traffic is turned off](</docs/en/llm-gateway-connect#turn-off-traffic-outside-the-gateway-path>), because the request goes only to your gateway. Before v2.1.257, discovery didn’t run while nonessential traffic was turned off. -### - -​ - -Request and response +### Request and response The request is `GET /v1/models?limit=1000` with a timeout of 3 seconds by default, and any redirect is treated as failure so the credential can’t leak to a redirect target. A gateway that responds slower than the timeout, or one that redirects `/v1/models`, even `http` to `https`, fails discovery silently; serve the endpoint directly at the configured base URL. To give a slow gateway longer, set [`CLAUDE_CODE_GATEWAY_MODEL_DISCOVERY_TIMEOUT_MS`](</docs/en/env-vars#variables>). The variable requires Claude Code v2.1.269 or later. Claude Code sends the discovery request with both credential headers below and omits a header whose value doesn’t resolve. Sending both headers requires Claude Code v2.1.248 or later. Earlier versions send only `Authorization` when `ANTHROPIC_AUTH_TOKEN` is set and only `x-api-key` otherwise. @@ -388,11 +296,7 @@ Claude Code keeps an entry when its `id` contains `claude` or `anthropic` anywhere in the string, matched case-insensitively, and ignores the rest. Provider-prefixed IDs such as `vertex_ai/claude-sonnet-4-6` or `bedrock/anthropic.claude-sonnet-4-5` pass the filter; an ID that contains neither substring doesn’t. Before v2.1.223, Claude Code kept an entry only when its `id` began with `claude` or `anthropic`, which hid provider-prefixed IDs. -### - -​ - -Picker entries and caching +### Picker entries and caching The picker is the interactive model list that opens when a developer runs `/model` in Claude Code. Each discovered entry uses `display_name` as its name when the gateway sends one that differs from the `id`. Otherwise the entry shows the model’s name when Claude Code [recognizes the `id`](</docs/en/model-config#customize-pinned-model-display-and-capabilities>), and the `id` when it doesn’t. For example, an entry with the `id` `my-gateway-claude-sonnet-4-6` and no `display_name` appears as `Sonnet 4.6`. Discovery adds only models that the [`availableModels` managed setting](</docs/en/settings-reference#availablemodels>) allows. Each entry also shows the model’s `description`, collapsed to one line. An entry without a `description` reads “From gateway” instead. Before v2.1.257, every discovered entry read “From gateway”. A discovered ID doesn’t get its own row when it matches a row already in the picker: @@ -401,11 +305,7 @@ Results are cached to `~/.claude/cache/gateway-models.json`, or `%USERPROFILE%\.claude\cache\gateway-models.json` on Windows, and refreshed on each startup. If you set [`CLAUDE_CONFIG_DIR`](</docs/en/env-vars>), the cache lives under that directory instead. If the request fails or the gateway doesn’t implement `/v1/models`, the picker falls back to the cached list from the previous startup or to the built-in model list. If your gateway serves Claude models under aliases that don’t match the discovery filter, developers can add those aliases manually with the [model configuration](</docs/en/model-config>) variables. -## - -​ - -Related resources +## Related resources For the rest of the gateway documentation set and the underlying API references:
modified Roll out an LLM gateway for your organization View current →
Show diff (215 lines)
--- a/llm-gateway-rollout.md +++ b/llm-gateway-rollout.md @@ -3,11 +3,7 @@ * To connect Claude Code on your own machine to an existing gateway, see [Connect Claude Code to an LLM gateway](</docs/en/llm-gateway-connect>) * For what Claude Code sends to a gateway and what to forward, see the [gateway compatibility guide](</docs/en/llm-gateway-protocol>) -## - -​ - -Prerequisites +## Prerequisites To complete the rollout, you’ll need: @@ -18,11 +14,7 @@ * A way to deliver settings files to developer machines, such as MDM or configuration management * If you don’t have one yet, [how settings reach devices](</docs/en/admin-setup#decide-how-settings-reach-devices>) compares the options -### - -​ - -Gateway requirements +### Gateway requirements Whichever product provides the gateway, it must: @@ -35,11 +27,7 @@ Optionally, serve `GET /v1/models` so Claude Code can populate the model picker from your gateway with [model discovery](</docs/en/llm-gateway-protocol#model-discovery>). -## - -​ - -Rollout steps +## Rollout steps The rollout takes five steps, each with a checkpoint: @@ -57,11 +45,7 @@ Gateway administrative credential| You, if your gateway product issues one for its admin or test interface| `<gateway-key>` Developer key| Each developer, issued by the gateway in Issue developer credentials| `<developer-key>` -### - -​ - -Confirm the gateway routes your models +### Confirm the gateway routes your models Your gateway should already be configured with your provider credential, listening at its base URL, and forwarding requests to your provider’s API. Test that the path works end to end with a minimal request, substituting two values from your deployment: @@ -87,11 +71,7 @@ Avoid serving the gateway behind a redirect. A redirect can drop the request body or strip the credential header on inference requests, and [model discovery](</docs/en/llm-gateway-protocol#model-discovery>) treats any redirect as a failure so the credential cannot leak to a redirect target. -### - -​ - -Issue developer credentials +### Issue developer credentials Each developer needs their own gateway key to authenticate. Create a credential per developer at the gateway, following your product’s credential management documentation. Confirm a freshly issued key works against the gateway with the same request as Confirm the gateway routes your models, replacing `<gateway-key>` with the new `<developer-key>`: @@ -112,11 +92,7 @@ **Checkpoint** : a `200` with a `content` field means the developer key reaches the gateway and the gateway forwards it. A `401` here, when the previous step succeeded, means the developer key is wrong or hasn’t taken effect at the gateway yet. Issuing one key per developer rather than a shared key is what makes per-developer usage attribution and individual offboarding work. The environment variable that holds the key depends on which header the gateway reads. For a gateway that checks credentials in the `Authorization: Bearer` header, developers set their key in `ANTHROPIC_AUTH_TOKEN`. For a gateway that reads keys from the `x-api-key` header, developers set `ANTHROPIC_API_KEY` instead; the [credential table](</docs/en/llm-gateway-connect#set-the-credential-variable>) covers the mapping. -### - -​ - -Test Claude Code against the gateway +### Test Claude Code against the gateway Run Claude Code through the gateway yourself before distributing anything, using the same configuration the rollout will deliver fleet-wide. Type these directly in a terminal, not in a `.env` or settings file; they last only for this terminal session, so closing it returns your machine to its normal configuration. Use `ANTHROPIC_API_KEY` instead of `ANTHROPIC_AUTH_TOKEN` if your gateway reads the `x-api-key` header: @@ -134,26 +110,18 @@ claude -p "Reply with one word: connected" -**Checkpoint** : the prompt returns a response, and the request appears in the gateway’s log as a `POST` to the `/v1/messages` path with status `200`. Claude Code appends a query string such as `?beta=true`, so match on the path, not the full URL. Two failure messages point in different directions: - - * `Not logged in`: check the gateway log to tell the two causes apart. If it’s empty, no credential reached the session and no request left the machine; re-run the exports in the shell you’re testing from. If it shows a rejected request with `x-api-key` in the `401` body, the gateway expects keys in that header instead; switch to `ANTHROPIC_API_KEY` +**Checkpoint** : the prompt returns a response, and the request appears in the gateway’s log as a `POST` to the `/v1/messages` path with status `200`. Claude Code appends a query string such as `?beta=true`, so match on the path, not the full URL. Check the failure message: + + * `Not logged in`: check the gateway log. If it’s empty, no credential reached the session and no request left the machine; re-run the exports in the shell you’re testing from. If it shows a `401` from the gateway naming `x-api-key`, the gateway expects keys in that header instead; switch to `ANTHROPIC_API_KEY`. If it shows a `401` from `api.anthropic.com` or your provider’s endpoint, fix the provider credential the gateway holds * `Failed to authenticate. API Error: 401` means a credential was sent and rejected, and the gateway log says where: a `401` naming `api.anthropic.com` or your provider’s endpoint means the gateway reached the upstream but its provider credential was rejected, so the developer key worked and the provider credential the gateway holds is wrong or a placeholder A wrong or unreachable base URL produces a different symptom: Claude Code [retries the connection with backoff](</docs/en/errors#automatic-retries>) and can sit with no output for several minutes before reporting an error. If the command appears to hang, check the gateway log instead of waiting; no arriving request means `ANTHROPIC_BASE_URL` doesn’t point at the gateway. -### - -​ - -Distribute the configuration +### Distribute the configuration Every developer machine needs the gateway address and a credential. You can distribute them centrally through [managed settings](</docs/en/managed-settings#delivery-mechanisms>), so developers configure nothing, or give developers the values to set themselves. -#### - -​ - -What to distribute +#### What to distribute The same set of variables applies whichever path you choose. Most rollouts only need `ANTHROPIC_BASE_URL` and a credential; include the conditional rows when your gateway setup calls for them. @@ -169,11 +137,7 @@ `ANTHROPIC_MODEL` or [`ANTHROPIC_DEFAULT_HAIKU_MODEL`](</docs/en/model-config>)| Set which model name Claude Code requests for the main session and for background traffic| Your gateway routes model names that don’t match Claude Code’s defaults, or you route [background functionality](</docs/en/model-config#environment-variables>) to a different model. Route both the override names and the built-in model IDs Claude Code requests when no override is set, since some background sub-calls request a built-in ID regardless of the override `ANTHROPIC_BEDROCK_BASE_URL`, `ANTHROPIC_VERTEX_BASE_URL`, `ANTHROPIC_FOUNDRY_BASE_URL`, or `ANTHROPIC_AWS_BASE_URL` with the [variables for that provider](</docs/en/llm-gateway-connect#route-to-a-cloud-provider-through-a-gateway>)| Point Claude Code at the gateway through a provider-specific base URL. Amazon Bedrock and Google Cloud’s Agent Platform also switch to those providers’ native request format| Your gateway fronts Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, or the Claude Platform on AWS; see [API formats](</docs/en/llm-gateway-protocol#api-formats>) -#### - -​ - -Distribute through managed settings +#### Distribute through managed settings Deliver the variables through the `env` block of a [managed settings file](</docs/en/managed-settings#delivery-mechanisms>), pushed by MDM, registry policy, or configuration management: @@ -190,11 +154,7 @@ * CI runners need `ANTHROPIC_BASE_URL` and the credential set in the [runner’s environment](</docs/en/llm-gateway-connect#configure-each-surface>) * WSL on managed Windows machines reads the Windows managed settings only when [`wslInheritsWindowsSettings`](</docs/en/settings-reference#wslinheritswindowssettings>) is `true` -#### - -​ - -The HIPAA configuration behind a gateway +#### The HIPAA configuration behind a gateway Sessions that go through a gateway aren’t eligible for the HIPAA configuration. [Check how developers sign in and connect](</docs/en/hipaa-setup#check-how-developers-sign-in-and-connect>) lists which sign-in and connection methods are. To restrict features for those sessions in the managed settings file, use the keys in [Map egress paths to managed controls and events](</docs/en/monitoring-usage#map-egress-paths-to-managed-controls-and-events>). These keys don’t make a session eligible for the HIPAA configuration, and they don’t cover everything the configuration changes. For example: @@ -203,11 +163,7 @@ Don’t use `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` in place of these keys. It turns off some of these features, but it also turns off the auto-updater, and it leaves WebFetch on. -#### - -​ - -Hand developers the values to set themselves +#### Hand developers the values to set themselves If you don’t have managed-settings distribution in place, send each developer what they need to follow the [connect page](</docs/en/llm-gateway-connect#configure-claude-code-yourself>): @@ -218,11 +174,7 @@ The [connect page](</docs/en/llm-gateway-connect#configure-claude-code-yourself>) walks developers through setting each one. **Checkpoint** : on a developer machine, `claude` starts a session without showing the login screen, since the distributed credential satisfies authentication. Then run `/status` and open the **Status** tab: the `Anthropic base URL` line shows the gateway address, and for managed distribution the `Setting sources` line includes managed settings. A login screen, or a missing `Anthropic base URL` line, means the configuration didn’t reach the machine. -### - -​ - -Verify the rollout +### Verify the rollout Confirm everything works from a developer machine, not the gateway host, so the test covers the network path developers use. Send a streaming request, which checks the endpoint, streaming pass-through, and model routing at once: @@ -243,19 +195,15 @@ -H "content-type: application/json" ` --data-binary '@-' -You should see `data:` lines arrive incrementally. The whole response arriving at once after a pause means the gateway is buffering, which stalls Claude Code; a `404` means the model name isn’t routed. Repeat per model name. Then start `claude` and send a message. Each symptom at this step has one cause: - - * A login prompt means a credential gap. Run `/status` and open the **Status** tab: when the `Setting sources` line doesn’t include managed settings, the distribution didn’t reach the machine; when it does, the developer credential wasn’t delivered, so set `ANTHROPIC_AUTH_TOKEN` or the `apiKeyHelper` - * `Failed to authenticate` errors mean the gateway is rejecting requests; its log says which credential failed. A rejection the gateway logs itself names the developer key, while a `401` from `api.anthropic.com` or your provider’s endpoint means the provider credential the gateway holds was rejected +You should see `data:` lines arrive incrementally. The whole response arriving at once after a pause means the gateway is buffering, which stalls Claude Code; a `404` means the model name isn’t routed. Repeat per model name. Then start `claude`, send a message, and match what you see: + + * A login screen, or `Not logged in` with nothing new in the gateway log, means a credential gap. Run `/status` and open the **Status** tab: when the `Setting sources` line doesn’t include managed settings, the distribution didn’t reach the machine; when it does, the developer credential wasn’t delivered, so set `ANTHROPIC_AUTH_TOKEN` or the `apiKeyHelper` + * `Please run /login · API Error: 401`, `Not logged in`, or `Invalid API key` with a `401` in the gateway log: check who wrote the `401`. Fix the developer key or its header if the gateway wrote it, or the provider credential it holds if it came from `api.anthropic.com` or your provider’s endpoint * A one-time approval prompt for the key is expected on first use when the gateway expects keys in the `x-api-key` header, set as `ANTHROPIC_API_KEY` If your organization uses [fast mode](</docs/en/fast-mode>), run `/fast` here too: the availability check calls `api.anthropic.com` directly rather than following the gateway base URL, so a gateway-routed session can report fast mode as unavailable or disabled even though inference works. [Use fast mode behind proxies and LLM gateways](</docs/en/fast-mode#use-fast-mode-behind-proxies-and-llm-gateways>) maps each message to the variable that restores it, distributed with the rest of the configuration. Finally, check the gateway’s logs for the message you sent: the credential identifies the developer, and the [`x-claude-code-session-id` header](</docs/en/llm-gateway-protocol#request-headers>) groups requests by session. If features fail with the [troubleshooting symptoms](</docs/en/llm-gateway-connect#troubleshoot-gateway-errors>), the gateway is stripping headers or rewriting errors; see the gateway requirements above. -## - -​ - -Maintain the gateway +## Maintain the gateway After rollout, three kinds of change reach the gateway over time. Each has a symptom to watch for and an action to take. @@ -267,11 +215,7 @@ When sizing per-key rate limits, account for the client [retrying transient failures](</docs/en/errors#automatic-retries>), including `429` responses, up to 10 times with backoff, honoring `Retry-After`. Keep the [compatibility guide](</docs/en/llm-gateway-protocol>) as the reference for what each Claude Code release sends. -### - -​ - -Plan Claude Code version upgrades +### Plan Claude Code version upgrades Some Claude Code behavior is built into the installed version rather than set at your gateway, so moving developers to a new release can change behavior across your deployment even when the gateway configuration hasn’t changed. To control when that happens, pin developers to a tested version with [`requiredMaximumVersion`](</docs/en/settings-reference#requiredmaximumversion>), or with [`DISABLE_UPDATES`](</docs/en/setup#disable-auto-updates>) if you distribute Claude Code through your own channel. Before you raise the pin, read the new release’s [changelog](</docs/en/changelog>) entry and test it against the gateway. When you test a release, new headers or request fields that the gateway rejects appear as the `400` errors described in Maintain the gateway. The table below covers version-dependent changes that don’t produce an error, with the setting that keeps each one constant across upgrades. @@ -281,11 +225,7 @@ Model capability assumptions| A model ID that the installed version doesn’t recognize, such as the gateway alias `prod-opus`, runs on default assumptions for [adaptive reasoning](</docs/en/model-config#adaptive-reasoning-and-fixed-thinking-budgets>), the effort parameter, and the [context window](</docs/en/model-config#correct-the-window-for-a-gateway-or-custom-model-id>) until a later version recognizes the ID or you map it| Route Anthropic model IDs at the gateway, or add a [`modelOverrides`](</docs/en/model-config#override-model-ids-per-version>) entry that maps the Anthropic model ID to your alias. On a cloud provider connection, you can instead [declare a pinned model’s capabilities](</docs/en/model-config#customize-pinned-model-display-and-capabilities>) Default model and aliases| The model that new sessions start on by default, and the models that aliases such as `opus` and `sonnet` resolve to, are [built into each version](</docs/en/model-config#pin-models-for-third-party-deployments>) and can change when developers upgrade| [`ANTHROPIC_DEFAULT_MODEL`](</docs/en/model-config#set-a-default-model-for-new-sessions>) for the model new sessions start on, and the [`ANTHROPIC_DEFAULT_*_MODEL` variables](</docs/en/model-config#environment-variables>), such as `ANTHROPIC_DEFAULT_OPUS_MODEL`, for what each alias resolves to. `ANTHROPIC_DEFAULT_MODEL` requires Claude Code v2.1.236 or later -## - -​ - -Related resources +## Related resources * [Connect Claude Code to an LLM gateway](</docs/en/llm-gateway-connect>): the developer-facing setup steps, with per-surface configuration and a troubleshooting table you can hand to developers * [Gateway compatibility guide](</docs/en/llm-gateway-protocol>): the reference for gateway operators, covering endpoints, headers to forward, and the feature pass-through table
modified Plugin loading reference View current →
Show diff (411 lines)
--- a/loading.md +++ b/loading.md @@ -13,11 +13,7 @@ * A `--plugin-dir` plugin didn’t load, or a same-named plugin loaded instead: Name conflicts * A plugin under `~/.claude/skills/` or `.claude/skills/` didn’t load, and no error says why: Skills-directory plugins blocked by managed settings -## - -​ - -Check which stage a plugin reached +## Check which stage a plugin reached An `enabledPlugins` entry becomes a plugin you can use in stages: your settings declare it, Claude Code fetches it to disk, and the running session loads it. When a plugin doesn’t behave as a settings file suggests, check which stage it reached: @@ -28,11 +24,7 @@ * `cache/` holds the plugin files * **Loaded, in the running session** : the plugin set Claude Code loaded at startup or at the last `/reload-plugins`. Changes to settings or to disk don’t reach this layer until you run `/reload-plugins` or start a new session. That is why `claude plugin update` ends with `Restart to apply changes.` and background updates prompt you with `Run /reload-plugins to apply` -### - -​ - -Plugins and marketplaces that aren’t on disk at session start +### Plugins and marketplaces that aren’t on disk at session start Plugins load at session start from `installed_plugins.json` and the cache without using the network. After the session starts, Claude Code checks the declared marketplaces in the background: @@ -41,11 +33,7 @@ An enabled plugin that neither path fetched and that has no usable cache directory shows `Plugin "<name>" not cached at <path>` in the `/plugin` **Errors** tab. For the fix, see [`Plugin "<name>" not cached at <path>`](</docs/en/plugins/troubleshooting#plugin-not-cached-at>). -## - -​ - -Find where a plugin came from +## Find where a plugin came from Every plugin has an id of the form `<name>@<origin>`, which is what you see in settings files and in `claude plugin list --json`. The part after `@` tells you where Claude Code found the plugin: @@ -58,30 +46,18 @@ For a marketplace plugin, `<name>` is the entry name in `marketplace.json`; for `@inline` and `@skills-dir` it’s the `name` in the plugin’s manifest. The origin names in this table are reserved, so no marketplace can be named `inline`, `skills-dir`, or `synced`. -### - -​ - -Entry name and manifest name +### Entry name and manifest name A marketplace plugin has two names, and they can differ: * **The entry name in`marketplace.json`**: the install and enable key. It’s what you write in `enabledPlugins`, what the cache directory is named after, and what `claude plugin list` shows * **The`name` in the manifest**: what the plugin’s components are namespaced under, and what name conflicts compare -### - -​ - -Plugins shared through a repository +### Plugins shared through a repository To share a plugin through a repository, list it under `enabledPlugins` in `.claude/settings.json` or place it under `.claude/skills/`. Claude Code doesn’t scan a project’s `.claude/plugins/` directory. A cloud session doesn’t add the marketplaces a repository lists under [`extraKnownMarketplaces`](</docs/en/settings-reference#extraknownmarketplaces>), because that requires the workspace trust dialog, which a cloud session never shows. -#### - -​ - -Trust check and component limits for repository plugins +#### Trust check and component limits for repository plugins A project-scope plugin is checked into the repository and reaches every collaborator who clones it. Because that content comes from the repository rather than from you, it loads only after the same trust check that applies to project allow rules in `.claude/settings.json`. Trusting a parent folder or running with `-p` isn’t enough. Components that run code are restricted further: @@ -91,11 +67,7 @@ Neither the trust check nor these component limits apply to a plugin under your own `~/.claude/skills/`. For how to write `--plugin-dir` and skills-directory plugins, see [Create plugins](</docs/en/plugins/create>). -#### - -​ - -Check why a repository plugin didn’t load +#### Check why a repository plugin didn’t load If a plugin in your repository’s `.claude/skills/` doesn’t load, check for these causes: @@ -104,11 +76,7 @@ * **In a folder you haven’t trusted** : the plugin loads only after you accept the [workspace trust dialog](</docs/en/permissions#what-runs-before-you-trust-a-folder>) for that folder * **In an organization that manages Claude Code** : see Skills-directory plugins blocked by managed settings -### - -​ - -Skills-directory plugins blocked by managed settings +### Skills-directory plugins blocked by managed settings If a plugin folder in `~/.claude/skills/` or a project’s `.claude/skills/` didn’t load and you see no error, your administrator may have blocked it through [managed settings](</docs/en/managed-settings>). These folders come from you or your repository rather than from a marketplace, so Claude Code skips them when your administrator sets one of these restrictions: @@ -120,38 +88,22 @@ * **Confirm the cause** : run `/status` in a Claude Code session. If the `Setting sources` line lists `Enterprise managed settings`, ask your administrator whether one of these settings applies to you. If it doesn’t, see Check why a repository plugin didn’t load for other causes. * **Load the whole plugin** : add it to a [marketplace](</docs/en/plugins/create-marketplace#create-a-marketplace>) your organization allows and install it from there. To load it for one session instead, start `claude` from your shell with [`--plugin-dir`](</docs/en/plugins/cli-reference#flags-that-load-a-plugin-for-one-session>) and the folder’s path, which works unless your administrator has also turned off that flag. -### - -​ - -Plugins synced from claude.ai +### Plugins synced from claude.ai A plugin you turn on for your claude.ai account also loads in Claude Code, alongside the plugins you install from marketplaces. That includes plugins your organization turns on for its members. Each of these plugins loads as `<name>@synced`, with no marketplace and no install record. In terminal sessions, a synced plugin’s skills, agents, hooks, MCP servers, and LSP servers all load, with the same trust as a marketplace plugin you installed. For the components Cowork loads, see the [component support table](<https://claude.com/docs/plugins/platform-support#compare-component-support-by-app>) on claude.com. Synced plugins load in Cowork sessions and in terminal sessions where you sign in with your claude.ai account: * **[Cowork](<https://claude.com/product/cowork>)** : Claude Code downloads them into the session’s own environment when the session starts * **Terminal sessions** : each time you start Claude Code, it syncs once in the background, downloading new and updated plugins and removing the ones that you or your organization turned off. Syncing in terminal sessions requires Claude Code v2.1.273 or later -#### - -​ - -Sync timing in cloud Cowork sessions +#### Sync timing in cloud Cowork sessions If you turn a plugin on or off for your claude.ai account during a Cowork session that runs in the cloud, keep working in that session. If nothing has changed after a few messages, start a new session. -#### - -​ - -Sync timing in terminal sessions +#### Sync timing in terminal sessions Because the terminal sync runs in the background, it can finish after your session has started. When it adds, updates, or removes a synced plugin in an interactive session, you see `Plugins changed. Run /reload-plugins to activate.` Run `/reload-plugins` to load the change in that session, or leave it for the next time you start Claude Code. If you turn a plugin on or off for your claude.ai account during a terminal session, Claude Code downloads or removes it the next time you start Claude Code. -#### - -​ - -Sign-in requirements for terminal sync +#### Sign-in requirements for terminal sync In your terminal, plugins sync only in sessions where you sign in with your claude.ai account. Claude Code neither downloads nor loads synced plugins in these terminal sessions, even after you sign in with `/login`: @@ -162,11 +114,7 @@ If you signed in on an earlier version of Claude Code, that sign-in doesn’t cover plugins until Claude Code renews it in the background. To get access sooner, run `/login` again. Plugin sync then starts the next time you start Claude Code. -#### - -​ - -Control which synced plugins load +#### Control which synced plugins load You can turn synced plugins off one at a time, except a plugin your organization requires, or turn off every synced plugin on the machine: @@ -176,11 +124,7 @@ For removing a plugin on claude.ai, see [Manage installed plugins](</docs/en/plugins/install#manage-installed-plugins>). -## - -​ - -Find where a plugin is enabled +## Find where a plugin is enabled You can set an `enabledPlugins` entry in any of six sources. The table lists them from lowest precedence to highest, and who each one applies to. For the settings files themselves, see [Settings files and who they affect](</docs/en/settings#where-settings-live>). @@ -195,19 +139,11 @@ These sources merge key by key. For each plugin id, the value that applies is the one from the highest-precedence source that mentions the id. A source that doesn’t mention the id leaves the value from the lower-precedence source in effect. -### - -​ - -Disabled in user settings but still loads +### Disabled in user settings but still loads If you set a plugin to `false` in `~/.claude/settings.json` and it still loads, a `true` in a higher-precedence source is overriding it. The plugin’s row in `claude plugin list` and in `/plugin` shows `Disabled in ~/.claude/settings.json but still loads — project settings enable it, which overrides your user setting`. The message names the source that overrode you: `project`, `project, gitignored` for `.claude/settings.local.json`, `cli flag`, or `managed`. To opt out of a project-enabled plugin on your machine, set the id to `false` in `.claude/settings.local.json`, which has higher precedence than the project file. -### - -​ - -Enabled in an `--add-dir` directory but not loaded +### Enabled in an `--add-dir` directory but not loaded Claude Code reads an `enabledPlugins` entry of `true` in one of the added directory’s files only when that file’s setting sources are on: @@ -219,11 +155,7 @@ * **`settings.json`** : `--setting-sources user,project` * **`settings.local.json`** : `--setting-sources user,project,local` -### - -​ - -Enabled in project settings but not installed +### Enabled in project settings but not installed By default, a plugin enabled only in your project’s `.claude/settings.json` doesn’t load at session start until you install it on your machine. With the marketplace on your machine, the `/plugin` **Errors** tab shows [`Plugin "<name>" is enabled in project settings but isn't installed here`](</docs/en/plugins/troubleshooting#plugin-is-enabled-in-project-settings-but-isnt-installed-here>) or [`Plugin "<name>" not cached at <path>`](</docs/en/plugins/troubleshooting#plugin-not-cached-at>). @@ -246,11 +178,7 @@ * The `--settings` flag * Managed settings -## - -​ - -Find plugins on disk +## Find plugins on disk Claude Code keeps plugin files and state records under one plugins root, which is `~/.claude/plugins` unless you set [`CLAUDE_CODE_PLUGIN_CACHE_DIR`](</docs/en/env-vars>). Every path in the table is relative to that root. @@ -267,11 +195,7 @@ Because `${CLAUDE_PLUGIN_ROOT}` points at a version directory, a plugin’s root path changes with every version. Keep a plugin’s durable files in `${CLAUDE_PLUGIN_DATA}` instead. -### - -​ - -In-place and copied plugins +### In-place and copied plugins Claude Code loads some plugins in place from where you keep them and copies the rest into the cache, according to their origin: @@ -280,11 +204,7 @@ * **`command`-source plugins in [link mode](</docs/en/plugins/marketplace-reference#command-plugin-source>)**: the directory the command printed loads in place, through links in the cache entry * **Every other marketplace plugin** : Claude Code copies the plugin into `cache/<marketplace>/<plugin>/<version>/` at install and loads that copy. Files outside the plugin directory aren’t copied, so when a script inside a copied plugin reads a path above the plugin root, such as `../shared`, it doesn’t find them -### - -​ - -Paths that escape the plugin directory +### Paths that escape the plugin directory Whether a plugin loads in place or from a cached copy, Claude Code doesn’t let it declare components outside its own directory. It rejects a component path that resolves outside the plugin root, whether the path is declared in `plugin.json` or in a marketplace entry: @@ -294,27 +214,15 @@ A rejected path appears as a [`path escapes plugin directory`](</docs/en/errors#path-escapes-plugin-directory>) error, and the plugin loads without that component. -### - -​ - -Cleanup of previous versions +### Cleanup of previous versions When you update or uninstall a plugin, Claude Code writes an `.orphaned_at` marker into the previous version directory. It removes that directory in a background cleanup 14 days later, so a session that already loaded the old version keeps running. The sweep runs only while `installed_plugins.json` records at least one install. After you uninstall your last plugin, orphaned directories stay until you install another. -### - -​ - -Node.js package dependencies +### Node.js package dependencies When Claude Code copies a plugin into the cache, it also installs the plugin’s Node.js package dependencies there, so the plugin’s hooks and MCP servers can load them. This section covers the npm and Bun packages a plugin declares in its own `package.json`. For plugins that depend on other plugins, see [plugin dependency versions](</docs/en/plugins/dependencies>). -#### - -​ - -When the dependency install runs +#### When the dependency install runs Claude Code installs the dependencies into the copied version directory each time it creates one: @@ -337,11 +245,7 @@ Include an npm lockfile to reach the most users. Claude Code runs the matched lockfile’s package manager from the user’s PATH and doesn’t try the other lockfile instead if that package manager is missing. For a plugin distributed through an npm source, use `npm-shrinkwrap.json`, because npm excludes `package-lock.json` from published packages. -#### - -​ - -Limits on the dependency install +#### Limits on the dependency install Claude Code constrains this dependency install so that no code from the plugin or its packages executes during it, and bounds how long it can run: @@ -355,27 +259,15 @@ Claude Code fetches an npm-source plugin before this dependency install, and none of the package’s own install scripts run during the fetch. See [npm plugin source](</docs/en/plugins/marketplace-reference#npm-plugin-source>). You can’t turn the automatic install off. No setting or environment variable disables it. In restricted networks, see the [network access requirements](</docs/en/network-config#network-access-requirements>) for the hosts to allow. -#### - -​ - -When the dependency install fails or is skipped +#### When the dependency install fails or is skipped If the install fails or is skipped, the plugin still loads, but the parts of it that need the missing packages may not work. `/plugin` and `claude plugin list` show a note on an enabled plugin whose cached copy has a lockfile and a `package.json` that lists runtime dependencies, but no `node_modules` directory. The note says whether the install didn’t finish or can’t run for this plugin. See [the troubleshooting entry](</docs/en/plugins/troubleshooting#the-packages-it-lists-are-not-installed>) for what to do about each. When the automatic install can’t provide a dependency, install it from a hook into the [persistent data directory](</docs/en/plugins/components#path-variables-and-persistent-data>). That includes packages that need their lifecycle scripts to build, Python dependencies, plugins locked with Yarn or pnpm, and dependencies that aren’t registry packages, such as git dependencies. -## - -​ - -Versions and updates +## Versions and updates If a plugin’s author pushed new commits and `claude plugin update` prints `<name> is already at the latest version (<version>).`, the version Claude Code computes for the plugin is unchanged, so the plugin’s files on disk don’t change. Claude Code computes a version for every plugin it installs, and that version is how it detects an update. `claude plugin update` and background auto-update compute the version again and don’t replace the cached copy when it matches what `installed_plugins.json` records. An update that you start can still [retry an unfinished dependency install](</docs/en/plugins/troubleshooting#the-packages-it-lists-are-not-installed>) in that copy. The version also names the plugin’s cache directory. A manifest that pins `"version"` is one way the computed version stays the same across commits. See How Claude Code computes the version for the resolution order. A plugin loaded in place from a marketplace you added from a local path loads its current source files at every session start, whatever its version string says. For a plugin from a [marketplace hosted on claude.ai](</docs/en/plugins/install#add-from-claude-ai>), the version claude.ai records for the plugin is its version, and the manifest’s `version` isn’t read. -### - -​ - -How Claude Code computes the version +### How Claude Code computes the version For a marketplace you added by source, Claude Code picks the rule by the `source` type of the plugin’s marketplace entry. The [marketplace reference](</docs/en/plugins/marketplace-reference#plugin-sources>) lists the source types. For every source type in that list except `command`: @@ -393,11 +285,7 @@ Claude Code doesn’t take the version from a repository that encloses the install path, such as a git-managed `~/.claude`. For a `command` source, Claude Code always derives the version from what the command produced: a 12-character hash on its own, or `<manifest version>-<hash>` when the manifest sets one. The marketplace entry’s `version` is ignored for command sources. For what the hash covers, see [Copy mode and link mode](</docs/en/plugins/marketplace-reference#copy-mode-and-link-mode>). Because the manifest comes first, a manifest that pins `"version": "1.0.0"` keeps every user on the cached copy until its author changes the string, however many commits they push. To let users track commits instead, leave `version` out of both the manifest and the entry. [Host a marketplace](</docs/en/plugins/host-marketplace>) covers which choice fits which release setup. -### - -​ - -When Claude Code refreshes a marketplace before an install +### When Claude Code refreshes a marketplace before an install When you install a plugin, Claude Code looks it up in its local copy of the marketplace catalog. You can run `/plugin install` in a session or `claude plugin install` in your shell, and name the plugin with or without its marketplace. The table shows which of those combinations refresh the local copy. @@ -415,19 +303,11 @@ * You set `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` * [Managed settings](</docs/en/plugins/org#restrict-what-users-can-install>) block the marketplace, in which case Claude Code also refuses the install -### - -​ - -When auto-update runs +### When auto-update runs In an interactive session, after you send your first message, Claude Code waits a random delay of up to ten minutes. It then refreshes every marketplace with auto-update on and updates the plugins installed from them on disk. The running session keeps the versions it loaded, and you see `Plugin updated: <name> · Run /reload-plugins to apply`. Whether or not you reload, the new versions load on your next launch. -#### - -​ - -Which marketplaces and plugins auto-update +#### Which marketplaces and plugins auto-update Whether a marketplace auto-updates follows the first of these that is set: @@ -437,11 +317,7 @@ If you set `DISABLE_UPDATES=1`, `DISABLE_AUTOUPDATER=1`, or `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1`, the whole pass is off and the **Enable auto-update** toggle is hidden, unless you also set `FORCE_AUTOUPDATE_PLUGINS=1`. The [environment variables reference](</docs/en/env-vars>) covers each variable’s wider effect. Auto-update also skips a plugin whose marketplace entry declares a `headersHelper`. [Installs and updates that refuse a command instead of asking](</docs/en/plugins/host-marketplace#installs-and-updates-that-refuse-the-command-instead-of-asking>) explains when such a plugin appears in the `/plugin` **Errors** tab and how you update it from there. When a copied plugin updates mid-session, hook commands, monitors, MCP servers, and LSP servers keep using the previous version’s path. Run `/reload-plugins` to switch hooks, MCP servers, and LSP servers to the new path. Monitors require a session restart. -### - -​ - -When a command source re-runs +### When a command source re-runs Plugins with a `command` source don’t wait for the auto-update pass. The printed directory reflects the tool’s state at the time the command ran, so Claude Code runs the [command you accepted](</docs/en/plugins/host-marketplace#change-the-command-of-a-command-source>) again at these times: @@ -451,11 +327,7 @@ Claude Code skips the two background runs when you set [`CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`](</docs/en/env-vars>). Explicit installs and updates still run the command with that variable set. When the command’s hashed output has changed, Claude Code installs the result as a new version and reloads it in the running interactive session, switching [the same components that `/reload-plugins` switches](</docs/en/plugins/cli-reference#reload-plugins>). You see a notification that the plugin was reloaded. If reloading in place would invalidate the session’s prompt cache, Claude Code instead prompts you to run `/reload-plugins`, which [warns about the cache cost and applies when rerun with `--force`](</docs/en/prompt-caching#enabling-or-disabling-a-plugin>). -## - -​ - -Name conflicts +## Name conflicts When enabled plugins from different origins share a manifest name, this order decides which one loads, from highest precedence to lowest: @@ -469,27 +341,15 @@ Because the order compares manifest names, a `--plugin-dir` plugin named `hello-plugin` replaces `hello@example-marketplace` when that plugin’s manifest also says `"name": "hello-plugin"`. -### - -​ - -Hooks when two enabled plugins share a name +### Hooks when two enabled plugins share a name When you install and enable two plugins with the same manifest name from different marketplaces, both appear as enabled in `/plugin`, but the hooks of one of them are left out. One plugin per name registers the hooks in its `hooks/hooks.json`, and one plugin per name loads a [hooks module](</docs/en/plugins/mods/overview>). When your organization’s managed settings turn on one of the copies, that copy holds the name. Otherwise the copy Claude Code loads first holds it. To see which copy holds the name, run `/plugin` in your session and open the **Errors** tab. A note there for the copy whose hooks were left out names the copy that holds the name, and the left-out copy’s details show the same note. For `hooks/hooks.json` hooks the note begins `Its hooks.json hooks do not run`, and for a hooks module it begins `Its hooks module does not load`. The note requires Claude Code v2.1.296 or later. To run the left-out copy’s hooks instead, disable or uninstall the copy that holds the name, then run `/reload-plugins` in your session. The reload registers the remaining copy’s hooks and clears the note. When the copy that holds the name is one your managed settings turn on, you can’t disable it, and the other copy’s hooks stay off while both are installed. -### - -​ - -Keep a session-only plugin from loading +### Keep a session-only plugin from loading To keep a `--plugin-dir` plugin from shadowing anything, or to turn one off when a parent process passes the flag for you, set its id to `false` in any settings file. For a plugin whose manifest name is `hello-plugin`, the entry is `"enabledPlugins": {"hello-plugin@inline": false}`. A disabled session-only plugin doesn’t shadow, so the marketplace or skills-directory copy loads instead. -## - -​ - -Next steps +## Next steps * [Install and manage plugins](</docs/en/plugins/install>): the install, enable, disable, and update steps themselves * [Troubleshoot plugins](</docs/en/plugins/troubleshooting>): error messages by the stage that produces them
modified Control MCP server access for your organization View current →
Show diff (373 lines)
--- a/managed-mcp.md +++ b/managed-mcp.md @@ -9,11 +9,7 @@ The [Security](</docs/en/security>) page covers the MCP threat model and how to evaluate a server before approving it. [Decide what to enforce](</docs/en/admin-setup#decide-what-to-enforce>) covers MCP restrictions alongside the other administrative controls. -## - -​ - -Choose a pattern +## Choose a pattern Claude Code supports a range of restriction levels. Each pattern uses one or more of the mechanisms covered below: `managed-mcp.json` for deploying a fixed set, the `managedMcpServers` managed setting for providing servers alongside the ones users add, and `allowedMcpServers`/`deniedMcpServers` for filtering what users configure. @@ -30,11 +26,7 @@ Claude Code doesn’t have a built-in MCP server registry that users can browse and install from. For the approved-catalog pattern, share the approved list and its `claude mcp add` commands somewhere your users will find them, such as an internal wiki, or distribute the servers as plugins through a [managed plugin marketplace](</docs/en/plugins/org#restrict-what-users-can-install>) so users can browse and install them from `/plugin`. -## - -​ - -Exclusive control with managed-mcp.json +## Exclusive control with managed-mcp.json When you deploy a `managed-mcp.json` file, Claude Code loads only these MCP servers: @@ -45,11 +37,7 @@ Users can’t add, modify, or use any other MCP servers, including plugin-provided servers and servers passed with the [`--mcp-config` CLI flag](</docs/en/cli-reference#cli-flags>). The file also suppresses the claude.ai connectors Claude Code fetches itself unless you allow them alongside the managed set. -### - -​ - -Deploy managed-mcp.json +### Deploy managed-mcp.json `managed-mcp.json` is a standalone file, so it cannot be delivered through [server-managed settings](</docs/en/server-managed-settings>). To deliver servers through managed settings instead, without exclusive control, use `managedMcpServers`. Any process that can write to a system path with administrator privileges can deploy the file. Across a fleet, that’s usually through device management tooling, such as Jamf or a configuration profile on macOS, Group Policy or Intune on Windows, or your fleet management of choice on Linux. Claude Code looks for the file at one of these paths: @@ -82,11 +70,7 @@ } } -### - -​ - -Authenticate with per-user credentials +### Authenticate with per-user credentials Any user on the machine can read this file, so don’t store API keys or other credentials in `env` blocks. Pass per-user credentials with one of these instead: @@ -94,11 +78,7 @@ * [OAuth or per-user headers](</docs/en/mcp#authenticate-with-remote-mcp-servers>) so each user authenticates as themselves. * [`headersHelper`](</docs/en/mcp#use-dynamic-headers-for-custom-authentication>) to generate credentials at connection time. -### - -​ - -Servers passed with `--mcp-config` or `--strict-mcp-config` +### Servers passed with `--mcp-config` or `--strict-mcp-config` When a session receives servers through `--mcp-config` while a `managed-mcp.json` that Claude Code can read and parse is deployed, what the user sees differs between a workstation and a cloud session: @@ -107,11 +87,7 @@ The `--strict-mcp-config` flag asks to replace the managed set. If a user passes it while such a file is deployed, Claude Code exits at startup on a workstation and in a cloud session alike. -### - -​ - -How allowlists and denylists apply to the managed set +### How allowlists and denylists apply to the managed set The denylist can further filter the servers in `managed-mcp.json`: @@ -120,11 +96,7 @@ The servers in `managed-mcp.json` need no `allowedMcpServers` entry, with one exception: Claude Code checks a server against the allowlist when it uses [`${VAR}` expansion](</docs/en/mcp#environment-variable-expansion-in-mcp-json>) outside `env`. Before v2.1.305, it also checked a server that used `${VAR}` expansion only in `env`, and before v2.1.259, every managed server whenever an allowlist was set. See How a server is evaluated for which fields trigger the `${VAR}` check and the full order of checks. If you used `allowedMcpServers` to keep some of your `managed-mcp.json` servers from loading, add `deniedMcpServers` entries for them, or deploy a separate `managed-mcp.json` per group, before your users upgrade. Unless they use `${VAR}` expansion outside `env`, these servers start loading on each user’s first launch of a version that doesn’t check them, with no prompt or notice. -### - -​ - -Validate the configuration +### Validate the configuration To confirm the file is in effect, run two checks on a managed machine: @@ -133,11 +105,7 @@ * If the file’s servers don’t appear and the `MCP config diagnostics` section marks the enterprise config as failed to parse, Claude Code can’t read or parse the file. Fix the error that section names, then have the user restart Claude Code. 2. `claude mcp add --transport http test https://example.com/mcp` fails with `Cannot add MCP server: enterprise MCP configuration is active and has exclusive control over MCP servers`. The URL doesn’t need to be a real server, since the policy check rejects the command before anything is contacted. -### - -​ - -Disable MCP entirely +### Disable MCP entirely Deploy a `managed-mcp.json` containing an empty server map to block every MCP server except the ones that load under exclusive control: @@ -147,27 +115,15 @@ `claude mcp add` fails with the enterprise-policy error above. Servers users had previously configured stop loading the next time they start a session, with no warning that policy is the reason. Servers you provide through `managedMcpServers`, and anything else you allow alongside the managed set, still load under an empty map, so leave those keys unset to turn MCP off completely. -### - -​ - -Allow claude.ai connectors alongside the managed set +### Allow claude.ai connectors alongside the managed set By default, deploying `managed-mcp.json` suppresses the [claude.ai connectors](</docs/en/mcp#use-mcp-servers-from-claude-ai>) Claude Code fetches itself, including connectors an administrator configured for the organization in the claude.ai admin console. To load those connectors alongside the servers in `managed-mcp.json`, set `"allowAllClaudeAiMcps": true` in a [managed settings source](</docs/en/admin-setup#decide-how-settings-reach-devices>). With the setting enabled, Claude Code loads the same claude.ai connectors it would load if `managed-mcp.json` weren’t deployed. Allowlists and denylists still apply to those connectors, so you can block specific ones with `deniedMcpServers`. The setting affects only the claude.ai connectors Claude Code fetches itself; plugin-provided servers stay suppressed. Cloud sessions and the desktop app’s local and SSH sessions receive connectors another way, described in [How connectors reach Claude Code](</docs/en/mcp#how-connectors-reach-claude-code>). A `managed-mcp.json` on the host that runs a cloud session, such as a [self-hosted runner host](</docs/en/self-hosted-environments-configuration#mcp-servers>), suppresses that session’s connectors whether or not you set `allowAllClaudeAiMcps`. No `managed-mcp.json` reaches the connectors the desktop app delivers to its local and SSH sessions. Claude Code reads `allowAllClaudeAiMcps` only from admin-controlled policy tiers: server-managed settings, an MDM-deployed plist or HKLM registry key, or a system `managed-settings.json` file. Placing it in user or project settings has no effect, so users cannot re-enable connectors that exclusive control suppressed. -### - -​ - -Allow Claude in Chrome alongside the managed set +### Allow Claude in Chrome alongside the managed set By default, when you deploy `managed-mcp.json`, Claude Code blocks the built-in [Claude in Chrome](</docs/en/chrome>) server in terminal sessions. Users don’t get the [extension install prompt](</docs/en/chrome#install-the-extension-when-claude-asks>), and a session where the user [turned on Chrome by default](</docs/en/chrome#enable-chrome-by-default>) starts without it and prints no warning. If a user who could otherwise run Claude in Chrome starts `claude --chrome`, Claude Code exits at startup with an error that names the `allowClaudeInChromeWithManagedMcp` setting. To let users run Claude in Chrome alongside the managed set, set `"allowClaudeInChromeWithManagedMcp": true` in the device’s own managed settings. Put it in an MDM-deployed plist, an HKLM registry key, or a system `managed-settings.json` file, whichever of those Claude Code [selects](</docs/en/managed-settings#precedence-within-the-managed-tier>) on that device. Requires Claude Code v2.1.282 or later. Claude Code reads the setting only from those device sources, even when [server-managed settings](</docs/en/server-managed-settings>) deliver the rest of your policy. A `deniedMcpServers` entry for `claude-in-chrome` still blocks the server with the setting on. -## - -​ - -Provide servers through managed settings +## Provide servers through managed settings To give every user a set of remote MCP servers without taking exclusive control of MCP, list them under `managedMcpServers` in a [managed settings source](</docs/en/admin-setup#decide-how-settings-reach-devices>): server-managed settings, a [Claude apps gateway](</docs/en/claude-apps-gateway-config#what-goes-in-cli>) policy, an MDM profile or registry policy, or `managed-settings.json`. Users keep the servers they add themselves and receive yours in addition. Requires Claude Code v2.1.259 or later. Earlier clients ignore the key. The value is an object keyed by server name. Each entry has the same shape as an HTTP or SSE server in a project [`.mcp.json`](</docs/en/mcp#project-scope>) file, including the optional `headers` and `oauth` members described in [Authenticate with remote MCP servers](</docs/en/mcp#authenticate-with-remote-mcp-servers>). This example provides a search server that each user signs in to with OAuth, and a records server that sends a header your organization issues: @@ -189,11 +145,7 @@ Anyone who can read the managed settings on a machine, including the user, can read a header value you set here. Use a credential issued for that whole audience, or leave `headers` out and let each user sign in with OAuth. -### - -​ - -What an entry can contain +### What an entry can contain Claude Code loads an entry only when it passes every check below. It drops an entry that fails one, records a notice you can read with `/status`, and still loads the other entries: @@ -205,11 +157,7 @@ Claude Desktop has a managed setting with the same name whose value is an array of a different entry shape, so don’t copy one into the other. Claude Code doesn’t accept the array form and records a notice instead of loading it. A Claude apps gateway runs the same checks when it boots; see [MCP servers in a policy](</docs/en/claude-apps-gateway-config#mcp-servers-in-a-policy>). -### - -​ - -How provided servers load +### How provided servers load These rules decide what loads when a provided server overlaps with another server definition or with another setting on this page: @@ -225,11 +173,7 @@ With `managed-mcp.json` deployed, both flags behave as Exclusive control with managed-mcp.json describes. -### - -​ - -What users can see and change +### What users can see and change Users can’t edit or remove a provided server: @@ -239,19 +183,11 @@ `claude mcp get` and `/mcp` show a provided server’s URL as its host only, for example `https://mcp.example.com/…`, and `claude mcp get` shows its header names without their values. -### - -​ - -Where `managedMcpServers` applies +### Where `managedMcpServers` applies Claude Code reads `managedMcpServers` from the managed source it selects under [How Claude Code combines managed sources](</docs/en/managed-settings#how-claude-code-combines-managed-sources>). When that source sets [`managedSourcesBehavior`](</docs/en/settings-reference#managedsourcesbehavior>) to `"merge"`, Claude Code provides the servers from every admin source instead, and when two sources define the same name, the higher-ranked source’s entry applies whole. It never reads the key from the user-writable HKCU registry, from [parent settings an embedding host supplies](</docs/en/managed-settings#parent-settings-from-embedding-hosts>), or from user, project, or local settings files, where it drops the key with a warning. Claude Code doesn’t read the key in the Claude Desktop app’s Code tab on a third-party deployment or in the app’s Cowork sessions, because Claude Desktop supplies and locks those sessions’ MCP servers itself. `/status` and `claude doctor` say so when your managed settings carry the key there. -### - -​ - -When provided servers connect +### When provided servers connect When `managedMcpServers` arrives through server-managed settings, its timing follows [Fetch and caching behavior](</docs/en/server-managed-settings#fetch-and-caching-behavior>): @@ -264,21 +200,13 @@ * **Change a server’s entry** : those sessions reconnect to it with the new definition. * **Remove a server** : a running interactive session disconnects it once it reads the changed settings. A non-interactive (`-p`) run keeps it until it ends. -## - -​ - -Policy-based control with allowlists and denylists +## Policy-based control with allowlists and denylists Allowlists and denylists filter which configured servers are allowed to load. They aren’t a registry: a server still has to be added by a user, a plugin, or your organization before either list applies to it. Servers your organization delivers through `managedMcpServers` load without an allowlist entry, and Servers that skip the allowlist check covers `managed-mcp.json` servers. The denylist applies to every server regardless of where it came from, other than in-process `type: "sdk"` entries. To deploy servers to users, use `managed-mcp.json` or `managedMcpServers`. Both lists also filter servers a user passes with the [`--mcp-config` CLI flag](</docs/en/cli-reference#cli-flags>), other than in-process `type: "sdk"` entries; `--strict-mcp-config` limits which configuration files load and doesn’t bypass either list. To make the allowlist authoritative, set `allowedMcpServers` and `allowManagedMcpServersOnly: true` together in a [managed settings source](</docs/en/admin-setup#decide-how-settings-reach-devices>), such as server-managed settings or a deployed `managed-settings.json` file. The lock applies from every admin-controlled managed source, so a lockdown in a deployed file still applies when server-managed settings that don’t mention MCP are also in use. While the lock is on, the managed allowlist comes from the highest-ranked admin source that sets one. Reading the lock and the allowlist across sources requires Claude Code v2.1.273 or later. Restrict the allowlist to managed settings only shows the configuration. Without `allowManagedMcpServersOnly`, allowlists from every settings scope merge, including a user’s own `~/.claude/settings.json`, so a user can broaden what your allowlist permits. Denylists merge from every scope regardless. `allowManagedMcpServersOnly` is separate from `allowManagedPermissionRulesOnly`, which locks down [permission rules](</docs/en/permissions#managed-settings>) only. Setting that flag does not enforce the MCP allowlist. -### - -​ - -Match servers by URL, command, or name +### Match servers by URL, command, or name `allowedMcpServers` and `deniedMcpServers` are lists of entries. Each entry is an object with a single key that identifies servers by their URL, their command, or their name: @@ -297,11 +225,7 @@ See [Invalid entries in managed settings](</docs/en/managed-settings#invalid-entries-in-managed-settings>) for what happens when an entry fails schema validation. -#### - -​ - -How `serverName` entries match +#### How `serverName` entries match A `serverName` entry matches the user-assigned label exactly, with no wildcards. @@ -314,22 +238,14 @@ To turn off all the claude.ai connectors Claude Code fetches itself, see [`disableClaudeAiConnectors`](</docs/en/mcp#disable-claude-ai-connectors>). -#### - -​ - -How `serverCommand` entries match +#### How `serverCommand` entries match A `serverCommand` entry holds the command and its arguments as one array, as in `{ "serverCommand": ["npx", "-y", "server"] }`. Claude Code compares that array with the command and arguments in the server’s configuration: * **Commands match exactly.** Every argument, in order. `["npx", "-y", "server"]` does not match `["npx", "server"]` or `["npx", "-y", "server", "--flag"]`. * **The`env` block isn’t compared.** `["node", "server.js"]` matches a server that runs that command with any `env` values. Some environment variables change what `node` loads at startup. To set the `env` values yourself, define the server in `managed-mcp.json`. -#### - -​ - -How `serverUrl` entries match +#### How `serverUrl` entries match URLs support `*` wildcards, including `*` as the whole scheme. Hostname matching is case-insensitive and ignores a trailing FQDN dot, so `https://Mcp.Example.com/*` matches `https://mcp.example.com/api`. Paths stay case-sensitive. If you give no port, how you write the hostname decides whether the pattern matches only the scheme’s default port or every port: @@ -354,11 +270,7 @@ * `https://staging.example.com:*/*`: blocks `https` servers on that host on every port * `*://staging.example.com:*/*`: blocks that host over any scheme and on any port -#### - -​ - -Environment variables in `serverCommand` and `serverUrl` entries +#### Environment variables in `serverCommand` and `serverUrl` entries `serverCommand` and `serverUrl` values expand before matching. Both the policy entry and the server’s configured value go through [`${VAR}` and `${VAR:-default}` expansion](</docs/en/mcp#environment-variable-expansion-in-mcp-json>), so an entry written as `["${HOME}/bin/server"]` matches a server config that uses either the same reference or the expanded path. `serverName` values match literally and never expand. The two sides read different environments: @@ -374,11 +286,7 @@ The pinned environment and the rules in this table require Claude Code v2.1.219 or later. -### - -​ - -How a server is evaluated +### How a server is evaluated Before loading a server, including one from `managed-mcp.json`, Claude Code runs the three checks below in order. It runs them again when a user reconnects a server or turns a disabled one back on in `/mcp`. In-process `type: "sdk"` servers, which the [app that started the session registers](</docs/en/mcp#how-connectors-reach-claude-code>), skip all three. @@ -391,11 +299,7 @@ Remote (HTTP or SSE)| A `serverUrl` entry. A `serverName` match counts only when the allowlist contains no `serverUrl` entries Stdio| A `serverCommand` entry. A `serverName` match counts only when the allowlist contains no `serverCommand` entries -#### - -​ - -Servers that skip the allowlist check +#### Servers that skip the allowlist check Three groups of servers skip the allowlist check, in addition to the in-process `type: "sdk"` servers that skip all three checks: @@ -405,11 +309,7 @@ A `managed-mcp.json` server that uses `${VAR}` expansion in its command, arguments, URL, or headers is still checked. Claude Code also checks every server a user, a plugin, or claude.ai adds, and every server a user passes with `--mcp-config`. For the versions that changed which `managed-mcp.json` servers are checked, and how to keep one from loading, see How allowlists and denylists apply to the managed set. -### - -​ - -Example configuration +### Example configuration The configuration below sets up a hard allowlist with a denylist. The highlighted lines change how the rest of the list is evaluated, and the callouts after the block explain each one: @@ -516,11 +416,7 @@ HTTP server at `https://staging.example.com:8443/api`| Allowed: matches allowlist URL pattern, no denylist match on this port HTTP server at `https://other.com/mcp`| Blocked: doesn’t match the allowlist -### - -​ - -Restrict the allowlist to managed settings only +### Restrict the allowlist to managed settings only To make the managed allowlist the only one that applies, set `allowManagedMcpServersOnly` in the managed settings file: @@ -534,11 +430,7 @@ When `allowManagedMcpServersOnly` is `true`, allowlists from user, project, and local settings are ignored. The denylist still merges from every settings scope, so users can always block servers for themselves. -## - -​ - -How restrictions appear to users +## How restrictions appear to users For what users see at startup when `managed-mcp.json` is deployed and the session also has `--mcp-config` servers, see Exclusive control with managed-mcp.json. Use this table to recognize the other reports and to tell users what to expect before you roll out a change: @@ -555,19 +447,11 @@ When a server silently disappears, the user gets no signal that policy is the reason, so tell affected users which servers are blocked when you roll out a new restriction. -## - -​ - -Monitor MCP usage +## Monitor MCP usage When you configure [OpenTelemetry export](</docs/en/monitoring-usage>), Claude Code can record which MCP servers and tools users invoke. Set `OTEL_LOG_TOOL_DETAILS=1` to include MCP server and tool names in tool events and on the [cost and token counters](</docs/en/monitoring-usage#cost-counter>), then aggregate them in your collector to see which servers your users actually connect to. See [Monitoring](</docs/en/monitoring-usage>) to set up the exporter and for the full event schema. -## - -​ - -Configuration summary +## Configuration summary Every file and setting this page covers, what it controls, and how to deliver it: @@ -581,11 +465,7 @@ `allowClaudeInChromeWithManagedMcp`| Lets the built-in Claude in Chrome server run alongside `managed-mcp.json`| Managed settings on the device only: an MDM profile, the HKLM registry, or `managed-settings.json`. Server-managed settings and user-writable sources have no effect| MDM, GPO, fleet management, or any process with administrator privileges `allowAllClaudeAiMcps`| Loads the claude.ai connectors Claude Code fetches itself alongside `managed-mcp.json`. A `managed-mcp.json` on the host that runs a cloud session still suppresses that session’s connectors| Managed settings sources only; the setting has no effect elsewhere| Same as `allowedMcpServers` -## - -​ - -Related resources +## Related resources * [Decide what to enforce](</docs/en/admin-setup#decide-what-to-enforce>): MCP restrictions alongside permission rules, sandboxing, and the other admin controls * [Connect Claude Code to tools via MCP](</docs/en/mcp>): the full MCP reference, including transports, scopes, and authentication
modified Deploy managed settings View current →
Show diff (282 lines)
--- a/managed-settings.md +++ b/managed-settings.md @@ -1,10 +1,6 @@ Managed settings are the settings your organization deploys to every developer’s machine. Claude Code applies them above every other level, so no user, project, local, or `--settings` value overrides them, apart from a few [security-sensitive exceptions](</docs/en/settings#exceptions-to-managed-settings-precedence>) where a stricter value from a lower level still counts. This page is for the administrator who deploys managed settings or debugs why one isn’t applying. To decide what to enforce, start with the [Decide what to enforce](</docs/en/admin-setup#decide-what-to-enforce>) table. For the claude.ai console path, see [Server-managed settings](</docs/en/server-managed-settings>). For which file a developer’s own values go in, see [Settings](</docs/en/settings>). -## - -​ - -Deploy a managed settings file +## Deploy a managed settings file This is the quickest way to put a policy on each machine: a `managed-settings.json` file. If you haven’t picked how to deliver managed settings yet, or your devices are under MDM or developers run cloud sessions, read Choose a delivery mechanism first. @@ -45,11 +41,7 @@ On one machine, run `/status` inside Claude Code. The `Setting sources` line shows `Enterprise managed settings (file)`. Roll out to the rest of the fleet after that; Check that a policy is in force covers what to look at when the line is missing. -## - -​ - -Choose a delivery mechanism +## Choose a delivery mechanism The file in the steps above is one of four ways to get managed settings onto a machine. Every mechanism carries the same policy keys as a `settings.json` file, so the [settings reference](</docs/en/settings-reference>) applies to all of them. A few keys are tied to particular sources, and each entry’s Scope line says which: @@ -67,11 +59,7 @@ 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>). -### - -​ - -Where and when a policy applies +### Where and when a policy applies A deployed policy reaches the developer’s sessions as follows: @@ -89,11 +77,7 @@ * **Changes that need approval** : apart from the [updates that wait for the next launch](</docs/en/server-managed-settings#fetch-and-caching-behavior>), a server-managed change to a setting that [needs approval](</docs/en/server-managed-settings#security-approval-dialogs>), such as a hook or an `env` variable, waits for the developer to accept the dialog in an interactive session, and applies for the current run in a session an IDE extension or the Agent SDK hosts. Other server-managed changes apply on the next poll. * **Long-lived sessions** : a session left open for weeks can still lag a rollout. [`requiredMinimumVersion`](</docs/en/settings-reference#requiredminimumversion>) blocks an outdated binary from starting and doesn’t end a session that’s already running. -### - -​ - -Where each mechanism stores the policy +### Where each mechanism stores the policy The keys are the same everywhere, but each mechanism stores them in a different place and shape: @@ -103,11 +87,7 @@ * **File-based** : `managed-settings.json`, an optional `managed-settings.d/` directory, and `managed-mcp.json` in the system directory: `/Library/Application Support/ClaudeCode/` on macOS, `/etc/claude-code/` on Linux and WSL, and `C:\Program Files\ClaudeCode\` on Windows. Claude Code doesn’t read the legacy Windows path `C:\ProgramData\ClaudeCode\managed-settings.json`. You can deploy any of these files as a symbolic link, and Claude Code reads the file the link leads to. The policy still applies when the link leads outside the system directory or Claude Code can’t confirm that it stays inside. A warning naming the file then appears in `/status` and `claude doctor`. To clear the warning, point the link at a target inside the system directory. * **Windows HKCU registry** : the same `Settings` value under `HKCU\SOFTWARE\Policies\ClaudeCode`. -### - -​ - -Split a file-based policy across teams +### Split a file-based policy across teams If several teams own parts of one policy, put each part in its own file in `managed-settings.d/`, next to `managed-settings.json` in the same system directory, instead of editing one shared file. Claude Code merges `managed-settings.json` first, then every `*.json` file in the directory in alphabetical order. Name the files with numeric prefixes to control the order, such as `10-telemetry.json` and `20-security.json`. Claude Code ignores hidden files and files that don’t end in `.json`. When two files set the same key, Claude Code combines them by these rules: @@ -118,11 +98,7 @@ * **[`extraKnownMarketplaces`](</docs/en/settings-reference#extraknownmarketplaces>) and [`managedMcpServers`](</docs/en/settings-reference#managedmcpservers>)**: a later entry with the same name replaces the earlier one whole * **[`modelPicker`](</docs/en/settings-reference#modelpicker>)** : the later lineup replaces the earlier one whole -## - -​ - -How Claude Code combines managed sources +## How Claude Code combines managed sources When your organization delivers more than one managed source to the same machine, the [`managedSourcesBehavior`](</docs/en/settings-reference#managedsourcesbehavior>) key decides what Claude Code does with the others: @@ -143,11 +119,7 @@ This diagram shows the ranking, with examples of the cross-source keys Claude Code reads from the first three sources under either setting: -### - -​ - -When an admin document counts as present +### When an admin document counts as present In the ranking of managed sources, Claude Code never applies the user-writable HKCU registry beneath an admin document that is present. A document is present when: @@ -156,11 +128,7 @@ On WSL, `/etc/claude-code` is user-writable as well, and the [`wslInheritsWindowsSettings`](</docs/en/settings-reference#wslinheritswindowssettings>) entry says when the Windows documents stand above it. -### - -​ - -Keys read from every admin source +### Keys read from every admin source Under the default `"first-wins"` setting, Claude Code reads most keys only from the source it selected, and ignores a value in a lower-ranked source even when the selected source leaves that key unset. A few keys work differently. Claude Code reads them from every admin source, so a lower-ranked MDM policy or managed settings file can still set them when the selected source doesn’t. Claude Code leaves the user-writable HKCU registry out of that scan; when HKCU is the only source and no host supplies parent settings, HKCU applies like any selected source. The cross-source keys include: @@ -182,22 +150,14 @@ [`allowedProviders`](</docs/en/settings-reference#allowedproviders>) has its own rule: its entry’s Scope note says how a list set on the machine combines with a server-managed one. Requires Claude Code v2.1.285 or later. When an admin source sets `allowManagedMcpServersOnly` or an `allowedMcpServers` list and that value isn’t the one in force, `/status` and `claude doctor` name that source and key. -#### - -​ - -Which managed source supplies login keys +#### Which managed source supplies login keys On a machine with an MDM policy or managed settings file, Claude Code takes the login keys from that policy or file, even for a key remote settings also set. Settings from the claude.ai admin console are remote settings, so set login keys such as [`forceLoginOrgUUID`](</docs/en/settings-reference#forceloginorguuid>) in the MDM policy or file. If a machine has both an MDM policy and a managed settings file, use the MDM policy. When that policy sets any policy key, Claude Code ignores login keys in the file, even under `managedSourcesBehavior: "merge"`. The login keys are: * `forceLoginOrgUUID` and `forceLoginMethod` set to `"claudeai"` or `"console"`: if the policy or file omits either key, the value in remote settings applies. Until every client runs v2.1.299 or later, set the keys in [server-managed settings](</docs/en/server-managed-settings>) from claude.ai as well * The gateway login keys: Claude Code doesn’t use a value in remote settings for the gateway sign-in -### - -​ - -Compose every managed source +### Compose every managed source To have Claude Code apply every admin source your organization delivers, set [`managedSourcesBehavior`](</docs/en/settings-reference#managedsourcesbehavior>) to `"merge"` in the highest-ranked source you deploy. Claude Code reads the key only from the highest-ranked source that carries either the key or a policy key, so a lower source can’t opt itself into merging with the source above it, and a machine that never receives server-managed settings needs the key in its MDM profile too. The user-writable HKCU registry never merges with another source. Requires Claude Code v2.1.242 or later. Under `"merge"`, Claude Code adds a lower source’s list entries, such as `permissions.allow` rules and hooks, to the policy, so turn it on only when every source ranked below your highest one is under an administrator’s control. This table shows how Claude Code combines each kind of key under `"merge"`. The [`managedSourcesBehavior` entry](</docs/en/settings-reference#managedsourcesbehavior>) names every key in three of the rows: restriction allowlists, values taken whole, and keys read from the highest-ranked source only. @@ -215,11 +175,7 @@ To confirm which sources combined on a machine, read the `Setting sources` line in `/status`; that section says what each label means. -### - -​ - -Compute the policy with a helper program +### Compute the policy with a helper program A [`policyHelper`](</docs/en/settings-reference#policyhelper>) is an executable your MDM policy or managed settings file names, and Claude Code runs it to compute managed settings at startup. When the selected source configures one and the helper emits a `managedSettings` object, that output changes what Claude Code reads: @@ -227,11 +183,7 @@ For which helper runs fail, and what Claude Code does when one does, see [Helper failures](</docs/en/settings-reference#helper-failures>). -### - -​ - -Let an embedding host add policy +### Let an embedding host add policy When another application launches Claude Code, such as Claude Desktop, an IDE extension, or an Agent SDK app, that host can pass its own managed settings through the SDK `managedSettings` option. Claude Code calls these parent settings. By default, Claude Code ignores parent settings whenever an admin source is present: server-managed settings, an MDM or OS-level policy, or a managed settings file. To have Claude Code merge parent settings alongside an admin source, set [`parentSettingsBehavior`](</docs/en/settings-reference#parentsettingsbehavior>) to `"merge"` in the highest-priority managed source; Claude Code reads the key from that source only. Claude Code then keeps only the host’s values that restrict what Claude can do, with one gap to know about: unless you also set the `allowManaged*Only` locks, the host’s permission allow rules and sandbox allowlists still apply. See [Restrict parent settings](</docs/en/claude-apps-gateway#restrict-parent-settings>) for the locks. A [`policyHelper`](</docs/en/settings-reference#policyhelper>) can turn parent merging off regardless of this key; its entry says when. Claude Code also applies these checks to parent-supplied values on their own: @@ -242,11 +194,7 @@ * For `allowedProviders`, a list in the selected managed source blocks a parent-supplied one, and under the [`managedSourcesBehavior`](</docs/en/settings-reference#managedsourcesbehavior>) `"merge"` opt-in a list in any admin source does. Requires Claude Code v2.1.285 or later * A parent-supplied `blockedMarketplaces` applies in addition to any blocklist that a managed source sets. Requires Claude Code v2.1.282 or later -#### - -​ - -Keep Cowork folder access when only managed rules apply +#### Keep Cowork folder access when only managed rules apply [Cowork](<https://claude.com/docs/cowork/overview>) in the Claude Desktop app runs its sessions on Claude Code and grants each session access to its working folders, such as the folder the user connects, through allow rules it supplies when it launches the session. When your managed policy sets [`allowManagedPermissionRulesOnly`](</docs/en/settings-reference#allowmanagedpermissionrulesonly>), Claude Code keeps only the allow rules in the managed policy: it drops allow rules a host supplies as parent settings, as `--allowedTools`, or in a settings file, so writes to those folders lose their pre-approval. In a Cowork session that asks before edits, Cowork can’t show the prompt, and Claude reports each write as blocked because the path resolves to a protected location or a path outside the connected folder. To restore the writes, add allow rules for those folders to the managed source Claude Code selects on those machines: on an MDM-managed fleet, that’s the MDM policy rather than a separate managed settings file. This example uses the file form, and an MDM policy takes the same keys. It keeps `allowManagedPermissionRulesOnly` set and allows edits under a `CoworkProjects` folder in each user’s home directory; replace the path with the folders your users connect: @@ -263,11 +211,7 @@ After you deploy the policy, Claude can save files under that folder in a new Cowork session. [Read and Edit rules](</docs/en/permissions#read-and-edit>) cover the path syntax, including the `//` form for absolute paths. -### - -​ - -What a developer can change +### What a developer can change A developer’s own settings files, `--settings` values, and project files never override a managed value; the [exceptions](</docs/en/settings#exceptions-to-managed-settings-precedence>) only let a stricter lower-level value count. These cases sit outside that rule: @@ -277,19 +221,11 @@ * **The server-managed cache** : server-managed settings come from Anthropic’s servers, and an edit to the local cache [lasts only until the next successful fetch](</docs/en/server-managed-settings#security-considerations>). * **Other tools** : managed settings bind Claude Code only. A developer who calls the API from another tool isn’t under them. -## - -​ - -Check that a policy is in force +## Check that a policy is in force A developer reports that a policy isn’t applying, or you want to confirm a rollout landed before pushing it to the fleet. Two commands on that machine answer it: `/status` shows which managed source Claude Code selected, and `claude doctor` lists what it dropped. -### - -​ - -Read the source in /status +### Read the source in /status On the developer’s machine, run `/status` inside Claude Code and read the `Setting sources` line. When a managed source is in effect, the line lists `Enterprise managed settings` with the source Claude Code selected in parentheses: @@ -306,11 +242,7 @@ * **The line is missing** : Claude Code found no managed source that delivers a policy key. If you deployed a managed settings file, check that it sits at the path for the OS and that it contains a policy key rather than only the control keys. A file that isn’t valid JSON doesn’t produce this state; Claude Code refuses to start instead. When you deployed through server-managed settings instead, run `claude doctor`, which reports the [fetch outcome](</docs/en/server-managed-settings#verify-settings-delivery>). * **The line names a source other than the one you deployed** : a higher-priority source is present and Claude Code ignored yours, and `Skipped sources` lists it. How Claude Code combines managed sources gives the order. -### - -​ - -Find entries Claude Code dropped +### Find entries Claude Code dropped If your managed settings file, MDM profile, registry value, or server-managed payload fails schema validation, Claude Code first skips each individual entry it can repair, such as one invalid permission rule, and warns about each one. Claude Code then drops any value that still fails, unless the value belongs to one of the keys that fail closed instead. Claude Code is stricter with the `managedSettings` a [`policyHelper`](</docs/en/settings-reference#policyhelper>) emits: it makes the same entry repairs, but any schema violation that survives fails the whole helper run, and at startup Claude Code refuses to start, the same as for a helper that exits non-zero. When a managed settings file, drop-in file, MDM plist, or HKLM registry value is present but can’t be parsed as a JSON object, Claude Code refuses to start and prints [an error naming the source](</docs/en/errors#managed-settings-document-could-not-be-parsed>), even when another admin source delivers a valid policy. Each source fails this way when: @@ -335,11 +267,7 @@ * Non-interactive runs with `-p` print a summary to stderr. * [`claude doctor`](</docs/en/debug-your-config>) lists each invalid entry with its source and field. -#### - -​ - -Keys that fail closed +#### Keys that fail closed When a managed source sets a top-level key that has a single restrictive value, such as `allowManagedPermissionRulesOnly`, `disableAutoMode`, or `skipDangerousModePermissionPrompt`, to something Claude Code can’t read, the key reads as that value until you fix it. The report says the key `was present but invalid` and names the value Claude Code treats it as. For a key inside `sandbox`, see Invalid values inside `sandbox`. These cases don’t fail closed: @@ -379,11 +307,7 @@ `allowedHttpHookUrls` and `httpHookAllowedEnvVars` merge across settings files, so entries in your user, project, or local settings still apply while the managed list is empty. The fallbacks for those two keys and for `allowedChannelPlugins` require Claude Code v2.1.267 or later; earlier versions drop the whole key when its value or any entry is invalid. The `strictKnownMarketplaces` and `blockedMarketplaces` fallbacks require Claude Code v2.1.277 or later; earlier versions drop the whole key when its value or any entry is invalid. The `strictPluginOnlyCustomization` and `enabledPlugins` fallbacks require Claude Code v2.1.282 or later. `requiredMinimumVersion` and `requiredMaximumVersion` fail open by design: an invalid value is dropped rather than enforced. This tolerance applies only to managed settings. User, project, and local settings files remain strict: a file whose JSON or top-level shape fails validation is rejected as a whole and reported, and an individual entry that fails, such as a malformed permission rule, is skipped with a warning while the rest of the file applies. -#### - -​ - -Invalid values inside `sandbox` +#### Invalid values inside `sandbox` When one value in your managed `sandbox` block is invalid, Claude Code doesn’t drop the whole block, because it validates each field on its own. This per-field handling requires Claude Code v2.1.283 or later. On versions before v2.1.283, Claude Code drops every `sandbox` field except [`credentials`](</docs/en/settings-reference#invalid-credential-entries-in-managed-settings>) when a value outside `credentials` is invalid. The warning you get for an invalid field names the field and tells you what happens to it. What happens depends on what the field controls: @@ -394,11 +318,7 @@ * While `network.deniedDomains` or any entry in it is invalid, Claude Code also withholds `network.allowedDomains`, so the managed allowlist grants nothing until you fix the deny list. * While `filesystem.denyRead`, `filesystem.denyWrite`, or any entry in either is invalid, Claude Code also withholds both `filesystem.allowRead` and `filesystem.allowWrite` until you fix the deny list. -## - -​ - -Keys only a managed source can set +## Keys only a managed source can set Claude Code reads the following keys only from a managed source; placing them in user or project settings files has no effect. Most of them are locks: the value a lock governs, such as permission rules or `sandbox.network.allowedDomains`, is an ordinary key that any level can set, and the lock tells Claude Code to honor only the managed value. The table covers the permission, plugin, and delivery controls. For any key not listed here, the Scope column of the [settings reference](</docs/en/settings-reference#all-settings>) index says whether it’s managed-only. @@ -428,11 +348,7 @@ On Team and Enterprise plans, an Owner enables or disables [Remote Control](</docs/en/remote-control>) and [cloud sessions](</docs/en/claude-code-on-the-web>) organization-wide in [Claude Code admin settings](<https://claude.ai/admin-settings/claude-code>). When an Owner turns Remote Control off, already-connected sessions that run Claude Code v2.1.286 or later disconnect too. Each one disconnects the next time it refreshes your organization’s policy, about once an hour. For what happens in those sessions, see [`Remote Control was turned off by your organization's policy`](</docs/en/remote-control#remote-control-was-turned-off-by-your-organizations-policy>).Remote Control can additionally be disabled per device with the [`disableRemoteControl`](</docs/en/settings-reference#disableremotecontrol>) setting. Cloud sessions have no per-device managed settings key.To check whether these organization settings reached a given machine, run `claude doctor` there and read the `Organization policy` line, which says where Claude Code loaded the policy from or why it didn’t load. Requires Claude Code v2.1.261 or later. In a running session, `/status` shows the same line when the policy didn’t load. -## - -​ - -Turn telemetry off for your organization +## Turn telemetry off for your organization Claude Code sends Anthropic operational [telemetry](</docs/en/data-usage#telemetry-services>) by default on sessions that use the Anthropic API, whether directly, through an LLM gateway, or through a custom `ANTHROPIC_BASE_URL`; [Default behaviors by API provider](</docs/en/data-usage#default-behaviors-by-api-provider>) says which providers send it. To turn it off for every developer without relying on each person’s shell, deliver `DISABLE_TELEMETRY` through the `env` block of your managed settings. This example sets `DISABLE_TELEMETRY` for everyone the policy reaches: @@ -444,11 +360,7 @@ Claude Code applies a value of `1` without showing the user the [approval dialog](</docs/en/server-managed-settings#environment-variables-and-the-approval-dialog>). If you turn telemetry off, Claude Code stops sending the usage data that feeds your organization’s [analytics dashboard](</docs/en/analytics>) for the developers the policy reaches. The variable also turns off [feature-flag fetching](</docs/en/env-vars#features-that-need-feature-flag-fetching>) for those developers. For Remote Control, see the [Remote Control requirements](</docs/en/remote-control#requirements>). Where and when a policy applies says which delivery mechanism reaches each surface, and [Platform availability](</docs/en/server-managed-settings#platform-availability>) says which sessions skip the server-managed settings fetch. If your organization uses customer-managed encryption keys and routes Claude Code through a gateway, [Configure proxies and gateways](</docs/en/third-party-integrations#configure-proxies-and-gateways>) says why those sessions need this variable. -## - -​ - -See also +## See also * [Set up Claude Code for your organization](</docs/en/admin-setup>): decide what to enforce and how * [Server-managed settings](</docs/en/server-managed-settings>): deliver policy from the claude.ai console or a gateway
modified Plugin manifest reference View current →
Show diff (459 lines)
--- a/manifest-reference.md +++ b/manifest-reference.md @@ -13,11 +13,7 @@ * Where each component’s files go: Standard layout * A message from `claude plugin validate`: the [troubleshooting page](</docs/en/plugins/troubleshooting>) lists each message with its fix and links to the relevant sections on this page -## - -​ - -Manifest file +## Manifest file The manifest is optional. Without it, Claude Code loads the components it finds in the standard layout. The plugin name then comes from the marketplace entry, or from the directory name when you load the plugin with `--plugin-dir`. Write a manifest when you want metadata, a component outside its default directory, `userConfig`, or an inline component definition. Save the manifest at `.claude-plugin/plugin.json` under the plugin root. Put every other plugin file at the plugin root, not inside `.claude-plugin/`. That includes `skills/`, `commands/`, and `hooks/`. The following example sets most of the keys in the Fields table. It passes validation in a plugin directory that contains each referenced path. @@ -73,22 +69,14 @@ } } -### - -​ - -Unrecognized fields +### Unrecognized fields An unrecognized top-level key is stripped, and an unrecognized key inside a `userConfig` option, `channels` entry, `lspServers` config, or `monitors` entry is rejected: * **Top-level fields** : the field is stripped and the plugin loads. `claude plugin validate` reports each unrecognized top-level field as a warning * **Strict objects** : `userConfig` options, `channels` entries, `lspServers` configs, and `monitors` entries are strict. An unknown key inside one is an error, and the plugin doesn’t load -### - -​ - -Validate the manifest +### Validate the manifest `claude plugin validate` is the authoritative check for a manifest. Run it from your shell against the plugin directory: @@ -105,13 +93,9 @@ * **Errors** : an entry Claude Code would drop when it loads the plugin, a `${user_config.KEY}` reference to an option the manifest doesn’t declare, and a remote `url` that isn’t a valid absolute URL * **Warnings** : an `http://` or `ws://` URL to a non-loopback host, and a header value that looks like a literal credential -## - -​ - -Fields - -The table lists the top-level keys in `plugin.json`. `name` is the only required key. Where a field name is a link, the linked section has its full rules. For component keys such as `commands` and `hooks`, Component path forms shows each accepted shape with an example, and every path follows the path rules for the `./` prefix, extensions, and containment. +## Fields + +The table lists top-level keys in `plugin.json`. `name` is the only required key. Where a field name is a link, the linked section has its full rules. For component keys such as `commands` and `hooks`, Component path forms shows each accepted shape with an example, and every path follows the path rules for the `./` prefix, extensions, and containment. Field| Type| Description ---|---|--- @@ -133,7 +117,6 @@ `termsOfServiceUrl`| String| Terms of service link for the plugin’s listing in Anthropic’s directory. Claude Code doesn’t read it `defaultEnabled`| Boolean| Whether the plugin starts enabled when the user hasn’t set it. Defaults to `true` `dependencies`| Array of strings or objects| Plugins that must be enabled for this one to work -`settings`| Object| Settings Claude Code applies while the plugin is enabled. Only `agent` and `subagentStatusLine` take effect `userConfig`| Object| Values Claude Code prompts the user for when the plugin is enabled `types`| Path| A `.d.ts` file that declares the `$.state` values and `$` nouns of a [mod](</docs/en/plugins/mods/reference#files>) `channels`| Array of objects| Message channels the plugin provides, each bound to one of its MCP servers @@ -152,11 +135,7 @@ In the Type column, a path is a string relative to the plugin root, such as `"./custom/commands"`. -### - -​ - -`name` +### `name` The plugin identifier. It must be non-empty, with no spaces, `@`, `:`, path separators, control characters, or bidirectional-formatting characters; use kebab-case. Claude Code namespaces every component under it, so an agent `reviewer` in plugin `deploy-tools` appears as `deploy-tools:reviewer`. `claude plugin validate` also checks that the name doesn’t pass as one of Anthropic’s own plugins. The check ignores case and treats any run of separators as one: @@ -169,77 +148,37 @@ 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. -### - -​ - -`displayName` +### `displayName` The name shown in UI in place of `name`. It may contain spaces and any casing, and it isn’t used for namespacing or lookup. For a marketplace-installed plugin, a `displayName` on the [marketplace entry](</docs/en/plugins/marketplace-reference#plugin-entries>) takes precedence over this value. -### - -​ - -`version` +### `version` A version string, not checked against semver. Setting it pins the plugin to that version until you change it; see [Versions and updates](</docs/en/plugins/loading#versions-and-updates>). A plugin with a [`command` source](</docs/en/plugins/marketplace-reference>), a plugin from a [marketplace hosted on claude.ai](</docs/en/plugins/install#add-from-claude-ai>), and a plugin [loaded in place](</docs/en/plugins/loading#find-plugins-on-disk>) from a marketplace added from a local path aren’t pinned by this field. -### - -​ - -`metadata` +### `metadata` A free-form object for your own data, such as catalog or entitlement fields. Claude Code doesn’t read it. -### - -​ - -Directory listing fields +### Directory listing fields Anthropic’s directory reads the `icon`, `documentationUrl`, `supportUrl`, `privacyPolicyUrl`, and `termsOfServiceUrl` fields from `plugin.json` for your plugin’s listing when you [submit the plugin](</docs/en/plugins/publish#submit-to-anthropics-directory>). Claude Code ignores them at load time. Set them only in `plugin.json`. In a marketplace entry, `claude plugin validate` reports each one as an unknown field. Set `icon` to the path of an image file inside the plugin, such as `./logo.png`, and each of the four URL fields to an `https://` URL. `claude plugin validate` doesn’t report these fields in `plugin.json` as unknown on Claude Code v2.1.281 or later. Earlier versions print an `Unknown field` warning for each one, so a `--strict` run fails on those versions. -### - -​ - -`defaultEnabled` +### `defaultEnabled` Whether the plugin starts enabled when the user hasn’t set it in [`enabledPlugins`](</docs/en/settings-reference#enabledplugins>). Defaults to `true`. A plugin that an enabled plugin depends on starts enabled regardless. The same field in the marketplace entry overrides this one. Once a user’s `enabledPlugins` entry is written, it persists across plugin updates, so changing `defaultEnabled` in a later release doesn’t change the setting for an existing user. -### - -​ - -`dependencies` +### `dependencies` Plugins that must be enabled for this one to work. Each entry is `"name"`, `"name@marketplace"`, or `{ "name": "...", "marketplace": "...", "version": "..." }`. Bare names resolve against this plugin’s own marketplace. See [dependency constraints](</docs/en/plugins/dependencies>). -### - -​ - -`settings` - -Settings Claude Code applies while the plugin is enabled. Only `agent` and `subagentStatusLine` take effect; other keys are dropped at load. A `settings.json` at the plugin root takes precedence over this key. See [Default settings](</docs/en/plugins/components#default-settings>). - -## - -​ - -Component path forms +## Component path forms Every component key accepts a path relative to the plugin root. `hooks`, `mcpServers`, `lspServers`, and `experimental.monitors` also accept inline configuration, `commands` also accepts an object map, and `mcpServers` also accepts MCP bundle paths and URLs. The examples that follow show each accepted shape once. For what each component does at runtime, see [Plugin components](</docs/en/plugins/components>). -### - -​ - -Path-only fields +### Path-only fields `agents`, `skills`, `outputStyles`, `workflows`, and `experimental.themes` take one path or an array of paths. `agents` entries must be `.md` files, and `skills` entries must be directories. The other three accept a directory or a file. @@ -249,11 +188,7 @@ "outputStyles": "./styles/" } -### - -​ - -`commands` +### `commands` `commands` takes a path, an array of paths, or an object map. A path names a flat `.md` command file or a directory. In the object map, each key becomes the command name after the plugin prefix. For example, `"about"` in plugin `deploy-tools` runs as `/deploy-tools:about`. Each value sets exactly one of `source` or `content`, and an entry that sets both or neither fails validation. The other fields in this table are optional: @@ -275,11 +210,7 @@ } } -### - -​ - -`hooks` +### `hooks` `hooks` takes a `.json` file path, an inline hooks object in the same shape as [`hooks` in `settings.json`](</docs/en/hooks#configuration>), or an array mixing both. For hook events and handler fields, see the [hooks reference](</docs/en/hooks#hook-events>). A hooks file wraps the event map in a top-level `"hooks"` key, the shape [`hooks/hooks.json`](</docs/en/plugins/components#hooks>) uses. A file that contains only the event map, without that wrapper, fails to load. An inline object is the event map itself, with no wrapper. Claude Code merges whatever you declare with `hooks/hooks.json` when that file exists. This array loads one hooks file and declares one inline `PostToolUse` hook: @@ -316,11 +247,7 @@ } } -### - -​ - -`mcpServers` +### `mcpServers` `mcpServers` takes a `.json` file path, an MCP bundle path or URL, an inline map, or an array mixing them. For server config fields, see [plugin-provided MCP servers](</docs/en/mcp#plugin-provided-mcp-servers>). Claude Code loads `.mcp.json` at the plugin root first, then each declared shape in order. A server name declared later replaces an earlier one. An `mcpServers` value takes one of these shapes: @@ -333,11 +260,7 @@ A bundle path or URL must end in `.mcpb` or `.dxt`. Any other extension fails validation. -### - -​ - -`lspServers` +### `lspServers` `lspServers` takes a `.json` file path, an inline map of server name to config, or an array of either. Claude Code loads `.lsp.json` at the plugin root first, then each declared config in order. A server name declared later replaces an earlier one. Each server config is a strict object with these fields. An unknown key fails validation. @@ -372,11 +295,7 @@ For the language servers Anthropic publishes as plugins and how the servers behave at runtime, see [Code intelligence](</docs/en/plugins/code-intelligence>). -### - -​ - -`monitors` +### `monitors` `experimental.monitors` takes a `.json` file path or the inline array. When you omit the key, Claude Code loads `monitors/monitors.json` if it exists. Each entry is a strict object with these fields. @@ -404,11 +323,7 @@ A monitor `command` can’t reference `${user_config.*}`. See Fields that run through a shell. -## - -​ - -Path rules +## Path rules Every component path in a manifest is relative to the plugin root and must start with `./`. A path such as `commands/foo.md` fails validation. `skills` and `mcpServers` each accept one form outside that rule: @@ -417,11 +332,7 @@ `experimental.evals` isn’t a component path, so the rules in this section don’t cover it, and `claude plugin eval` checks the value when it runs instead. It names a directory below the plugin root, such as `"quality/evals"`, with or without the `./` prefix. With an array, only the first entry is used. For what the value accepts and what happens with an unusable one, see [Use a different eval directory](</docs/en/plugin-evals#use-a-different-eval-directory>). -### - -​ - -Containment and existence +### Containment and existence Every component path must resolve inside the plugin root and must exist. `claude plugin validate` checks the paths under every component key: @@ -430,11 +341,7 @@ For `outputStyles`, `lspServers`, `monitors`, and `themes` paths, the `claude plugin validate` check requires Claude Code v2.1.283 or later. -### - -​ - -How each key combines with its default location +### How each key combines with its default location Each component key either replaces its default location, adds to it, or merges with it: @@ -444,11 +351,7 @@ If a plugin has a default folder such as `commands/` and also sets the manifest key that replaces it, Claude Code loads the manifest paths and not the folder. `claude plugin list` and the `/plugin` interface then show the warning `Default <folder>/ folder is ignored because the manifest sets "<key>"`. To avoid the warning, set the key to a path inside that folder: `"commands": ["./commands/deploy.md"]` names a file in the default folder and produces no warning. -## - -​ - -User configuration +## User configuration `userConfig` declares values Claude Code prompts the user for when the plugin is enabled, so users don’t edit `settings.json` themselves. Keys are identifiers made of letters, digits, and underscores, and can’t start with a digit. Each value is a strict object with these fields. An unknown key fails validation. @@ -482,11 +385,7 @@ } } -### - -​ - -Limit a field to fixed options +### Limit a field to fixed options Set `options` on a `userConfig` field to make users pick its value from a fixed list. To limit a `tone` field to three options, list them in `options` and set `default` to one of them: @@ -504,30 +403,18 @@ If you declare `options` on any field, users on Claude Code versions before v2.1.271 can’t load the plugin. `options` applies to a `string` field that isn’t `multiple` or `sensitive`. Set `default` to one of the listed values, or set `required: true` so the user must pick one. Each option is a plain label of 1 to 64 characters, and `claude plugin validate`, which you run in your shell, reports anything else it rejects. A plugin whose `options` break these rules fails to load. -### - -​ - -Where values are stored +### Where values are stored Non-sensitive values are saved under [`pluginConfigs`](</docs/en/settings-reference#pluginconfigs>) in the user’s `settings.json`. Sensitive values go to the platform’s secure credential store instead. The [settings page](</docs/en/settings-reference#pluginconfigs>) lists which settings files `pluginConfigs` is read from. -### - -​ - -Reference a saved value +### Reference a saved value Reference a saved value where the plugin needs it, in one of two forms: * **`${user_config.KEY}`** : substituted in MCP server config, LSP server config, [exec-form](</docs/en/hooks#exec-form-and-shell-form>) hook `args`, and skill and agent content. In skill and agent content, only non-sensitive values are substituted, and a sensitive value there becomes a placeholder * **`CLAUDE_PLUGIN_OPTION_<KEY>`**: exported to hook processes for every option, with `<KEY>` uppercased. A shell-form hook reads `$CLAUDE_PLUGIN_OPTION_API_TOKEN` for `api_token` -### - -​ - -Fields that run through a shell +### Fields that run through a shell Shell-form hook commands, monitor commands, and MCP [`headersHelper`](</docs/en/mcp#use-dynamic-headers-for-custom-authentication>) reject `${user_config.*}`. A component that references it in one of these fields fails with an [error](</docs/en/errors#plugin-command-references-user-config>) instead of running, because the field’s value is passed to a shell that would re-parse the substituted value. The table shows how the value can reach each of these fields instead. @@ -537,11 +424,7 @@ Monitor commands| Not through Claude Code. Monitor processes don’t receive `CLAUDE_PLUGIN_OPTION_<KEY>`, so the monitor script has to obtain the value on its own MCP `headersHelper`| Not through Claude Code. The helper’s environment carries `CLAUDE_PLUGIN_ROOT`, `CLAUDE_CODE_MCP_SERVER_NAME`, and `CLAUDE_CODE_MCP_SERVER_URL` but no option values, so the helper script has to obtain the value on its own -## - -​ - -Channels +## Channels `channels` declares the message channels a plugin provides, such as a bridge to a chat app. When you declare one, Claude Code can prompt for the channel’s configuration when the plugin is enabled. For how the server injects messages, see the [channels reference](</docs/en/channels-reference#package-as-a-plugin>). Each entry is a strict object bound to one of the plugin’s MCP servers, with these fields: @@ -577,11 +460,7 @@ ] } -## - -​ - -Environment variables +## Environment variables Claude Code provides three path variables to plugin components. Reference them as `${NAME}` in the fields listed under Where each variable resolves, and read them as environment variables in the processes that receive them. @@ -593,11 +472,7 @@ `${CLAUDE_PLUGIN_ROOT}` changes when the plugin updates, so don’t write state there. For where the root moves and when the old directory is cleaned up, see the [loading page](</docs/en/plugins/loading>). By default, Claude Code deletes the `${CLAUDE_PLUGIN_DATA}` directory when you uninstall the plugin from the last place it’s installed. For `--keep-data` and the other cases where it stays, see [plugin uninstall](</docs/en/plugins/cli-reference#plugin-uninstall>). -### - -​ - -Where each variable resolves +### Where each variable resolves In each plugin component, `${...}` references resolve inline in specific fields, and some components also receive the variables in their process environment: @@ -612,11 +487,7 @@ The variables aren’t present in the environment of commands Claude runs through the Bash tool, in the main session or in a subagent. In skill, command, and agent content, write the `${...}` reference in the Markdown body instead, and Claude Code substitutes the path inline when it loads the content. -### - -​ - -Quoting and path separators +### Quoting and path separators Keep each substituted path a single argument: @@ -642,11 +513,7 @@ On Windows, most substituted paths use forward slashes, as in `C:/Users/you/...`. They keep their native backslashes in an [exec-form hook](</docs/en/hooks#exec-form-and-shell-form>) and in a hook that runs through PowerShell, which is the default shell on Windows when Git Bash isn’t installed. -## - -​ - -Standard layout +## Standard layout Each component type has a default location under the plugin root, used when the manifest doesn’t point elsewhere. @@ -664,9 +531,8 @@ Themes| `themes/`| Theme JSON files Monitors| `monitors/monitors.json`| The monitors array Executables| `bin/`| Files here are on the Bash tool’s `PATH` while the plugin is enabled, so Claude runs them as bare commands. claude.ai and Cowork don’t install a plugin that has this directory, including one you [distribute through claude.ai organization settings](<https://claude.com/docs/plugins/org-sync#keep-executables-out-of-the-top-level-bin-directory>) -Settings| `settings.json`| `agent` and `subagentStatusLine` defaults applied while the plugin is enabled - -A plugin that uses every default location, plus a `scripts/` folder that its hooks call, is laid out like this: + +A plugin that uses default locations, plus a `scripts/` folder that its hooks call, is laid out like this: deploy-tools/ ├── .claude-plugin/ @@ -692,25 +558,16 @@ │ └── deploy-tool ├── scripts/ │ └── format.sh - ├── settings.json ├── .mcp.json └── .lsp.json To click through this layout and read what each file does, open the [plugin explorer](</docs/en/plugins/components#explore-the-plugin-directory>). A `CLAUDE.md` at the plugin root isn’t loaded as context, and `claude plugin validate` warns when it finds one. To include instructions that load into Claude’s context, put them in a skill. -## - -​ - -Marketplace entries and the manifest +## Marketplace entries and the manifest A [marketplace entry](</docs/en/plugins/marketplace-reference>) accepts [its own fields](</docs/en/plugins/marketplace-reference#plugin-entries>), including `strict`, and every field on this page except the directory listing fields. The `strict` field decides whether the entry may add components to a plugin that has its own `plugin.json`. It defaults to `true`. -### - -​ - -How entry fields combine with `plugin.json` +### How entry fields combine with `plugin.json` The entry either serves as the manifest, adds components to it, or conflicts with it: @@ -720,11 +577,7 @@ When a [marketplace entry whose `source` is the marketplace root](</docs/en/plugins/marketplace-reference>) lists specific `skills` subdirectories, only those subdirectories load, and the plugin’s default `skills/` directory isn’t scanned. A `skills` key in the manifest instead adds to the default. -### - -​ - -Metadata precedence +### Metadata precedence Some metadata fields have a fixed precedence regardless of `strict`: @@ -734,11 +587,7 @@ For the full precedence table, see [Strict mode](</docs/en/plugins/marketplace-reference>). -## - -​ - -Next steps +## Next steps * [Add components to a plugin](</docs/en/plugins/components>): what each component does at runtime, with an example that validates * [Marketplace reference](</docs/en/plugins/marketplace-reference>): the entry fields a marketplace can set for your plugin
modified Marketplace reference View current →
Show diff (366 lines)
--- a/marketplace-reference.md +++ b/marketplace-reference.md @@ -12,19 +12,11 @@ * **A`source` object in settings**: Marketplace sources * **Output from[`claude plugin validate <path>`](</docs/en/plugins/cli-reference>)**: Validation messages, which maps each message to the field it names -## - -​ - -Marketplace file +## Marketplace file Save the marketplace file at `.claude-plugin/marketplace.json` in your marketplace’s directory. If you keep the file somewhere else in the repository, users have to declare the marketplace in [`extraKnownMarketplaces`](</docs/en/settings-reference#extraknownmarketplaces>) with `path` set on its source, because `claude plugin marketplace add` has no option for it. The directory that contains `.claude-plugin/` is called the marketplace root, and every relative plugin source resolves from it, not from `.claude-plugin/`. Each user registers one marketplace per `name`, so a user can’t have two marketplaces with the same name registered at once. Claude Code ignores an unknown top-level key or plugin-entry key rather than rejecting it, so a typo loads silently. `claude plugin validate` reports each unknown key as a warning. -### - -​ - -Reserved names +### Reserved names You can’t give your marketplace any of the following names: @@ -41,11 +33,7 @@ When a registered marketplace stops loading because its name imitates an official one, `claude plugin list` and `/plugin` report `Claude Code refuses the marketplace name "<name>"`. The message tells you to remove the marketplace. Removing it also uninstalls its plugins and deletes their data, options, and secrets. This named refusal message requires Claude Code v2.1.282 or later. If a settings file declares the marketplace inline, the message tells you to rename its entry before you remove the old name. For the steps, see [Claude Code refuses the marketplace name](</docs/en/errors#claude-code-refuses-the-marketplace-name>). The message lists them in Claude Code v2.1.292 or later. -## - -​ - -Top-level fields +## Top-level fields The table lists every key Claude Code reads from `marketplace.json`. `name`, `owner`, and `plugins` are required. @@ -63,11 +51,7 @@ `allowCrossMarketplaceDependenciesOn`| array of strings| Marketplace names whose plugins may be installed as dependencies of this marketplace’s plugins. When you install a plugin, only the list in that plugin’s own marketplace applies, for its whole dependency chain. See [Plugin dependencies](</docs/en/plugins/dependencies>) `renames`| object| Map from a former plugin `name` to its current name, or to `null` for a plugin you removed. See [Host and maintain a marketplace](</docs/en/plugins/host-marketplace>) -## - -​ - -Plugin entries +## Plugin entries Each object in the top-level `plugins` array of `marketplace.json` names a plugin and says where to fetch it. `name` and `source` are required. Apart from the [directory listing fields](</docs/en/plugins/manifest-reference#directory-listing-fields>), an entry also accepts every [`plugin.json` field](</docs/en/plugins/manifest-reference>), such as `description`, `version`, `author`, `commands`, and `hooks`. For when those fields apply, see How an entry combines with plugin.json. The table lists the entry’s own fields and the manifest fields whose meaning changes in an entry. @@ -88,30 +72,18 @@ `headers`| object| HTTP headers Claude Code sends when it downloads this entry’s archive. A header set here replaces a header of the same name from the marketplace source’s `headers`. Requires Claude Code v2.1.238 or later `headersHelper`| string| Command that prints this entry’s archive-download headers as one JSON object, for a credential that expires. The entry must also set `"strict": false`. Requires Claude Code v2.1.238 or later. See [Authenticate archive downloads](</docs/en/plugins/host-marketplace#authenticate-archive-downloads>) -### - -​ - -How an entry combines with plugin.json +### How an entry combines with plugin.json The entry’s fields apply differently to a fetched plugin that has its own `.claude-plugin/plugin.json` and to one that doesn’t: * **No`plugin.json`**: the entry is the manifest regardless of `strict`. Every manifest field that the entry accepts applies, including [`mcpServers`, `lspServers`, `userConfig`, and `channels`](</docs/en/plugins/manifest-reference>). * **`plugin.json` present**: `plugin.json` is the manifest. Strict mode decides whether the entry’s six component fields, `commands`, `agents`, `skills`, `hooks`, `outputStyles`, and `themes`, are combined with it or rejected as a conflict. Entry `mcpServers`, `lspServers`, `userConfig`, and `channels` don’t apply. Declare them in `plugin.json`. -#### - -​ - -Hooks in an entry +#### Hooks in an entry Write entry `hooks` as an inline object that maps hook event names to matcher arrays. If you write a file path or an array instead, `claude plugin validate` passes it. Those hooks never run, and Claude Code reports a `not yet supported in a marketplace entry` error for the plugin. Put file-based hooks in the plugin’s own [`hooks/hooks.json`](</docs/en/plugins/components>) or `plugin.json`. -#### - -​ - -Display fields +#### Display fields Both the entry and the plugin’s own `plugin.json` can set the display fields `displayName`, `description`, `author`, `homepage`, `repository`, `license`, and `keywords`. Users see these values in plugin listings and details, before and after install: @@ -120,11 +92,7 @@ Before install, Claude Code can read `plugin.json` only for entries with a relative-path source, whose plugin files are inside the marketplace itself. For an entry with any other source type, users see only the entry’s own fields until they install the plugin. -### - -​ - -Strict mode +### Strict mode `strict` decides what happens when the fetched plugin has its own `plugin.json` and the entry also declares any of the component fields: `commands`, `agents`, `skills`, `hooks`, `outputStyles`, or `themes`. With `strict: true`, the default, Claude Code appends the entry’s component fields to `plugin.json`, except `hooks`, whose matchers replace the manifest’s per event. With `strict: false`, an entry that declares any component field is a conflict, and the plugin fails to load. The table shows each combination of `strict`, `plugin.json`, and the entry’s component fields. @@ -135,11 +103,7 @@ `false`| present| none| `plugin.json` is the manifest, as with `true` `false`| present| one or more| Conflict. The plugin fails to load with `Plugin <name> has conflicting manifests: both plugin.json and marketplace entry specify components` -## - -​ - -Plugin sources +## Plugin sources A plugin entry’s `source` says where Claude Code fetches that one plugin from. It’s either a relative path string or an object whose own `source` key names the type, so an entry looks like `"source": { "source": "github", "repo": "your-org/formatter" }`. The table lists each plugin source type and its fields. @@ -160,11 +124,7 @@ For how each type is fetched, cached, and versioned, see [Plugin loading reference](</docs/en/plugins/loading>). -### - -​ - -Relative path plugin source +### Relative path plugin source The path resolves from the marketplace root. `./plugins/formatter` is `<root>/plugins/formatter` even though the marketplace file is in `<root>/.claude-plugin/`. A path containing `..` fails validation. On macOS and Linux, Claude Code refuses an entry path that contains a backslash anywhere after the leading `./`, so write the path with forward slashes. @@ -176,11 +136,7 @@ * **`url`** : Claude Code fetches only `marketplace.json`, so relative paths can’t resolve. Give each plugin an object source instead, such as `github` or `git-subdir`. * **`settings`** : relative paths are rejected outright. -#### - -​ - -Git submodules in the marketplace repository +#### Git submodules in the marketplace repository When Claude Code clones a marketplace repository, it fetches only the git submodules that hold plugin files. Requires Claude Code v2.1.295 or later. Earlier versions fetch every submodule, nested ones included. If the repository has a large submodule, Claude Code can then run past the [clone timeout](</docs/en/plugins/troubleshooting#git-clone-timed-out-after-120s>) while fetching it. For a plugin in a subdirectory, such as `./plugins/formatter`, Claude Code fetches a submodule in these cases: @@ -202,11 +158,7 @@ If you add a marketplace with `--sparse`, or its source sets `sparsePaths`, Claude Code checks out only the directories named there and fetches no submodule. Earlier versions do the same. To keep a submodule your plugins don’t use out of the clone, see [Keep unused submodules out of the clone](</docs/en/plugins/create-marketplace#keep-unused-submodules-out-of-the-clone>). -#### - -​ - -Bare names under pluginRoot +#### Bare names under pluginRoot A bare name is a single directory name with no `/`, such as `"formatter"`. To write bare names instead of `./` paths, set `metadata.pluginRoot` to the directory they resolve under. With `"pluginRoot": "./plugins"`, `"source": "formatter"` resolves to `./plugins/formatter`. Requires Claude Code v2.1.239 or later. `metadata.pluginRoot` has these limits: @@ -214,11 +166,7 @@ * It has no effect on a source that already starts with `./`. * A source that contains a `/`, such as `team-a/formatter`, isn’t a bare name and still needs the `./` prefix, even when `metadata.pluginRoot` is set. -### - -​ - -github plugin source +### github plugin source `repo` takes `owner/repo`. `ref` and `sha` are optional. @@ -232,11 +180,7 @@ } } -### - -​ - -url plugin source +### url plugin source `url` is a full git URL: `https://`, `http://`, `file://`, or `git@`. A `.git` suffix isn’t required, so Azure DevOps and AWS CodeCommit URLs work as written. This type doesn’t take `owner/repo` shorthand. @@ -249,11 +193,7 @@ } } -### - -​ - -git-subdir plugin source +### git-subdir plugin source `url` accepts a full git URL or GitHub `owner/repo` shorthand. `path` is the subdirectory that holds the plugin, and Claude Code checks out only that subdirectory. Over an `https` or SSH URL, Claude Code asks the server for a partial clone, so from a host that supports partial clones, a plugin in a large monorepo installs without downloading the rest of the repository. @@ -266,11 +206,7 @@ } } -### - -​ - -npm plugin source +### npm plugin source An `npm` source takes these fields: @@ -296,11 +232,7 @@ } } -### - -​ - -archive plugin source +### archive plugin source `url` must use `https://` and can’t point at a loopback, link-local, or cloud-metadata host. For the size, timeout, redirect, and extraction limits on the download, see [Stay within the download limits for hosted files](</docs/en/plugins/host-marketplace#stay-within-the-download-limits-for-hosted-files>). The plugin root may be at the top of the zip or one directory down. `sha256` is the archive’s digest as 64 hex characters, uppercase or lowercase. When you set it, Claude Code refuses a download that doesn’t match. @@ -313,11 +245,7 @@ } } -### - -​ - -command plugin source +### command plugin source Use a `command` source when a tool installed on the user’s machine produces the plugin directory, such as an IDE that renders its plugin for the toolchain the user has selected. Claude Code runs the command when the user installs or updates the plugin, and [again once per session](</docs/en/plugins/loading#when-a-command-source-re-runs>), so users get the tool’s changed output without reinstalling. A `command` source takes these fields: @@ -336,11 +264,7 @@ For how users accept the command, see [Install from your shell](</docs/en/plugins/install#install-from-your-shell>). For what users see after you change it, see [Change the command of a command source](</docs/en/plugins/host-marketplace#change-the-command-of-a-command-source>). Administrators turn command sources off with [`disableCommandPluginSources`](</docs/en/settings-reference#disablecommandpluginsources>). -#### - -​ - -What the command must do +#### What the command must do Write the command to meet these requirements: @@ -348,11 +272,7 @@ * **Output** : print exactly one line on stdout, the absolute path of the plugin directory, and exit 0 within `timeout` seconds. * **Directory contents** : the directory holds the complete plugin by the time the command exits. The path can differ from one run to the next. -#### - -​ - -Output that fails the install or update +#### Output that fails the install or update The install or update fails when the command exits non-zero, runs longer than `timeout`, or prints anything other than one absolute path. It also fails when the printed directory is one of these: @@ -361,11 +281,7 @@ * **A network path** : on Windows, the printed path is a UNC path. * **Too large to copy** : in copy mode, the directory is larger than 256 MiB or has more than 20,000 entries. -#### - -​ - -Copy mode and link mode +#### Copy mode and link mode `mode` decides whether Claude Code copies the printed directory or uses it in place: @@ -381,11 +297,7 @@ * **Sessions started inside the directory** : a session started in the printed directory or anywhere below it doesn’t load the plugin. * **Not on Windows** : Claude Code refuses to install a link-mode plugin on Windows. Declare `"mode": "copy"` there. -## - -​ - -Marketplace sources +## Marketplace sources A marketplace source says where Claude Code fetches a `marketplace.json` from. The CLI builds one for you when you add a marketplace, and you write one yourself in settings: @@ -416,11 +328,7 @@ `hostPattern`| `hostPattern`| Not produced| Fails to load: `Unsupported marketplace source type`| Allows `github`, `git`, and `url` sources whose host matches| Blocks those sources `pathPattern`| `pathPattern`| Not produced| Fails to load: `Unsupported marketplace source type`| Allows `file` and `directory` sources whose `path` matches| Blocks those sources -### - -​ - -Fields by type +### Fields by type The table lists each marketplace source field that has a default, a constraint, or a meaning specific to its type. @@ -440,11 +348,7 @@ `name`| `settings`| Must equal the `extraKnownMarketplaces` key and can’t be a reserved name `plugins`| `settings`| The inline catalog, with no hosted file. Each item takes `name`, `source`, `description`, `version`, `strict`, `headers`, and `headersHelper`. Write each item’s `source` as an object type, because a relative path has no repository to resolve against -### - -​ - -Source values valid only in policy lists +### Source values valid only in policy lists `hostPattern`, `pathPattern`, `skills-dir`, and the `owner/*` form of `repo` are valid only in the two policy lists, `strictKnownMarketplaces` and `blockedMarketplaces`: @@ -454,11 +358,7 @@ For match order, exact-`ref` semantics, and recipes, see [Manage plugins for your organization](</docs/en/plugins/org>). -### - -​ - -Source objects in settings +### Source objects in settings An `extraKnownMarketplaces` value is a map from marketplace name to an object with `source`. This entry registers a marketplace from a git repository at its `main` branch: @@ -483,11 +383,7 @@ ] } -## - -​ - -Validation messages +## Validation messages `claude plugin validate <path>` takes the marketplace root or the marketplace file itself. To have that file [validated as a marketplace](</docs/en/plugins/cli-reference#validate-a-manifest-file>) rather than a plugin manifest, name it `marketplace.json`. For exit codes and `--strict`, see [plugin validate](</docs/en/plugins/cli-reference#plugin-validate>). A message names a plugin entry by its index, written as `plugins.1.source` or `plugins[1].source`. A message prefixed with an entry index and `plugin.json →`, such as `plugins[2] plugin.json →`, is about that plugin’s own files. [`claude plugin validate` reports errors](</docs/en/plugins/troubleshooting#claude-plugin-validate-reports-errors>) lists those messages with their fixes. Warnings that mention Claude Desktop flag names that Claude Desktop rejects. The table maps marketplace-level messages to the field each is about. @@ -529,11 +425,7 @@ `Marketplace name "x" is not accepted by Claude Desktop (letters, digits, ".", "_", "-"; must start alphanumeric; max 128 chars)`| Warning| `name`. Claude Desktop rejects the marketplace `Plugin name "x" is not accepted by Claude Desktop (letters, digits, ".", "_", "-"; must start alphanumeric; max 128 chars)`| Warning| `plugins[i].name`. Claude Desktop drops the entry -### - -​ - -Invalid input on a source +### Invalid input on a source `Invalid input` on a `source` means the object matched no source type. Check for these causes: @@ -543,19 +435,11 @@ A relative path that doesn’t start with `./`, other than `"."` or a bare name under `metadata.pluginRoot`, fails with `Invalid string: must start with "./"`. Before v2.1.285, it printed `Invalid input` like the causes above. -### - -​ - -Failures that validation doesn’t catch +### Failures that validation doesn’t catch `claude plugin validate` doesn’t report every failure. An entry `hooks` written as a file path or array passes validation, and the error appears only when the plugin loads, as Hooks in an entry describes. Errors fetching a `source` also appear only after install, not in validation. [`claude plugin list`](</docs/en/plugins/cli-reference>) shows a plugin that failed to load with its error, and [Troubleshoot plugins](</docs/en/plugins/troubleshooting>) covers the load-time strings. -## - -​ - -Next steps +## Next steps * [Create a marketplace](</docs/en/plugins/create-marketplace>): build a marketplace from these fields and install from it locally * [Host and maintain a marketplace](</docs/en/plugins/host-marketplace>): where to put the file and how users receive changes
modified Connect to external tools with MCP View current →
Show diff (380 lines)
--- a/mcp.md +++ b/mcp.md @@ -2,11 +2,7 @@ This page covers MCP configuration for the Agent SDK. To add MCP servers to the Claude Code CLI so they load in every project, see [MCP installation scopes](</docs/en/mcp#mcp-installation-scopes>). -## - -​ - -Quickstart +## Quickstart This example connects to the [Claude Code documentation](<https://code.claude.com/docs>) MCP server using HTTP transport and uses `allowedTools` with a wildcard to permit all tools from the server. @@ -58,19 +54,11 @@ The agent connects to the documentation server, searches for information about hooks, and returns the results. -## - -​ - -Add an MCP server +## Add an MCP server You can configure MCP servers in code when calling `query()`, or in a `.mcp.json` file loaded via `settingSources`. -### - -​ - -Add a server 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: @@ -121,11 +109,7 @@ asyncio.run(main()) -### - -​ - -Add a server 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: @@ -138,11 +122,7 @@ } } -## - -​ - -Connection timing +## Connection timing Claude Code starts connecting your MCP servers when the session starts, and sends the init message once the first-turn wait, if any, ends. How long the first turn waits for a server depends on where you configured it. If you set `permissionPromptToolName`, the first turn always waits for that tool’s server, up to `MCP_TIMEOUT`, wherever you configured it. For a server in `options.mcpServers`, find its type in the first column to see how long the first turn waits for it. @@ -159,19 +139,11 @@ * **Otherwise, with[tool search](</docs/en/agent-sdk/tool-search>) on, which is the default**: the first turn waits up to 2 seconds, and only for pending servers that set [`alwaysLoad: true`](</docs/en/mcp#exempt-a-server-from-deferral>) or that you named. The rest keep connecting in the background, and Claude [reaches their tools](</docs/en/mcp#tool-availability>) once they connect. * **Otherwise, with tool search off** : the first turn waits up to 2 seconds for every pending settings-file and plugin server. Tool search is off when your [`ENABLE_TOOL_SEARCH` value or model](</docs/en/agent-sdk/tool-search#configure-tool-search>) turns it off, or when you exclude the `ToolSearch` tool, for example through `disallowedTools`. -### - -​ - -Named servers +### Named servers You name a server by listing any of its tools, such as `mcp__github__list_issues` or `mcp__github__*`, in `allowedTools` or in a `permissions.allow` rule in the `settings` option. An [`mcp_tool` hook](</docs/en/hooks#mcp-tool-hook-fields>) also names the server it calls when you configure it on a prompt-submission, tool-use, permission, subagent, task, elicitation, or worktree event. Before v2.1.284, naming a server had no effect on the first-turn wait. -### - -​ - -Set the first-turn wait yourself +### Set the first-turn wait yourself To choose the first-turn wait yourself, set `CLAUDE_CODE_MCP_STARTUP_WAIT_MS` in the [`env` option](</docs/en/agent-sdk/configuration#set-environment-variables>), for example `CLAUDE_CODE_MCP_STARTUP_WAIT_MS: "5000"`. The first turn then waits up to that many milliseconds for pending settings-file and plugin servers, whether or not tool search is on. The same limit replaces the `MCP_TIMEOUT` wait for the stdio, HTTP, and SSE servers in `options.mcpServers`. Three waits apply whatever value you set, including `0`: @@ -181,11 +153,7 @@ Set the variable to `0` to skip the wait for every other server. Servers still pending when the wait ends keep connecting in the background. `CLAUDE_CODE_MCP_STARTUP_WAIT_MS` requires Claude Code v2.1.274 or later. -### - -​ - -Make startup wait for servers +### Make startup wait for servers Two settings make startup itself wait, before Claude Code sends the init message: @@ -194,19 +162,11 @@ The init message reports each server’s status as of the moment Claude Code sends it. -## - -​ - -Allow MCP tools +## Allow MCP tools MCP tools require explicit permission before Claude can use them. Without permission, Claude will see that tools are available but won’t be able to call them. -### - -​ - -Tool naming convention +### Tool naming convention MCP tools are named `mcp__<server-name>__<tool-name>`, where `<server-name>` is the name you register the server under, such as its key in `mcpServers`. Characters in the server name such as `.` and spaces are replaced by `_`. This table shows the full name of a `list_issues` tool for two server keys: @@ -217,11 +177,7 @@ Use the full tool names in `allowedTools` and in [MCP permission rules](</docs/en/permissions#mcp>). For a server that a [plugin](</docs/en/agent-sdk/plugins>) provides, `<server-name>` takes the [plugin-scoped form](</docs/en/mcp#plugin-provided-mcp-servers>) and starts with `plugin_`. -### - -​ - -Auto-approve with allowedTools +### Auto-approve with allowedTools Use `allowedTools` to auto-approve specific MCP tools: @@ -257,11 +213,7 @@ **Prefer`allowedTools` over permission modes for MCP access.** `permissionMode: "acceptEdits"` does not auto-approve MCP tools (only file edits and filesystem Bash commands). `permissionMode: "bypassPermissions"` does auto-approve MCP tools but also disables most other safety prompts, which is broader than necessary; see [How permissions are evaluated](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) for the prompts that remain. A wildcard in `allowedTools` grants exactly the MCP server you want and nothing more. See [Permission modes](</docs/en/agent-sdk/permissions#permission-modes>) for a full comparison. -### - -​ - -Discover available tools +### Discover available tools To see what tools an MCP server provides, check the server’s documentation or inspect the `tools` array in the `system` init message. MCP tool names start with `mcp__`. Claude Code emits the init message after the first-turn connection wait for servers passed in `options.mcpServers`, so the `tools` array lists the `mcp__` tools of each server that has connected by then, plus those of servers with a cached tool list, which connect on first use. Tools of any other server that hasn’t connected are absent; see Error handling for reading each server’s status. This filter prints the MCP tool names: @@ -302,11 +254,7 @@ You can also ask Claude to list the tools available from a server. -## - -​ - -Transport types +## Transport types MCP servers communicate with your agent using different transport protocols. Check the server’s documentation to see which transport it supports: @@ -314,11 +262,7 @@ * If the docs give you a **URL** , use HTTP or SSE * If you’re building your own tools in code, use an SDK MCP server -### - -​ - -stdio servers +### 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 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: @@ -352,11 +296,7 @@ allowed_tools=["mcp__filesystem__read_file", "mcp__filesystem__list_directory"], ) -### - -​ - -HTTP/SSE servers +### HTTP/SSE servers Use HTTP or SSE for cloud-hosted MCP servers and remote APIs. For the `.mcp.json` form, use the same fields as the example at HTTP headers for remote servers, with `"type": "sse"` for an SSE server. In code, pass the server’s URL: @@ -392,35 +332,19 @@ For the streamable HTTP transport, use `"type": "http"` instead. In `.mcp.json` and other JSON config files, `"streamable-http"` is accepted as an alias for `"http"`. The SDKs’ `McpHttpServerConfig` type declares only `"http"`, so use `"http"` for servers you pass in code. -### - -​ - -SDK MCP servers +### SDK MCP servers Define custom tools directly in your application code instead of running a separate server process. See the [custom tools guide](</docs/en/agent-sdk/custom-tools>) for implementation details. An SDK MCP server registered by an [`initialize` control request](</docs/en/agent-sdk/typescript#sdkcontrolinitializeresponse>) begins connecting as soon as Claude Code processes the request. -## - -​ - -MCP tool search +## MCP tool search When you have many MCP tools configured, tool definitions can consume a significant portion of your context window. Tool search solves this by withholding tool definitions from context and loading only the ones Claude needs for each turn. Tool search is enabled by default. See [Tool search](</docs/en/agent-sdk/tool-search>) for configuration options, best practices, and using tool search with custom SDK tools. -## - -​ - -Authentication +## Authentication Most MCP servers require authentication to access external services. Pass credentials through environment variables in the server configuration. -### - -​ - -Pass credentials via environment variables +### Pass credentials via environment variables Use the `env` field to pass API keys, tokens, and other credentials to the MCP server: @@ -472,11 +396,7 @@ The `${API_KEY}` syntax expands environment variables at runtime. -### - -​ - -HTTP headers for remote servers +### HTTP headers for remote servers For HTTP and SSE servers, pass authentication headers directly in the server configuration: @@ -530,11 +450,7 @@ For a complete working example of a remote server authenticated with headers, see List issues from a repository. -### - -​ - -OAuth2 authentication +### OAuth2 authentication The [MCP specification supports OAuth 2.1](<https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization>) for authorization. The SDK doesn’t open a browser or run an interactive OAuth flow. When a configured server returns an authorization challenge and Claude Code has no token to send, the SDK reports the server as `needs-auth` or `failed`: @@ -579,17 +495,9 @@ allowed_tools=["mcp__oauth-api__*"], ) -## - -​ - -Examples - -### - -​ - -List issues from a repository +## Examples + +### List issues from a repository This example connects to the remote [GitHub MCP server](<https://github.com/github/github-mcp-server>) to list recent issues. The example includes debug logging to verify the MCP connection and tool calls. Before running, create a [GitHub personal access token](<https://github.com/settings/personal-access-tokens>) with read access to the repositories you want to query and set it as an environment variable: @@ -680,11 +588,7 @@ In the `MCP servers:` line, a `status` of `connected` for `github` confirms the token works. If Claude Code has a cached tool list for the server, the status can read `pending` instead and the server connects on its first tool call. If the status is `failed` or `needs-auth`, see Error handling before trusting the result, since Claude can fall back to built-in tools when the server is unavailable. -### - -​ - -Query a database +### Query a database This example uses [DBHub](<https://github.com/bytebase/dbhub>) to query a Postgres database. The agent automatically discovers the database schema, writes the SQL query, and returns the results. DBHub’s `execute_sql` tool runs whatever SQL the agent emits, including writes, unless you restrict it. Setting `readonly = true` in the [DBHub configuration file](<https://dbhub.ai/config/toml>) makes DBHub reject `INSERT`, `UPDATE`, `DELETE`, and DDL statements, so the example cannot modify your data even if the agent emits a write. DBHub resolves `${DATABASE_URL}` from the process environment when it loads the config, so the connection string stays out of the file. Create this `dbhub.toml` next to your script: @@ -758,11 +662,7 @@ asyncio.run(main()) -## - -​ - -Error handling +## Error handling MCP servers can fail to connect for various reasons: the server process might not be installed, credentials might be invalid, or a remote server might be unreachable. Claude Code emits a `system` message with subtype `init` at the start of each query. This message includes the connection status for each MCP server. The `status` field can be `"pending"`, `"connected"`, `"failed"`, `"needs-auth"`, or `"disabled"`. Claude Code emits the init message after the first-turn connection wait for servers passed in `options.mcpServers`, so such a server that connected within the wait shows `"connected"`. In the init message, don’t treat `"pending"` as a failure on its own. It can mean any of these: @@ -849,17 +749,9 @@ A remote server’s status can also change after it reports `"connected"`. When the connection to it drops mid-session, Claude Code moves the server back to `"pending"` while [reconnecting](</docs/en/mcp#automatic-reconnection>). A later `mcpServerStatus()` call in TypeScript, or [`ClaudeSDKClient.get_mcp_status()`](</docs/en/agent-sdk/python#methods>) in Python, can then report `"pending"` for a server you saw connected earlier, with no configuration change on your side. After five reconnection attempts fail, the server reports `"failed"`, or `"needs-auth"` when it needs authorizing again. A `"failed"` HTTP or SSE server can still return to `"connected"` without a call from you, because Claude Code keeps [retrying in the background](</docs/en/mcp#mid-session-drops-of-a-remote-server>) after a transient error. To retry manually, call [`reconnectMcpServer()`](</docs/en/agent-sdk/typescript#methods>) in TypeScript or [`ClaudeSDKClient.reconnect_mcp_server()`](</docs/en/agent-sdk/python#methods>) in Python. -## - -​ - -Troubleshooting - -### - -​ - -Server shows “failed” status +## Troubleshooting + +### Server shows “failed” status Check the `init` message to see which servers failed to connect: @@ -887,11 +779,7 @@ * **Invalid connection string** : For database servers, verify the connection string format and that the database is accessible. * **Network issues** : For remote HTTP/SSE servers, check the URL is reachable and any firewalls allow the connection. -### - -​ - -Tools not being called +### Tools not being called If Claude sees tools but doesn’t use them, check that you’ve granted permission with `allowedTools`: @@ -915,11 +803,7 @@ allowed_tools=["mcp__servername__*"], # Auto-approve calls from this server ) -### - -​ - -A tool is missing from an SDK MCP server +### A tool is missing from an SDK MCP server In the TypeScript SDK, when a tool’s input schema can’t be converted to JSON Schema, the server you created with [`createSdkMcpServer()`](</docs/en/agent-sdk/typescript#createsdkmcpserver>) leaves that tool out when it lists its tools. The SDK emits a warning at that point. Under Node.js the warning is a process warning with code `CLAUDE_SDK_MCP_TOOL_SCHEMA_UNCONVERTIBLE`, and it starts with this text: @@ -927,11 +811,7 @@ The rest of the warning gives the conversion error’s message when it has one, then says what to check and change. Before TypeScript Agent SDK v0.3.286, one unconvertible schema made the server’s whole tool listing fail without this warning, so none of that server’s tools reached Claude. -### - -​ - -Connection timeouts +### Connection timeouts MCP server connections time out after 30 seconds by default. To change how long a running tool call may take, set [`MCP_TOOL_TIMEOUT`](</docs/en/env-vars>). If your server takes longer to start, the connection fails. Raise the connection limit with the [`MCP_TIMEOUT`](</docs/en/env-vars>) environment variable, in milliseconds. For servers that need more startup time, also consider: @@ -941,19 +821,11 @@ In TypeScript, you can set the tool-call limit for a single SDK MCP server by passing [`timeout` to `createSdkMcpServer()`](</docs/en/agent-sdk/typescript#createsdkmcpserver>). -### - -​ - -Tool output exceeds maximum allowed tokens +### Tool output exceeds maximum allowed tokens The SDK applies the same MCP output limits as Claude Code. When a successful tool result with no image content is larger than 25,000 tokens, Claude Code saves the output to a file and replaces the tool result with an error message that names the file path, so the agent can read the output back in portions. To change the token limit, set the [`MAX_MCP_OUTPUT_TOKENS`](</docs/en/env-vars>) environment variable. Unless the tool declares `anthropic/maxResultSizeChars`, a successful text result longer than 50,000 characters is saved to a file regardless of the token limit. See [MCP output limits and warnings](</docs/en/mcp#mcp-output-limits-and-warnings>) for the full behavior, including how a server declares that annotation. -## - -​ - -Related resources +## Related resources * **[Custom tools guide](</docs/en/agent-sdk/custom-tools>)** : Build your own MCP server that runs in-process with your SDK application * **[Permissions](</docs/en/agent-sdk/permissions>)** : Control which MCP tools your agent can use with `allowedTools` and `disallowedTools`
modified Connect to MCP servers View current →
Show diff (175 lines)
--- a/mcp-quickstart.md +++ b/mcp-quickstart.md @@ -4,22 +4,14 @@ For every way to connect and configure MCP servers in Claude Code, see the [MCP reference](</docs/en/mcp>). -## - -​ - -Before you begin +## Before you begin Make sure you have: * [Claude Code installed](</docs/en/quickstart>) and authenticated * A terminal open in a project directory. Any directory works, including an empty one. -## - -​ - -Add and verify a server +## Add and verify a server The example below connects to the [Claude Code documentation MCP server](<https://code.claude.com/docs/mcp>), a hosted server with full-text search over the Claude Code docs. It doesn’t require authentication or any special configuration, so it works well as a first server to test the setup flow with. The steps are the same for any server: add it, check the connection status, then use it in a session, with an optional cleanup step at the end. Some servers add a step, like a browser sign-in, shown in Additional MCP server examples. For more servers to connect, browse the [Anthropic Directory](</docs/en/mcp#find-and-build-mcp-servers>). @@ -89,11 +81,7 @@ Each connected server takes some space in [Claude’s context window](</docs/en/how-claude-code-works#the-context-window>) because its tool names and server instructions load into every session. Removing servers you no longer use keeps that space free. -## - -​ - -Where servers are saved +## Where servers are saved The `claude mcp add` command writes the server’s details to a configuration file. By default it registers the server at `local` scope: private to you, active only in the current project. Pass `--scope user` to register it once for all your projects, or `--scope project` to share it with teammates. Change server scope walks through both. @@ -105,11 +93,7 @@ * Edit `.mcp.json` directly: write the JSON entry yourself instead of using the command. * Connect a server that requires sign-in: add a hosted server that needs a browser sign-in before its tools work. -### - -​ - -Find your configuration on disk +### Find your configuration on disk The `claude mcp add` command writes the server to one of three scopes, stored across two files, depending on the `--scope` flag. You don’t need to edit these files directly, but knowing where they are helps with debugging and version control. @@ -121,31 +105,19 @@ On Windows, `~/.claude.json` resolves to `%USERPROFILE%\.claude.json`, typically `C:\Users\YourName\.claude.json`. If you’ve set [`CLAUDE_CONFIG_DIR`](</docs/en/env-vars>), Claude Code reads `.claude.json` from inside that directory instead. Run `claude mcp get claude-code-docs` to see which scope holds a server’s definition. For how the scopes interact when the same server is defined in more than one, see [MCP installation scopes](</docs/en/mcp#mcp-installation-scopes>). -## - -​ - -Change server scope +## Change server scope A server’s scope is fixed when you add it, so changing scope means removing the entry and re-adding it at the new one. Both cases below start by removing the local entry from the first walkthrough, so the server has only one definition. If you already removed it at the end of that walkthrough, skip this command: claude mcp remove claude-code-docs --scope local -### - -​ - -Use a server in all your projects +### Use a server in all your projects Re-add the server at `user` scope to make it active in every project you open, still private to you: claude mcp add --scope user --transport http claude-code-docs https://code.claude.com/docs/mcp -### - -​ - -Share a server with your team +### Share a server with your team Re-add the server at `project` scope, which writes to `.mcp.json` in the project root: @@ -153,19 +125,11 @@ Commit `.mcp.json` to version control. Teammates who clone the repository and start Claude Code see a prompt to approve the server, then it connects for them too. -## - -​ - -Additional MCP server examples +## Additional MCP server examples The first walkthrough used a hosted server that connects without any sign-in. The examples below cover the other two common shapes, with the same add, check, use flow. -### - -​ - -Add a local server +### Add a local server A local stdio server is a program Claude Code starts as a subprocess on your machine, rather than a service it reaches over a URL. Use one for tools that need access to local resources like a browser, your filesystem, or a database socket. The [Playwright MCP server](<https://github.com/microsoft/playwright-mcp>) is a good one to try: it gives Claude a browser it can navigate, click, and read, and it needs no account. It runs through `npx`, so it requires [Node.js](<https://nodejs.org/en/download>) 18 or later. @@ -205,11 +169,7 @@ A browser window opens so you can watch it work, and the tool calls in Claude’s output are labeled with the `playwright` server name and the action, like `browser_navigate`.Try pointing it at your local dev server to check that a page still renders after a change, or have it walk through a bug report step by step. -### - -​ - -Connect a server that requires sign-in +### Connect a server that requires sign-in Hosted services like Sentry, Linear, and Notion run their MCP servers behind OAuth: you add the server’s URL, then sign in through your browser. The steps below use Sentry as the example. To connect a different service, substitute its URL, which you can find in the [Anthropic Directory](</docs/en/mcp#find-and-build-mcp-servers>) or the service’s documentation. @@ -241,11 +201,7 @@ Servers that authenticate with a static token instead of OAuth take the token at add time with `--header "Authorization: Bearer <token>"`. See the [GitHub example](</docs/en/mcp#example-connect-to-github-for-code-reviews>) for a worked version. -## - -​ - -Edit .mcp.json directly +## Edit .mcp.json directly Every file in the scope table uses the same JSON format for server entries. This section edits `.mcp.json`, the project-scope file. It’s the one most worth writing by hand because it’s checked into the repository, where it doubles as configuration-as-code for your team. Create `.mcp.json` in your project root. The example below defines both servers from this guide, the hosted docs server reached over HTTP and the Playwright server as a local `stdio` process: @@ -270,11 +226,7 @@ After saving the file, start a new Claude Code session in the project. Claude Code reads `.mcp.json` at startup. The first time Claude Code sees a project-scoped server, it asks you to approve it. The prompt exists so a repository you clone can’t launch processes on your machine without your consent. Approve the prompt, or run `/mcp` to approve later if you missed it. Once you’ve approved, run `/mcp` and check that the servers show as connected. If one shows an error instead, see Troubleshooting. -## - -​ - -Connect from other surfaces +## Connect from other surfaces This guide uses the `claude mcp` CLI commands, but every Claude Code surface can connect to MCP servers: @@ -284,11 +236,7 @@ * **Cloud sessions** : outside a [project](</docs/en/claude-projects#what-threads-pick-up-from-your-repositories>)’s threads, commit a `.mcp.json` to your repository; a session with one repository loads it. Cloud threads in a project use your claude.ai connectors instead. See Edit .mcp.json directly and [What carries over from your setup](</docs/en/cloud-environments#what-carries-over-from-your-setup>). * **Claude.ai** : connectors you add at [claude.ai/customize/connectors](<https://claude.ai/customize/connectors>) load automatically in the CLI when you sign in with that account. See [Use MCP servers from Claude.ai](</docs/en/mcp#use-mcp-servers-from-claude-ai>). -## - -​ - -Troubleshooting +## Troubleshooting If a server doesn’t connect, check its status with `/mcp` inside a session or `claude mcp list` from your shell, then match the symptom below. The `/mcp` panel also lets you reconnect or authenticate without leaving the session. @@ -360,11 +308,7 @@ Run `/mcp`, select the server, and choose `Authenticate` again. If the browser doesn’t open automatically, copy the URL shown in the terminal and open it manually. See [Authenticate with remote MCP servers](</docs/en/mcp#authenticate-with-remote-mcp-servers>) for fixed callback ports and pre-configured credentials. -## - -​ - -Next steps +## Next steps With one server connected, explore the rest of what MCP enables:
modified Measure plugin cost and usage View current →
Show diff (150 lines)
--- a/measure.md +++ b/measure.md @@ -7,11 +7,7 @@ Start with Measure what a plugin costs. -## - -​ - -Measure what a plugin costs +## Measure what a plugin costs To see what a plugin adds to Claude’s context, run [`claude plugin details`](</docs/en/plugins/cli-reference#plugin-details>) with the plugin’s name. You run it in your shell, not at the prompt of a running Claude Code session. The plugin has to be loaded: installed, in a skills directory, or passed with `--plugin-dir` in the same command, as in `claude --plugin-dir ./formatter plugin details formatter`. This example reads an installed plugin named `formatter` that has two skills, a command, an agent, a hook, and an MCP server: @@ -47,11 +43,7 @@ * **Always-on** : the tokens that the names and descriptions of the plugin’s skills, agents, and commands add to every session where the plugin is enabled, whether or not anything runs. This is the number every user carries, and the one to reduce. * **Per-component** : each row splits one skill, agent, or command into its always-on share and its on-invoke cost, which is the body that loads only when that component runs. Use the always-on column to find which component contributes most. -### - -​ - -Lower the always-on figure +### Lower the always-on figure If you maintain the plugin, these changes reduce what it adds to every session. If you only use it, your options are to disable or uninstall it; see [Manage installed plugins](</docs/en/plugins/install#manage-installed-plugins>). The always-on figure counts each component’s name plus its `description` and `when_to_use` frontmatter. To lower it: @@ -60,19 +52,11 @@ A skill’s description is also what Claude matches a request against, so a shorter one can stop the skill triggering. After you trim descriptions, check triggering with a [`tool_used: Skill` grader](</docs/en/plugin-evals#create-your-first-eval-suite>) in your eval suite. For what each component type contributes, see [plugin components](</docs/en/plugins/components>). -### - -​ - -Cost shown to users before install +### Cost shown to users before install Plugins in the official marketplace show their cost to users before install. In `/plugin`, when a user browses a marketplace’s plugin list and selects a plugin, the details pane shows a **Context cost** section with an `Every turn:` line and a `When invoked:` line. When the always-on figure is 2,000 tokens or more, the `Every turn:` line appears highlighted. A plugin in your own marketplace has no **Context cost** section. -## - -​ - -Check whether a plugin is used +## Check whether a plugin is used Claude Code doesn’t report a plugin’s usage back to its author. Usage is recorded on the machine of each person who installed the plugin, so what you can learn depends on your relationship to those people: @@ -82,11 +66,7 @@ For usage of a plugin listed in Anthropic’s directory, see [Track published plugin usage](<https://claude.com/docs/connectors/building/after-publishing#track-published-plugin-usage>) on claude.com. -### - -​ - -Not used recently in `/plugin` +### Not used recently in `/plugin` On the **Installed** tab of `/plugin`, a plugin the user installed from a marketplace moves under a **Not used recently** header once it has gone unused for at least 14 days and 10 sessions. The plugin’s details also show a `Last used:` line. For what users do with that header and line, see [Find plugins you no longer use](</docs/en/plugins/install#find-plugins-you-no-longer-use>). The **Not used recently** header never appears for: @@ -96,46 +76,26 @@ A plugin’s [language server](</docs/en/plugins/components#lsp-servers>) counts as used when it delivers diagnostics or answers a code navigation request, so an LSP plugin whose server is active in your sessions isn’t listed as unused. When the user’s organization sets [`strictKnownMarketplaces`](</docs/en/plugins/org#restrict-what-users-can-install>), neither the header nor the `Last used:` line appears. -### - -​ - -Find skills that never run +### Find skills that never run Run `/skill-doctor` to see what each of your skills costs and how often it gets used. It flags skills that are in Claude’s skill listing but have never been invoked, including skills from plugins. In an interactive session, the report opens in the `/plugin` manager’s **Stats** tab. See [Find unused skills](</docs/en/skills#find-unused-skills>) for what the report covers and where it’s available. -### - -​ - -Unused plugins in `/doctor` +### Unused plugins in `/doctor` The `/doctor` checkup lists each user-installed skill, MCP server, and plugin, and recommends disabling the ones that were not used. See [`/doctor` in the commands reference](</docs/en/commands#all-commands>). -### - -​ - -Usage share in `/usage` +### Usage share in `/usage` On a Pro, Max, Ultra, Team, or Enterprise plan, the `/usage` breakdown attributes recent usage to skills, subagents, plugins, and MCP servers as a share of the total. See [Using the `/usage` command](</docs/en/costs#using-the-/usage-command>). -## - -​ - -Measure across a fleet +## Measure across a fleet If you administer Claude Code for an organization, you can measure plugin cost and usage across every machine from either of these sources: * **OpenTelemetry events** : Claude Code exports these to your own backend once you [configure an exporter](</docs/en/monitoring-usage>). See OpenTelemetry events for plugin installs and use. * **Analytics API** : served from Anthropic’s records, with no exporter needed. See Query the Analytics API. -### - -​ - -OpenTelemetry events for plugin installs and use +### OpenTelemetry events for plugin installs and use These OpenTelemetry events and attributes answer each plugin question from your backend: @@ -147,11 +107,7 @@ What a plugin’s hooks report| [`claude_code.hook_plugin_metrics`](</docs/en/monitoring-usage#hook-plugin-metrics-event>), emitted only for hooks in official-marketplace plugins What a plugin costs in API spend| `plugin.name` and `marketplace.name` on the [cost counter](</docs/en/monitoring-usage#cost-counter>), set when the active skill or subagent belongs to a plugin -### - -​ - -Redacted plugin names in your backend +### Redacted plugin names in your backend Plugins from the official marketplace report their plugin name and marketplace name to your backend verbatim. Every other plugin’s name is redacted or omitted by default, including a plugin from your organization’s own marketplace. The plugin’s [trust tier](</docs/en/plugins/security#find-plugins-in-telemetry>) decides which. To get real names on some events, set the [`OTEL_LOG_TOOL_DETAILS`](</docs/en/monitoring-usage#common-configuration-variables>) environment variable to `1` on the machines that export telemetry, for example in the `env` block of the same [managed settings](</docs/en/monitoring-usage#administrator-configuration>) that configure the exporter: @@ -163,19 +119,11 @@ On `plugin_loaded`, `plugin_id_hash` still identifies each plugin by default, so you can count distinct third-party plugins. -### - -​ - -Query the Analytics API +### Query the Analytics API On the Enterprise plan, the Analytics API answers “which plugins does my organization install and invoke” from Anthropic’s records, with no exporter needed. [`GET /v1/organizations/analytics/plugins`](<https://platform.claude.com/docs/en/api/admin/analytics/plugins/list>) returns per-plugin, per-day install and invocation counts across Claude Code and Cowork, which you can group by user, RBAC group, or product. Plugin activity that reaches Anthropic without a plugin name appears in one aggregate `third-party` row. [Find plugins in telemetry](</docs/en/plugins/security#find-plugins-in-telemetry>) says which plugins Claude Code reports by name. Authenticate the request with an API key that has the `read:analytics` scope, which a Primary Owner creates as described under [Access data programmatically](</docs/en/analytics#access-data-programmatically>). See the [endpoint reference](<https://platform.claude.com/docs/en/api/admin/analytics/plugins/list>) for the parameters and response fields. -## - -​ - -Next steps +## Next steps * [Test plugins with evals](</docs/en/plugin-evals>): measure how reliably the plugin steers Claude, not only what it costs * Lower the always-on figure: what to change in the plugin to reduce its per-turn cost
modified How Claude remembers your project View current →
Show diff (493 lines)
--- a/memory.md +++ b/memory.md @@ -11,11 +11,7 @@ * Configure auto memory so Claude takes notes automatically * Troubleshoot when instructions aren’t being followed -## - -​ - -CLAUDE.md vs auto memory +## CLAUDE.md vs auto memory Claude Code has two complementary memory systems. Both are loaded at the start of every conversation. Claude treats them as context, not enforced configuration. To block an action regardless of what Claude decides, use a [PreToolUse hook](</docs/en/hooks-guide>) instead. The more specific and concise your instructions, the more consistently Claude follows them. @@ -29,19 +25,11 @@ Use CLAUDE.md files when you want to guide Claude’s behavior. Auto memory lets Claude learn from your corrections without manual effort. Subagents can also maintain their own auto memory. See [subagent configuration](</docs/en/sub-agents#enable-persistent-memory>) for details. -## - -​ - -CLAUDE.md files +## CLAUDE.md files CLAUDE.md files are markdown files that give Claude persistent instructions for a project, your personal workflow, or your entire organization. You write these files in plain text; Claude reads them at the start of every session. If your repository uses `AGENTS.md` instead, see AGENTS.md. -### - -​ - -When to add to CLAUDE.md +### When to add to CLAUDE.md Treat CLAUDE.md as the place you write down what you’d otherwise re-explain. Add to it when: @@ -52,11 +40,7 @@ Keep it to facts Claude should hold in every session: build commands, conventions, project layout, “always do X” rules. If an entry is a multi-step procedure or only matters for one part of the codebase, move it to a [skill](</docs/en/skills>) or a path-scoped rule instead. The [extension overview](</docs/en/features-overview#build-your-setup-over-time>) covers when to use each mechanism. -### - -​ - -Choose where to put CLAUDE.md files +### Choose where to put CLAUDE.md files CLAUDE.md files can live in several locations, each with a different scope. The table below lists them in load order, from broadest scope to most specific, so a project instruction appears in context after a user instruction. @@ -71,21 +55,13 @@ CLAUDE.md and CLAUDE.local.md files in the directory hierarchy above the working directory are loaded at launch. Files in subdirectories load on demand. See How CLAUDE.md files load for when they load and the full resolution order. For large projects, you can break instructions into topic-specific files using project rules. Rules let you scope instructions to specific file types or subdirectories. -### - -​ - -Set up a project CLAUDE.md +### Set up a project CLAUDE.md A project CLAUDE.md can be stored in either `./CLAUDE.md` or `./.claude/CLAUDE.md`. Create this file and add instructions that apply to anyone working on the project: build and test commands, coding standards, architectural decisions, naming conventions, and common workflows. These instructions are shared with your team through version control, so focus on project-level standards rather than personal preferences. To confirm the file loaded, run [`/context all`](</docs/en/commands#all-commands>) in a session and check the list under **Memory files**. In [fullscreen mode](</docs/en/fullscreen>), `/context` alone collapses that list. Run `/init` to generate a starting CLAUDE.md automatically. Claude analyzes your codebase and creates a file with build commands, test instructions, and project conventions it discovers. If a CLAUDE.md already exists, `/init` suggests improvements rather than overwriting it. Refine from there with instructions Claude wouldn’t discover on its own.For an interactive multi-phase flow instead, set the `CLAUDE_CODE_NEW_INIT` environment variable to `1` before you run `/init`. Set it in your shell or in the `env` block of a settings file, as shown in [Set environment variables](</docs/en/env-vars#set-environment-variables>). With it set, `/init` asks which artifacts to set up: CLAUDE.md files, skills, and hooks. It then explores your codebase with a subagent, fills in gaps via follow-up questions, and presents a reviewable proposal before writing any files. The variable only changes how `/init` runs, so you can leave it set. -### - -​ - -Write effective instructions +### Write effective instructions Claude treats CLAUDE.md files as context, not enforced configuration, so how you write instructions affects how reliably Claude follows them. Write instructions that are concrete enough to verify: @@ -99,19 +75,11 @@ * **Structure** : group related instructions under markdown headers and bullets. Organized sections are easier for Claude to follow than dense paragraphs. * **Consistency** : if two instructions contradict each other, Claude may pick one arbitrarily. Review your CLAUDE.md files, nested CLAUDE.md files in subdirectories, and `.claude/rules/` periodically to remove outdated or conflicting instructions. To have Claude find them for you, run a prompt audit. -#### - -​ - -Audit your instruction files +#### Audit your instruction files To have Claude check your instruction files for outdated or conflicting content, run `/doctor prompt-audit` in a session. Claude looks for problems such as instructions written for older models, references to files or commands that don’t exist, and files that contradict each other. You get a report of findings with proposed edits, and nothing in your files changes until you ask Claude to apply them. By default, the audit covers your CLAUDE.md, CLAUDE.local.md, and AGENTS.md files, plus the rules, skills, commands, subagents, and output styles under `.claude/` and `~/.claude/`. To audit one file or directory instead, pass its path, for example `/doctor prompt-audit .claude/skills/deploy`. The audit runs through the bundled `/claude-api` skill. It’s unavailable while that skill is turned off in [`skillOverrides`](</docs/en/skills#override-skill-visibility-from-settings>) or with [`disableBundledSkills`](</docs/en/settings-reference#disablebundledskills>). `/doctor prompt-audit` requires Claude Code v2.1.283 or later. -### - -​ - -Import additional files +### Import additional files CLAUDE.md files can import additional files using `@path/to/import` syntax. Imported files are expanded and loaded into context alongside the CLAUDE.md that references them. Both relative and absolute paths are allowed. Relative paths resolve relative to the file containing the import, not the working directory. Imported files can recursively import other files, with a maximum depth of four hops. To import a file whose path contains spaces, put a backslash before each space. Without the backslashes, the path ends at the first space, even when the import is on a line of its own. A path wrapped in quotes isn’t imported at all, with or without the backslashes. This import loads a file from a folder named `Design Docs`: @@ -131,19 +99,11 @@ An import in a project-level memory file is external when its path resolves outside your working directory, like the home directory import above. The first time Claude Code encounters external imports in a project, it shows an approval dialog listing the files. If you decline, the imports stay disabled and the dialog doesn’t appear again.Claude Code shows the dialog to protect you from files other people commit to a shared project. User-scope memory files, such as `~/.claude/CLAUDE.md` and `~/.claude/rules/`, are files you wrote yourself. Except in [Cowork](<https://claude.com/product/cowork>) sessions on your desktop, Claude Code loads their imports without the dialog and trusts them like the rest of your personal configuration.In Cowork sessions on your desktop, Claude Code skips any import in a user-scope file that resolves to a path outside the session’s working directory and loads the rest of the file. In those sessions it also skips a `~/.claude/CLAUDE.md` that is itself a symlink or hard link, and a symlinked `~/.claude/rules/` directory or rule file that points outside the working directory. -### - -​ - -How CLAUDE.md files load +### How CLAUDE.md files load Claude Code loads `CLAUDE.md` and `CLAUDE.local.md` from your current working directory and every directory above it. Run Claude Code in `foo/bar/` and it loads instructions from `foo/bar/CLAUDE.md`, `foo/CLAUDE.md`, and any `CLAUDE.local.md` files alongside them. All discovered files are concatenated into context rather than overriding each other. Across the directory tree, content is ordered from the filesystem root down to your working directory. For the `foo/bar/` example, `foo/CLAUDE.md` appears in context before `foo/bar/CLAUDE.md`, so instructions closer to where you launched Claude are read last. Within each directory, `CLAUDE.local.md` is appended after `CLAUDE.md`, so your personal notes are the last thing Claude reads at that level. Claude also discovers `CLAUDE.md` and `CLAUDE.local.md` files in subdirectories under your current working directory. Instead of loading them at launch, Claude Code loads each one once Claude reads, writes, or edits another file in that subdirectory. Reading includes viewing the file with a Bash command that [counts as a read](</docs/en/tools-reference#edit-tool-behavior>), such as `cat` or `head` on a single file. For files inside a worktree under `.claude/worktrees/`, see [Isolate subagents with worktrees](</docs/en/worktrees#isolate-subagents-with-worktrees>). If you work in a large monorepo where other teams’ CLAUDE.md files get picked up, use `claudeMdExcludes` to skip them. For the full layout of root and per-directory CLAUDE.md files and rules, see [Monorepos and large repos](</docs/en/large-codebases>). Block-level HTML comments (`<!-- maintainer notes -->`) in CLAUDE.md files are stripped before the content is injected into Claude’s context. Use them to leave notes for human maintainers without spending context tokens on them. Comments inside code blocks are preserved. When you open a CLAUDE.md file directly with the Read tool, comments remain visible. -#### - -​ - -Load from additional directories +#### Load from additional directories The `--add-dir` flag gives Claude access to additional directories outside your main working directory. By default, CLAUDE.md files from these directories are not loaded. To also load memory files from additional directories, set the `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD` environment variable: @@ -151,21 +111,13 @@ The inline form sets the variable for that one launch in Bash or Zsh. To keep it on for every session, add it to the `env` block in `~/.claude/settings.json` as shown in [Set environment variables](</docs/en/env-vars#set-environment-variables>). With the variable set, Claude Code loads the additional directory’s `CLAUDE.md`, `.claude/CLAUDE.md`, `CLAUDE.local.md`, and `.claude/rules/*.md` files except rules that set a `paths` field. `CLAUDE.local.md` is skipped if you exclude `local` from [`--setting-sources`](</docs/en/cli-reference>). -### - -​ - -Organize rules with `.claude/rules/` +### Organize rules with `.claude/rules/` For larger projects, you can organize instructions into multiple files using the `.claude/rules/` directory. This keeps instructions modular and easier for teams to maintain. Rules can also be scoped to specific file paths, so they only load into context when Claude works with matching files, reducing noise and saving context space. Rules load into context every session or when matching files are opened. For task-specific instructions that don’t need to be in context all the time, use [skills](</docs/en/skills>) instead, which only load when you invoke them or when Claude determines they’re relevant to your prompt. -#### - -​ - -Set up rules +#### Set up rules Place markdown files in your project’s `.claude/rules/` directory. Each file should cover one topic, with a descriptive filename like `testing.md` or `api-design.md`. All `.md` files are discovered recursively, so you can organize rules into subdirectories like `frontend/` or `backend/`: @@ -179,11 +131,7 @@ Rules without `paths` frontmatter are loaded at launch with the same priority as `.claude/CLAUDE.md`. Project rules are skipped if you exclude `project` from [`--setting-sources`](</docs/en/cli-reference>). Before v2.1.211, rules that load on demand, including path-scoped rules and rules in nested `.claude/rules/` directories, loaded even when `project` was excluded. -#### - -​ - -Path-specific rules +#### Path-specific rules Rules can be scoped to specific files using YAML frontmatter with the `paths` field. These conditional rules only apply when Claude is working with files matching the specified patterns. @@ -224,11 +172,7 @@ Each brace group multiplies the number of expanded patterns: `src/*.{ts,tsx}` expands to two patterns, and `{a,b}/{c,d}/*.{ts,tsx}` to eight. To keep expansion bounded, a rule’s whole `paths` list shares one budget of 1,000 expanded patterns and 4 MiB, and patterns without braces don’t count against it. Claude Code uses any pattern that would exceed the budget unexpanded, and its literal braces match no files. Glob syntax treats `[` as the start of a bracket expression such as `[abc]`. A pattern with a `[` that can’t be read as a bracket expression, such as `photos [2024/**`, is invalid: it matches nothing, and the rule’s other patterns keep working. To match a literal `[` in a file name, escape it as `photos \[2024/**`. -#### - -​ - -Rule frontmatter reference +#### Rule frontmatter reference Configure a rule with YAML [frontmatter](</docs/en/glossary#frontmatter>) between `---` markers at the top of the file. `paths` is the only field Claude Code reads from a rule; any other field is ignored without an error. Claude Code removes the frontmatter before loading the rule into context. @@ -238,11 +182,7 @@ If the YAML between the markers doesn’t parse, Claude Code ignores the frontmatter and loads the rule as if it had no `paths`. Run `claude --debug` to see the parse error. -#### - -​ - -Share rules across projects with symlinks +#### Share rules across projects with symlinks The `.claude/rules/` directory supports symlinks, so you can maintain a shared set of rules and link them into multiple projects. Circular symlinks are detected and handled gracefully. Claude Code treats a symlink whose target is outside your working directory like an external import. The linked rules don’t load until you approve external imports for the project, and after that only the ones without a `paths` field load. Claude Code asks for that approval once per project, in a dialog at the start of an interactive session. The dialog lists the linked rule files alongside any external `@path` imports. To load shared rules without that approval, keep them in `~/.claude/rules/`, where they apply to every project on your machine. This example links both a shared directory and an individual file: @@ -251,11 +191,7 @@ If you point a `.claude/rules/` or `CLAUDE.md` symlink at a network path such as the UNC share `\\server\share` or a path under `/net` or `/Network`, the linked instructions don’t load. Claude Code doesn’t follow the link, because looking up such a path can contact the host it names. `\\wsl$` paths don’t count as network paths. -#### - -​ - -User-level rules +#### User-level rules Personal rules in `~/.claude/rules/` apply to every project on your machine. Use them for preferences that aren’t project-specific: @@ -265,19 +201,11 @@ Claude Code loads user-level rules before project rules, so a project rule appears later in Claude’s context than a user rule. Neither set overrides the other: if a user rule and a project rule conflict, Claude may follow either one, so keep the two consistent. -### - -​ - -Manage CLAUDE.md for large teams +### Manage CLAUDE.md for large teams For organizations deploying Claude Code across teams, you can centralize instructions and control which CLAUDE.md files are loaded. -#### - -​ - -Deploy organization-wide CLAUDE.md +#### Deploy organization-wide CLAUDE.md Organizations can deploy a centrally managed CLAUDE.md that applies to all users on a machine. Developers can exclude other CLAUDE.md files with the `claudeMdExcludes` setting, but not this one. If a developer starts a session with CLAUDE.md loading turned off altogether, that session doesn’t load the managed content either. Use the file for guidance, and enforce rules with [managed settings](</docs/en/managed-settings>) such as `permissions.deny`. @@ -315,11 +243,7 @@ Settings rules are enforced by the client regardless of what Claude decides to do. CLAUDE.md instructions shape Claude’s behavior but are not a hard enforcement layer. -#### - -​ - -Exclude specific CLAUDE.md files +#### Exclude specific CLAUDE.md files In large monorepos, ancestor CLAUDE.md files may contain instructions that aren’t relevant to your work. The `claudeMdExcludes` setting lets you skip specific files by path or glob pattern. You can’t exclude a managed CLAUDE.md file with `claudeMdExcludes`. This example excludes a top-level CLAUDE.md and a rules directory from a parent folder. Add it to `.claude/settings.local.json` so the exclusion stays local to your machine: @@ -332,11 +256,7 @@ Patterns are matched against absolute file paths using glob syntax. You can configure `claudeMdExcludes` at any [settings layer](</docs/en/settings#where-settings-live>): user, project, local, or managed policy. Arrays merge across layers. To exclude a rules file you reach through a symlink, whether the file or its directory is the link, write the pattern against either path: the file’s path under `.claude/rules/` or its link target. A pattern that matches either path excludes the file. Before v2.1.239, only a pattern that matched the link target excluded the file. -## - -​ - -AGENTS.md +## AGENTS.md Claude Code can read [`AGENTS.md`](</docs/en/glossary#agents-md>) as your project instructions, so a repository already set up for other coding agents works without adding a `CLAUDE.md`, an import, or a setting. This table shows what Claude reads by default for each combination of instruction files in your repository: @@ -350,11 +270,7 @@ Reading `AGENTS.md` directly requires Claude Code v2.1.277 or later. In some sessions Claude can’t read `AGENTS.md`, so import it from a `CLAUDE.md` there instead. -### - -​ - -When Claude Code reads AGENTS.md +### When Claude Code reads AGENTS.md By default, Claude reads `AGENTS.md` only when you have no `CLAUDE.md` in your working directory or above it. Here’s which of your files count for that check: @@ -370,11 +286,7 @@ Because `CLAUDE.local.md` counts, adding one to keep your own uncommitted instructions in a project that relies on `AGENTS.md` stops Claude from reading `AGENTS.md` for you. To keep your `CLAUDE.local.md` and still have Claude read `AGENTS.md`, set **Project instructions** to `claude-md-and-agents-md`. -### - -​ - -Choose which instruction files load +### Choose which instruction files load To change which files Claude reads, type `/config` in a Claude Code session to open the settings panel, then set **Project instructions** to one of these values: @@ -399,11 +311,7 @@ Before v2.1.285, the plugin’s ID was `agents-md@builtin`, and Claude Code ignored an entry under `cc-plugin-agents-md@builtin`. If earlier versions also read your settings file, use `agents-md@builtin` there. Claude Code v2.1.285 and later reads an entry under either ID. Your change applies from the next message you send and in every new session. -### - -​ - -When AGENTS.md support is unavailable +### When AGENTS.md support is unavailable In these sessions Claude reads `CLAUDE.md` files only, and **Project instructions** doesn’t appear in the `/config` settings panel: @@ -413,11 +321,7 @@ Before v2.1.281, some sessions, such as those on Amazon Bedrock or with telemetry disabled, read `CLAUDE.md` files only. On those versions, update Claude Code. To give Claude your `AGENTS.md` in any of these sessions, import it from a `CLAUDE.md`. -### - -​ - -Where AGENTS.md differs from CLAUDE.md +### Where AGENTS.md differs from CLAUDE.md An `AGENTS.md` that Claude reads through the **Project instructions** setting differs from a `CLAUDE.md` in these places: @@ -427,11 +331,7 @@ Directories you add with `--add-dir` while `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD` is set| Their `CLAUDE.md` loads| Their `AGENTS.md` doesn’t load An `@path` import of a file outside your working directory| Claude Code asks you to approve external imports| Loads only if you already approved external imports for this project, with no prompt -### - -​ - -Remove an earlier AGENTS.md workaround +### Remove an earlier AGENTS.md workaround If you set Claude Code up to read `AGENTS.md` before it did so on its own, here’s what to do with each common setup: @@ -440,11 +340,7 @@ * **A`CLAUDE.md` symlinked to `AGENTS.md`**: nothing, or delete the symlink. Either way Claude reads the content once. * **A`SessionStart` hook that prints `AGENTS.md`**: remove it. Once Claude reads `AGENTS.md` directly, the hook adds a second copy to the context. -### - -​ - -Share one file with other coding tools +### Share one file with other coding tools When Claude isn’t reading your `AGENTS.md` directly, you can still keep it as the one file every tool shares by putting an `@AGENTS.md` import in a `CLAUDE.md` next to it. Do this when your project also has a `CLAUDE.md`, when you’ve set **Project instructions** to `claude-md`, or in sessions that can’t load `AGENTS.md`. Add any Claude-specific instructions below the import, and Claude reads the imported file first, then the rest: @@ -467,11 +363,7 @@ With either approach, run `/context all` in your next session and confirm `CLAUDE.md` appears under **Memory files**. -### - -​ - -Migrate instructions from other tools +### Migrate instructions from other tools Running [`/init`](</docs/en/commands>) reads other tools’ instruction files and incorporates the relevant parts into the generated `CLAUDE.md`: @@ -481,11 +373,7 @@ You can also run [`/import`](</docs/en/commands>) to bring a supported coding agent’s configuration into Claude Code, which appends a one-time copy of instruction files such as `AGENTS.md` to the matching `CLAUDE.md` and carries over MCP servers, commands, subagents, and skills. -## - -​ - -Auto memory +## Auto memory Auto memory lets Claude accumulate knowledge across sessions without you writing anything. As it works, Claude saves four kinds of notes for itself. Claude records the kind as a `type` field in the memory file’s frontmatter: @@ -496,11 +384,7 @@ Claude skips anything it can derive from the codebase, such as architecture, file paths, or debugging fixes. It also skips anything your CLAUDE.md files already say. Claude doesn’t save something every session. It decides what’s worth remembering based on whether the information would be useful in a future conversation. -### - -​ - -Enable or disable auto memory +### Enable or disable auto memory Auto memory is on by default in local sessions. Outside [Claude Tag](<https://claude.com/docs/claude-tag/overview>) sessions, a session in a [self-hosted environment](</docs/en/self-hosted-environments-configuration#how-each-session%E2%80%99s-config-is-assembled>) runs with auto memory off by default. To toggle it, open `/memory` in a session and use the auto memory toggle, which saves `autoMemoryEnabled` to your user settings at `~/.claude/settings.json`. The toggle turns auto memory off but doesn’t turn it back on in these sessions: @@ -515,11 +399,7 @@ To disable auto memory via environment variable, set `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1`. -### - -​ - -Storage location +### Storage location Each project gets its own memory directory at `~/.claude/projects/<project>/memory/`. The `<project>` path is derived from the git repository, so all worktrees and subdirectories within the same repo share one auto memory directory. Outside a git repo, the project root is used instead. If you set [`CLAUDE_CODE_PROJECT_DIR_NAME`](</docs/en/sessions#name-the-project-directory-yourself>) beside `CLAUDE_CONFIG_DIR`, Claude Code uses that name as the `<project>` directory under `<config dir>/projects/` instead, whichever repository you launch it in, so projects launched with that config directory share one auto memory directory. Requires Claude Code v2.1.234 or later. To store auto memory in a different location, set `autoMemoryDirectory` in your `settings.json`. It is read from any [settings scope](</docs/en/settings#settings-precedence>): user, project, local, policy, or `--settings`. @@ -537,11 +417,7 @@ `MEMORY.md` acts as an index of the memory directory. Claude reads and writes files in this directory throughout your session, using `MEMORY.md` to keep track of what’s stored where. Auto memory is machine-local. All worktrees and subdirectories within the same git repository share one auto memory directory. Files are not shared across machines or cloud environments. Claude Code deletes old session transcripts after the [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>) retention period, but excludes the memory files in the memory directory from that [retention sweep](</docs/en/claude-directory#cleaned-up-automatically>). `MEMORY.md` and topic files stay until you or Claude edits or deletes them. -### - -​ - -How it works +### How it works The first 200 lines of `MEMORY.md`, or the first 25KB, whichever comes first, are loaded at the start of every conversation. Content beyond that threshold is not loaded at session start. Claude keeps `MEMORY.md` concise by moving detailed notes into separate topic files. After Claude writes to `MEMORY.md`, Claude Code measures the file against the 200-line and 25KB read limits. If the file is near a limit, Claude Code reminds Claude to shorten it: keep one line per entry, move detail into topic files, and merge or drop stale entries. If the file is over a limit, the write still succeeds, but Claude Code returns an [error telling Claude to rewrite the index](</docs/en/errors#memory-index-is-over-its-read-limit>), because everything past the limit is dropped on the next load. @@ -549,35 +425,19 @@ Claude Code doesn’t load topic files such as `user_role.md` or `feedback_testing.md` at startup. Claude reads them on demand using its standard file tools when it needs the information. The main conversation’s auto memory isn’t loaded into [subagents](</docs/en/sub-agents#what-loads-at-startup>); the exception is a [fork](</docs/en/sub-agents#fork-the-current-conversation>), which inherits the parent conversation and system prompt. A subagent’s own auto memory, enabled with the subagent `memory` field, is a separate directory. Claude reads and writes memory files during your session. When you see messages like “Saved 2 memories” or “Recalled 2 memories” in the Claude Code interface, Claude is actively updating or reading from `~/.claude/projects/<project>/memory/`. When Claude writes a memory file that begins with YAML frontmatter, Claude Code records the write time in a `modified` frontmatter field as an ISO 8601 timestamp. The timestamp shows how current the fact is, both to you and to Claude when it reads the memory back. -### - -​ - -Audit and edit your memory +### Audit and edit your memory Auto memory files are plain markdown you can edit or delete at any time. Run `/memory` to browse and open memory files from within a session. -## - -​ - -View and edit with `/memory` +## View and edit with `/memory` The `/memory` command lists your CLAUDE.md, CLAUDE.local.md, and other memory file locations across user and project scopes. The list includes user and project CLAUDE.md entries for files that don’t exist yet. The command also lets you toggle auto memory on or off and provides an option to open the auto memory folder. Select any file to open it in your editor; selecting one that doesn’t exist yet creates it first. GUI editors such as VS Code open the file in a separate window, and you can keep using the session while it’s open. Terminal editors such as Vim take over the terminal until you exit. When you ask Claude to remember something, like “always use pnpm, not npm” or “remember that the API tests require a local Redis instance,” Claude saves it to auto memory. To add instructions to CLAUDE.md instead, ask Claude directly, like “add this to CLAUDE.md,” or edit the file yourself via `/memory`. -## - -​ - -Troubleshoot memory issues +## Troubleshoot memory issues These are the most common issues with CLAUDE.md and auto memory, along with steps to debug them. -### - -​ - -Claude isn’t following my CLAUDE.md +### Claude isn’t following my CLAUDE.md CLAUDE.md content is delivered as a user message after the system prompt, not as part of the system prompt itself. Claude reads it and tries to follow it, but there’s no guarantee of strict compliance, especially for vague or conflicting instructions. To debug: @@ -593,11 +453,7 @@ Use the [`InstructionsLoaded` hook](</docs/en/hooks#instructionsloaded>) to log which `CLAUDE.md` and rules files are loaded, when they load, and why. This is useful for debugging path-specific rules or lazy-loaded files in subdirectories. -### - -​ - -My AGENTS.md isn’t loading +### My AGENTS.md isn’t loading If your repository has an `AGENTS.md` and Claude doesn’t seem to know what it says, the usual cause is a `CLAUDE.md` somewhere on the project path. By default Claude reads `AGENTS.md` only when you have no `CLAUDE.md` or `CLAUDE.local.md` in your working directory or above it. Check these in order: @@ -607,29 +463,17 @@ To check whether Claude read your `AGENTS.md`, run `/memory` and look for its path in the list. Before v2.1.280, `/memory` and `/context` didn’t list an `AGENTS.md` that Claude read directly. On those versions, ask Claude what its project instructions say instead. If you want to keep the `CLAUDE.md` you found, or your session can’t load `AGENTS.md`, add a `CLAUDE.md` next to your `AGENTS.md` that imports it. -### - -​ - -I don’t know what auto memory saved +### I don’t know what auto memory saved Run `/memory` and select the auto memory folder to browse what Claude has saved. Everything is plain markdown you can read, edit, or delete. -### - -​ - -My CLAUDE.md is too large +### My CLAUDE.md is too large Files over 200 lines consume more context and may reduce adherence. Claude Code skips a file over 4 MiB. Use path-scoped rules to load instructions only when Claude works with matching files, or trim content that isn’t needed in every session. Splitting into `@path` imports helps organization but doesn’t reduce context, since imported files load with the CLAUDE.md importing them. If one of your instruction files is over the recommended length, you see a warning at startup and when you run `/status`. You also see a warning when files that are each within that length add up past a combined limit at session start. Each CLAUDE.md, rules file, and `@path` import counts as a separate file. The [`/doctor`](</docs/en/commands#all-commands>) checkup proposes trims for a checked-in CLAUDE.md: it cuts content Claude can derive from the codebase, such as directory layouts, dependency lists, and architecture overviews, and keeps pitfalls, rationale, and conventions that differ from tool defaults. Keep each path-scoped rules file within its own per-file size limit, because Claude receives only the start of a file that’s over it. -### - -​ - -Claude ignores the end of my subdirectory CLAUDE.md +### Claude ignores the end of my subdirectory CLAUDE.md When a subdirectory `CLAUDE.md` or a rules file that loads on demand is over a per-file size limit, Claude receives only the start of it. That part ends with a note telling Claude to read the rest with the Read tool, and until Claude chooses to, the later instructions aren’t in its context. Check whether your file is over the limit, and shrink it if it is: @@ -647,19 +491,11 @@ Before v2.1.309, Claude Code didn’t apply this limit to files that load on demand. -### - -​ - -Instructions seem lost after `/compact` +### Instructions seem lost after `/compact` Project-root CLAUDE.md survives compaction: after `/compact`, Claude re-reads it from disk and re-injects it into the session. Nested CLAUDE.md files in subdirectories and rules with `paths:` frontmatter load again on demand. If an instruction disappeared after compaction, it was given only in conversation, lives in a nested CLAUDE.md that hasn’t reloaded yet, or is a path-scoped rule that hasn’t matched a file since. Add conversation-only instructions to CLAUDE.md to make them persist. See [What survives compaction](</docs/en/context-window#what-survives-compaction>) for the full breakdown. See Write effective instructions for guidance on size, structure, and specificity. -## - -​ - -Related resources +## Related resources * [Debug your configuration](</docs/en/debug-your-config>): diagnose why CLAUDE.md or settings aren’t taking effect * [Skills](</docs/en/skills>): package repeatable workflows that load on demand
modified Claude Code on Microsoft Foundry View current →
Show diff (184 lines)
--- a/microsoft-foundry.md +++ b/microsoft-foundry.md @@ -1,8 +1,4 @@ -## - -​ - -Prerequisites +## Prerequisites Before configuring Claude Code with Microsoft Foundry, ensure you have: @@ -12,17 +8,9 @@ If you are deploying Claude Code to multiple users, pin your model versions before rolling out. -## +## Setup -​ - -Setup - -### - -​ - -1\. Provision Microsoft Foundry resource +### 1\. Provision Microsoft Foundry resource First, create a Claude resource in Azure: @@ -34,11 +22,7 @@ * Claude Haiku When you configure a deployment, you also choose its [hosting option](<https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry#hosting-options>), which determines whether inference runs on Azure or on Anthropic infrastructure. -### - -​ - -2\. Configure Azure credentials +### 2\. Configure Azure credentials Claude Code supports three authentication methods for Microsoft Foundry. Choose the method that best fits your security requirements: @@ -48,11 +32,7 @@ When using Microsoft Foundry, the `/logout` command is unavailable since authentication is handled through Azure credentials. -#### - -​ - -Use an API key +#### Use an API key Copy a key from the Microsoft Foundry portal, then set it as an environment variable: @@ -63,11 +43,7 @@ export ANTHROPIC_FOUNDRY_API_KEY=your-azure-api-key -#### - -​ - -Use Microsoft Entra ID +#### Use Microsoft Entra ID Leave `ANTHROPIC_FOUNDRY_API_KEY` and `ANTHROPIC_FOUNDRY_AUTH_TOKEN` unset. Claude Code then uses the Azure SDK [default credential chain](<https://learn.microsoft.com/en-us/azure/developer/javascript/sdk/authentication/credential-chains#defaultazurecredential-overview>). This supports a variety of methods for authenticating local and remote workloads. On a local machine, sign in with the Azure CLI: @@ -75,11 +51,7 @@ For the roles your identity needs, see Azure RBAC configuration. -#### - -​ - -Use a bearer token +#### Use a bearer token Claude Code sends the value of `ANTHROPIC_FOUNDRY_AUTH_TOKEN` on every request as the `Authorization: Bearer` header. Use this option when another process, such as a host application or a sign-in script, has already obtained an access token for you. Set the variable to a bearer token that Microsoft Entra ID issued for your resource: @@ -87,11 +59,7 @@ `ANTHROPIC_FOUNDRY_AUTH_TOKEN` takes precedence over `ANTHROPIC_FOUNDRY_API_KEY` and over the default credential chain. -### - -​ - -3\. Configure Claude Code +### 3\. Configure Claude Code Set the following environment variables to enable Microsoft Foundry: @@ -105,11 +73,7 @@ Set `ANTHROPIC_FOUNDRY_RESOURCE` to the resource name alone, such as `my-resource`. Claude Code [refuses a URL or host name](</docs/en/errors#anthropic-foundry-resource-must-be-a-foundry-resource-name>) when you send a message. -### - -​ - -4\. Pin model versions +### 4\. Pin model versions Pin specific model versions for every deployment. Without pinning, model aliases such as `sonnet` and `opus` resolve to Claude Code’s built-in default for Microsoft Foundry, which can lag the newest release and may not yet be available in your account. Microsoft Foundry has no startup model check, so requests fail when the default is unavailable. When you create Azure deployments, select a specific model version rather than “auto-update to latest.” @@ -125,11 +89,7 @@ To set different TTLs for your main conversation and for the requests Claude Code makes outside it, [choose the TTL yourself](</docs/en/prompt-caching#choose-the-ttl-yourself>). -### - -​ - -5\. Run Claude Code +### 5\. Run Claude Code With the environment variables set, start Claude Code from your project directory: @@ -137,31 +97,11 @@ Claude Code reads `CLAUDE_CODE_USE_FOUNDRY` and the other Microsoft Foundry variables from the environment and connects to your Azure resource on the first prompt. Unlike Amazon Bedrock and Google Cloud’s Agent Platform, Microsoft Foundry has no interactive setup wizard, so the environment variables in steps 3 and 4 are the only configuration path. To verify your setup, run `/status` inside Claude Code. The API provider line shows `Microsoft Foundry`, along with the resource name or base URL you configured. -## +## Azure RBAC configuration -​ +If you authenticate with Microsoft Entra ID or a bearer token it issued, assign your identity the `Foundry User` or `Cognitive Services User` role on your Foundry resource. You might still see `Foundry User` under its previous name, `Azure AI User`. If these roles don’t meet your needs, see [Microsoft Foundry RBAC documentation](<https://learn.microsoft.com/en-us/azure/foundry/concepts/rbac-foundry>) for custom roles. -Azure RBAC configuration - -The `Azure AI User` and `Cognitive Services User` default roles include all required permissions for invoking Claude models. For more restrictive permissions, create a custom role with the following: - - { - "permissions": [ - { - "dataActions": [ - "Microsoft.CognitiveServices/accounts/providers/*" - ] - } - ] - } - -For details, see [Microsoft Foundry RBAC documentation](<https://learn.microsoft.com/en-us/azure/ai-foundry/concepts/rbac-azure-ai-foundry>). - -## - -​ - -1M token context window +## 1M token context window On Microsoft Foundry, when Claude Code can tell which model your deployment serves, Fable models, Sonnet 5 and later, and Opus 4.7 and later run with the [1M token context window](<https://platform.claude.com/docs/en/build-with-claude/context-windows#context-window-sizes-by-model>) by default, with no `[1m]` suffix needed. Claude Code reads the model from the deployment name in your model variables. Name each deployment with its model ID, such as `claude-opus-4-8`, or map the model to your deployment name with [`modelOverrides`](</docs/en/model-config#override-model-ids-per-version>). For a deployment name it can’t match to a model, Claude Code assumes a 200K window unless you [declare a different one](</docs/en/model-config#correct-the-window-for-a-gateway-or-custom-model-id>). This `settings.json` entry tells Claude Code that a deployment named `team-opus-prod` serves Opus 4.8: @@ -173,11 +113,7 @@ To keep a 200K window instead, set [`CLAUDE_CODE_DISABLE_1M_CONTEXT=1`](</docs/en/model-config#turn-off-1m-context>). Opus 4.6 and Sonnet 4.6 reach the 1M window when you append `[1m]` to the deployment name in `ANTHROPIC_DEFAULT_OPUS_MODEL` or `ANTHROPIC_DEFAULT_SONNET_MODEL`, as [Pin models for third-party deployments](</docs/en/model-config#pin-models-for-third-party-deployments>) describes. Before v2.1.287, the Fable models and Opus 4.7 and later also needed that suffix on Microsoft Foundry and ran with a 200K window by default without it. -## - -​ - -Troubleshooting +## Troubleshooting If you receive an error “Failed to get token from azureADTokenProvider: ChainedTokenCredential authentication failed”: @@ -187,11 +123,7 @@ * Check that `ANTHROPIC_FOUNDRY_RESOURCE` is set to your actual resource name rather than a placeholder. Claude Code builds the endpoint URL from this value, so an incorrect name points at a host that doesn’t exist. -## - -​ - -Additional resources +## Additional resources * [Microsoft Foundry documentation](<https://learn.microsoft.com/en-us/azure/ai-foundry/what-is-azure-ai-foundry>) * [Microsoft Foundry models](<https://ai.azure.com/explore/models>)
modified Migrate to Claude Agent SDK View current →
Show diff (113 lines)
--- a/migration-guide.md +++ b/migration-guide.md @@ -1,16 +1,8 @@ -## - -​ - -Overview +## Overview The Claude Code SDK has been renamed to the **Claude Agent SDK** and its documentation has been reorganized. This change reflects the SDK’s broader capabilities for building AI agents beyond coding tasks. Migrating from the OpenAI Agents SDK instead? The [OpenAI Agents SDK migration recipe](<https://platform.claude.com/cookbook/claude-agent-sdk-04-migrating-from-openai-agents-sdk>) maps each primitive onto the Claude Agent SDK through a single worked example. -## - -​ - -What’s Changed +## What’s Changed Aspect| Old| New ---|---|--- @@ -18,17 +10,9 @@ **Python Package**| `claude-code-sdk`| `claude-agent-sdk` **Documentation Location**| Claude Code docs| Claude Code docs → dedicated [Agent SDK](</docs/en/agent-sdk/overview>) section -## +## Migration Steps -​ - -Migration Steps - -### - -​ - -Migrate a TypeScript or JavaScript project +### Migrate a TypeScript or JavaScript project **1\. Uninstall the old package:** @@ -48,11 +32,7 @@ **4\. Update package.json:** If `@anthropic-ai/claude-code` is still listed in your `package.json`, replace it with `@anthropic-ai/claude-agent-sdk` and update the version range as well, for example from `"^0.0.42"` to `"^0.3.0"`. **5\. Reviewbreaking changes** Make any code changes needed to complete the migration. -### - -​ - -Migrate a Python project +### Migrate a Python project **1\. Uninstall the old package:** @@ -72,19 +52,11 @@ **4\. Reviewbreaking changes** Make any code changes needed to complete the migration. -## - -​ - -Breaking changes +## Breaking changes To improve isolation and explicit configuration, Claude Agent SDK v0.1.0 introduces breaking changes for users migrating from Claude Code SDK. -### - -​ - -Python: ClaudeCodeOptions renamed to ClaudeAgentOptions +### Python: ClaudeCodeOptions renamed to ClaudeAgentOptions **What changed:** The Python SDK type `ClaudeCodeOptions` has been renamed to `ClaudeAgentOptions`. **Migration:** @@ -98,11 +70,7 @@ options = ClaudeAgentOptions(model="claude-opus-4-7", permission_mode="acceptEdits") -### - -​ - -System prompt no longer default +### System prompt no longer default **What changed:** The SDK no longer uses Claude Code’s system prompt by default. **Migration:** @@ -159,21 +127,13 @@ asyncio.run(main()) -### - -​ - -Settings sources default +### Settings sources default This default was briefly changed in v0.1.0 to load no filesystem settings and then reverted, so no migration action is needed. **Current behavior:** Omitting `settingSources` on `query()` loads user, project, and local filesystem settings, matching the CLI. This includes `~/.claude/settings.json`, `.claude/settings.json`, `.claude/settings.local.json`, CLAUDE.md files, and custom commands. To run isolated from filesystem settings, pass `settingSources: []`, or `setting_sources=[]` in Python. See [Control filesystem settings with settingSources](</docs/en/agent-sdk/claude-code-features#control-filesystem-settings-with-settingsources>) for what each source loads. Isolation is especially important for CI/CD pipelines, deployed applications, test environments, and multi-tenant systems where local customizations should not leak in. Python SDK 0.1.59 and earlier treated an empty list the same as omitting the option, so upgrade before relying on `setting_sources=[]`. See [What settingSources does not control](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>) for inputs that are read even when `settingSources` is `[]`. -## - -​ - -Next Steps +## Next Steps * Explore the [Agent SDK Overview](</docs/en/agent-sdk/overview>) to learn about available features * Check out the [TypeScript SDK Reference](</docs/en/agent-sdk/typescript>) for detailed API documentation
modified Claude Code on mobile View current →
--- a/mobile.md +++ b/mobile.md @@ -2,11 +2,7 @@ Claude Code doesn’t have a separate mobile app: cloud sessions and Remote Control both live in the **Code** tab in the Claude app, and Dispatch is a task you message in the app. -## - -​ - -Get the app +## Get the app 1 @@ -28,11 +24,7 @@ Tap **Code** in the app’s navigation to reach your sessions, or open [claude.ai/code/new](<https://claude.ai/code/new>) on your phone to start a new Code session in the app. If you don’t see the Code tab, your plan or organization may not include these features; see [availability by subscription plan](</docs/en/feature-availability#availability-by-subscription-plan>). -## - -​ - -Work from your phone +## Work from your phone From the app you can start cloud sessions, open a project, drive a Claude Code session running on your computer, or message Dispatch a task. The app is the same for each; they differ in where the work happens. @@ -45,19 +37,11 @@ If your computer will be off, use cloud sessions or a project, which run in the cloud and continue with your laptop closed. Remote Control and Dispatch drive your own machine, so it needs to stay on with Claude Code or the Desktop app running. If your machine sleeps during a Remote Control session, Claude Code reconnects when the machine comes back online. For a fuller comparison, see [work when you are away from your terminal](</docs/en/platforms#work-when-you-are-away-from-your-terminal>). Cloud sessions and Remote Control run from the **Code** tab. For Dispatch, which you message as a task in the app, see [sessions from Dispatch](</docs/en/desktop#sessions-from-dispatch>). -### - -​ - -Start and monitor cloud sessions +### Start and monitor cloud sessions Cloud sessions run tasks on cloud infrastructure, Anthropic-managed by default, so a session continues after you put your phone away. From the Code tab, select a repository and branch, describe the task, and submit it. Sessions persist across devices: a task you start on your laptop is ready to review from your phone, and one you start from your phone is waiting when you’re back at your desk. Open a session in the app to check progress, answer Claude’s questions, or steer it in a new direction. You can also tell Claude to [watch a pull request](</docs/en/claude-code-on-the-web#auto-fix-pull-requests>) and fix CI failures or review comments as they arrive. To connect GitHub and set up your environment, follow the [cloud quickstart](</docs/en/web-quickstart>), and see [Use Claude Code in the cloud](</docs/en/claude-code-on-the-web>) for everything cloud sessions can do. -### - -​ - -Continue a local session with Remote Control +### Continue a local session with Remote Control Remote Control connects the Claude app to a Claude Code session running on your machine, so code execution and filesystem access stay local while you drive the session from your phone. Start the session on your computer with `claude remote-control`, or run `/remote-control` in a session that’s already open. Then scan the QR code the terminal can display, or open the Claude app, tap **Code** , and pick the session from the list. See [connect from another device](</docs/en/remote-control#connect-from-another-device>) for each option. When you add an attachment in the Claude app, it reaches the local session too: @@ -66,19 +50,11 @@ For requirements, invocation modes, and troubleshooting, see the [Remote Control overview](</docs/en/remote-control>). -### - -​ - -Get push notifications +### Get push notifications When Remote Control is active, Claude can send push notifications to your phone when a long-running task finishes or when it needs a decision from you. You can also ask for one in your prompt, such as `notify me when the tests finish`. See [mobile push notifications](</docs/en/remote-control#mobile-push-notifications>) for the two `/config` toggles and delivery troubleshooting. Dispatch sends its own notification when a Code session it spawned finishes or needs your approval, described in [sessions from Dispatch](</docs/en/desktop#sessions-from-dispatch>). -## - -​ - -Limitations +## Limitations The mobile client covers most of what a session needs, with a few limitations: @@ -86,11 +62,7 @@ * **Permission modes** : cloud sessions offer Accept edits, Plan, and Auto, and Remote Control sessions offer Manual, Accept edits, Plan, and Auto. You can’t select Bypass permissions from the app in either case. See [switch permission modes](</docs/en/permission-modes#switch-permission-modes>) for when Auto is available. * **Dispatch plans** : Dispatch requires a Pro, Max, or Ultra plan and isn’t available on Team or Enterprise. -## - -​ - -Related resources +## Related resources * [Platforms and integrations](</docs/en/platforms>): compare every surface Claude Code runs on * [Use Claude Code in the cloud](</docs/en/claude-code-on-the-web>): how cloud sessions run and how to move work to and from your terminal
modified Model configuration View current →
Show diff (740 lines)
--- a/model-config.md +++ b/model-config.md @@ -1,8 +1,4 @@ -## - -​ - -Available models +## Available models For the `model` setting in Claude Code, you can configure either: @@ -17,11 +13,7 @@ `ANTHROPIC_BASE_URL` changes where requests are sent, not which model answers them. To route Claude through an LLM gateway, see [LLM gateways](</docs/en/llm-gateway>). -### - -​ - -Model aliases +### Model aliases Use a model alias to select model settings without remembering exact version numbers: @@ -50,11 +42,7 @@ Sonnet 5.5 requires Claude Code v2.1.284 or later, and Opus 5.5 requires v2.1.280 or later. If a request for one of them from an older version fails, see [Claude Code does not support this model](</docs/en/errors#claude-code-does-not-support-this-model>). Use v2.1.293 or later with Haiku 5.5. Run `claude update` to upgrade. -### - -​ - -Work with Fable +### Work with Fable [Claude Fable models](<https://platform.claude.com/docs/en/about-claude/models/overview>) are the most capable models in Claude Code, suited to tasks larger than a single sitting. They sustain long autonomous sessions, investigate before acting, and verify their work more often than smaller models. No Fable model is the account-type default on any plan or provider. Select one explicitly: @@ -77,11 +65,7 @@ On the Anthropic API, a Fable model appears in the `/model` picker unless `availableModels` or organization model restrictions exclude it. When your organization can’t use Fable at all, for example under [zero data retention](</docs/en/zero-data-retention#model-availability-under-zdr>), the row stays in the picker grayed out, with a note on why. -#### - -​ - -Fable and usage credits +#### Fable and usage credits Depending on your plan and seat tier, Fable usage can bill to [usage credits](<https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans>) instead of drawing on your plan’s included limits. When it does, the `/model` picker shows “Requires usage credits” on the Fable row. To manage usage credits, see [Add usage credits to your subscription](</docs/en/costs#add-usage-credits-to-your-subscription>). In interactive sessions, Claude Code can show a Fable usage-credits consent prompt. You can continue on Fable using usage credits or switch to your default model. You can also dismiss the prompt: @@ -96,11 +80,7 @@ In a session another application hosts through the [Agent SDK](</docs/en/agent-sdk/overview>), whether the prompt appears is up to that application. If it appears and nobody answers before the same [`dialogExpiry`](</docs/en/settings-reference#dialogexpiry>) deadline, Claude Code ends the turn without sending the request. In [non-interactive mode](</docs/en/headless>) with the `-p` flag, and in an Agent SDK application that doesn’t show the prompt, Claude Code never asks for consent. When a Fable request there would bill to usage credits, Claude Code bills it without asking. -### - -​ - -Setting your model +### Setting your model You can configure your model in several ways, listed in order of priority: @@ -121,7 +101,7 @@ * If model restrictions exclude the recorded model or it isn’t available to your account, and your admin hasn’t set an organization default model, the Default option resolves as if nothing were recorded. * If you choose Default or `opusplan` in `/model`, the recorded choice doesn’t change. -If you switch models with `/model`, the switch also reaches [subagents that inherit the main conversation’s model](</docs/en/sub-agents#choose-a-model>), because Claude Code resolves their model from the one your session is using when Claude starts them. Switch to Opus before Claude delegates research or test runs to one of them, and that work runs on Opus too. To keep a custom subagent on a smaller model, set `model` in its definition. If you set a model with `/model` in [non-interactive mode](</docs/en/headless>), with the `-p` flag, your choice applies to the current session only and isn’t saved as your default; `/model` in that mode requires Claude Code v2.1.205 or later. Project and managed settings still take precedence and reapply on the next launch. An organization default model that your admin has configured to override user selection also reapplies on the next launch. In v2.1.144 through v2.1.152, `/model` applied to the current session only and `d` in the picker saved a default. The `--model` flag and `ANTHROPIC_MODEL` environment variable apply only to the session you launch with them. To run different models in different terminals at the same time, launch each one with its own `--model` flag rather than switching with `/model`. Prices in the `/model` picker appear when Claude Code talks to the Anthropic API, directly or through an [LLM gateway](</docs/en/llm-gateway>) that proxies it, and the price on a row is the price of the model that row selects. On [third-party providers](</docs/en/third-party-integrations>) such as Amazon Bedrock and on the [Claude apps gateway](</docs/en/claude-apps-gateway>), your provider or gateway determines what you pay, so picker rows show no price. The price is a display label only; it doesn’t affect which model a row selects or what your provider bills. Before v2.1.206, [Claude Platform on AWS](</docs/en/claude-platform-on-aws>) and gateway sessions showed Anthropic list prices, and a row could show the price of a different model than the one it selected. Resumed sessions started with `claude --resume`, `--continue`, or the `/resume` picker keep the model they were using when the transcript was saved. If the restored model has been retired or is excluded by `availableModels`, the session falls through to the normal precedence order. On providers that use provider-specific deployment IDs rather than Anthropic model IDs, such as Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry, the transcript model isn’t restored at all and the session resolves its model through the normal precedence order. If your `model` setting is `haiku`, a session saved on a Haiku model resumes on the model that `haiku` resolves to now. For example, once `haiku` resolves to Haiku 5.5, a session saved on Haiku 4.5 resumes on Haiku 5.5. A model you pick for the new launch with `--model` or `ANTHROPIC_MODEL` still takes precedence over the restored model. As of v2.1.195, so does an `ANTHROPIC_DEFAULT_OPUS_MODEL` family variable. `ANTHROPIC_DEFAULT_MODEL` can too, under the conditions listed in its section. When the active model at startup comes from project or managed settings rather than your own selection, the startup header shows which settings file set it. Run `/model` to override; the project or managed setting reapplies on the next launch. On platforms that embed Claude Code and set [`CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST`](</docs/en/env-vars>), the host’s model configuration takes precedence over managed model settings, while a managed `availableModels` allowlist stays in force unless the host supplies its own; [Exceptions to managed settings precedence](</docs/en/settings#exceptions-to-managed-settings-precedence>) says which keys and variables the host overrides. If you or your organization configure [PreModelSwitch hooks](</docs/en/hooks#premodelswitch>), they run before a requested switch applies and can block it or ask you to confirm. When Claude Code can’t tell which PreModelSwitch hooks your organization’s [managed plugins](</docs/en/settings-reference#enabledplugins>) deliver, for example because a managed plugin failed to load, it refuses the switch rather than apply it unchecked, and it checks again on each new attempt. See [Model switch was blocked by a PreModelSwitch hook](</docs/en/errors#model-switch-was-blocked-by-a-premodelswitch-hook>) for the message and recovery. When you switch models through the [Agent SDK](</docs/en/agent-sdk/overview>) `setModel()` method, through an app such as the [Desktop app](</docs/en/desktop>), or from a device connected through [Remote Control](</docs/en/remote-control>), Claude Code checks the value at the switch: +If you switch models with `/model`, the switch also reaches [subagents that inherit the main conversation’s model](</docs/en/sub-agents#choose-a-model>), because Claude Code resolves their model from the one your session is using when Claude starts them. Switch to Opus before Claude delegates research or test runs to one of them, and that work runs on Opus too. To keep a custom subagent on a smaller model, set `model` in its definition. If you set a model with `/model` in [non-interactive mode](</docs/en/headless>), with the `-p` flag, your choice applies to the current session only and isn’t saved as your default; `/model` in that mode requires Claude Code v2.1.205 or later. Project and managed settings still take precedence and reapply on the next launch. An organization default model that your admin has configured to override user selection also reapplies on the next launch. In v2.1.144 through v2.1.152, `/model` applied to the current session only and `d` in the picker saved a default. The `--model` flag and `ANTHROPIC_MODEL` environment variable apply only to the session you launch with them. To run different models in different terminals at the same time, launch each one with its own `--model` flag rather than switching with `/model`. Prices in the `/model` picker appear when Claude Code talks to the Anthropic API, directly or through an [LLM gateway](</docs/en/llm-gateway>) that proxies it, and the price on a row is the price of the model that row selects. On [third-party providers](</docs/en/third-party-integrations>) such as Amazon Bedrock and on the [Claude apps gateway](</docs/en/claude-apps-gateway>), your provider or gateway determines what you pay, so picker rows show no price. The price is a display label only; it doesn’t affect which model a row selects or what your provider bills. Before v2.1.206, [Claude Platform on AWS](</docs/en/claude-platform-on-aws>) and gateway sessions showed Anthropic list prices, and a row could show the price of a different model than the one it selected. Resumed sessions started with `claude --resume`, `--continue`, or the `/resume` picker keep the model they were using when the transcript was saved. If the restored model has been retired or is excluded by `availableModels`, the session falls through to the normal precedence order. On providers that use provider-specific deployment IDs rather than Anthropic model IDs, such as Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry, the transcript model isn’t restored at all and the session resolves its model through the normal precedence order. If your `model` setting is `haiku`, a session saved on a Haiku model resumes on the model that `haiku` resolves to now. For example, once `haiku` resolves to Haiku 5.5, a session saved on Haiku 4.5 resumes on Haiku 5.5. A model you pick for the new launch with `--model` or `ANTHROPIC_MODEL` still takes precedence over the restored model. As of v2.1.195, so does an `ANTHROPIC_DEFAULT_OPUS_MODEL` family variable. `ANTHROPIC_DEFAULT_MODEL` can too, under the conditions listed in its section. When the active model at startup comes from project or managed settings rather than your own selection, the startup header shows which settings file set it. Run `/model` to override; the project or managed setting reapplies on the next launch. On platforms that embed Claude Code and set [`CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST`](</docs/en/env-vars>), the host’s model configuration takes precedence over managed model settings, while a managed `availableModels` allowlist stays in force unless the host supplies its own; [Exceptions to managed settings precedence](</docs/en/settings#exceptions-to-managed-settings-precedence>) says which keys and variables the host overrides. If you or your organization configure [PreModelSwitch hooks](</docs/en/hooks#premodelswitch>), they run before a requested switch applies and can block it or ask you to confirm. To find out why a hook blocked a switch and what to do, see [Model switch was blocked by a PreModelSwitch hook](</docs/en/errors#model-switch-was-blocked-by-a-premodelswitch-hook>). If a [managed plugin](</docs/en/settings-reference#enabledplugins>) or its hooks fail to load, you can still switch models. The plugin’s PreModelSwitch hooks don’t run, so a switch that one of them would have blocked can go ahead. Other PreModelSwitch hooks that loaded still run and can block it. If Claude Code before v2.1.323 refuses the switch with `so organization-managed PreModelSwitch hooks could not be checked`, update Claude Code. To see what failed, run `/plugin` in your session and open the [**Errors** tab](</docs/en/plugins/troubleshooting#failed-to-load-hooks-from-and-hooks-that-dont-fire>). If nothing is listed there, start a new session with `claude --debug` from your shell and switch to a different model, then read the [debug log](</docs/en/hooks#debug-hooks>). After you fix the plugin, or a [plugin update](</docs/en/plugins/install#keep-plugins-updated>) brings your admin’s fix to your machine, run `/reload-plugins` in your session to get its hooks running. When you switch models through the [Agent SDK](</docs/en/agent-sdk/overview>) `setModel()` method, through an app such as the [Desktop app](</docs/en/desktop>), or from a device connected through [Remote Control](</docs/en/remote-control>), Claude Code checks the value at the switch: * **Agent SDK or an app** : with Claude Code v2.1.268 or later, unless Claude Code accepts a model ID locally, as it does for your custom model option, it confirms the ID with your provider the first time the session switches to it. The confirmation runs on every provider, and an ID your provider doesn’t offer is refused at the switch instead of failing on your next request. * **Remote Control** : on the Anthropic API, Claude Code checks the value locally and sends no request. @@ -143,11 +123,7 @@ "model": "opus" } -#### - -​ - -Fix a mistyped model name +#### Fix a mistyped model name Either of these warnings means Claude Code doesn’t recognize the model ID you set, and the ID nearly spells a model name or alias it does recognize: @@ -157,11 +133,7 @@ * **You mistyped the ID** : change it to the suggestion wherever you set the model * **The ID is deliberate** : leave it as it is. The session sends it as you wrote it. If the context window Claude Code assumes for it is wrong, correct the window -#### - -​ - -Set a default model for new sessions +#### Set a default model for new sessions Set `ANTHROPIC_DEFAULT_MODEL=<alias|name>` to choose the model your sessions start on by default. Requires Claude Code v2.1.236 or later. Claude Code starts a new session on the variable’s model only when none of these selects a model: @@ -179,11 +151,7 @@ When a new session would start on the variable’s model, a session you resume with `claude --resume`, `--continue`, or the `/resume` picker starts on it too. Claude Code doesn’t restore the model saved in that session’s transcript. Otherwise Claude Code doesn’t use the variable when you resume a session. -#### - -​ - -A new session starts on a different model than you picked +#### A new session starts on a different model than you picked When you pick a model with `/model` and your next session starts on something else, these are the usual causes: @@ -192,11 +160,7 @@ * **Claude Code couldn’t save your choice.** `/model` writes `model` to `~/.claude/settings.json`. If you can’t write to that file, for example because another tool generates it or links it to a read-only copy, the model you chose lasts for the session and the next launch reads the old value. Set `model` in the tool that generates the file, or make the file writable. See [A change you made in Claude Code is lost in new sessions](</docs/en/settings#a-change-you-made-in-claude-code-is-lost-in-new-sessions>). * **You resumed a session.** A session you resume with `claude --resume` or `--continue` usually keeps the model it was using rather than your current default. -## - -​ - -Restrict model selection +## Restrict model selection Administrators can use `availableModels` in [managed or policy settings](</docs/en/managed-settings>) to restrict which models users can select. Each entry matches one of these: @@ -243,11 +207,7 @@ "availableModels": ["sonnet", "haiku"] } -### - -​ - -Surface coverage +### Surface coverage Every surface enforces the allowlist it receives. Which delivery mechanism reaches each surface differs: @@ -264,19 +224,11 @@ * The Desktop Code tab also hosts [SSH sessions](</docs/en/desktop#ssh-sessions>), which read the managed settings file from the remote host they run on. See [Desktop managed settings](</docs/en/desktop#managed-settings>). * The model pickers on claude.ai and in the Desktop app hide or grey out models excluded by your organization’s allowlist. The picker state is a convenience for users; it doesn’t enforce the allowlist. -### - -​ - -Default model behavior +### Default model behavior With the default prefix matching, `availableModels` on its own leaves the Default option on the system’s runtime default for the account until you also set `enforceAvailableModels`. If that default is a model you intend to restrict, set `enforceAvailableModels` as well, or block that model. With `availableModels: []`, named model selections are blocked and `enforceAvailableModels` has no effect. -### - -​ - -Enforce the allowlist for the Default model +### Enforce the allowlist for the Default model Set `enforceAvailableModels: true` alongside a non-empty `availableModels` in managed settings to extend the allowlist to the Default option. This requires Claude Code v2.1.175 or later. @@ -287,11 +239,7 @@ For a member with no model recorded on their account, the Default option resolves to the account-type default, or to the organization default model when an admin has set one. When that model is not in the allowlist, the Default option instead resolves to the first `availableModels` entry that names an allowed, available model, and the `/model` picker’s Default row shows that model. This applies everywhere the default is reached: session startup, selecting Default in `/model`, the `"default"` keyword in fallback model chains, and the fallback used when an excluded selection is dropped. A model recorded on a member’s account is checked against `availableModels` too; Setting your model describes how the Default option treats it. `enforceAvailableModels` remaps the Default option only when `availableModels` is non-empty. When `availableModels` is non-empty but no entry resolves to an allowed and available model, enforcement is skipped with a warning visible only under `--debug`. Keep at least one guaranteed-available entry in the list to avoid this. Deploy both keys together in the highest-ranked managed source you deliver. By default Claude Code reads only that source, so a pair placed in a managed settings file is ignored when the admin console delivers any settings; under the opt-in merge in [how Claude Code combines managed sources](</docs/en/managed-settings#how-claude-code-combines-managed-sources>), Claude Code still ignores a `modelOverrides` map from a source ranked below the one that sets `availableModels`. -### - -​ - -Control the model users run on +### Control the model users run on The `model` setting is an initial selection, not enforcement. It sets which model is active when a session starts, but users can still open `/model` and pick Default, which resolves to the system’s runtime default regardless of what `model` is set to, unless `enforceAvailableModels` or the keys that block specific versions apply to it. To fully control the model experience, combine these settings: @@ -314,27 +262,15 @@ Without `enforceAvailableModels` or the `env` block, a user who selects Default in the picker gets the runtime default rather than the version pinned in `model`. The two settings cover different scopes: `enforceAvailableModels` makes Default obey the allowlist, while the `env` block pins which version a permitted alias such as `sonnet` resolves to. Use `enforceAvailableModels` alone when restricting model families is enough; add the `env` block when you also need to pin a specific version. -### - -​ - -Merge behavior +### Merge behavior When the managed settings Claude Code applies define `availableModels`, that list alone applies, apart from a [host platform that supplies its own](</docs/en/settings#exceptions-to-managed-settings-precedence>): entries in user, project, or local settings cannot extend it, and Claude Code never merges `availableModels` across managed sources either; [how Claude Code combines managed sources](</docs/en/managed-settings#how-claude-code-combines-managed-sources>) says which source’s list applies. Otherwise, lists from user, project, and local settings are [concatenated and deduplicated](</docs/en/settings#settings-precedence>) like other array settings. Before Claude Code v2.1.175, entries from lower-precedence scopes merged into the managed list instead of being replaced by it. Within the effective list, an entry naming a specific model in a family, whether a version prefix or a full model ID, disables that family’s wildcard entry. For example, with `["sonnet", "claude-sonnet-4-5"]`, users can pick only the model IDs that `claude-sonnet-4-5` matches, not every Sonnet model. -### - -​ - -Mantle model IDs +### Mantle model IDs Entries in `availableModels` that start with `anthropic.` are added to the `/model` picker as custom options. This is an exception to the alias matching described in Pin models for third-party deployments. With the [Amazon Bedrock Mantle endpoint](</docs/en/amazon-bedrock#use-the-mantle-endpoint>) enabled, Claude Code routes the entries that match the Mantle format to that endpoint. The setting still restricts the picker to listed entries, and a Mantle ID embeds a family name, so it counts as a specific entry and disables that family’s wildcard: alongside any Mantle IDs, list the version prefixes or full IDs you want to keep selectable. See Merge behavior. -### - -​ - -Block specific models or versions +### Block specific models or versions An `availableModels` entry such as `claude-opus-5` also permits later releases that extend it, such as Opus 5.5, as soon as Claude Code supports them. Two managed settings let you hold a release back, and both require Claude Code v2.1.283 or later: @@ -356,11 +292,7 @@ If none of those is permitted, a session starting on the Default option [refuses to start](</docs/en/errors#managed-settings-block-the-default-model>) with an error that names the key to fix. An `"exact"` list affects the Default option only when the managed `availableModels` list names at least one model or family. Claude Code reads both keys from managed settings only. If you set either one in user, project, or local settings or with `--settings`, Claude Code ignores it with a warning. -### - -​ - -Organization model restrictions +### Organization model restrictions Organization admins on Claude Enterprise plans restrict which models members can run by disabling individual models in the claude.ai admin console. This restriction is delivered with the account’s entitlements when Claude Code authenticates, separate from any `availableModels` list in settings, and the server enforces the same restriction independently when a session is created. Requires Claude Code v2.1.187 or later. The restriction applies when a member signs in or uses their own API key. Organization-scoped credentials, such as organization service keys, are not tied to a user, so the restriction does not apply to them. The Claude Console has no model restriction control. Organizations without a Claude Enterprise plan, including those whose members authenticate through the Anthropic API, restrict models with `availableModels` in [managed settings](</docs/en/managed-settings>) instead, adding `enforceAvailableModels` to cover the Default option. Surface coverage says how each surface receives and enforces these settings. A restricted model is hidden from the `/model` picker. Selecting it by name with `--model`, the `ANTHROPIC_MODEL` environment variable, or the `model` setting shows the notice `Model "<name>" is restricted by your organization's settings. Using <model> instead.` and the session starts on an allowed model. Typing `/model <name>` for a restricted model is rejected with `Model '<name>' is restricted by your organization's settings. Run /model to choose a different model.` and the session keeps its current model. A model family alias such as `opus` resolves to its usual model when the organization permits it. When the organization restricts that model, Claude Code substitutes the newest version of the family that the organization permits, with the same substitution notice. `/model <alias>` is rejected only when every version of its family is restricted; an alias set with `--model`, `ANTHROPIC_MODEL`, or the `model` setting is still replaced at startup in that case. Before v2.1.205, a family alias was substituted or rejected based on its newest released version alone, even when an older version was allowed. Restrictions apply org-wide or per role: @@ -371,11 +303,7 @@ Both restrictions apply together: a model is selectable only when it is permitted by `availableModels` and not restricted by the organization. Organization restrictions reach sessions on the Anthropic API and [LLM gateway](</docs/en/llm-gateway>) deployments only; on any other provider, use `availableModels` instead. -## - -​ - -Organization default model +## Organization default model Organization admins on Claude Enterprise plans can set a default model for Claude Code members from the claude.ai admin console, for the whole organization or per custom role. When one is set, the Default option resolves to that model. Requires Claude Code v2.1.196 or later. The Default row in the `/model` picker shows the organization default’s name with the label Org default. The label reads Org default whether the admin set the default for the whole organization or for your role. A role default covers members of that custom role and takes precedence over the organization-wide default; when several of your roles set different defaults, the most capable model applies. The organization default is a starting point, not a restriction. These selections take precedence over it: @@ -392,11 +320,7 @@ As of v2.1.199, when the organization default is a different model family from your account type’s usual default, the `/model` picker keeps a separate row for that usual family, so you can still switch to it for a session. In v2.1.196 through v2.1.198 that row is missing from the picker. The organization default reaches only sessions authenticated with the Anthropic API. To set a default anywhere else, including [LLM gateway](</docs/en/llm-gateway>) deployments, use the `model` key in [managed settings](</docs/en/managed-settings>) instead. -## - -​ - -Organization effort limits +## Organization effort limits Your organization can cap the effort level in two ways. On a Claude Enterprise plan, organization admins set per-role effort limits, described below. On any plan and any provider, including Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry, the [`maxEffortLevel`](</docs/en/settings-reference#maxeffortlevel>) managed setting caps effort on the client instead. When both apply to a model, the lower cap applies. Organization admins on Claude Enterprise plans can set a maximum effort level per model for each custom role, alongside role-level organization model restrictions. Requires Claude Code v2.1.195 or later. @@ -406,17 +330,9 @@ Effort limits are delivered together with organization model restrictions and reach the same sessions. -## - -​ - -Special model behavior - -### - -​ - -`default` model setting +## Special model behavior + +### `default` model setting The behavior of `default` depends on your account type: @@ -428,11 +344,7 @@ Fable models are not the account-type default on any plan or provider. Choosing one with `/model` saves it as the selected model in your user settings, so later sessions start on it, apart from the one-time change to a saved Fable 5.1 pick. -### - -​ - -`opusplan` model setting +### `opusplan` model setting The `opusplan` model alias provides an automated hybrid approach: @@ -441,11 +353,7 @@ This pairs Opus’s reasoning for planning with Sonnet’s efficiency for execution. The plan-mode Opus phase uses the same context window as the `opus` model setting, and the execution phase uses the same window as `sonnet`. When `opus` and `sonnet` resolve to models that run with the 1M context window by default, as the current models do on the Anthropic API, both phases run with it. To request 1M context for both phases where they don’t, set the model to `opusplan[1m]`, for example with `/model opusplan[1m]`. Setting it with `/model` requires Claude Code v2.1.265 or later; on earlier versions, use the `--model` flag or the `model` setting instead. When `availableModels` excludes the newest Opus but permits an older version, for example `["sonnet", "claude-opus-4-6"]`, `opusplan` uses the newest permitted Opus for planning and stays on Sonnet only when every Opus is excluded. A Haiku session that would normally upgrade to Sonnet in plan mode likewise uses the newest permitted Sonnet, and stays on Haiku only when every Sonnet is excluded. Before v2.1.205, plan mode stayed on the session’s model whenever the newest version of the upgrade family was excluded, even when the allowlist permitted an older one. The substitution of an older permitted version applies on the Anthropic API and [Claude Platform on AWS](</docs/en/claude-platform-on-aws>). On Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, and Mantle, whose deployments use provider-specific model IDs, plan mode stays on the session’s model whenever the upgrade model is excluded. For a hybrid approach where Claude decides mid-task when to consult a second model rather than switching at the plan boundary, see the [advisor tool](</docs/en/advisor>). -### - -​ - -Fallback model chains +### Fallback model chains When the primary model is overloaded, unavailable, or returns another non-retryable server error, Claude Code can switch to a fallback model instead of failing the request. Authentication, billing, rate-limit, request-size, and transport errors, and a [denial by your organization’s policy check](</docs/en/errors#automatic-retries>), never trigger a switch; those follow their normal retry and error handling. It does switch when [Amazon Bedrock](</docs/en/amazon-bedrock#when-a-model-is-disabled-mid-session>) or [Google Cloud’s Agent Platform](</docs/en/google-vertex-ai#when-a-model-is-disabled-mid-session>) refuses a model your account can’t invoke, which Claude Code treats as the model being unavailable rather than as an authentication error. Configure one or more fallback models and Claude Code tries them in order, showing a notice when it switches. The switch lasts for the current turn only, so your next message tries the primary model first again. Claude Code caps chains at three models after duplicate removal and ignores extra entries. Set a chain for one session with the `--fallback-model` flag, which accepts a comma-separated list: @@ -464,11 +372,7 @@ Claude Code also applies the chain to [subagents](</docs/en/sub-agents>). When a subagent’s request fails over, Claude Code tries your configured fallback models in order, and the subagent continues on the model that accepts the request. Your session’s model is unchanged. Before v2.1.247, a failure the chain covers ended the subagent instead. -### - -​ - -Automatic model fallback +### Automatic model fallback This section covers content-based fallback from Fable models, Opus 5.5, Sonnet 5.5, and Opus 5. For availability-based fallback when a model is overloaded or unavailable, see Fallback model chains. Fable models, Opus 5.5, Sonnet 5.5, and Opus 5 run with safety classifiers, which most often flag cybersecurity and biology content. For those two categories, the fallback model depends on which model refused: @@ -478,11 +382,7 @@ On Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry, Claude Code resolves these targets through your deployment’s model IDs instead. See Enable fallback on Bedrock, Agent Platform, and Foundry. When Claude Code switches a flagged request to the fallback model for its category, it re-runs the request on that model. In your main conversation, it shows a notice in the transcript. To be asked first, see Ask before switching. After a fallback, the session continues on the fallback model. To return to your original model, run `/model`. Category-based fallback requires Claude Code v2.1.219 or later. Before v2.1.219, every flagged Fable 5 request re-ran on your provider’s default Opus model, and Opus 5 was not a fallback source. The fallback model is checked against `availableModels`. When it is blocked, no fallback occurs. The refusal is shown as a normal error and the session’s model is unchanged. -#### - -​ - -Effort level after a fallback +#### Effort level after a fallback When Claude Code switches your session to the fallback model, it keeps the effort level the flagged request ran at. For example, a session on Opus 5.5 at its default `medium` that falls back to Opus 4.8 stays at `medium`, although Opus 4.8 defaults to `high`. A different level applies in cases such as these: @@ -491,19 +391,11 @@ To see the level set for your session after a fallback, run `/effort status`. To change it, run `/effort`. -#### - -​ - -Check what triggered fallback +#### Check what triggered fallback Fallback can trigger on the first request of a session, before you send anything unusual, because the first request carries workspace context such as your CLAUDE.md content and git status. A repository that contains security or biology material can trip the classifier on that context alone. To check whether customizations are the trigger, start a session with `claude --safe-mode`, which disables customizations such as CLAUDE.md, skills, MCP servers, and hooks. Git status and directory names are not customizations and are still included. -#### - -​ - -Ask before switching +#### Ask before switching To decide what happens each time a request is flagged, run `/config`, select **Switch models when a message is flagged** , and choose **Ask each time**. You can also set [`switchModelsOnFlag`](</docs/en/settings-reference#switchmodelsonflag>) to `false` in your settings file. Claude Code then pauses at a flagged request that would switch models and gives you two options: switch to the fallback model, or edit the prompt and retry. The first time a flagged request would switch models in an interactive session, Claude Code may ask whether to switch automatically from then on. It asks only if you haven’t set `switchModelsOnFlag`, and it saves your choice as that key in your user settings. If you choose to stay on the current model instead, the saved value is `false`, the same as **Ask each time**. If you dismiss the question, Claude Code saves nothing and asks again the next time a flagged request would switch models. When you’ve chosen **Ask each time** , some cases behave differently: @@ -514,11 +406,7 @@ * In a subagent that Claude starts with the [Agent tool](</docs/en/tools-reference#agent-tool-behavior>), Claude Code doesn’t pause to ask, and the subagent fails instead of switching models. See Subagents switch or fail without asking. * When the fallback target is blocked by `availableModels`, Claude Code doesn’t show the prompt. The flagged request ends with the refusal, the same as automatic fallback when the target is blocked. -#### - -​ - -Subagents switch or fail without asking +#### Subagents switch or fail without asking In a built-in or custom [subagent](</docs/en/sub-agents>) that Claude starts with the [Agent tool](</docs/en/tools-reference#agent-tool-behavior>), Claude Code doesn’t pause to ask at a flagged request. If a fallback model is available, the request re-runs on it or the subagent fails, according to your **Switch models when a message is flagged** choice in `/config`: @@ -527,11 +415,7 @@ When no fallback model is available, the subagent fails the same way with either choice. Before v2.1.318, a subagent’s flagged request re-ran on an available fallback model whichever you chose. -#### - -​ - -Enable fallback on Bedrock, Agent Platform, and Foundry +#### Enable fallback on Bedrock, Agent Platform, and Foundry On [Amazon Bedrock](</docs/en/amazon-bedrock>), [Google Cloud’s Agent Platform](</docs/en/google-vertex-ai>), and [Microsoft Foundry](</docs/en/microsoft-foundry>), model IDs are provider-specific, so automatic fallback only operates when Claude Code can identify each model involved: @@ -547,19 +431,11 @@ The fallback model must also have a context window at least as large as the session’s, or Claude Code doesn’t switch and the flagged request ends with the same refusal. On these providers the source models run with the 1M context window by default. Pin a model that also does, such as Opus 4.8 in `ANTHROPIC_DEFAULT_OPUS_MODEL` or Sonnet 5 in `ANTHROPIC_DEFAULT_SONNET_MODEL`, by an ID Claude Code can match to that model. -#### - -​ - -Security research and biology workloads +#### Security research and biology workloads Workloads in offensive security or biology, including penetration testing, Capture the Flag (CTF) exercises, and biology-adjacent codebases, trigger fallback frequently, often on the first request. This is expected routing for these domains, not an account flag. If your organization needs Fable-class capability for this work, ask your Anthropic account team about trusted access programs. For substantive biology work on a Fable model or Opus 5.5, the first flagged request that switches models moves the session to Opus 5. Later biology-flagged requests end in refusals there, because Opus 5 has no biology fallback. On Opus 5 and Sonnet 5.5, those refusals start with the first flagged request. -### - -​ - -Adjust effort level +### Adjust effort level [Effort levels](<https://platform.claude.com/docs/en/build-with-claude/effort>) control adaptive reasoning, which lets the model decide whether and how much to think on each step based on task complexity. Lower effort is faster and cheaper for straightforward tasks, while higher effort provides deeper reasoning for complex problems. The available effort levels depend on the model. Models not listed here do not support effort: @@ -599,11 +475,7 @@ In those cases `--effort ultracode` starts the session with ultracode off, at the highest effort level the model and any cap allow, up to `xhigh`. -#### - -​ - -Choose an effort level +#### Choose an effort level Each level trades token spend against capability. The default suits most coding tasks; adjust when you want a different balance. @@ -618,11 +490,7 @@ In tests on Opus 5.5 and Fable 5.1, Claude at a higher level tested more edge cases and verified more of its work before answering. It also made more choices on its own. At a lower level, Claude returned a starting point sooner, which fits work where you review each result and steer the next step. To see the same tasks run at each level, read [Using Claude Code: Spending your effort](<https://claude.dev/blog/spending-your-effort/>) on the blog. The effort scale is calibrated per model, so the same level name does not represent the same underlying value across models. Opus 5.5 defaults to `medium`, one level below Opus 5’s default of `high`. In Anthropic’s testing, Opus 5.5 at `medium` matches or exceeds Opus 5 at `high` on coding and knowledge-work evaluations. At a given level, Opus 5.5 tends to think more per turn than Opus 5. When you move from Opus 5 to Opus 5.5, start at `medium` rather than carrying over the level you used on Opus 5. To test levels against your own work, see [Calibrate effort](<https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5-5#calibrate-effort>) in the Opus 5.5 prompting guide. -#### - -​ - -Use ultrathink for one-off deep reasoning +#### Use ultrathink for one-off deep reasoning Include `ultrathink` anywhere in your prompt to request deeper reasoning on that turn without changing your session effort setting. Claude Code recognizes the keyword and adds an in-context instruction. Claude Code passes other phrases such as “think”, “think hard”, and “think more” through as ordinary prompt text and doesn’t recognize them as keywords. Typed in the terminal prompt, the word can also raise that turn to `xhigh` effort. When it can, the word shows in rainbow colors. Requires Claude Code v2.1.311 or later. If the word isn’t rainbow when you start a new turn, try one of these: @@ -630,11 +498,7 @@ * Unset `CLAUDE_CODE_EFFORT_LEVEL` if it’s set below `xhigh`, raise your own [`maxEffortLevel`](</docs/en/settings-reference#maxeffortlevel>) to `xhigh` or above, or ask an organization admin to raise your organization’s limit * Run `/model` in your session to switch to an Opus 5.5, Sonnet 5.5, Haiku 5.5, Fable 5.2, or Fable 5.1 model. Where the word can’t raise a turn, such as on Amazon Bedrock, set the effort level instead -#### - -​ - -Set the effort level +#### Set the effort level You can change effort through any of the following: @@ -648,27 +512,15 @@ A skill’s `effort` applies until the end of the turn it runs in, or for the forked subagent’s run with `context: fork`. A subagent’s `effort` applies while the subagent runs, unless [its invocation overrides it](</docs/en/sub-agents#choose-an-effort-level>). While either one applies, the skill or subagent runs at its level, whatever level you launch with, save, or pick. If `CLAUDE_CODE_EFFORT_LEVEL` is set, that level applies instead. A [`maxEffortLevel`](</docs/en/settings-reference#maxeffortlevel>) or organization effort cap still limits the level the skill or subagent runs at. If you set `effortLevel` in [managed settings](</docs/en/managed-settings>), Claude Code applies it at the settings step of the effort resolution order, and users can still change the level with `/effort` or `--effort`. To keep users at or below a level, set [`maxEffortLevel`](</docs/en/settings-reference#maxeffortlevel>). -#### - -​ - -Effort level of subagents and teammates +#### Effort level of subagents and teammates On the main conversation’s model, a [subagent](</docs/en/sub-agents#choose-an-effort-level>) or [teammate](</docs/en/agent-teams#specify-teammates-and-models>) with no `effort` of its own runs at the level you pick in the session or set with `--effort`. On another model, that level doesn’t apply. To pick a subagent’s level, set `effort` in its definition. -#### - -​ - -Check the effort level you set +#### Check the effort level you set The effort slider appears in `/model` when a supported model is selected. A level in the session header, for example “with low effort”, comes from your effort setting, even if Claude is still working at the old level. At startup and when you change it, the footer also briefly shows the level set for your session. -#### - -​ - -When a new effort level starts +#### When a new effort level starts In a terminal session, once `/effort` confirms the new level, the next message you send runs at that level. You can send it after the turn in progress ends or [while Claude is still working](</docs/en/interactive-mode#queue-messages-while-claude-works>): @@ -677,11 +529,7 @@ Before v2.1.242, Claude Code could queue `/effort` itself until the turn finished, and always did 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>). -#### - -​ - -Send no effort level +#### Send no effort level When Claude Code sends no effort level to a supported model, the [API’s default](<https://platform.claude.com/docs/en/build-with-claude/effort>) applies instead of Claude Code’s. To have Claude Code send none, start `claude` from a shell that exports `CLAUDE_CODE_EFFORT_LEVEL` with the value `auto` or the value `unset`, which do the same thing: @@ -694,19 +542,11 @@ Before v2.1.304, `/effort status` printed `Effort level: auto (currently high)` even while no level was sent. -#### - -​ - -Adaptive reasoning and fixed thinking budgets +#### Adaptive reasoning and fixed thinking budgets Adaptive reasoning makes thinking optional on each step, so Claude can respond faster to routine prompts and reserve deeper thinking for steps that benefit from it. If you want Claude to think more or less often than the current level produces, you can say so directly in your prompt or in `CLAUDE.md`; the model responds to that guidance within its effort setting. Fable models, Sonnet 5 and later, Haiku 5.5, and Opus 4.7 and later always use adaptive reasoning. The fixed thinking budget mode and `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING` don’t apply to them. On Opus 4.6 and Sonnet 4.6, you can set `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING=1` to revert to the previous fixed thinking budget controlled by `MAX_THINKING_TOKENS`. See [environment variables](</docs/en/env-vars>). -### - -​ - -Extended thinking +### Extended thinking Extended thinking is the reasoning Claude emits before responding. On models that support adaptive reasoning, the effort level is the primary control for how much thinking happens; the settings below turn thinking on or off and control how it displays. With thinking turned off on the Anthropic API, Claude Code sends effort `high` instead of a higher level to models it knows [don’t accept that combination](</docs/en/errors#effort-isnt-available-with-thinking-turned-off>), such as Opus 5. @@ -718,22 +558,14 @@ Claude Code collapses thinking output by default. Press `Ctrl+O` to toggle verbose mode and see the reasoning as gray italic text. Interactive sessions on the Anthropic API receive redacted thinking blocks by default, so set [`showThinkingSummaries: true`](</docs/en/settings-reference#showthinkingsummaries>) in settings if you want the full summaries available when you expand. You are charged for all thinking tokens generated, even when collapsed or redacted. -#### - -​ - -Where you can’t turn thinking off +#### Where you can’t turn thinking off You can’t turn thinking off on Opus 5.5, Sonnet 5.5, Haiku 5.5, or the Fable models. The session toggle and the `/config` row show `Thinking can't be turned off` for these models instead of offering the switch, and a saved `alwaysThinkingEnabled: false` or `MAX_THINKING_TOKENS=0` has no effect there. On these models, the model decides per step how much to think based on the effort level. The saved setting applies again when you switch to a model that accepts it. To stop or reduce thinking, use the step for your provider: * **Anthropic API** : you can turn thinking off on models such as `claude-opus-5`, `claude-sonnet-5`, and `claude-haiku-4-5`. Aliases such as `sonnet` select models where you can’t, so set the model by its ID. * **[Third-party providers](</docs/en/third-party-integrations>)** : on providers such as Amazon Bedrock and Microsoft Foundry, models with adaptive reasoning may still think with thinking off. Lower the effort level to reduce thinking. -### - -​ - -Extended context +### Extended context Long sessions with large codebases can use a [1 million token context window](<https://platform.claude.com/docs/en/build-with-claude/context-windows#context-window-sizes-by-model>). Fable models, Sonnet 5 and later, Haiku 5.5, Opus 4.6 and later, and Sonnet 4.6 support it. Fable models, Sonnet 5 and later, Haiku 5.5, and Opus 4.7 and later run with the 1M window by default, with no `[1m]` suffix needed. That includes sessions on Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry, and [Claude apps gateway](</docs/en/claude-apps-gateway>) sessions. To run them with a 200K window instead, see Turn off 1M context. Opus 4.6 and Sonnet 4.6 reach 1M only through their `[1m]` variant, and access to that variant depends on your plan. On Max, Ultra, Team, and Enterprise plans, including both Team Standard and Team Premium seats, Opus 4.6 with 1M context is included with your subscription. Sonnet 4.6 with 1M context requires [usage credits](<https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans>) on every subscription plan, including Max and Ultra. @@ -745,11 +577,7 @@ Claude Code checks these plan requirements only when it connects to the Anthropic API directly. If you point `ANTHROPIC_BASE_URL` at an [LLM gateway](</docs/en/llm-gateway#subscriptions-and-gateways>) and your saved claude.ai login stays the active credential, Claude Code doesn’t check your plan’s usage credits. The `[1m]` options stay available in `/model`, and the gateway decides whether the request succeeds. Before v2.1.229, Claude Code rejected `/model sonnet[1m]` in that configuration when it couldn’t confirm usage credits on the account. On the Anthropic API, the 1M context window uses standard model pricing with no premium for tokens beyond 200K, except on Haiku 5.5, which costs more on prompts longer than 100K tokens. For plans where extended context is included with your subscription, usage remains covered by your subscription. For plans that access extended context through usage credits, tokens are billed to usage credits. -#### - -​ - -Select 1M context for Opus 4.6 or Sonnet 4.6 +#### Select 1M context for Opus 4.6 or Sonnet 4.6 To select a 1M variant by name, append the `[1m]` suffix to a model alias or a full model name: @@ -760,46 +588,26 @@ # Or to an alias: the suffix applies to the model the alias resolves to /model opus[1m] -#### - -​ - -Context window behind an LLM gateway +#### Context window behind an LLM gateway If you set `ANTHROPIC_BASE_URL` to an [LLM gateway](</docs/en/llm-gateway>) or another proxy, Claude Code gives each model it recognizes the same context window the model has on the Anthropic API. Fable models, Sonnet 5 and later, Haiku 5.5, and Opus 4.7 and later get the 1M window with no `[1m]` variant. A model that reaches 1M only through its `[1m]` variant, such as Opus 4.6, runs at 200K without it. Claude Code can’t detect a lower limit that the gateway or the server behind it enforces. If your gateway rejects requests above 200K tokens, set [`CLAUDE_CODE_AUTO_COMPACT_WINDOW=200000`](</docs/en/env-vars>) in the environment that starts Claude Code, so sessions on every model compact at that boundary. -#### - -​ - -Turn off 1M context +#### Turn off 1M context To keep sessions at a 200K window, set `CLAUDE_CODE_DISABLE_1M_CONTEXT=1` in your shell or in a [settings file](</docs/en/env-vars#set-environment-variables>). Claude Code removes the `[1m]` model variants from the model picker. On models that run with the 1M window by default, such as the Fable models, Sonnet 5 and later, and Opus 4.7 and later, it also treats the model as having a 200K context window: * With auto-compaction on, sessions compact at the 200K boundary through auto-compaction. Setting the auto-compact window above 200K doesn’t lift the hold, because Claude Code caps that window at the model’s context window. * With auto-compaction off, sessions stop at the 200K boundary with the [context-limit error](</docs/en/errors#prompt-is-too-long>) instead of compacting. -#### - -​ - -Haiku 5.5 context window and pricing +#### Haiku 5.5 context window and pricing On the Anthropic API, Haiku 5.5 runs with the 1M context window on every plan, with no `[1m]` suffix to select. Its model ID is `claude-haiku-5-5`. To use it, run `/model claude-haiku-5-5` in a session, or start Claude Code from your shell with `claude --model claude-haiku-5-5`. A Haiku 5.5 request costs more per token when its prompt is longer than 100K tokens. See [Anthropic pricing](<https://platform.claude.com/docs/en/about-claude/pricing>) for both rates. Sessions auto-compact at about 967K tokens by default. To compact earlier, set a smaller auto-compact window for the model. -## - -​ - -Context window and auto-compaction +## Context window and auto-compaction The auto-compact window is how full the context window can get before Claude Code compacts the conversation. For what compaction keeps and drops per mechanism, see [What survives compaction](</docs/en/context-window#what-survives-compaction>). -### - -​ - -Set the auto-compact window +### Set the auto-compact window If Claude Code warned about the value of `CLAUDE_CODE_AUTO_COMPACT_WINDOW`, see the variable’s values and warnings. @@ -819,11 +627,7 @@ Whichever way you set the window, Claude Code caps it at the model’s context window. -#### - -​ - -Values and warnings for `CLAUDE_CODE_AUTO_COMPACT_WINDOW` +#### Values and warnings for `CLAUDE_CODE_AUTO_COMPACT_WINDOW` A warning that quotes your `CLAUDE_CODE_AUTO_COMPACT_WINDOW` value means the value falls outside 100,000 to 1,000,000 or isn’t a token count. To stop the warning, set a number in that range, such as `CLAUDE_CODE_AUTO_COMPACT_WINDOW=200000`. On Claude Code v2.1.304 or later, you can also write the number with `k` for thousands or `M` for millions, as in `200k` or `1M`. Find your warning’s wording in the first column, then read across for the window your session uses and what to change: @@ -835,11 +639,7 @@ A number with no suffix is read as that many tokens, so `CLAUDE_CODE_AUTO_COMPACT_WINDOW=200` means 200 tokens even though `/autocompact 200` means 200,000. -### - -​ - -Default auto-compact thresholds +### Default auto-compact thresholds If you don’t set an auto-compact window, Claude Code compacts when the conversation reaches the model’s context limit, except in these sessions: @@ -851,13 +651,9 @@ See the [`idleCompaction`](</docs/en/settings-reference#idlecompaction>) setting for when Claude Code also compacts a conversation you leave idle. -### - -​ - -Correct the window for a gateway or custom model ID - -Either of these startup warnings means Claude Code doesn’t recognize your session’s model ID, so it can’t tell the model’s context window and assumes 200K tokens: +### Correct the window for a gateway or custom model ID + +Either of these warnings means Claude Code doesn’t recognize your session’s model ID, so it can’t tell the model’s context window and assumes 200K tokens: ⚠ Model "my-gateway-opus" isn't recognized · context assumed to be 200k tokens · ... Claude Code doesn't recognize the model "my-gateway-opus", so it assumes a context window of 200k tokens. Update Claude Code, or see https://code.claude.com/docs/en/model-config#correct-the-window-for-a-gateway-or-custom-model-id to set the window. @@ -871,11 +667,7 @@ Once Claude Code recognizes the ID or uses the window you gave it, the warning no longer appears when you start a session on that ID. -#### - -​ - -Which IDs `CLAUDE_CODE_MAX_CONTEXT_TOKENS` applies to +#### Which IDs `CLAUDE_CODE_MAX_CONTEXT_TOKENS` applies to On an [LLM gateway](</docs/en/llm-gateway>) or other custom deployment, Claude Code can assume a context window for the model ID that differs from the model’s real window, whether or not it resolves the ID to a Claude model. Set [`CLAUDE_CODE_MAX_CONTEXT_TOKENS`](</docs/en/env-vars>) to the window Claude Code should assume instead. How the variable applies depends on the ID. Claude Code treats an ID as a provider or custom spelling when it doesn’t start with `claude-`, in any casing, or when it carries a suffix that Claude Code strips when reading the ID, such as the `@YYYYMMDD` date used on Google Cloud’s Agent Platform. Before v2.1.259, Claude Code didn’t count a stripped suffix, so an unrecognized `claude-` ID with a date suffix was treated as a bare `claude-` name. An unrecognized provider or custom spelling, the same spelling with `[1m]`, and every other ID are three separate cases: @@ -885,22 +677,14 @@ For a model ID Claude Code doesn’t recognize, set [`CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENT=1`](</docs/en/env-vars>) to have Claude Code compact only after the API rejects the conversation with a [too-long error Claude Code recognizes](</docs/en/errors#prompt-is-too-long>). Claude Code doesn’t run that recovery when a gateway [rewrites the error](</docs/en/llm-gateway-connect#troubleshoot-gateway-errors>) to wording Claude Code doesn’t recognize. -## - -​ - -Checking your current model +## Checking your current model You can see which model you’re currently using in two places: * In the [status line](</docs/en/statusline>), if you have one configured * In `/status`, which also displays your account information -## - -​ - -Add a custom model option +## Add a custom model option Use `ANTHROPIC_CUSTOM_MODEL_OPTION` to add a single custom entry to the `/model` picker without replacing the built-in aliases. This is useful for testing model IDs that Claude Code does not list by default. For LLM gateway deployments, Claude Code can populate the picker from the gateway’s `/v1/models` endpoint when `CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1` is set, so this variable is needed only when discovery is disabled or does not return the model you want. See [gateway model discovery](</docs/en/llm-gateway-protocol#model-discovery>). To list several models instead, in your own order and under labels you choose, set [`modelPicker`](</docs/en/settings-reference#modelpicker>). Its entry says which rows the picker keeps when that lineup replaces the built-in one. This example sets all three variables to make a gateway-routed Opus deployment selectable. Claude Code reads environment variables at startup, so run the exports before launching `claude`, or restart an existing session to pick them up: @@ -915,11 +699,7 @@ Claude Code lists the custom entry after the built-in entries, and any [`modelPicker`](</docs/en/settings-reference#modelpicker>) rows you append come after it. Claude Code skips validation for the model ID set in `ANTHROPIC_CUSTOM_MODEL_OPTION`, so you can use any string your API endpoint accepts. When `availableModels` is set, include the custom model ID in the allowlist as well. Otherwise Claude Code filters the custom entry from the picker and rejects a `--model` selection of it like any other excluded model. A custom ID that embeds a family name, such as `my-gateway/claude-opus-5-5`, counts as a specific entry for that family and disables its wildcard, so also list the versions you intend to keep selectable. See Merge behavior. -## - -​ - -Environment variables +## Environment variables Use the following environment variables to control the model names that the aliases map to. Each value must be a full model name, or the equivalent identifier for your API provider. To choose the model your sessions start on, set `ANTHROPIC_DEFAULT_MODEL`, which this table omits. @@ -933,11 +713,7 @@ On third-party providers, Customize pinned model display and capabilities describes what a pinned model’s row in the `/model` picker shows. Note: `ANTHROPIC_SMALL_FAST_MODEL` is deprecated in favor of `ANTHROPIC_DEFAULT_HAIKU_MODEL`. -### - -​ - -Pin models for third-party deployments +### Pin models for third-party deployments When deploying Claude Code through [Amazon Bedrock](</docs/en/amazon-bedrock>), [Google Cloud’s Agent Platform](</docs/en/google-vertex-ai>), [Microsoft Foundry](</docs/en/microsoft-foundry>), or [Claude Platform on AWS](</docs/en/claude-platform-on-aws>), pin model versions before rolling out to users. Without pinning, Claude Code uses model aliases such as `fable`, `opus`, `sonnet`, and `haiku` that resolve to a built-in default model ID for each provider. That default can lag the newest Anthropic release, and the model it points to may not yet be enabled in a user’s account. When the default is unavailable, Amazon Bedrock and Google Cloud’s Agent Platform users see a notice and the session falls back to an earlier version of the default model, or to the default Sonnet model when the default is an Opus model and no Opus version is available. Microsoft Foundry users see errors instead, because Microsoft Foundry has no equivalent startup check. On Amazon Bedrock and Google Cloud’s Agent Platform, a user who starts the session on a specific Sonnet or Opus version, for example with `--model`, `ANTHROPIC_MODEL`, or the `model` setting, pins that version as the session’s default for the matching alias: the startup check skips the built-in default it replaces and shows no fallback notice. Before v2.1.211, the check ran and could show a notice even when a session model was explicitly configured. @@ -970,11 +746,7 @@ Any `[1m]` suffix is stripped from both the allowlist entry and the requested model before matching. -### - -​ - -Customize pinned model display and capabilities +### Customize pinned model display and capabilities When you pin a model on a third-party provider, its row in the `/model` picker shows the model’s name by default if Claude Code recognizes the pinned ID, and the raw ID otherwise: @@ -1007,11 +779,7 @@ export ANTHROPIC_DEFAULT_OPUS_MODEL_DESCRIPTION='Opus 4.7 routed through a Bedrock custom endpoint' export ANTHROPIC_DEFAULT_OPUS_MODEL_SUPPORTED_CAPABILITIES='effort,xhigh_effort,max_effort,thinking,adaptive_thinking,interleaved_thinking' -### - -​ - -Override model IDs per version +### Override model IDs per version On platforms that embed Claude Code and set [`CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST`](</docs/en/env-vars>), the host’s model configuration takes precedence over managed model settings, while a managed `availableModels` allowlist stays in force unless the host supplies its own; [Exceptions to managed settings precedence](</docs/en/settings#exceptions-to-managed-settings-precedence>) says which keys and variables the host overrides. The family-level environment variables above configure one model ID per family alias. If you need to map several versions within the same family to distinct provider IDs, use the `modelOverrides` setting instead. `modelOverrides` maps individual Anthropic model IDs to the provider-specific strings that Claude Code sends to your provider’s API. When a user selects a mapped model in the `/model` picker, Claude Code uses your configured value instead of the built-in default. This lets enterprise administrators route each model version to a specific Amazon Bedrock inference profile ARN, Google Cloud’s Agent Platform version name, or Microsoft Foundry deployment name for governance, cost allocation, or regional routing. Set `modelOverrides` in your [settings file](</docs/en/settings#where-settings-live>): @@ -1025,11 +793,7 @@ Keys must be Anthropic model IDs as listed in the [Models overview](<https://platform.claude.com/docs/en/about-claude/models/overview>). For dated model IDs, include the date suffix exactly as it appears there. Unknown keys are ignored. To stop the `[claude-code:unrecognized_model]` [diagnostic line](</docs/en/errors#unrecognized-model-id-on-a-request>) for an ID such as a gateway alias, add an entry with that ID as its value. Overrides replace the built-in model IDs that back each entry in the `/model` picker. On Amazon Bedrock, `modelOverrides` entries take precedence over any inference profiles that Claude Code discovers automatically at startup. Claude Code passes values that are already provider-native, such as Amazon Bedrock inference profile ARNs or Microsoft Foundry deployment names, to the provider as-is. Overrides also apply when you pass an Anthropic model ID directly through `--model`, the `ANTHROPIC_MODEL` environment variable, or an `ANTHROPIC_DEFAULT_*_MODEL` environment variable. On Amazon Bedrock, Google Cloud’s Agent Platform, and [Mantle](</docs/en/amazon-bedrock#use-the-mantle-endpoint>), an Anthropic model ID with no `modelOverrides` entry resolves to the same provider-specific ID as the `/model` picker row for that version, when the provider supports that version. Mantle supports a subset of versions. For an Anthropic model ID outside that subset, Claude Code sends the raw ID to Mantle without mapping it, unless a `modelOverrides` entry covers it. Before v2.1.200, `--model` and the environment-variable values reached the provider as-is without going through the override map. `modelOverrides` works alongside `availableModels`. The allowlist is evaluated against the Anthropic model ID, not the override value, so an entry like `"opus"` in `availableModels` continues to match even when Opus versions are mapped to ARNs. When `enforceAvailableModels` is set in managed settings, the enforced Default resolves through `modelOverrides` from [managed settings](</docs/en/managed-settings#how-claude-code-combines-managed-sources>) only. An admin’s mapping, such as a version pinned to an inference profile ARN, is honored in the enforced Default. Overrides from user or project settings do not affect it. When `availableModels` is set in [managed settings](</docs/en/managed-settings>), only `modelOverrides` from managed settings apply to an Anthropic model ID passed directly through `--model` or the environment variables above. Claude Code ignores overrides in user or project settings for those IDs, and never resolves an ID the managed list excludes through `modelOverrides` from any settings source. This managed-source restriction requires Claude Code v2.1.200 or later. See Restrict model selection for how blocked IDs are handled. -### - -​ - -Prompt caching configuration +### Prompt caching configuration Claude Code automatically uses [prompt caching](</docs/en/prompt-caching>) to optimize performance and reduce costs. You can disable prompt caching globally or for specific model tiers: @@ -1043,11 +807,7 @@ To choose the cache TTL for the main conversation and for subagents separately, see [choose the TTL yourself](</docs/en/prompt-caching#choose-the-ttl-yourself>). For what triggers a cache miss, see [How Claude Code uses prompt caching](</docs/en/prompt-caching>). -## - -​ - -Version history +## Version history This table lists the Claude Code version at which each model alias changed the model it resolves to, newest first.
modified Modifying system prompts View current →
Show diff (271 lines)
--- a/modifying-system-prompts.md +++ b/modifying-system-prompts.md @@ -1,10 +1,6 @@ System prompts define Claude’s behavior, capabilities, and response style. Start from the `claude_code` preset for CLI or IDE-like coding tools where a human watches and steers the work. Write your own prompt for agents with a different surface, identity, or permission model. -## - -​ - -How system prompts work +## How system prompts work A system prompt is the initial instruction set that shapes how Claude behaves throughout a conversation. The Agent SDK has three starting points for it: @@ -12,11 +8,7 @@ * **`claude_code` preset**: the system prompt that the Claude Code CLI uses, with tool usage instructions and security and safety instructions. Set `systemPrompt: { type: "preset", preset: "claude_code" }` in TypeScript or `system_prompt={"type": "preset", "preset": "claude_code"}` in Python, optionally with `append` to add your own instructions on the end. * **Custom string** : a prompt you write yourself. The SDK sends only what you provide. -### - -​ - -Decide on a starting point +### Decide on a starting point The deciding factor is how closely your agent resembles Claude Code: a coding agent operating in a repository, with a human watching streaming output and steering the work. The further your product is from that, the more you’ll want to write your own prompt. @@ -36,27 +28,15 @@ The comparison table shows what each customization method preserves. -## - -​ - -Customize agent behavior +## Customize agent behavior `append` and a custom prompt string each change the system prompt directly, and an output style changes the instructions Claude Code gives Claude for every response. CLAUDE.md takes a different path: the SDK reads it and injects its content into the conversation as project context, so it shapes behavior alongside whichever system prompt you choose. [Skills](</docs/en/agent-sdk/skills>), [hooks](</docs/en/agent-sdk/hooks>), and [permissions](</docs/en/agent-sdk/permissions>) also shape behavior outside the system prompt and are covered on their own pages. -### - -​ - -CLAUDE.md files for project-level instructions +### CLAUDE.md files for project-level instructions CLAUDE.md files give Claude persistent project context and instructions. The SDK injects their content into the conversation and leaves the system prompt untouched, so they work with any system prompt configuration. For what to put in CLAUDE.md, where to place it, and how to write effective instructions, see [When to add to CLAUDE.md](</docs/en/memory#when-to-add-to-claude-md>) and the rest of [How Claude remembers your project](</docs/en/memory>). This section covers what’s specific to the SDK: how CLAUDE.md loads. The SDK reads CLAUDE.md when the matching setting source is enabled: `'project'` loads `CLAUDE.md` or `.claude/CLAUDE.md` from the working directory, and `'user'` loads `~/.claude/CLAUDE.md`. Default `query()` options enable both sources, so CLAUDE.md loads automatically. If you set `settingSources` in TypeScript or `setting_sources` in Python explicitly, include the sources you need. CLAUDE.md loading is controlled by setting sources, not by the `claude_code` preset. -#### - -​ - -Load CLAUDE.md with the SDK +#### Load CLAUDE.md with the SDK To load CLAUDE.md, set `settingSources` to include the level where you keep your CLAUDE.md. The example below loads a project-level CLAUDE.md alongside the `claude_code` preset, so Claude has both the coding-agent prompt and your project’s conventions: @@ -108,19 +88,11 @@ When you run either example, the SDK streams messages as Claude works: a system init message, assistant messages, user messages carrying tool results, and a final result message with the session outcome. CLAUDE.md is persistent across all sessions in a project, shared with your team through git, and discovered automatically without code changes. It is not loaded if you pass an empty `settingSources` array. -### - -​ - -Output styles for persistent configurations +### Output styles for persistent configurations Output styles are saved sets of instructions that change Claude’s role, tone, and output format. They’re stored as markdown files and can be reused across sessions and projects. -#### - -​ - -Create an output style +#### Create an output style An output style is a markdown file with [frontmatter](</docs/en/output-styles#frontmatter>) for metadata, followed by the prompt content. Save it to `~/.claude/output-styles/` for a user-level style available in every project, or `.claude/output-styles/` in your repository for a project-level style you can commit and share with your team. A custom output style leaves the `claude_code` preset’s software engineering instructions out and uses your own. To keep them and layer your instructions on top, set `keep-coding-instructions: true` in the frontmatter. Those instructions are only in Claude Code’s full system prompt, so the setting has no effect in a session on the shorter system prompt; set [`CLAUDE_CODE_SIMPLE_SYSTEM_PROMPT`](</docs/en/env-vars#variables>) to `0` to select the full prompt on any model. Keep them when your agent is still doing software engineering work. Leave them out when you’re replacing the role entirely. The example below defines a code-review persona that keeps the coding instructions, since reviewing code still benefits from Claude Code’s security and code-quality guidance. Save it as `~/.claude/output-styles/code-reviewer.md` to make it available across projects: @@ -140,11 +112,7 @@ 3. Suggest improvements 4. Rate code quality (1-10) -#### - -​ - -Activate an output style +#### Activate an output style Once created, activate output styles via: @@ -156,11 +124,7 @@ In the Python SDK, set `outputStyle` through the `settings` option, which takes a JSON string such as `'{"outputStyle": "Explanatory"}'` or a path to a settings file that sets it. **Note for SDK users:** Output styles are loaded when you include `settingSources: ['user']` or `settingSources: ['project']` (TypeScript) / `setting_sources=["user"]` or `setting_sources=["project"]` (Python) in your options. -### - -​ - -Append to the `claude_code` preset +### Append to the `claude_code` preset You can use the Claude Code preset with an `append` property to add your custom instructions while preserving all built-in functionality. @@ -211,11 +175,7 @@ asyncio.run(main()) -#### - -​ - -Improve prompt caching across users and machines +#### Improve prompt caching across users and machines By default, two sessions that use the same `claude_code` preset and `append` text still can’t share a prompt cache entry when their auto memory locations differ. The preset embeds that location in the system prompt ahead of your `append` text. The location defaults to an absolute path under `~/.claude/projects/` named for the repository’s path on disk, so it differs across users, machines, and checkouts. CLAUDE.md content and environment details such as the working directory, platform, shell, and OS version don’t affect the system prompt cache, because Claude Code delivers them in the conversation, not the system prompt. To make the system prompt identical across sessions, set `excludeDynamicSections: true` in TypeScript or `"exclude_dynamic_sections": True` in Python. The per-user context moves into the first user message, leaving only the static preset and your `append` text in the system prompt so identical configurations share a cache entry across users and machines. @@ -265,11 +225,7 @@ **Tradeoffs:** the text that moves out of the system prompt still reaches Claude, but in a user message. That text is at least the auto memory directory’s location, and often the whole auto memory section. Instructions in a user message carry marginally less weight than the same text in the system prompt, so Claude may follow its auto memory guidance less consistently. Enable this option when cross-session cache reuse matters more than that. For the equivalent flag in non-interactive CLI mode, see [`--exclude-dynamic-system-prompt-sections`](</docs/en/cli-reference>). -### - -​ - -Custom system prompts +### Custom system prompts You can provide a custom string as `systemPrompt` to replace the default entirely with your own instructions. @@ -328,11 +284,7 @@ In Python, load a large custom prompt from a file with `system_prompt={"type": "file", "path": "..."}` instead of passing it as a string. The Python SDK passes a string prompt as one command-line argument to the CLI subprocess, so a prompt that exceeds the OS argument-length limit fails at process spawn before any API request is sent. On Linux the error is `Argument list too long`. See [`SystemPromptFile`](</docs/en/agent-sdk/python#systempromptfile>) for the platform thresholds and the Windows behavior. -#### - -​ - -Cache the static part of a custom prompt +#### Cache the static part of a custom prompt In the TypeScript SDK, you can pass a custom prompt as an array of strings instead of one string, with the `SYSTEM_PROMPT_DYNAMIC_BOUNDARY` marker between the static part and the rest. Use this when your prompt combines instructions that are the same on every request with context that changes per request, such as the customer or ticket the agent is handling. When you pass both parts as one string, a change to the per-request part changes the whole system prompt, so the static instructions miss the cache too. The array form isn’t available in the Python SDK; [`ClaudeAgentOptions`](</docs/en/agent-sdk/python#claudeagentoptions>) lists the forms `system_prompt` accepts. @@ -367,46 +319,26 @@ With the CLI’s [`--system-prompt` or `--system-prompt-file` flags](</docs/en/cli-reference#system-prompt-flags>), the prompt is one string, so there is no array to carry the marker. Include a line containing only `__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__` between the static and per-request parts instead. Claude Code splits the prompt at the first such line into the same two blocks and removes that line. Requires Claude Code v2.1.275 or later. In the SDK, prefer the array form, which carries the boundary without a marker line. -### - -​ - -Change the prompt of an existing session +### Change the prompt of an existing session By default, if you pass a different `append` or custom prompt when you return to a session with `resume` or `continue`, Claude doesn’t see it on the next turn. Claude Code records the system prompt on a session’s first request and reuses that record until the session is compacted. The new text takes effect after that compaction, or in a new session. -#### - -​ - -Update Claude’s instructions mid-session +#### Update Claude’s instructions mid-session If the instructions you put in the system prompt need to change while a session is running, for example because your user switched the agent to a read-only mode or edited its configuration in your app, send the new instructions in the conversation instead of changing `systemPrompt`: * **In your next message** : include the new instructions in the next user message you send. * **From a hook** : return [`additionalContext`](</docs/en/hooks#add-context-for-claude>) from a `UserPromptSubmit` or `PostToolUse` [hook callback](</docs/en/agent-sdk/hooks#outputs>), written as a factual statement such as “The workspace is now read-only”. The SDK inserts the text into the conversation at the point where the hook fired, so the recorded prompt stays unchanged. -#### - -​ - -Turn recording off while you iterate on wording +#### Turn recording off while you iterate on wording While you iterate on prompt wording and want each edit to reach a session you resume, set `snapshot` to false on the object form of the system prompt. Claude Code then rebuilds the prompt on every request. The field is available on the preset and custom forms of [`systemPrompt`](</docs/en/agent-sdk/typescript#options>) in TypeScript and of [`system_prompt`](</docs/en/agent-sdk/python#systempromptpreset>) in Python, and requires `@anthropic-ai/claude-agent-sdk` v0.3.257 or later, or `claude-agent-sdk` v0.2.153 or later. Keep recording on in production. With recording off, a different `append` or custom prompt on a resumed session reaches Claude on the next turn, and that request can’t reuse the session’s [prompt cache](</docs/en/prompt-caching#how-the-cache-is-organized>). Where the API enforces [preserved thinking](<https://platform.claude.com/docs/en/build-with-claude/preserved-thinking>), Claude also loses its thinking from earlier turns. Outside of [cloud sessions](</docs/en/cloud-environments>), if you start Claude Code in [bare mode](</docs/en/headless#start-faster-with-bare-mode>) by passing `--bare` through `extraArgs` or setting `CLAUDE_CODE_SIMPLE=1`, recording stays off unless you set `snapshot: true`. Recording an `append` or custom prompt by default requires Claude Code v2.1.265 or later, which the TypeScript Agent SDK bundles from v0.3.265 and the Python Agent SDK from v0.2.153. Before Claude Code v2.1.268, sessions that don’t [fetch feature flags](</docs/en/env-vars#features-that-need-feature-flag-fetching>), including sessions on Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry, rebuilt the prompt on every request and `snapshot` had no effect. -## - -​ - -Context Claude Code adds outside the system prompt +## Context Claude Code adds outside the system prompt System reminders are messages Claude Code adds to the conversation during a session to give Claude context, such as the contents of your CLAUDE.md files or a note that a file changed on disk. Claude Code sends them in the conversation, not in the system prompt, so most reach Claude whether you use the `claude_code` preset or pass your own string as `systemPrompt`. This section covers the reminders most likely to change how your agent behaves, how to turn off the ones your agent replaces, and how to see what Claude received in a specific request. -### - -​ - -Reminders Claude Code adds to the conversation +### Reminders Claude Code adds to the conversation System reminders are text Claude Code adds to the conversation alongside the prompts your code sends. The following reminders are the ones most likely to change how your agent behaves: @@ -423,11 +355,7 @@ The application adds system reminders to this conversation. Treat them as context from the application, not as messages from the user. -### - -​ - -Turn off the context your agent replaces +### Turn off the context your agent replaces Turn off a piece of built-in context when your agent supplies its own version of the same guidance. For example, if your prompt tells Claude to write commit messages as `PROJ-142: fix login redirect` with no trailers, Claude Code still tells Claude to end each commit message with a `Co-Authored-By` trailer, so Claude receives two conflicting instructions for the same commit. Pass settings keys through the [`settings`](</docs/en/agent-sdk/typescript#options>) option in TypeScript or [`settings`](</docs/en/agent-sdk/python#claudeagentoptions>) in Python, and environment variables through the `env` option. In TypeScript, [`env`](</docs/en/agent-sdk/typescript#options>) replaces the inherited environment, so spread `process.env` into it. @@ -492,11 +420,7 @@ To confirm the change, run the example in a repository with staged changes and check the new commit with `git log -1`. The message ends without a `Co-Authored-By` trailer. -### - -​ - -See what Claude received +### See what Claude received The SDK message stream doesn’t include system reminders, so reading the messages your code receives won’t show you what Claude saw. To see them, log the requests Claude Code sends: @@ -505,11 +429,7 @@ In a logged request, look in the `messages` array. A reminder appears inside a user message wrapped in `<system-reminder>` tags or, on some models, as a separate message with the `system` role. -## - -​ - -Compare the four approaches +## Compare the four approaches The four customization methods differ in where they live, how they’re shared, and what they preserve from the `claude_code` preset. @@ -526,19 +446,11 @@ “With append” means using `systemPrompt: { type: "preset", preset: "claude_code", append: "..." }` in TypeScript or `system_prompt={"type": "preset", "preset": "claude_code", "append": "..."}` in Python. CLAUDE.md doesn’t change the system prompt itself: the SDK injects its content into the conversation as project context. -## - -​ - -Combine approaches +## Combine approaches The approaches compose. A persistent output style or CLAUDE.md sets the long-lived behavior, and `append` layers session-specific instructions on top without touching the saved configuration. -### - -​ - -Combine an output style with session-specific additions +### Combine an output style with session-specific additions The example below assumes a Code Reviewer output style is already active. The `append` block layers session-specific focus areas on top of the persona, so a single review session can prioritize OAuth and token storage without changing the saved output style: @@ -598,11 +510,7 @@ asyncio.run(main()) -## - -​ - -See also +## See also * [Output styles](</docs/en/output-styles>): create, manage, and share output styles for the CLI, including the file format and storage locations * [How Claude remembers your project](</docs/en/memory>): what to put in CLAUDE.md, where to place it, and how to write effective project instructions
modified Monitoring View current →
Show diff (1044 lines)
--- a/monitoring-usage.md +++ b/monitoring-usage.md @@ -2,11 +2,7 @@ For the Claude API or Managed Agents, see [OpenTelemetry for the Claude API](<https://platform.claude.com/docs/en/manage-claude/opentelemetry>). -## - -​ - -Quick start +## Quick start Configure OpenTelemetry using environment variables: @@ -33,11 +29,7 @@ To verify a setup that exports metrics, check your backend for the `claude_code.session.count` metric, which Claude Code emits when a session starts. To verify a logs-only setup, submit a prompt and check for the `claude_code.user_prompt` event. If nothing arrives, start Claude Code with `claude --debug-file <path>` and check the log it writes to that path. Claude Code reports failures from the exporters you configure as `[3P telemetry]` errors, where 3P means third-party. Lines prefixed `[Anthropic telemetry]` describe [Anthropic’s separate operational telemetry](</docs/en/data-usage#telemetry-services>) and don’t indicate a problem with your setup. For full configuration options, see the [OpenTelemetry specification](<https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options>). -## - -​ - -Administrator configuration +## Administrator configuration Administrators can configure OpenTelemetry settings for all users through the [managed settings file](</docs/en/managed-settings#delivery-mechanisms>). See the [settings precedence](</docs/en/settings#settings-precedence>) for more information about how settings are applied. Example managed settings configuration: @@ -54,11 +46,7 @@ In the Claude Desktop app, Code tab sessions read these managed settings from the sources that [reach each kind of Desktop session](</docs/en/desktop#managed-settings>). The OpenTelemetry form for Cowork under **Monitoring** in the admin console’s [Data and privacy settings](<https://claude.ai/admin-settings/data-privacy-controls>) applies to Cowork sessions only, so neither the terminal CLI nor the Code tab exports to a collector you set there. Claude Code ignores the [OpenTelemetry exporter variables](</docs/en/settings-reference#variables-claude-code-ignores-in-env>) in a repository’s `.claude/settings.json` and `.claude/settings.local.json`, so a repository can’t use them to turn telemetry on, choose where it goes, or capture content. Set them in managed settings, or have each developer set them in their shell or `~/.claude/settings.json`. A repository can still turn a signal off by setting its exporter selector, such as `OTEL_LOGS_EXPORTER`, to `none`, unless managed settings, a `--settings` file, or the environment you start Claude Code from sets that variable. Claude Code doesn’t pass `OTEL_*` environment variables to the subprocesses it spawns, including the Bash tool, hooks, MCP servers, and language servers. An OpenTelemetry-instrumented application that you run through the Bash tool doesn’t inherit Claude Code’s exporter endpoint or headers, so set those variables directly in the command if that application needs to export its own telemetry. -### - -​ - -How managed settings lock the OTLP destination +### How managed settings lock the OTLP destination When you set an `OTEL_EXPORTER_OTLP_*` variable in managed settings, Claude Code removes conflicting developer-set variables at startup and logs a warning in the debug log. What it removes depends on which variable you set: @@ -75,17 +63,9 @@ Claude Code doesn’t remove per-signal variables that you set in managed settings itself, so you can route one signal to a different collector by setting its variable there, as the SIEM example does. If you set a per-signal credential there, Claude Code removes the developer-set endpoint for that signal. This removal behavior changes where telemetry is delivered, not what Claude Code collects. Before v2.1.217, every variable followed per-key settings precedence independently, so a signal-specific endpoint set in user settings or the shell redirected that signal away from the managed collector. When the desktop app or a [self-hosted environment](</docs/en/self-hosted-environments>) runner launches Claude Code and names an OTLP endpoint in the environment it provides, Claude Code pins the destination the same way: the launcher’s telemetry variables remove developer-set variables exactly as managed settings do. Claude Code doesn’t remove variables that the launcher itself set. Requires Claude Code v2.1.251 or later. -## - -​ - -Configuration details - -### - -​ - -Common configuration variables +## Configuration details + +### Common configuration variables These variables configure exporters, endpoints, and export behavior for all deployments. If you set a per-signal endpoint or protocol variable, such as `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT`, Claude Code uses it instead of the generic variable for that signal. If you set a per-signal headers variable, such as `OTEL_EXPORTER_OTLP_METRICS_HEADERS`, Claude Code merges it with the generic `OTEL_EXPORTER_OTLP_HEADERS` for that signal. On machines with managed settings, see How managed settings lock the OTLP destination for what Claude Code removes. @@ -117,11 +97,7 @@ For the `http/protobuf` and `http/json` protocols, Claude Code sends each export request with a `Content-Length` header. -### - -​ - -mTLS authentication +### mTLS authentication How you configure client certificates for the OTLP exporter depends on the OTLP protocol in use for that signal, set via `OTEL_EXPORTER_OTLP_PROTOCOL` or the per-signal override. The same configuration applies to metrics, logs, and traces. @@ -132,11 +108,7 @@ For `grpc`, the OpenTelemetry SDK reads the standard OTLP variables directly, so existing configurations that set the per-signal metrics variables continue to work. On machines with managed settings, Claude Code may remove developer-set per-signal credentials and endpoints at startup. -### - -​ - -Metrics cardinality control +### Metrics cardinality control The following environment variables control which attributes are included in metrics and events to manage cardinality: @@ -151,11 +123,7 @@ Lower cardinality generally means better performance and lower storage costs but less granular data for analysis. -### - -​ - -Traces (beta) +### Traces (beta) Distributed tracing exports spans that link each user prompt to the API requests and tool executions it triggers, so you can view a full request as a single trace in your tracing backend. Tracing is off by default. To enable it, set both `CLAUDE_CODE_ENABLE_TELEMETRY=1` and `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1`, then set `OTEL_TRACES_EXPORTER` to choose where spans are sent. Traces reuse the common OTLP configuration for endpoint, protocol, headers, and mTLS. On machines with managed settings, Claude Code may remove developer-set per-signal credentials and endpoints at startup. @@ -170,11 +138,7 @@ Spans redact user prompt text, tool input details, and tool content by default. Set `OTEL_LOG_USER_PROMPTS=1`, `OTEL_LOG_TOOL_DETAILS=1`, and `OTEL_LOG_TOOL_CONTENT=1` to include them. When tracing is active, Bash and PowerShell subprocesses automatically inherit a `TRACEPARENT` environment variable containing the W3C trace context of the active tool execution span. This lets any subprocess that reads `TRACEPARENT` parent its own spans under the same trace, enabling end-to-end distributed tracing through scripts and commands that Claude runs. When tracing is active and Claude Code is connected directly to the Anthropic API, each model request carries a W3C `traceparent` header set to the `claude_code.llm_request` span’s context, and the API’s `traceresponse` header is recorded as a span link. Together these connect Claude Code’s client-side spans to the server-side trace through any compliant intermediary. Outbound HTTP MCP requests carry `traceparent` the same way. The header is not sent to third-party providers. By default, the `traceparent` header on model and HTTP MCP requests is sent only when `ANTHROPIC_BASE_URL` is unset or points at the Anthropic API, since some proxies reject unrecognized headers. The subprocess `TRACEPARENT` variable is controlled by the same switch for consistency. If you run Claude Code through a custom `ANTHROPIC_BASE_URL` proxy and want trace context propagated, set `CLAUDE_CODE_PROPAGATE_TRACEPARENT=1`. In Agent SDK and non-interactive sessions started with `-p`, Claude Code also reads `TRACEPARENT` and `TRACESTATE` from its own environment when starting each interaction span. This lets an embedding process pass its active W3C trace context into the subprocess so Claude Code’s spans appear as children of the caller’s distributed trace. Interactive sessions ignore inbound `TRACEPARENT` to avoid accidentally inheriting ambient values from CI or container environments. The inbound trace context also applies to events. In Agent SDK and `-p` sessions with `TRACEPARENT` set, each OTLP event log record carries `trace_id` and `span_id` values that join it to your application’s trace, even when the traces exporter isn’t configured, so your logging backend can correlate events with the rest of the trace. A record emitted while an interaction is active carries the interaction span’s IDs, even when Claude Code emits it outside the span’s async context, such as in a permission prompt callback or for a record buffered during startup and exported later. A record emitted with no active interaction span carries the inbound `TRACEPARENT` IDs directly. -#### - -​ - -Span hierarchy +#### Span hierarchy Each user prompt starts a `claude_code.interaction` root span. API calls, tool calls, and hook executions are recorded as its children. Tool spans have two child spans of their own: one for the time spent waiting on a permission decision and one for the execution itself. When the Agent tool, or legacy Task tool, spawns a subagent, the subagent’s API and tool spans nest under the parent’s `claude_code.tool` span. @@ -188,11 +152,7 @@ In Agent SDK and `claude -p` sessions, `claude_code.interaction` itself becomes a child of the caller’s span when `TRACEPARENT` is set in the environment. When a `PreToolUse` hook [defers a tool call](</docs/en/hooks#defer-a-tool-call-for-later>), Claude Code saves the trace context of the turn that deferred it. When you resume the session and the tool re-runs, the tool’s spans join that earlier turn’s trace as children of the turn’s `claude_code.interaction` span. -#### - -​ - -Span attributes +#### Span attributes Every span carries the standard attributes plus a `span.type` attribute matching its name. The tables below list the additional attributes set on each span. The `llm_request`, `tool.execution`, and `hook` spans set OpenTelemetry status `ERROR` when they record a failure; the other spans always end with status `UNSET`. **`claude_code.interaction`** @@ -331,19 +291,11 @@ Under detailed beta tracing with `OTEL_LOG_USER_PROMPTS=1`, Claude Code also emits a `claude_code.system_prompt` event that carries the complete system prompt, truncated at the content limit. It arrives the first time a session sends each distinct system prompt, and again after compaction. -### - -​ - -Dynamic headers +### Dynamic headers For enterprise environments that require dynamic authentication, you can configure a script to generate headers dynamically. Dynamic headers apply only to the `http/protobuf` and `http/json` protocols. With the `grpc` protocol, Claude Code uses only the static headers variables, `OTEL_EXPORTER_OTLP_HEADERS` and its per-signal variants. -#### - -​ - -Settings configuration +#### Settings configuration Add to your `.claude/settings.json`, replacing the path with your own script: @@ -353,11 +305,7 @@ The value can be the path to an executable file, including a path that contains spaces, or a shell command line with arguments. On Windows, the value always runs through the shell, so quote a path that contains spaces inside the JSON value. -#### - -​ - -Script requirements +#### Script requirements The script must output valid JSON with string key-value pairs representing HTTP headers: @@ -372,19 +320,11 @@ * The debug log, when running with [`--debug`](</docs/en/cli-reference#cli-flags>) or after running `/debug` in the session * stderr, in non-interactive sessions started with `-p` -#### - -​ - -Refresh behavior +#### Refresh behavior The headers helper script runs at startup and periodically thereafter to support token refresh. By default, the script runs every 29 minutes. Customize the interval with the `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS` environment variable. -### - -​ - -Multi-team organization support +### Multi-team organization support Organizations with multiple teams or departments can add custom attributes to distinguish between different groups using the `OTEL_RESOURCE_ATTRIBUTES` environment variable: @@ -405,7 +345,7 @@ * **No spaces allowed** : values can’t contain spaces. For example, `user.organizationName=My Company` is invalid * **Format** : must be comma-separated key=value pairs: `key1=value1,key2=value2` * **Allowed characters** : only US-ASCII characters excluding control characters, whitespace, double quotes, commas, semicolons, and backslashes - * **Special characters** : characters outside the allowed range must be percent-encoded + * **Special characters** : characters outside the allowed range must be percent-encoded, and an `=` inside a value must be written as `%3D` For a value that would need a space, use underscores or camelCase instead. The following examples set `org.name` with each form: @@ -418,11 +358,7 @@ Wrapping values in quotes doesn’t escape spaces. For example, `org.name="My Company"` results in the literal value `"My Company"` with the quotes included, not `My Company`. -### - -​ - -Attribute telemetry to Desktop SSH sessions +### Attribute telemetry to Desktop SSH sessions To see which remote machine a [Desktop SSH session](</docs/en/desktop#ssh-sessions>) ran on, name each machine in a custom attribute. Metrics and events don’t name the machine a session ran on. On each remote machine, add `OTEL_RESOURCE_ATTRIBUTES` to the `env` block that turns telemetry on, in the [managed settings file the session reads](</docs/en/desktop#managed-settings>). Write the name out in each machine’s file. Claude Code doesn’t expand the value, so `host.name=$(hostname)` arrives as those characters. The following example names the machine `build-7`: @@ -444,11 +380,7 @@ * **A value has a space inside it** : Claude Code then copies none of the keys onto events or datapoints and reports no error. Take the space out of the value. * **Something else already sets the variable** : in a session that the desktop app starts, a variable already set in the launch environment [takes precedence over settings files](</docs/en/settings-reference#how-env-values-interact-with-your-shell>). The [debug log](</docs/en/debug-your-config>) names each ignored variable. When a third-party Desktop deployment names an OTLP endpoint in the environment it provides, that environment carries Desktop’s own `OTEL_RESOURCE_ATTRIBUTES`. -### - -​ - -Example configurations +### Example configurations Set these environment variables before running `claude`. Each scenario below shows a complete configuration, and each variable is described under Common configuration variables. To confirm a configuration took effect, check your backend for the `claude_code.session.count` metric after starting a session; the Quick start covers logs-only verification and what to check when nothing arrives. For console debugging with a 1-second export interval: @@ -498,11 +430,7 @@ export OTEL_EXPORTER_OTLP_PROTOCOL=grpc export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 -## - -​ - -Telemetry from cloud sessions and Claude Tag +## Telemetry from cloud sessions and Claude Tag [Cloud sessions](</docs/en/claude-code-on-the-web>), including [Claude Tag](<https://claude.com/docs/claude-tag/overview>) channel sessions, run in [cloud environments](</docs/en/cloud-environments>) rather than on your users’ devices, so a managed settings file or shell profile on those devices doesn’t configure their telemetry. For sessions in Anthropic-hosted environments, this section covers where to set the telemetry variables, how to make your collector reachable from the environment, and how to tell cloud and Claude Tag sessions apart in the exported data. To export telemetry from those sessions, set `CLAUDE_CODE_ENABLE_TELEMETRY` and the `OTEL_*` variables, using the same keys as the administrator configuration example, in one of two places: @@ -515,11 +443,7 @@ * **Claude Tag channels** : make the allowlist and any environment-variable changes on the [shared environment](</docs/en/cloud-environments#organization-shared-environments>) set as your organization’s default or pinned to the channel. * **Cowork is configured separately** : Cowork sessions don’t receive server-managed settings, as the [surface coverage table](</docs/en/model-config#surface-coverage>) shows, so the server-managed `env` block doesn’t configure their telemetry. -### - -​ - -Attribute telemetry to cloud sessions +### Attribute telemetry to cloud sessions By default, metrics and events from a cloud session carry the standard attributes, including `session.id`, `ccr.session.id`, and `organization.id`, so you can filter by session or organization without extra configuration. The `ccr.session.id` value is the session’s `CLAUDE_CODE_REMOTE_SESSION_ID`. To turn it into the session’s transcript URL, see [Link output back to the session](</docs/en/cloud-environments#link-output-back-to-the-session>). To tell cloud sessions apart, group or filter on `ccr.session.id`, not `session.id`. To attribute telemetry in more detail, use these options: @@ -528,17 +452,9 @@ In Claude Tag channel sessions, Claude works as your organization’s [shared identity](</docs/en/cloud-environments#set-the-environment-a-claude-tag-channel-uses>) rather than as any member, so don’t rely on the `user.*` attributes to identify who tagged Claude. -## - -​ - -Available metrics and events - -### - -​ - -Standard attributes +## Available metrics and events + +### Standard attributes All metrics and events share these standard attributes: @@ -570,11 +486,7 @@ * `agent_id`: identifier of the [subagent](</docs/en/sub-agents>) that raised the event, such as `a3f2c1b4d5e6f7a80`. Events that carry it include a subagent’s API and tool events, its `assistant_response` events, and `subagent_completed` for the finished subagent. Absent on main-session and [in-process teammate](</docs/en/agent-teams#choose-a-display-mode>) events. The subagent’s span `agent_id` is the same value, or adds a label after the leading `a` as in `acompact-3f2c1b4d5e6f7a80`. Requires Claude Code v2.1.310 or later * `parent_agent_id`: the `agent_id` of the agent that spawned or last resumed the subagent that raised the event. Absent when that agent is the main session. Requires Claude Code v2.1.310 or later -#### - -​ - -Repository attributes +#### Repository attributes Set `OTEL_METRICS_INCLUDE_REPOSITORY=true` to tag metrics and events with the identity of the session’s repository, so a shared collector can attribute usage per repository. Requires Claude Code v2.1.269 or later. Claude Code derives these attributes once per session from the repository’s `origin` remote. When the HTTPS and SSH remotes of a repository name the same host and the same path, as they do on GitHub, GitLab, and Bitbucket Cloud, both produce identical values: @@ -587,11 +499,7 @@ Values are lowercased, and credentials, query strings, and fragments from the remote URL never appear in them. The attributes are omitted when the session has no `origin` remote, when the remote isn’t URL-shaped, or when the only enclosing repository is your home directory. To get these attributes from a [cloud session](</docs/en/claude-code-on-the-web>), set the telemetry variables, including `OTEL_METRICS_INCLUDE_REPOSITORY`, on its [cloud environment](</docs/en/cloud-environments#set-environment-variables>). Also allow your collector’s domain in the environment’s [network access](</docs/en/cloud-environments#network-access>). A `vcs.*` key you declare in `OTEL_RESOURCE_ATTRIBUTES` replaces the derived value for that key. If you declare `vcs.repository.url.full`, Claude Code never reads the remote and reports only the keys you declare. If HTTPS and SSH clones of one repository report different values, such as on a self-hosted install whose HTTPS clone URL carries a path prefix the SSH URL lacks, declare `vcs.repository.url.full` in `OTEL_RESOURCE_ATTRIBUTES` along with every other `vcs.*` key you want reported. Every clone then reports the identity you declare. The attributes flow only to your own exporters; Anthropic’s telemetry drops every `vcs.*` key. -### - -​ - -Metrics +### Metrics Claude Code exports the following metrics. The Unit column shows the OpenTelemetry unit string attached to each metric; count metrics carry none. @@ -608,30 +516,18 @@ When `prometheus` is the only exporter listed in `OTEL_METRICS_EXPORTER`, Claude Code omits the `USD`, `tokens`, and `s` units from the exported metrics so the scrape stays valid Prometheus text format. Metric names don’t change, and configurations that combine exporters, such as `otlp,prometheus`, keep the units. -### - -​ - -Metric details +### Metric details Each metric includes the standard attributes listed above. Metrics with additional context-specific attributes are noted below. -#### - -​ - -Session counter +#### Session counter Incremented at the start of each session. To count people instead, see Usage monitoring. **Attributes** : * All standard attributes * `start_type`: How the session was started. One of `"fresh"`, `"resume"`, `"continue"`, or `"agents_view"`. The `"agents_view"` value identifies the `claude agents` dashboard process, a user-launched local UI rather than a conversational session. Filter on this value to separate UI process launches from conversational sessions in your dashboards. -#### - -​ - -Lines of code counter +#### Lines of code counter Incremented when code is added or removed. **Attributes** : @@ -639,31 +535,19 @@ * `type`: (`"added"`, `"removed"`) * `model`: Model identifier for the model that made the change (for example, “claude-sonnet-5”) -#### - -​ - -Pull request counter +#### Pull request counter Incremented when Claude Code creates a pull request or merge request through a shell command or an MCP tool. **Attributes** : * All standard attributes -#### - -​ - -Commit counter +#### Commit counter Incremented when creating git commits via Claude Code. **Attributes** : * All standard attributes -#### - -​ - -Cost counter +#### Cost counter Incremented after each API request. The `agent.name`, `skill.name`, `plugin.name`, `mcp_server.name`, and `mcp_tool.name` attributes each redact some names to a `"custom"` or `"third-party"` placeholder by default. If you set `OTEL_LOG_TOOL_DETAILS=1`, they carry the real names instead. Before v2.1.273, the cost and token counters and the `api_request`, `api_error`, and `api_refusal` events carried the redacted values even with `OTEL_LOG_TOOL_DETAILS=1` set. **Attributes** : @@ -680,11 +564,7 @@ * From v2.1.312, the name of a remote server with a fixed URL that a plugin from Anthropic’s official marketplace declares also appears verbatim, as `plugin_<plugin>_<server>`. That name is replaced with `"custom"` when the plugin’s marketplace copy didn’t come from Anthropic’s registered source, such as one mounted from a seed directory in a cloud session. * `mcp_tool.name`: MCP tool whose result this request consumed, with the same redaction and version behavior as `mcp_server.name`, except that it can read `"custom"` when `mcp_server.name` shows a `plugin_<plugin>_<server>` name. Absent when the request consumed no MCP tool result. -#### - -​ - -Token counter +#### Token counter Incremented after each API request. **Attributes** : @@ -696,11 +576,7 @@ * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request. See Cost counter for details. * `agent.name`, `skill.name`, `plugin.name`, `marketplace.name`, `mcp_server.name`, `mcp_tool.name`: Skill, plugin, agent, and MCP attribution for the request. See Cost counter for definitions and redaction behavior. -#### - -​ - -Code edit tool decision counter +#### Code edit tool decision counter Incremented when user accepts or rejects Edit, Write, or NotebookEdit tool usage. **Attributes** : @@ -710,30 +586,18 @@ * `source`: Where the decision came from. One of `"config"`, `"hook"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"`. See the Tool decision event for what each value means. * `language`: Programming language of the edited file, such as `"TypeScript"`, `"Python"`, `"JavaScript"`, or `"Markdown"`. Returns `"unknown"` for unrecognized file extensions. -#### - -​ - -Active time counter +#### Active time counter Tracks actual time spent actively using Claude Code, excluding idle time. This metric is incremented during user interactions, such as typing and reading responses, and during CLI processing, such as tool execution and AI response generation. **Attributes** : * All standard attributes * `type`: `"user"` for keyboard interactions, `"cli"` for tool execution and AI responses -### - -​ - -Events +### Events Claude Code exports the following events via OpenTelemetry logs/events (when `OTEL_LOGS_EXPORTER` is configured): -#### - -​ - -Event correlation attributes +#### Event correlation attributes When a user submits a prompt, Claude Code may make multiple API calls and run several tools. The `prompt.id` attribute lets you tie all of those events back to the single prompt that triggered them. @@ -751,11 +615,7 @@ * `request_id` on the API events, persisted as `requestId` on the transcript’s assistant entries * `tool_use_id` on `tool_result` and `tool_decision` events, and on `safety_event` events except those for the end of a turn -#### - -​ - -User prompt event +#### User prompt event Logged when a prompt is submitted, including on turns Claude Code starts on its own. **Event Name** : `claude_code.user_prompt` **Attributes** : @@ -770,11 +630,7 @@ * `command_name`: Command name when the prompt invokes one. Built-in and bundled command names such as `compact` or `debug` are emitted as-is; aliases such as `reset` emit as typed rather than the canonical name. Custom, plugin, and MCP command names collapse to `custom` or `mcp` unless `OTEL_LOG_TOOL_DETAILS=1` is set * `command_source`: Origin of the command when present: `builtin`, `custom`, or `mcp`. Plugin-provided commands report as `custom` -#### - -​ - -Assistant response event +#### Assistant response event Logged after each API request that returns text content from the model. Only the response’s text blocks are included; thinking blocks and tool-use blocks are excluded. **Event Name** : `claude_code.assistant_response` **Attributes** : @@ -789,11 +645,7 @@ * `message.uuid`: UUID of the response’s final transcript entry. An API response is persisted as one transcript entry per content block; this is the last one, which the next turn’s `parentUuid` chains from. * `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name -#### - -​ - -Tool result event +#### Tool result event Logged when a tool completes execution. Not emitted if the tool call was rejected; see the Tool decision event for rejections. **Event Name** : `claude_code.tool_result` **Attributes** : @@ -822,11 +674,7 @@ * For Agent tool or legacy Task tool: includes `subagent_type` * `tool_input` (when `OTEL_LOG_TOOL_DETAILS=1`): JSON-serialized tool arguments. Individual values over 512 characters are truncated, and the full payload is bounded to ~4 K characters. Applies to all tools including MCP tools. -#### - -​ - -API request event +#### API request event Logged for each API request to Claude. **Event Name** : `claude_code.api_request` **Attributes** : @@ -850,11 +698,7 @@ * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request: `"low"`, `"medium"`, `"high"`, `"xhigh"`, or `"max"`. Absent when Claude Code sends no effort level, for example on a model that doesn’t support effort. * `agent.name`, `skill.name`, `plugin.name`, `marketplace.name`, `mcp_server.name`, `mcp_tool.name`: Skill, plugin, agent, and MCP attribution for the request. See Cost counter for definitions and redaction behavior. -#### - -​ - -API error event +#### API error event Logged when an API request to Claude fails. **Event Name** : `claude_code.api_error` **Attributes** : @@ -874,11 +718,7 @@ * `effort`: [Effort level](</docs/en/model-config#adjust-effort-level>) applied to the request. Absent when Claude Code sends no effort level, for example on a model that doesn’t support effort. * `agent.name`, `skill.name`, `plugin.name`, `marketplace.name`, `mcp_server.name`, `mcp_tool.name`: Skill, plugin, agent, and MCP attribution for the request. See Cost counter for definitions and redaction behavior. -#### - -​ - -API refusal event +#### API refusal event Logged when an API request returns `stop_reason: "refusal"`. Refusals arrive on a successful response stream rather than as an HTTP error, so the `api_error` event doesn’t fire for them. This event lets you track refusal frequency and group refusals by the same attributes as `api_request` and `api_error`. **Event Name** : `claude_code.api_refusal` **Attributes** : @@ -898,11 +738,7 @@ * `category`: The `stop_details.category` value from the API response. One of `"cyber"`, `"bio"`, `"frontier_llm"`, or `"reasoning_extraction"`. Only present when `OTEL_LOG_TOOL_DETAILS=1` is set and `has_category` is `true`. * `agent.name`, `skill.name`, `plugin.name`, `marketplace.name`, `mcp_server.name`, `mcp_tool.name`: Skill, plugin, agent, and MCP attribution for the request. See Cost counter for definitions and redaction behavior. -#### - -​ - -API request body event +#### API request body event Logged for each API request attempt when `OTEL_LOG_RAW_API_BODIES` is set. One event is emitted per attempt, so retries with adjusted parameters each produce their own event. **Event Name** : `claude_code.api_request_body` **Attributes** : @@ -918,11 +754,7 @@ * `query_source`: Subsystem that issued the request (for example, `"compact"`) * `request_body_id`: UUID that identifies this attempt’s request body. The `api_response_body` event for the attempt that succeeds carries the same value, so you can pair a response with the exact request that produced it. Requires Claude Code v2.1.274 or later -#### - -​ - -API response body event +#### API response body event Logged for each successful API response when `OTEL_LOG_RAW_API_BODIES` is set. In file mode (`OTEL_LOG_RAW_API_BODIES=file:<dir>`), Claude Code also appends one JSON line to `<dir>/index.jsonl` for each successful response, with the fields `timestamp`, `session_id`, `query_source`, `model`, `request_id`, `message_id`, `message_uuid`, `request_file`, and `response_file`. Read it to find the request and response files behind a given transcript message without querying your telemetry backend. The index file requires Claude Code v2.1.274 or later. **Event Name** : `claude_code.api_response_body` **Attributes** : @@ -941,11 +773,7 @@ * `message.id`: Message ID the API assigned to the response, the `id` field of the response body. Requires Claude Code v2.1.274 or later * `message.uuid`: UUID of the response’s final transcript entry. Together with `request_body_id`, it links a transcript message to the request and response bodies behind it. Requires Claude Code v2.1.274 or later -#### - -​ - -Tool decision event +#### Tool decision event Logged when a tool permission decision is made (accept/reject). **Event Name** : `claude_code.tool_decision` **Attributes** : @@ -1010,11 +838,7 @@ `permission_mode`, `classifier_category`, and `classifier_verdict` drop in this order on Claude Code v2.1.302 or later. `parent_agent_id`, `agent_id`, and `request_id` require v2.1.310 or later. -#### - -​ - -Safety event +#### Safety event Claude Code has stopped sending `claude_code.safety_event`: @@ -1102,11 +926,7 @@ A prompt has no category when no `category` value names its check, such as the `default` mode prompt for an edit inside your working directory. -#### - -​ - -Permission mode changed event +#### Permission mode changed event Logged when the permission mode changes, for example from `Shift+Tab` cycling, exiting plan mode, or an auto mode gate check. To group tool calls by the permission mode each was checked in, use `permission_mode` on the Tool decision event. **Event Name** : `claude_code.permission_mode_changed` **Attributes** : @@ -1118,11 +938,7 @@ * `to_mode`: The new permission mode * `trigger`: What caused the change, for example `"shift_tab"`, `"exit_plan_mode"`, or `"auto_gate_denied"`. Absent for some changes, such as when the SDK sets the permission mode through [`setPermissionMode()`](</docs/en/agent-sdk/typescript#query-object>) -#### - -​ - -Auth event +#### Auth event Logged when `/login` or `/logout` completes. **Event Name** : `claude_code.auth` **Attributes** : @@ -1136,11 +952,7 @@ * `error_category`: Categorical error kind when the action failed. The raw error message is never included * `status_code`: HTTP status code as a string when the action failed with an HTTP error -#### - -​ - -MCP server connection event +#### MCP server connection event Logged when an MCP server connects, disconnects, or fails to connect. **Event Name** : `claude_code.mcp_server_connection` **Attributes** : @@ -1159,11 +971,7 @@ * `server_name` (when `OTEL_LOG_TOOL_DETAILS=1`): Configured server name * `error` (when `OTEL_LOG_TOOL_DETAILS=1`): Full error message when the connection failed -#### - -​ - -Internal error event +#### Internal error event Logged when Claude Code catches an unexpected internal error. Only the error class name and an errno-style code are recorded. The error message and stack trace are never included. This event is not emitted when running against Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry, or when `DISABLE_ERROR_REPORTING` is set. **Event Name** : `claude_code.internal_error` **Attributes** : @@ -1174,11 +982,7 @@ * `error_name`: Error class name, such as `"TypeError"` or `"SyntaxError"` * `error_code`: Node.js errno code such as `"ENOENT"` when present on the error -#### - -​ - -Plugin installed event +#### Plugin installed event Logged when a plugin finishes installing, from both the `claude plugin install` CLI command and the interactive `/plugin` UI. **Event Name** : `claude_code.plugin_installed` **Attributes** : @@ -1192,11 +996,7 @@ * `plugin.version`: Plugin version when declared in the marketplace entry. For third-party marketplaces this is included only when `OTEL_LOG_TOOL_DETAILS=1` * `marketplace.name`: Marketplace the plugin was installed from. For third-party marketplaces this is included only when `OTEL_LOG_TOOL_DETAILS=1` -#### - -​ - -Plugin loaded event +#### Plugin loaded event Logged once per enabled plugin at session start. Use this event to inventory which plugins are active across your fleet, as a complement to `plugin_installed` which records the install action itself. **Event Name** : `claude_code.plugin_loaded` **Attributes** : @@ -1218,11 +1018,7 @@ * `agent_path_count`: number of agent directories the plugin declares * `safe_mode`: `"true"` when the session was started with [`--safe-mode`](</docs/en/cli-reference>), `"false"` otherwise. In safe mode this event reports configured inventory only; the plugin’s commands, skills, hooks, and MCP servers don’t load. Requires Claude Code v2.1.169 or later -#### - -​ - -Skill activated event +#### Skill activated event Logged when a skill is invoked, whether Claude calls it through the Skill tool or you run it as a `/` command. **Event Name** : `claude_code.skill_activated` **Attributes** : @@ -1237,11 +1033,7 @@ * `plugin.name` (when `OTEL_LOG_TOOL_DETAILS=1` or the plugin is from an official marketplace): Name of the owning plugin when the skill is provided by a plugin * `marketplace.name` (when `OTEL_LOG_TOOL_DETAILS=1` or the plugin is from an official marketplace): Marketplace the owning plugin was installed from, when the skill is provided by a plugin -#### - -​ - -At mention event +#### 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. 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** : @@ -1252,11 +1044,7 @@ * `mention_type`: Type of mention (`"file"`, `"directory"`, `"agent"`, `"mcp_resource"`, `"peer"`). The `"peer"` value means you mentioned [one of your other Claude Code sessions](</docs/en/cross-session-messaging>). Requires Claude Code v2.1.232 or later * `success`: Whether the mention resolved successfully (`"true"` or `"false"`) -#### - -​ - -API retries exhausted event +#### API retries exhausted event Logged once when an API request fails after more than one attempt. Emitted alongside the final `api_error` event. **Event Name** : `claude_code.api_retries_exhausted` **Attributes** : @@ -1271,11 +1059,7 @@ * `total_retry_duration_ms`: Total wall-clock time across all attempts * `speed`: `"fast"` or `"normal"` -#### - -​ - -Hook registered event +#### Hook registered event Logged once per configured hook at session start. Use this event to inventory which hooks are active across your fleet, as a complement to the per-execution `hook_execution_start` and `hook_execution_complete` events. **Event Name** : `claude_code.hook_registered` **Attributes** : @@ -1291,11 +1075,7 @@ * `plugin.name` (when `hook_source` is `"pluginHook"`): name of the contributing plugin. For plugins outside the official marketplace and built-in bundle the value is `"third-party"` unless `OTEL_LOG_TOOL_DETAILS=1` * `plugin_id_hash` (when `hook_source` is `"pluginHook"`): deterministic hash of the plugin name and marketplace, sent only to your configured exporter. Lets you count distinct contributing plugins without recording their names. Claude Code computes it as described under the plugin loaded event -#### - -​ - -Hook execution start event +#### Hook execution start event Logged when one or more hooks begin executing for a hook event. **Event Name** : `claude_code.hook_execution_start` **Attributes** : @@ -1311,11 +1091,7 @@ * `safe_mode`: `"true"` when the session was started with [`--safe-mode`](</docs/en/cli-reference>), `"false"` otherwise. Requires Claude Code v2.1.169 or later * `hook_definitions`: JSON-serialized hook configuration. Included only when both detailed beta tracing and `OTEL_LOG_TOOL_DETAILS=1` are enabled -#### - -​ - -Hook execution complete event +#### Hook execution complete event Logged when all hooks for a hook event have finished. **Event Name** : `claude_code.hook_execution_complete` **Attributes** : @@ -1341,11 +1117,7 @@ * `safe_mode`: `"true"` when the session was started with [`--safe-mode`](</docs/en/cli-reference>), `"false"` otherwise. Requires Claude Code v2.1.169 or later * `hook_definitions`: JSON-serialized hook configuration. Included only when both detailed beta tracing and `OTEL_LOG_TOOL_DETAILS=1` are enabled -#### - -​ - -Hook plugin metrics event +#### Hook plugin metrics event Logged when an official-marketplace plugin hook emits per-invocation metrics. Only plugins installed from an official Anthropic marketplace can emit these. Third-party marketplace plugins and user-configured hooks don’t emit to this event. Use this event to monitor plugin behavior such as finding rates, costs, and durations from your own observability stack. **Event Name** : `claude_code.hook_plugin_metrics` **Attributes** : @@ -1357,11 +1129,7 @@ * `hook_event`: hook event type that emitted the metrics * Up to 20 plugin-emitted metric keys. Names match `^[a-z][a-z0-9_]{0,39}$`. Values are Boolean or number. -#### - -​ - -Compaction event +#### Compaction event Logged when conversation compaction completes. **Event Name** : `claude_code.compaction` **Attributes** : @@ -1377,11 +1145,7 @@ * `error`: Error message when compaction failed * `precompute_reuse`: Only set when `trigger` is `"manual"`, or when `trigger` is `"auto"` for an [idle compaction](</docs/en/settings-reference#idlecompaction>) in an interactive terminal session. Auto-compaction can prepare a summary in the background before the context window fills, and this attribute records whether the compaction reused that prepared summary. `"hit"` means it was reused; `"miss_custom_instructions"`, `"miss_hook"`, and `"miss_not_ready"` give the reason a fresh summary was computed instead -#### - -​ - -Subagent completed event +#### Subagent completed event Logged when a [subagent](</docs/en/sub-agents>) finishes and returns its result to the conversation that started it. Use it to roll up tool use and run time by subagent type; for token or cost rollups, use the token counter and cost counter filtered to `query_source` `"subagent"`, since this event’s `total_tokens` covers only the final request. The `"subagent"` category also counts requests from agent-based hooks, which emit no subagent event. **Event Name** : `claude_code.subagent_completed` **Attributes** : @@ -1401,11 +1165,7 @@ * `model_swapped`: Whether more than one model served the subagent’s requests * `plugin_id_hash`, `plugin.name`: Present for plugin-provided agents. Official-marketplace plugin names appear verbatim; other plugin names are replaced with `"third-party"` unless `OTEL_LOG_TOOL_DETAILS=1` is set -#### - -​ - -Feedback survey event +#### Feedback survey event Logged when a session quality survey is shown or answered. See [Session quality surveys](</docs/en/data-usage#session-quality-surveys>) for what the surveys collect and how to control them. **Event Name** : `claude_code.feedback_survey` **Attributes** : @@ -1419,11 +1179,7 @@ * `response`: The user’s selection on `responded` events * `enabled_via_override`: `true` when [`CLAUDE_CODE_ENABLE_FEEDBACK_SURVEY_FOR_OTEL`](</docs/en/env-vars>) is set. Emitted as a Boolean, not a string. Present on `session` survey events. Filter on this attribute to confirm the override is applied across a fleet -#### - -​ - -Retention sweep event +#### Retention sweep event Logged once per run of the retention cleanup sweep, which deletes [session transcripts and other application data](</docs/en/claude-directory#cleaned-up-automatically>) older than the [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>) setting. Claude Code runs the sweep in the background at most once per session, and a run that deletes nothing still emits the event. If Claude Code ran the sweep in any session on the same machine in the last 24 hours, it delays this session’s sweep by at least 10 minutes, so a session that exits sooner emits nothing. When you run `claude -p` with `--bare`, Claude Code doesn’t run the sweep and emits nothing. Like every OTel event on this page, it goes only to the telemetry backend you configure. Requires Claude Code v2.1.227 or later. Read `result` to see whether the sweep ran: @@ -1452,11 +1208,7 @@ * `files_past_cutoff`: Files older than the retention period that the sweep failed to delete, for example because of a permission error or a file held open. The count also includes each stale folder the sweep finds under `skills/synced/` or `plugins/synced/`, whether or not it moves the folder to the trash. Apart from those folders, a value above zero means files outlived the configured retention period; zero isn’t proof that none did, because a failed removal of a whole directory counts toward `error_count` instead * `error_count`: Number of errors the sweep encountered while listing or deleting files -#### - -​ - -Managed settings resolved event +#### Managed settings resolved event Logged with the [managed settings](</docs/en/managed-settings>) a session resolved: once at session start, again when either the managed settings or the [policy helper](</docs/en/managed-settings#compute-the-policy-with-a-helper-program>)’s state changes during the session, and when Claude Code refuses to start or ends the session for one of the reasons the `error.type` attribute lists. Use this event to find machines running on an unexpected managed source, machines whose policy helper is failing, and the reason a machine refused to start. Requires Claude Code v2.1.274 or later. By default, the event carries the managed sources and the policy helper’s state but not the settings themselves. To add the redacted `managed_settings.settings` attribute and the `managed_settings.resolved_sha256` digest, set `OTEL_LOG_MANAGED_SETTINGS=1`: @@ -1500,19 +1252,11 @@ For example, managed settings with `apiKeyHelper`, two `env` variables, and a deny rule are exported as `{"apiKeyHelper":"[REDACTED]","env":{"HTTPS_PROXY":"[REDACTED]","CLAUDE_CODE_ENABLE_TELEMETRY":"[REDACTED]"},"permissions":{"deny":["Read([REDACTED])"]}}`. Claude Code cuts the value at 8 KB of UTF-8, and the cut value isn’t valid JSON * `managed_settings.settings_truncated` (when `managed_settings.settings` is present): `true` when Claude Code cut `managed_settings.settings` at 8 KB, `false` otherwise. Emitted as a Boolean, not a string -## - -​ - -Interpret metrics and events data +## Interpret metrics and events data The exported metrics and events support a range of analyses: -### - -​ - -Usage monitoring +### Usage monitoring Metric| Analysis Opportunity ---|--- @@ -1522,11 +1266,7 @@ To compare active users across surfaces, set `OTEL_METRICS_INCLUDE_ENTRYPOINT=true` to add `app.entrypoint` to metrics and events. Then count distinct `user.account_uuid` values per entrypoint on `claude_code.user_prompt` events, or on `claude_code.token.usage` if you export only metrics. For example, use `cli` for interactive CLI sessions, and group `claude-desktop`, `claude-desktop-3p`, and `remote_desktop` for the Claude Desktop Code tab. `user.account_uuid` doesn’t identify people in Claude Tag channel sessions and is missing from sessions with no Claude account: see Attribute actions to users. When one person starts many sessions, or a session receives no prompt, `claude_code.session.count` goes up without adding an active user. -### - -​ - -Cost monitoring +### Cost monitoring The `claude_code.cost.usage` metric helps with: @@ -1538,11 +1278,7 @@ Claude Code counts each streaming response toward the cost and token metrics exactly once, including when a gateway or proxy behind `ANTHROPIC_BASE_URL` streams usage progressively across multiple frames. -### - -​ - -Alerting and segmentation +### Alerting and segmentation Common alerts to consider: @@ -1552,19 +1288,11 @@ All metrics can be segmented by the standard attributes. The `model` attribute is available on `claude_code.token.usage`, `claude_code.cost.usage`, and `claude_code.lines_of_code.count`. Per-model breakdowns of commits can only be approximated by joining against the token or cost metrics on `session.id`, since one session can span multiple models. Filter the token or cost side to rows where `query_source` is `"main"` so auxiliary and subagent requests don’t attribute the session’s commits to a model that didn’t make them. -### - -​ - -Detect retry exhaustion +### Detect retry exhaustion Claude Code retries failed API requests internally and emits a single `claude_code.api_error` event only after it gives up, so the event itself is the terminal signal for that request. Intermediate retry attempts are not logged as separate events. The `attempt` attribute on the event records the number of attempts. `CLAUDE_CODE_MAX_RETRIES` defaults to 10 and is capped at 15; with [`CLAUDE_CODE_RETRY_WATCHDOG`](</docs/en/env-vars>) set, the default is higher and there is no cap. When the request exhausts all retries on a transient error, `attempt` is at most one more than that effective limit: 11 by default. A lower value can still mean the retries ran out: `attempt` starts again from `1` each time Claude Code re-issues the request after a streaming failure. To distinguish a session that recovered from one that stalled, group events by `session.id` and check whether a later `api_request` event exists after the error. -### - -​ - -Event analysis +### Event analysis The event data describes each Claude Code interaction in detail: **Tool usage patterns** : analyze tool result events to identify: @@ -1575,11 +1303,7 @@ **Performance monitoring** : track API request durations and tool execution times to identify performance bottlenecks. -### - -​ - -Map input tokens to OpenTelemetry GenAI semantic conventions +### Map input tokens to OpenTelemetry GenAI semantic conventions Claude Code exports input token counts as they appear in the API response’s usage block, so these values exclude tokens read from or written to the [prompt cache](</docs/en/prompt-caching>): @@ -1596,29 +1320,17 @@ * `cache_read_tokens` maps to `gen_ai.usage.cache_read.input_tokens` * `cache_creation_tokens` maps to `gen_ai.usage.cache_write.input_tokens`. Older versions of the conventions name the cache write attribute `gen_ai.usage.cache_creation.input_tokens`, so use the name your backend expects. -## - -​ - -Audit security events +## Audit security events OpenTelemetry events are the audit data source for Claude Code activity. Every event carries identity attributes that tie tool calls, MCP activity, and permission decisions back to the user who triggered them. The OTLP logs exporter can deliver these events to any Security Information and Event Management (SIEM) platform with an OTLP receiver, or to an OpenTelemetry Collector that forwards to your SIEM. -### - -​ - -Attribute actions to users +### Attribute actions to users The standard attributes on each event include the authenticated user’s identity: `user.email`, `user.account_uuid`, `user.account_id`, and `organization.id` when signed in with a Claude account or, in a [cloud session](</docs/en/claude-code-on-the-web>), when the session’s own credentials carry them, plus `user.id` and the per-session `session.id`. `user.id` is an installation-scoped identifier, except in sessions signed in to a [Claude apps gateway](</docs/en/claude-apps-gateway>) through `/login`, where it is the IdP subject from the gateway-issued token. In a session a developer starts, MCP tool calls, Bash commands, and file edits are therefore attributed to that developer. Claude Code doesn’t act under a separate service account there; the identity recorded on each event is the developer’s own Claude account, or the developer’s IdP identity on a [Claude apps gateway](</docs/en/claude-apps-gateway>) session. In Claude Tag channel sessions, Claude works as your organization’s [shared identity](</docs/en/cloud-environments#set-the-environment-a-claude-tag-channel-uses>) instead. When Claude Code authenticates with a direct API key, or against Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry, there is no Claude account in the session and only `user.id` and `session.id` are populated. In these deployments, attach user identity yourself with `OTEL_RESOURCE_ATTRIBUTES`, set per user through the managed settings file or a launch wrapper. Claude apps gateway sessions need none of this: see Standard attributes for the identity their exports carry. export OTEL_RESOURCE_ATTRIBUTES="enduser.id=jdoe@example.com,enduser.directory_id=S-1-5-21-..." -### - -​ - -Audit MCP activity +### Audit MCP activity To capture MCP server activity with full call detail, enable the logs exporter and set `OTEL_LOG_TOOL_DETAILS=1`. Each MCP operation then produces structured events that carry the server name, tool name, and call arguments alongside the standard identity attributes: @@ -1634,11 +1346,7 @@ * `tool_decision`: keeps `tool_source` and a `tool_name` redacted to the literal `"mcp_tool"` for user-configured servers, omits argument content. For Claude Desktop’s built-in servers, in sessions Claude Desktop owns, it also keeps the `mcp_server_name`/`mcp_tool_name` pair inside `tool_parameters` * `mcp_server_connection`: omits `server_name` and the error message, but keeps `is_plugin`, `plugin_id_hash`, and `plugin.name`, with non-Anthropic plugin names redacted to the literal `"third-party"`, so plugin-provided servers remain distinguishable without detailed logging -### - -​ - -Map security questions to events +### Map security questions to events Rows for `safety_event` apply only to a session on v2.1.307 through v2.1.311 that still sends the event. When building detection rules, look up the signal you want to monitor and query your backend for the corresponding event and attributes: @@ -1661,11 +1369,7 @@ Claude Code emits the raw event stream only. Anomaly detection, baselining, correlation across sessions, and alerting are the responsibility of your SIEM or observability backend. -### - -​ - -Map egress paths to managed controls and events +### Map egress paths to managed controls and events The table pairs paths that can carry session content off a machine, plus local retention, with the [managed settings](</docs/en/managed-settings>) keys that restrict them and the events that record them. For what Claude Code itself sends to Anthropic, such as `/feedback` reports, see [Data usage](</docs/en/data-usage>). The names link to their reference entries, which give the values and defaults. @@ -1688,11 +1392,7 @@ `OTEL_LOG_TOOL_DETAILS=1` adds command strings, server and tool names, and tool input to these events. That detail can contain the same sensitive content as the session itself, so enable it only when your collector is approved to hold that content. -### - -​ - -Check the retention sweep +### Check the retention sweep To give every machine the same retention period, set [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>) in [managed settings](</docs/en/managed-settings>). To check that machines run the sweep with that value, collect the `retention_sweep` event. `period_days` and the counters are strings, so cast them to numbers before you compare them. @@ -1712,11 +1412,7 @@ The sweep doesn’t cover every path. [Kept until you delete them](</docs/en/claude-directory#kept-until-you-delete-them>) lists what stays, and [Clear local data](</docs/en/claude-directory#clear-local-data>) shows how to remove it. -### - -​ - -Send events to a SIEM +### Send events to a SIEM Point `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` at your SIEM’s OTLP receiver, or at an OpenTelemetry Collector that forwards to your SIEM’s native ingest API. The following managed-settings example exports events only, with full tool detail enabled for MCP and Bash auditing: @@ -1733,39 +1429,23 @@ To confirm events arrive, submit a prompt in a session running under this configuration and check your SIEM for the `claude_code.user_prompt` event. If nothing arrives, start Claude Code with `claude --debug-file <path>` and check that log for `[3P telemetry]` export errors. -## - -​ - -Backend considerations +## Backend considerations Your choice of metrics, logs, and traces backends determines the types of analyses you can perform: -### - -​ - -Backends for metrics +### Backends for metrics * **Time series databases** : Rate calculations, aggregated metrics * **Columnar stores** : Complex queries, unique user analysis * **Full-featured observability platforms** : Advanced querying, visualization, alerting -### - -​ - -Backends for events and logs +### Backends for events and logs * **Log aggregation systems** : Full-text search, log analysis * **Columnar stores** : Structured event analysis * **Full-featured observability platforms** : Correlation between metrics and events -### - -​ - -Backends for traces +### Backends for traces Choose a backend that supports distributed trace storage and span correlation: @@ -1774,11 +1454,7 @@ For organizations requiring Daily/Weekly/Monthly Active User (DAU/WAU/MAU) metrics, consider backends that support efficient unique value queries. -## - -​ - -Service information +## Service information All metrics and events are exported with the following resource attributes: @@ -1792,19 +1468,11 @@ If your collector pipelines or dashboards filter on `service.name = claude-code`, add `claude-code-desktop` to the filter to also capture telemetry from local Code tab sessions. -## - -​ - -ROI measurement resources +## ROI measurement resources For a comprehensive guide on measuring return on investment for Claude Code, including telemetry setup, cost analysis, productivity metrics, and automated reporting, see the [Claude Code ROI Measurement Guide](<https://github.com/anthropics/claude-code-monitoring-guide>). This repository provides ready-to-use Docker Compose configurations, Prometheus and OpenTelemetry setups, and templates for generating productivity reports integrated with tools like Linear. -## - -​ - -Security and privacy +## Security and privacy * OpenTelemetry export to your backend is opt-in and requires explicit configuration. For Anthropic’s separate operational telemetry and how to disable it, see [Data usage](</docs/en/data-usage#telemetry-services>) * By default, raw file contents and code snippets aren’t included in metrics or events. If you set a variable such as `OTEL_LOG_TOOL_DETAILS` or `OTEL_LOG_RAW_API_BODIES`, events can include them. Trace spans are a separate data path: see the `OTEL_LOG_TOOL_CONTENT` bullet below @@ -1834,10 +1502,6 @@ * With `=1`, Claude Code emits `api_request_body` and `api_response_body` log events for each API call. The events’ `body` attribute carries the JSON-serialized payload, truncated at the content limit (60 KB by default) * With `=file:<dir>`, Claude Code writes untruncated bodies to `.request.json` and `.response.json` files under that directory, and the events carry a `body_ref` path instead of the inline body. Ship the directory with a log collector or sidecar rather than through the telemetry stream. For each successful response, Claude Code also appends one line to `index.jsonl` in that directory, linking the response file to the request file that produced it and to the transcript message it became. Each line holds no message content, and the API response body event section lists its fields. The index file requires Claude Code v2.1.274 or later -## - -​ - -Monitor Claude Code on Amazon Bedrock +## Monitor Claude Code on Amazon Bedrock For detailed Claude Code usage monitoring guidance for Amazon Bedrock, see [Claude Code Monitoring Implementation (Amazon Bedrock)](<https://github.com/aws-solutions-library-samples/guidance-for-claude-code-with-amazon-bedrock/blob/main/assets/docs/MONITORING.md>).
modified Enterprise network configuration View current →
Show diff (201 lines)
--- a/network-config.md +++ b/network-config.md @@ -2,17 +2,9 @@ All environment variables shown on this page can also be configured in [`settings.json`](</docs/en/settings>). -## - -​ - -Proxy configuration - -### - -​ - -Environment variables +## Proxy configuration + +### Environment variables Claude Code respects standard proxy environment variables. In Claude Desktop sessions where the app manages the provider connection, Claude Code reads them only from managed settings and `~/.claude/settings.json`; see mTLS authentication for the scope rules. @@ -33,11 +25,7 @@ Claude Code does not support SOCKS proxies. -### - -​ - -Basic authentication +### Basic authentication If your proxy requires basic authentication, include credentials in the proxy URL: @@ -47,11 +35,7 @@ For proxies requiring advanced authentication (NTLM, Kerberos, etc.), consider using an LLM Gateway service that supports your authentication method. -## - -​ - -CA certificate store +## CA certificate store By default, Claude Code trusts both its bundled Mozilla CA certificates and your operating system’s certificate store. Reading the OS store requires a runtime with `tls.getCACertificates`: the native installer always has it, and npm installs need Node 22.15 or later. On older Node versions, only the bundled set and `NODE_EXTRA_CA_CERTS` apply. Enterprise TLS-inspection proxies work without additional configuration when their root certificate is installed in the OS trust store and the runtime can read it. If such a proxy mishandles gzip-compressed request bodies, set [`CLAUDE_CODE_GZIP_REQUEST_BODIES=0`](</docs/en/env-vars>) to turn off compression for Claude API, telemetry, and artifact publish requests. `CLAUDE_CODE_CERT_STORE` accepts a comma-separated list of sources. Recognized values are `bundled` for the Mozilla CA set shipped with Claude Code and `system` for the operating system trust store. The default is `bundled,system`. To trust only the bundled Mozilla CA set: @@ -63,11 +47,7 @@ `CLAUDE_CODE_CERT_STORE` has no dedicated `settings.json` schema key. Set it via the `env` block in `~/.claude/settings.json` or directly in the process environment. -## - -​ - -Custom CA certificates +## Custom CA certificates If your enterprise environment uses a custom CA, configure Claude Code to trust it directly: @@ -80,11 +60,7 @@ The full text of each warning says how to fix the file. A skipped certificate that’s also in the CA certificate store still works. -## - -​ - -mTLS authentication +## mTLS authentication For enterprise environments requiring client certificate authentication: @@ -116,11 +92,7 @@ Claude Code notes each ignored key in the session’s debug log. In [Claude Desktop](</docs/en/desktop>) sessions where the app manages the provider connection, such as the Code tab on a [third-party provider](</docs/en/third-party-integrations>) and Cowork sessions, Claude Code reads these variables except `CLAUDE_CODE_OAUTH_SCOPES`, and the proxy variables `HTTP_PROXY`, `HTTPS_PROXY`, and `NO_PROXY`, only from [managed settings](</docs/en/managed-settings>) and `~/.claude/settings.json`. It ignores them in a repository’s own settings files, so a checked-out repository can’t redirect the TLS or proxy path of a session whose credentials come from the app. Before v2.1.217, Claude Code ignored these variables in every settings file when the app managed the connection. In a local, SSH, or WSL Code tab session signed in through claude.ai, you can set these variables and the proxy variables in any settings file, apart from `CLAUDE_CODE_OAUTH_SCOPES`. Desktop sets `CLAUDE_CODE_OAUTH_SCOPES` itself in Code tab and Cowork sessions, so you can’t set it. When the session’s launch environment already sets a variable, Claude Code [ignores the settings file’s value](</docs/en/settings-reference#how-env-values-interact-with-your-shell>) and names the variable in the [debug log](</docs/en/debug-your-config>). To use your own proxy or certificate value in a local session, [add it to a saved local environment](</docs/en/desktop#set-environment-variables-for-local-sessions>). [Cloud sessions](</docs/en/claude-code-on-the-web>) follow the cloud-session rules above wherever you start them. -## - -​ - -Verify your configuration +## Verify your configuration You usually find out about a wrong proxy address or a bad certificate path from a [connection or certificate error](</docs/en/errors#network-and-connection-errors>) on a later request, since Claude Code doesn’t validate most of these settings when it reads them. The one setting it checks at startup is the proxy URL: when it can’t parse the value, such as one missing the `http://` scheme, Claude Code stops launch with an error naming the variable to fix. To confirm your configuration loaded before you send a request, start Claude Code with debug logging: @@ -138,37 +110,21 @@ * **mTLS client cert** and **mTLS client key** : appear only when the files loaded, so a missing row means the load failed and the debug log has the reason. * **Additional CA cert(s)** : shows the `NODE_EXTRA_CA_CERTS` path without checking that the file loaded, so confirm this one in the debug log. -## - -​ - -Apply network settings to background agents +## Apply network settings to background agents [Background agents](</docs/en/agent-view>) don’t run inside the terminal that dispatched them. A per-user supervisor process starts on demand, outlives your shell, and hosts every `claude agents`, `--bg`, and `/background` session. See [How background sessions are hosted](</docs/en/agent-view#how-background-sessions-are-hosted>). This changes how the configuration on this page reaches those sessions. -### - -​ - -Set network variables in settings, not the shell +### Set network variables in settings, not the shell The supervisor is one process shared by every terminal. It inherits the environment of whichever shell starts it first. If you export a proxy, CA path, or mTLS variable only in your shell, it reaches background agents when that shell happened to cold-start the supervisor, and silently doesn’t when a different shell did. Put the same variables in the `env` block of `~/.claude/settings.json` or [managed settings](</docs/en/settings>) instead. Every variable on this page can be set there, and settings are the only configuration that reaches every background session on every machine. -### - -​ - -Configure a corporate launcher as a setting +### Configure a corporate launcher as a setting Some organizations require every Claude Code process to start through a corporate launcher that applies sandboxing, network controls, or credential injection. The supervisor and its workers start Claude Code from a fixed path rather than by looking up `claude` on `PATH`, so every background agent bypasses a wrapper you place earlier on `PATH`. Set the [`processWrapper`](</docs/en/settings-reference#processwrapper>) setting to prefix the supervisor, its workers, and the other background processes listed under [What the launcher covers](</docs/en/corporate-launcher#what-the-launcher-covers>) with your launcher. The equivalent [`CLAUDE_CODE_PROCESS_WRAPPER`](</docs/en/env-vars>) environment variable takes precedence when both are set, and it is subject to the same rule: deliver it through managed settings or `~/.claude/settings.json`, not a shell export. [Run Claude Code behind a corporate launcher](</docs/en/corporate-launcher>) covers the contract the launcher must satisfy, what it does and doesn’t reach, and how to roll it out. An already-running supervisor keeps the launch configuration it started with. After deploying the launcher setting, run [`claude daemon stop --any`](</docs/en/agent-view#the-supervisor-process>) so the next `claude agents` or `--bg` starts a supervisor that honors it. -## - -​ - -Streaming idle watchdogs +## Streaming idle watchdogs Claude Code runs four independent timers that abort a streaming model response when it goes quiet, so a dead connection fails and retries instead of hanging. A request that gets no response headers at all ends in one of two ways: @@ -193,11 +149,7 @@ When a watchdog aborts a stalled stream, Claude Code treats the abort as a mid-stream failure, and what you see depends on how far the response had got. Claude Code retries the request or ends the turn with an error, keeps the completed output and shows an [incomplete-response notice](</docs/en/errors#the-response-above-may-be-incomplete>), or ends the turn normally. [Automatic retries](</docs/en/errors#automatic-retries>) says where each outcome applies. In a [non-interactive session](</docs/en/headless>), and for a subagent’s response in any session, Claude Code may first prompt Claude to continue the cut-off response; [that notice’s entry](</docs/en/errors#the-response-above-may-be-incomplete>) says when it does and when you still see the notice. When the first-byte deadline fires, no response has started, so there is no partial output to keep. For how Claude Code re-sends the request and when the turn ends instead, see [No response from API](</docs/en/errors#no-response-from-api>). -## - -​ - -Network access requirements +## Network access requirements Claude Code requires access to the following URLs. Allowlist these in your proxy configuration and firewall rules, especially in containerized or restricted network environments. The first-run setup connectivity check points here when it can’t reach `api.anthropic.com` or `platform.claude.com`; see [Unable to connect to Anthropic services](</docs/en/errors#unable-to-connect-to-anthropic-services>) for the check’s messages and recovery steps. @@ -225,51 +177,27 @@ If you install Claude Code through npm or manage your own binary distribution, end users don’t need the native installer and auto-updater uses of `downloads.claude.ai`, but npm and bun installs need their package registry, `registry.npmjs.org`, unless your organization mirrors it. The other uses in the table apply regardless of install method. The two Datadog intake hosts carry only optional operational telemetry, and setting [`CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`](</docs/en/env-vars>) disables both. Sessions on third-party providers never send to these hosts, even when a platform sets [`CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST`](</docs/en/env-vars>) and telemetry metrics default on. See [Telemetry services](</docs/en/data-usage#telemetry-services>) for everything Claude Code sends and how to disable it before finalizing your allowlist. -### - -​ - -Cloud provider and LLM gateway routing +### Cloud provider and LLM gateway routing When using [Amazon Bedrock](</docs/en/amazon-bedrock>), [Google Cloud’s Agent Platform](</docs/en/google-vertex-ai>), [Microsoft Foundry](</docs/en/microsoft-foundry>), or a signed-in [Claude apps gateway](</docs/en/claude-apps-gateway>) session, model traffic and authentication go to your provider or gateway instead of `api.anthropic.com`, `claude.ai`, or `platform.claude.com`. The WebFetch tool still calls `api.anthropic.com` for its [domain safety check](</docs/en/data-usage#webfetch-domain-safety-check>) unless you set `skipWebFetchPreflight: true` in [settings](</docs/en/settings>). If your developers use [fast mode](</docs/en/fast-mode>) behind an [LLM gateway](</docs/en/llm-gateway>) set with [`ANTHROPIC_BASE_URL`](</docs/en/llm-gateway-connect#set-the-base-url-and-credential>), keep `api.anthropic.com` reachable through your proxy. When Claude Code sends the fast mode availability check, it goes to that host through any configured HTTP proxy, never to the gateway. For when the check isn’t sent, and the variable that restores fast mode in each case, see [Use fast mode behind proxies and LLM gateways](</docs/en/fast-mode#use-fast-mode-behind-proxies-and-llm-gateways>). -### - -​ - -Organization IP allowlists and proxy egress +### Organization IP allowlists and proxy egress If your organization has [IP allowlisting](<https://support.claude.com/en/articles/13200993-restrict-access-to-claude-with-ip-allowlisting>) enabled for Claude, route `bridge.claudeusercontent.com` through the same proxy egress as `claude.ai` and `api.anthropic.com`, for example by placing it in the same Zscaler app segment or Netskope steering policy. If you can’t route it that way, add the egress address your proxy uses for that host to your organization’s IP allowlist, but only when that address is dedicated to your organization: a shared proxy egress range also admits the proxy vendor’s other customers. Anthropic checks connections to `bridge.claudeusercontent.com` against your organization’s IP allowlist using the address they arrive from. If your proxy sends traffic for that host out through an address that isn’t on that allowlist, Claude Code can’t connect to the [Claude in Chrome](</docs/en/chrome>) extension even though the rest of Claude Code works. -### - -​ - -GitHub allow lists and firewalls +### GitHub allow lists and firewalls [Cloud sessions](</docs/en/claude-code-on-the-web>) in Anthropic-hosted environments and [Code Review](</docs/en/code-review>) connect to your repositories from Anthropic-managed infrastructure; sessions in a [self-hosted environment](</docs/en/self-hosted-environments>) connect from inside your network, unless the runner opts into the [Anthropic git proxy](</docs/en/self-hosted-environments-deploy#use-the-anthropic-git-proxy>), which fetches from Anthropic’s side. If your GitHub Enterprise Cloud organization restricts access by IP address, enable [IP allow list inheritance for installed GitHub Apps](<https://docs.github.com/en/enterprise-cloud@latest/organizations/keeping-your-organization-secure/managing-security-settings-for-your-organization/managing-allowed-ip-addresses-for-your-organization#allowing-access-by-github-apps>) and also [add an allow list entry](<https://docs.github.com/en/enterprise-cloud@latest/organizations/keeping-your-organization-secure/managing-security-settings-for-your-organization/managing-allowed-ip-addresses-for-your-organization#adding-an-allowed-ip-address>) for Anthropic’s [outbound IP addresses](<https://platform.claude.com/docs/en/api/ip-addresses#outbound-ip-addresses>). Inheritance covers only the requests the Claude GitHub App makes as an installation, not the requests it makes on your users’ behalf. For other firewalls, see the [Anthropic API IP addresses](<https://platform.claude.com/docs/en/api/ip-addresses>). For self-hosted [GitHub Enterprise Server](</docs/en/github-enterprise-server>) instances behind a firewall, allowlist Anthropic’s [outbound IP addresses](<https://platform.claude.com/docs/en/api/ip-addresses#outbound-ip-addresses>) so Anthropic infrastructure can reach your GHES host to clone repositories and post review comments. Sessions in a [self-hosted environment](</docs/en/self-hosted-environments-deploy#configure-git>) reach your GHES host from inside your network instead, so that exposure applies only to Anthropic-hosted sessions, to hosted pre-session flows such as the repository picker, and to self-hosted runners that opt into the [Anthropic git proxy](</docs/en/self-hosted-environments-deploy#use-the-anthropic-git-proxy>), which fetches from Anthropic’s side. The [SCM connector](</docs/en/self-hosted-environments-reference#scm-connector-flags>) isn’t available, so the hosted pre-session flows can’t reach a GHES host that’s only routable inside your network. -### - -​ - -Desktop and claude.ai +### Desktop and claude.ai The preceding table covers the standalone CLI. The Claude Desktop app and claude.ai in a browser load their application code and user content from additional Anthropic CDN hosts, including `assets-proxy.anthropic.com` and the other `*.claudeusercontent.com` origins that serve [artifacts](</docs/en/artifacts>) in those apps. Allowing `claude.ai` while blocking those hosts produces a blank page rather than an error. See [network access requirements](</docs/en/desktop#network-access-requirements>) on the Desktop page. Claude Desktop and claude.ai also render some tool results inside a conversation as interactive widgets, such as the [MCP Apps](<https://claude.com/docs/connectors/building/mcp-apps/getting-started>) some connectors provide. Those widgets load from generated subdomains of `claudemcpcontent.com`, so allow `*.claudemcpcontent.com` with the wildcard intact. If you block it, the rest of the app keeps working, but those widgets don’t load. -#### - -​ - -Third-party hosts for artifact fonts and libraries +#### Third-party hosts for artifact fonts and libraries An [artifact](</docs/en/artifacts>) that loads a typeface from [Google Fonts](</docs/en/artifacts#improve-the-visual-design>) also requests `fonts.googleapis.com` and `fonts.gstatic.com`. Both hosts are optional. If you block them, artifacts render in fallback typefaces. Block with a fast rejection rather than a silent drop so the font request fails immediately instead of delaying the page’s first render. Artifacts can also load JavaScript libraries, such as React or a charting package, from `cdnjs.cloudflare.com`, `cdn.jsdelivr.net`, `cdn.tailwindcss.com`, `code.jquery.com`, and `unpkg.com`, and from no other external host. If you block those hosts, the parts of an artifact that depend on a library don’t work, and unlike a blocked font, a blocked library has no fallback. Block with a fast rejection here too, so a blocked library request fails at once rather than hanging until it times out. -## - -​ - -Additional resources +## Additional resources * [Settings files and precedence](</docs/en/settings>) * [Environment variables reference](</docs/en/env-vars>)
modified Observability with OpenTelemetry View current →
Show diff (115 lines)
--- a/observability.md +++ b/observability.md @@ -9,11 +9,7 @@ For the Claude API or Managed Agents, see [OpenTelemetry for the Claude API](<https://platform.claude.com/docs/en/manage-claude/opentelemetry>). -## - -​ - -How telemetry flows from the SDK +## How telemetry flows from the SDK The Agent SDK runs the Claude Code CLI as a child process and communicates with it over a local pipe. The CLI has OpenTelemetry instrumentation built in: it records spans around each model request and tool execution, emits metrics for token and cost counters, and emits structured log events for prompts and tool results. The SDK does not produce telemetry of its own. Instead, it passes configuration through to the CLI process, and the CLI exports directly to your collector. Configuration is passed as environment variables. By default, the child process inherits your application’s environment, so you can configure telemetry in either of two places: @@ -30,11 +26,7 @@ For the complete list of metric names, event names, and attributes, see the Claude Code [Monitoring](</docs/en/monitoring-usage>) reference. The Agent SDK emits the same data because it runs the same CLI. Span names are listed in Read agent traces below. -## - -​ - -Enable telemetry export +## Enable telemetry export Telemetry is off until you set `CLAUDE_CODE_ENABLE_TELEMETRY=1` and choose at least one exporter. The most common configuration sends all three signals over OTLP HTTP to a collector. The following example sets the variables in a dictionary and passes them through `options.env`. The agent runs a single task, and the CLI exports spans, metrics, and events to the collector at `collector.example.com` while the loop consumes the response stream: @@ -97,11 +89,7 @@ The `console` exporter writes telemetry to standard output, which the SDK uses as its message channel. Do not set `console` as an exporter value when running through the SDK. To inspect telemetry locally, point `OTEL_EXPORTER_OTLP_ENDPOINT` at a local OpenTelemetry Collector instead. -### - -​ - -Flush telemetry from short-lived calls +### Flush telemetry from short-lived calls The CLI batches telemetry and exports on an interval. On a clean process exit it attempts to flush pending data, but the flush is bounded by a short timeout, so spans can still be dropped if the collector is slow to respond. If your process is killed before the CLI shuts down, anything still in the batch buffer is lost. Lowering the export intervals reduces both windows. By default, metrics export every 60 seconds and traces and logs export every 5 seconds. The following example shortens all three intervals so that data reaches the collector while a short task is still running: @@ -123,11 +111,7 @@ OTEL_TRACES_EXPORT_INTERVAL: "1000", }; -## - -​ - -Read agent traces +## Read agent traces Traces give you the most detailed view of an agent run. With `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1` set, each step of the agent loop becomes a span you can inspect in your tracing backend: @@ -140,19 +124,11 @@ Tracing is in beta. Span names and attributes may change between releases. See [Traces (beta)](</docs/en/monitoring-usage#traces-beta>) in the Monitoring reference for the trace exporter configuration variables. -## - -​ - -Link traces to your application +## Link traces to your application The SDK automatically propagates W3C trace context into the CLI subprocess. When you call `query()` while an OpenTelemetry span is active in your application, the SDK injects `TRACEPARENT` and `TRACESTATE` into the child process environment, and the CLI reads them so its `claude_code.interaction` span becomes a child of your span. The agent run then appears inside your application’s trace instead of as a disconnected root. OTLP event log records emitted during the run carry the same trace context: with `TRACEPARENT` set, each record’s `trace_id` and `span_id` match your application’s trace, so you can join [events](</docs/en/monitoring-usage#events>) to spans in your backend. Before v2.1.212, event records emitted outside an active span didn’t carry `trace_id` or `span_id`. When trace-context propagation is enabled, the CLI also forwards `TRACEPARENT` to every Bash and PowerShell command it runs. If a command launched through the Bash tool emits its own OpenTelemetry spans, those spans nest under the `claude_code.tool.execution` span that wraps the command. Auto-injection is skipped when you set `TRACEPARENT` explicitly in `options.env`, so you can pin a specific parent context if needed. Interactive CLI sessions ignore inbound `TRACEPARENT` entirely; only Agent SDK and `claude -p` runs honor it. See [Traces (beta)](</docs/en/monitoring-usage#traces-beta>) in the Monitoring reference for the full span and attribute reference. -## - -​ - -Tag telemetry from your agent +## Tag telemetry from your agent By default, the CLI reports `service.name` as `claude-code`. If you run several agents, or run the SDK alongside other services that export to the same collector, override the service name and add resource attributes so you can filter by agent in your backend. The following example renames the service and attaches deployment metadata. These values are applied as OpenTelemetry resource attributes on every span, metric, and event the agent emits: @@ -178,11 +154,7 @@ }, }; -## - -​ - -Attribute actions to your end users +## Attribute actions to your end users The CLI attaches [identity attributes](</docs/en/monitoring-usage#standard-attributes>) to every event based on the credential it uses to call Anthropic. When you build an application that serves many end users from one deployment, these attributes identify your service’s credential, not the end user on whose behalf the agent acted. To make tool calls and MCP activity attributable to your application’s end users, inject end-user identity as resource attributes on each `query()` call. Percent-encode values before interpolating them, since `OTEL_RESOURCE_ATTRIBUTES` [reserves commas, spaces, and equals signs](</docs/en/monitoring-usage#multi-team-organization-support>). The following example attaches the requesting user and tenant to every span and event from one request. It assumes a `request` object from your web framework carrying the user and tenant IDs: @@ -217,11 +189,7 @@ These events export as log records named with a `claude_code.` prefix, such as `claude_code.tool_decision`. See [Audit security events](</docs/en/monitoring-usage#audit-security-events>) in the Monitoring reference for the full list of security-relevant events and the attributes each one carries. -## - -​ - -Control sensitive data in exports +## Control sensitive data in exports Telemetry is structural by default. Durations, model names, and tool names are recorded on every span; token counts are recorded when the underlying API request returns usage data, so spans for failed or aborted requests may omit them. The content your agent reads and writes is not recorded by default. These opt-in variables add content to the exported data: @@ -234,11 +202,7 @@ Leave these unset unless your observability pipeline is approved to store the data your agent handles. See [Security and privacy](</docs/en/monitoring-usage#security-and-privacy>) in the Monitoring reference for the full list of attributes and redaction behavior. -## - -​ - -Related documentation +## Related documentation These guides cover adjacent topics for monitoring and deploying agents:
modified Manage Claude Code plugins for your organization View current →
Show diff (338 lines)
--- a/org.md +++ b/org.md @@ -9,19 +9,11 @@ The sections follow the order most rollouts take: require plugins for everyone or per repository, seed containers and CI, restrict what users can add on their own, set update policy, then audit what’s installed. To review every policy key in one place, see the control matrix. -## - -​ - -Pre-install and require plugins +## Pre-install and require plugins A marketplace is a catalog of plugins that Claude Code fetches from a git repository, a URL, or a local path. Once you register a marketplace on a machine, Claude Code can install plugins from it. To install plugins for a fleet, set two keys together in [managed settings](</docs/en/managed-settings>), the policy file or server-delivered policy that every machine in your organization reads: `extraKnownMarketplaces` registers a marketplace on each machine, and `enabledPlugins` names the plugins to install and enable from it. Choose a delivery mechanism covers how managed settings reach each machine. -### - -​ - -Choose a delivery mechanism +### Choose a delivery mechanism Managed settings reach a machine through one of three delivery mechanisms: @@ -31,19 +23,11 @@ Use server-managed settings if you have a Claude for Teams or Enterprise organization on claude.ai and your devices aren’t all under MDM. Otherwise use an MDM policy or the managed settings file. For the trade-off, see [Choose between server-managed and endpoint-managed settings](</docs/en/server-managed-settings#choose-between-server-managed-and-endpoint-managed-settings>). -#### - -​ - -Which managed source applies on a machine +#### Which managed source applies on a machine By default, only one of these three sources applies on a machine. Claude Code uses the first that delivers a policy key, checking server-managed settings first, then MDM policies, then the managed settings file. If server-managed settings deliver even one unrelated policy key, Claude Code ignores the plugin keys in an MDM policy or managed settings file on that machine, apart from the [keys it reads from every source](</docs/en/managed-settings#keys-read-from-every-admin-source>). To apply every source instead, set [`managedSourcesBehavior`](</docs/en/managed-settings#compose-every-managed-source>) to `"merge"`. [How Claude Code combines managed sources](</docs/en/managed-settings#how-claude-code-combines-managed-sources>) also lists the keys Claude Code reads from every source in both modes. -### - -​ - -Require a marketplace and its plugins +### Require a marketplace and its plugins Add the marketplace under `extraKnownMarketplaces`, keyed by the marketplace’s own `name` from its `marketplace.json`. Then add each plugin under `enabledPlugins` as `plugin-name@marketplace-name`. Each marketplace entry carries a `source` object with a `source` field naming the type, such as `github`. This managed settings example registers an organization marketplace and force-enables two plugins from it: @@ -72,11 +56,7 @@ Anthropic’s official marketplace `claude-plugins-official` needs no `extraKnownMarketplaces` entry when `enabledPlugins` sets one of its plugins to `true`. That `name@claude-plugins-official` entry declares the marketplace by itself, wherever these keys apply. If you enable none of its plugins and still want it registered on every machine, give it an explicit entry, as Allow the official marketplace and your own does. -### - -​ - -Require plugins per repository +### Require plugins per repository To cover one repository’s contributors instead of your whole fleet, set `extraKnownMarketplaces` and `enabledPlugins` in that repository’s `.claude/settings.json`. The `extraKnownMarketplaces` entries apply only in a folder the contributor has trusted, and in an untrusted folder Claude Code ignores them without a message: @@ -85,11 +65,7 @@ Setting `enabledPlugins` in the repository doesn’t install the plugin. Once the marketplace is registered, ask each contributor to run `claude plugin install <name>@<marketplace> --scope project`. Until they do, the `/plugin` **Errors** tab can show `Plugin "<name>" is enabled in project settings but isn't installed here` or [`not cached`](</docs/en/plugins/troubleshooting#plugin-not-cached-at>). Contributors don’t need the install when a local `directory` or `file` marketplace lists the plugin with a [relative-path `source`](</docs/en/plugins/marketplace-reference#plugin-sources>). If you use a local `directory` or `file` source with a relative path, the path resolves against your repository’s main checkout. When you run Claude Code from a git worktree, the path still points at the main checkout, so all worktrees share the same marketplace location. To roll out a bundle of plugins with dependencies, put the bundle plugin in `enabledPlugins`, as [Plugin dependencies](</docs/en/plugins/dependencies>) describes. -### - -​ - -When each surface applies the plugin keys +### When each surface applies the plugin keys The table shows when each kind of Claude Code session applies `extraKnownMarketplaces` and `enabledPlugins`, from managed settings and from a repository’s `.claude/settings.json`. For the Desktop app and the IDE extensions, see [Install a plugin](</docs/en/plugins/install#install-a-plugin>). @@ -101,22 +77,14 @@ In a `-p` or CI run, marketplaces and plugins install in the background, so a plugin can be missing from the first turn. Set `CLAUDE_CODE_SYNC_PLUGIN_INSTALL=1` to make the run wait for the install before its first query. -### - -​ - -Confirm the rollout +### Confirm the rollout Check that the marketplace and plugins arrived on a machine or in a CI run: * **On one machine** : start Claude Code and run `/plugin`. The marketplace and the plugins are listed. * **In CI** : run `claude -p` with `--output-format stream-json --verbose`. The `init` event lists the loaded plugins under `plugins`. -## - -​ - -Seed containers and CI +## Seed containers and CI For container images and CI runners that can’t clone at runtime, pre-populate a plugins directory at build time and point `CLAUDE_CODE_PLUGIN_SEED_DIR` at it. Claude Code registers the seed’s marketplaces at startup and loads plugin caches from the seed in place, without cloning. A seed also serves users who have no git-host account. @@ -154,11 +122,7 @@ For fleets with no outbound git access, combine a seed with `directory` or `file` marketplace sources on a shared mount. Set `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1` as well, which also turns off [plugin auto-update](</docs/en/plugins/loading#when-auto-update-runs>). If a proxy is available, see [Proxy configuration](</docs/en/network-config#proxy-configuration>) for the variables to set. -## - -​ - -Restrict what users can install +## Restrict what users can install The managed `strictKnownMarketplaces` allowlist and `blockedMarketplaces` blocklist decide which marketplace sources plugins may come from. A marketplace’s source is the git repository, URL, or local path that Claude Code fetches it from. Both lists match the source of the marketplace a plugin comes from, not the plugin’s own entry inside that marketplace. For the common lockdown, which allows the official marketplace and your own, see Allow the official marketplace and your own. Pair it with `disableSideloadFlags` so users can’t load plugins from a local directory or URL either. Both lists apply before anything downloads and again at session start: @@ -172,11 +136,7 @@ While any allowlist is set, or a blocklist names any source other than `skills-dir`, a plugin whose marketplace Claude Code can’t find doesn’t load. `/plugin` shows the policy error for it rather than a not-found error. The common case is a stale `enabledPlugins` entry for a marketplace nobody registered. -### - -​ - -Control matrix +### Control matrix The table lists each plugin policy key, what it enforces, and what it can’t do. @@ -205,22 +165,14 @@ Each settings key here has an entry in the [settings reference](</docs/en/settings-reference>). -#### - -​ - -Aliases for the marketplace keys +#### Aliases for the marketplace keys `strictKnownMarketplaces` can also be spelled `allowedMarketplaces`, and `extraKnownMarketplaces` can also be spelled `additionalMarketplaces`. * **Version** : the aliases require Claude Code v2.1.232 or later, and older clients ignore them. In a file that a mixed fleet reads, keep the canonical names. * **Both spellings set** : when a file sets both spellings, the canonical key’s value applies. -### - -​ - -Allowlist with `strictKnownMarketplaces` +### Allowlist with `strictKnownMarketplaces` Set the allowlist to a list of these source objects. Most entries match exactly, `hostPattern` and `pathPattern` entries match as regular expressions, and `github` owner wildcards match by owner: @@ -233,11 +185,7 @@ * **`pathPattern`** : `{ "source": "pathPattern", "pathPattern": "^/opt/approved/" }`, matched against the `path` of `file` and `directory` sources. The pattern matches anywhere in the path, so start it with `^` to pin a directory prefix. `".*"` allows every local path. * **`skills-dir`** : `{ "source": "skills-dir" }` matches no marketplace. For what it does, see Keep skills-directory plugins loading. -#### - -​ - -How entries match +#### How entries match A `url` entry matches on its `url` value; `headers` aren’t compared. For `github` and `git` entries, the `repo` or `url`, the `ref`, and the `path` must all match, or be absent on both sides: @@ -247,35 +195,19 @@ Owner-wildcard entries follow the exact rules for `ref` and match any `path` inside the repository unless the entry pins one. Wildcard matching is case-sensitive on the allowlist. -#### - -​ - -Keep skills-directory plugins loading +#### Keep skills-directory plugins loading Skills-directory plugins are the plugins users keep under `~/.claude/skills/` or a project’s `.claude/skills/` in folders that carry a `.claude-plugin/plugin.json`. If you set any allowlist without a `{ "source": "skills-dir" }` entry, they stop loading. If you lock any customization type with [`strictPluginOnlyCustomization`](</docs/en/settings-reference#strictpluginonlycustomization>), they stop loading whether or not the entry is present. The allowlist doesn’t apply to plain [skills](</docs/en/skills>), meaning a `SKILL.md` without that manifest. -#### - -​ - -Marketplaces hosted on claude.ai +#### Marketplaces hosted on claude.ai The allowlist and blocklist match a [marketplace hosted on claude.ai](</docs/en/plugins/install#add-from-claude-ai>) by its host. To allow or block one, add a `hostPattern` entry that matches `claude.ai` to `strictKnownMarketplaces` or `blockedMarketplaces`. On the allowlist, such an entry admits your organization’s claude.ai marketplaces and the claude.ai default marketplaces, but not a marketplace made of a member’s own claude.ai uploads or one whose scope claude.ai didn’t state. Requires Claude Code v2.1.273 or later. -#### - -​ - -Lock every source out +#### Lock every source out An empty allowlist, `[]`, locks every marketplace source out, including the official marketplace. This lockdown doesn’t cover the plugins [synced from claude.ai](</docs/en/plugins/loading#synced-plugins>), which Claude Code downloads from each user’s account rather than from a marketplace. To stop those as well, set [`syncClaudeAiPlugins`](</docs/en/settings-reference#syncclaudeaiplugins>) to `false` in managed settings, or turn off Skills for your organization on claude.ai. -### - -​ - -Blocklist with `blockedMarketplaces` +### Blocklist with `blockedMarketplaces` `blockedMarketplaces` takes the same source objects as `strictKnownMarketplaces` and is checked first, so a source on both lists is blocked. Blocklist matching is wider than allowlist matching: @@ -294,11 +226,7 @@ The `url` entries in `blockedMarketplaces` also apply when a user adds an `https://` repository URL that Claude Code [clones rather than fetches](</docs/en/plugins/cli-reference#plugin-marketplace-add>), such as a bare `github.com` or `gitlab.com` repository URL. The user can’t add that URL if an entry names it. The match ignores the `.git` suffix and any ref the user appends after `#`. Requires Claude Code v2.1.232 or later. A `{ "source": "skills-dir" }` entry here stops skills-directory plugins from loading, from both `~/.claude/skills/` and a project’s `.claude/skills/`. A blocklist that names only that entry doesn’t count as an active restriction, so it doesn’t stop plugins whose marketplace Claude Code can’t find from loading. -### - -​ - -Allow the official marketplace and your own +### Allow the official marketplace and your own Most organizations allow the official marketplace and their own, and register both so every machine has them. This managed settings policy allows both marketplaces, registers both, force-enables two plugins, and rejects `--plugin-dir`: @@ -329,30 +257,18 @@ * **The official marketplace registers itself only in an interactive terminal session** : even there, it registers only when the allowlist permits it. A `-p` run or a terminal attached to a cloud session never registers it. * **A blocked attempt is remembered** : if a machine ever ran under a policy that blocked the official marketplace, Claude Code records the blocked attempt and doesn’t retry after the policy changes. An `[]` lockdown is one such policy. That machine registers it again only through an `extraKnownMarketplaces` entry such as the one in this policy, an `enabledPlugins` entry for one of its plugins, or a manual `/plugin marketplace add`. -## - -​ - -Set update policy +## Set update policy You can set update policy per marketplace, for the whole fleet, or per user group through release channels. -### - -​ - -Turn auto-update on or off per marketplace +### Turn auto-update on or off per marketplace Plugin auto-update runs in the background after startup for marketplaces that have it turned on. For which marketplaces have it on by default, see [When auto-update runs](</docs/en/plugins/loading#when-auto-update-runs>). To decide for the fleet, set `"autoUpdate": true` or `false` on a managed `extraKnownMarketplaces` entry: * If the managed entry sets the field, Claude Code refuses the user’s `/plugin` toggle with an error that starts `Auto-update for '<name>' is set by`. * If the managed entry leaves the field unset, the user’s toggle persists. -### - -​ - -Turn updates off for the whole fleet +### Turn updates off for the whole fleet To turn plugin auto-update off for every marketplace, set `DISABLE_AUTOUPDATER` in the managed `env` block, as this example does. The same variable also stops Claude Code’s own updates: @@ -364,11 +280,7 @@ To stop Claude Code’s own updates but keep plugin auto-update, add `"FORCE_AUTOUPDATE_PLUGINS": "1"` to the same block. The other [environment variables that stop plugin auto-update](</docs/en/plugins/loading#when-auto-update-runs>) work the same way. `DISABLE_AUTOUPDATER` doesn’t cover plugins with a [`command` source](</docs/en/plugins/marketplace-reference#command-plugin-source>). Claude Code re-runs each enabled one’s command every session and installs the output when it changed. For what stops those runs, see [When a command source re-runs](</docs/en/plugins/loading#when-a-command-source-re-runs>). -### - -​ - -Assign release channels to user groups +### Assign release channels to user groups To run stable and early-access channels, host two marketplaces that point at different refs of the same plugins. Then give each user group its own marketplace through separate endpoint-managed settings or a gateway policy. On an Enterprise plan, you can also use server-managed settings from the admin console. @@ -388,45 +300,25 @@ The early-access group receives `latest-tools` instead. To set up the two marketplaces, see [Run release channels](</docs/en/plugins/host-marketplace#run-release-channels>). -## - -​ - -Recommend plugins +## Recommend plugins Marketplace owners can attach `relevance` signals to entries so Claude Code suggests the plugin when a project matches. Suggestions from a marketplace appear only when it’s registered on the user’s machine, you list its name in `pluginSuggestionMarketplaces` in managed settings, and you declare its source in the same policy. Declare the source either as the marketplace’s `extraKnownMarketplaces` entry or as an allowlist entry. The official marketplace needs only the name. See [Enable suggestions in managed settings](</docs/en/plugins/relevance#enable-suggestions-in-managed-settings>). In a cloud session’s conversation, Claude can suggest plugins whether or not you set `pluginSuggestionMarketplaces`. To turn those suggestions off, see [Turn off plugin suggestions](</docs/en/claude-code-on-the-web#turn-off-plugin-suggestions>). -## - -​ - -Audit and review +## Audit and review OpenTelemetry events and the Analytics API tell you what your fleet installs and runs. For what a plugin can run on a machine and what each trust tier permits, read [Plugin security](</docs/en/plugins/security>) before you approve a marketplace. -### - -​ - -OpenTelemetry events +### OpenTelemetry events `claude_code.plugin_installed` records each install, and `claude_code.plugin_loaded` records each enabled plugin at session start. Both events redact or omit third-party plugin and marketplace names unless you set `OTEL_LOG_TOOL_DETAILS=1`, as [Redacted plugin names in your backend](</docs/en/plugins/measure#redacted-plugin-names-in-your-backend>) shows. Field lists are under [Plugin installed event](</docs/en/monitoring-usage#plugin-installed-event>) and [Plugin loaded event](</docs/en/monitoring-usage#plugin-loaded-event>). -### - -​ - -Analytics API +### Analytics API On the Enterprise plan, `GET /v1/organizations/analytics/plugins` returns per-plugin, per-day install and invocation counts across Claude Code and Cowork. You can group the counts by user or RBAC group. Plugin activity that reaches Anthropic without a plugin name appears in one aggregate `third-party` row. See the [endpoint reference](<https://platform.claude.com/docs/en/api/admin/analytics/plugins/list>) and [Access data programmatically](</docs/en/analytics#access-data-programmatically>) for the key it needs. -## - -​ - -Plan for what managed settings can’t enforce +## Plan for what managed settings can’t enforce These requests from security reviews have no dedicated key in the current settings schema. The nearest existing controls are: @@ -436,11 +328,7 @@ * **Gating`--plugin-dir` through the allowlist**: the allowlist doesn’t cover `--plugin-dir`. `disableSideloadFlags` does. * **Enforcing the claude.ai plugin toggles through these keys** : [**Organization settings > Plugins & skills**](<https://claude.ai/admin-settings/skills?tab=inventory>) doesn’t set the keys on this page. What members and your organization turn on there reaches the CLI as [synced plugins](</docs/en/plugins/loading#synced-plugins>), which have their own controls. -## - -​ - -Troubleshoot policy +## Troubleshoot policy If plugin policy doesn’t behave as expected on a machine, check for these symptoms first: @@ -449,11 +337,7 @@ * **A user reports`blocked by enterprise policy`**: the message names the marketplace or its source. For an allowlist, it also lists the allowed sources. The user-facing entries are on [Troubleshoot plugins](</docs/en/plugins/troubleshooting>). * **A plugin the user disabled in`~/.claude/settings.json` still loads**: another settings source re-enabled it, such as a managed `enabledPlugins` entry that force-enables it. `/plugin` and `claude plugin list` show `Disabled in ~/.claude/settings.json but still loads` with that settings source. -## - -​ - -Next steps +## Next steps * [Marketplace reference](</docs/en/plugins/marketplace-reference#marketplace-sources>): the `source` values `extraKnownMarketplaces`, `strictKnownMarketplaces`, and `blockedMarketplaces` accept * [Host and maintain a marketplace](</docs/en/plugins/host-marketplace>): run the marketplace your policy points at
modified Output styles View current →
Show diff (149 lines)
--- a/output-styles.md +++ b/output-styles.md @@ -9,11 +9,7 @@ * For something that has to happen every time, such as formatting after each edit or blocking a command, use a [hook](</docs/en/hooks-guide>). * For skills, subagents, and the other options, see Choose between an output style and other features. -## - -​ - -Built-in output styles +## Built-in output styles Claude Code starts in the **Default** style, its standard instructions for completing software engineering tasks. Each of the four other built-in styles keeps those instructions and adds its own. This table shows what each style changes about a session and when it fits: @@ -24,38 +20,22 @@ Explanatory| Claude adds short `Insight` blocks that explain the choices behind the code it writes| You’re getting to know a codebase or want the reasoning along with the change Learning| Claude explains its choices and leaves small pieces of code for you to write yourself| You want hands-on coding practice while the task still gets done -### - -​ - -Default +### Default Default means no output style is selected. Claude Code adds no style instructions, and Claude works from Claude Code’s standard system prompt, which is written for software engineering tasks. `default` appears in the `/output-style` list with the other styles, so you select it the same way. -### - -​ - -Proactive +### Proactive In the Proactive style, Claude starts implementing as soon as you send a task. It makes reasonable assumptions about routine decisions rather than stopping to ask, and it doesn’t switch to plan mode unless you ask for a plan. You can redirect it at any point. The style’s instructions also tell Claude to check with you in the conversation before an action that deletes data or changes a shared or production system. That check is an instruction Claude follows and is separate from permission prompts. Switching to the Proactive style doesn’t change your [permission mode](</docs/en/permission-modes>). Your permission mode still decides which tool calls run without asking you, so permission prompts appear the same way they did before you switched. -### - -​ - -Concise +### Concise In the Concise style, the first sentence of a response states what happened or what the answer is. Claude leaves out the lead-in, the step-by-step narration, and the closing recap, and answers a simple question in one to three sentences. It does the engineering work as thoroughly as in the Default style. Requires Claude Code v2.1.237 or later. Claude still writes at full length in these cases: * **Anything you ask for** : when you ask for an explanation or more detail, Claude answers in full. * **Anything you need in order to act safely** : error reports, failing test output, security warnings, and confirmations for destructive actions keep their complete content. -### - -​ - -Explanatory +### Explanatory In the Explanatory style, Claude does the task the way it does in the Default style and adds short explanations of why it made the choices it made. Each explanation appears in the conversation, before or after the code it’s about, in a block labeled `Insight`. The explanations aren’t written into your files as comments. An `Insight` block carries two or three points about your codebase or the code Claude wrote, such as this one after adding an API endpoint: @@ -64,11 +44,7 @@ - Rate limits are set per route in limits.ts, which is why this change adds an entry there rather than a global default. ───────────────────────────────────────────────── -### - -​ - -Learning +### Learning In the Learning style, Claude adds the same `Insight` blocks as the Explanatory style and also asks you to write some of the code. Claude handles routine implementation itself. When it reaches a piece with a real design decision, such as error handling, a data structure, or business logic with more than one valid approach, it leaves a few lines for you. Claude marks the spot with a `TODO(human)` comment in the file, then sends a request that says what’s already built, what to write, and what to weigh: @@ -82,11 +58,7 @@ Claude then stops and waits. Write your code at the `TODO(human)` comment and tell Claude when you’re done. Claude responds with one `Insight` about your code and continues the task. -## - -​ - -Change your output style +## Change your output style Pick a style with the command, a menu, or a settings file. The command and both menus save your choice to `.claude/settings.local.json` at the [local project level](</docs/en/settings>). @@ -103,11 +75,7 @@ The value is case-sensitive, so write the built-in names as `Proactive`, `Concise`, `Explanatory`, and `Learning`. A value that doesn’t match a style name exactly, such as `explanatory`, gives you the Default style. The `/output-style` command ignores case. To make a style your default across projects, set `outputStyle` in `~/.claude/settings.json`. A project’s own settings files [take precedence](</docs/en/settings#settings-precedence>) over that value. When you switch styles mid-session, Claude uses the new style starting with your next message. For what that first message costs in prompt caching, see [Changing output style](</docs/en/prompt-caching#changing-output-style>). Before v2.1.251, the new style applied only after you ran `/clear` or started a new session. -## - -​ - -Create a custom output style +## Create a custom output style A custom output style is a Markdown file: frontmatter for metadata, then the instructions for Claude. In the VS Code extension, you can also create the file from the [**Output styles** menu](</docs/en/vs-code#use-the-prompt-box>) rather than writing it by hand. This requires Claude Code v2.1.261 or later. @@ -149,11 +117,7 @@ [Plugins](</docs/en/plugins/manifest-reference>) can also ship output styles in an `output-styles/` directory. -### - -​ - -Frontmatter reference +### Frontmatter reference Configure an output style with YAML [frontmatter](</docs/en/glossary#frontmatter>) between `---` markers at the top of the file. All fields are optional, and field names use lowercase words separated by hyphens. A misspelled field is ignored without an error. If the YAML doesn’t parse, the style still loads under its file name with no fields set; run `claude --debug` to see the parse error. @@ -164,11 +128,7 @@ `keep-coding-instructions`| No| Set to `true` to keep Claude Code’s section of built-in software engineering instructions, which only the full system prompt includes, alongside your style. See How output styles work. Default: `false` `force-for-plugin`| No| Plugin output styles only. Set to `true` to apply this style automatically whenever the plugin is enabled, without requiring users to select it. Overrides the user’s `outputStyle` setting. If multiple enabled plugins set this, Claude Code uses the first one loaded. Default: `false` -## - -​ - -Choose between an output style and other features +## Choose between an output style and other features An output style applies to every response in a session. It’s an instruction Claude follows, so nothing enforces it. When what you want is narrower than every response, or has to happen without fail, another feature fits better. This table matches what you want to the feature that does it: @@ -183,11 +143,7 @@ These features combine. For example, you can use CLAUDE.md for what Claude should know, an output style for how it responds, and a hook for anything that has to be guaranteed. [Extend Claude Code](</docs/en/features-overview>) compares the rest of the extension features. -## - -​ - -How output styles work +## How output styles work An output style changes the instructions Claude Code gives Claude. @@ -196,11 +152,7 @@ Output styles apply to the main conversation and to a [fork](</docs/en/sub-agents#fork-the-current-conversation>), which inherits the parent’s whole conversation and system prompt. Other [subagents run their own system prompt](</docs/en/sub-agents#what-loads-at-startup>), so styles don’t change how they respond. Token usage depends on the style. A style’s instructions add input tokens, though prompt caching reduces this cost after the first request in a session. The built-in Explanatory and Learning styles produce longer responses than Default by design, which increases output tokens. The Concise style does the opposite by instructing Claude to keep responses short by default. For custom styles, output token usage depends on what your instructions tell Claude to produce. -## - -​ - -Related resources +## Related resources * [Settings](</docs/en/settings>): where the `outputStyle` field lives and how settings precedence works * [Permission modes](</docs/en/permission-modes>): how the Proactive style compares to auto mode
modified Agent SDK overview View current →
--- a/overview.md +++ b/overview.md @@ -1,10 +1,6 @@ An agent is an application that completes a task by planning its own steps and calling tools that read files, run commands, or edit code. The Agent SDK gives you the same tools, [agent loop](</docs/en/agent-sdk/agent-loop>), and context management that power Claude Code, programmable in Python and TypeScript. -## - -​ - -Compare the Agent SDK to other Claude tools +## Compare the Agent SDK to other Claude tools The Agent SDK, the CLI, the Client SDK, and Managed Agents differ in who runs the agent, what comes built in, and how you reach it. Find the row that matches how you want to build and run yours. @@ -17,11 +13,7 @@ To drive the same agent loop from a language other than Python or TypeScript, [run the CLI as a subprocess](</docs/en/headless>) with the `-p` flag and `--output-format json`. -## - -​ - -Capabilities +## Capabilities These Claude Code capabilities are available in the SDK: @@ -36,43 +28,27 @@ Skills, commands, and memory| Load automatically from your project’s `.claude/` and from `~/.claude/`, same as Claude Code| [Skills](</docs/en/agent-sdk/skills>), [Commands](</docs/en/agent-sdk/skills#commands-in-agent-sdk-sessions>), [Memory](</docs/en/agent-sdk/modifying-system-prompts>), [Configuration loading](</docs/en/agent-sdk/claude-code-features>) Plugins| Package skills, agents, hooks, and MCP servers, and load them by local path| [Plugins](</docs/en/agent-sdk/plugins>) -## - -​ - -Get started +## Get started Follow the [Quickstart](</docs/en/agent-sdk/quickstart>) to install the SDK, set your API key, and build your first agent, one that finds and fixes bugs in existing code. Unless previously approved, Anthropic does not allow third party developers to offer claude.ai login or rate limits for their products, including agents built on the Claude Agent SDK. Use the API key authentication methods described in the [Quickstart](</docs/en/agent-sdk/quickstart>) instead. -## - -​ - -Changelog +## Changelog View the full changelog for SDK updates, bug fixes, and new features: * **TypeScript SDK** : [view CHANGELOG.md](<https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/CHANGELOG.md>) * **Python SDK** : [view CHANGELOG.md](<https://github.com/anthropics/claude-agent-sdk-python/blob/main/CHANGELOG.md>) -## - -​ - -Report bugs +## Report bugs If you encounter bugs or issues with the Agent SDK: * **TypeScript SDK** : [report issues on GitHub](<https://github.com/anthropics/claude-agent-sdk-typescript/issues>) * **Python SDK** : [report issues on GitHub](<https://github.com/anthropics/claude-agent-sdk-python/issues>) -## - -​ - -Branding guidelines +## Branding guidelines For partners integrating the Claude Agent SDK, use of Claude branding is optional. When referencing Claude in your product: **Allowed:** @@ -87,19 +63,11 @@ Your product should maintain its own branding and not appear to be Claude Code or any Anthropic product. For questions about branding compliance, contact the Anthropic [sales team](<https://www.anthropic.com/contact-sales>). -## - -​ - -License and terms +## License and terms Use of the Claude Agent SDK is governed by [Anthropic’s Commercial Terms of Service](<https://www.anthropic.com/legal/commercial-terms>), including when you use it to power products and services that you make available to your own customers and end users, except to the extent a specific component or dependency is covered by a different license as indicated in that component’s LICENSE file. -## - -​ - -Next steps +## Next steps These resources cover deeper technical detail and example projects for building with the Agent SDK.
modified Choose a permission mode View current →
Show diff (609 lines)
--- a/permission-modes.md +++ b/permission-modes.md @@ -1,10 +1,6 @@ A permission mode sets which actions Claude can take in a session without asking you first. In Manual mode, Claude Code stops and asks you before most actions that edit files, run shell commands, or reach the network. In auto mode, a second model, the classifier, reviews actions instead of you; how the classifier evaluates actions lists which actions it reviews and which skip it. With Claude Code v2.1.283 or later, auto mode is the built-in starting permission mode for interactive terminal and VS Code sessions. On earlier versions, it’s the built-in starting permission mode only on Pro, Max, Ultra, and Team plans. Which mode a session starts in covers the surfaces and settings that change the starting permission mode. You can also change a running session’s permission mode at any time. -## - -​ - -Available modes +## Available modes Each mode makes a different tradeoff between convenience and oversight. The table below shows what Claude can do without a permission prompt in each mode. Manual mode appears under its config value, `default`. @@ -19,11 +15,7 @@ The mode that reviews every action is named **Manual** in the CLI, in `claude --help`, in the VS Code and JetBrains extensions, and in the desktop app. Its config value is `default`, which is what hooks and SDK integrations use. The CLI accepts `manual` as an alias wherever you type the value, for example `claude --permission-mode manual` or `"defaultMode": "manual"`. Each mode has its own rule for writes to protected paths. Modes set the baseline. Layer [permission rules](</docs/en/permissions#manage-permissions>) on top to pre-approve or block specific tools. Deny rules block in every mode, including `bypassPermissions`. Deny and ask rules don’t apply to [`EndConversation`](</docs/en/tools-reference#endconversation-tool-behavior>) as long as Claude still has at least one other tool it can call. Allow rules have no effect in `bypassPermissions`. -### - -​ - -Actions no mode auto-approves +### Actions no mode auto-approves Claude Code doesn’t auto-approve the following in any mode, including `bypassPermissions`, though you can turn off the prompt for dangerous `rm` commands in `bypassPermissions` mode. Each bullet links to the section that says what happens instead in each mode: @@ -35,11 +27,7 @@ * Reads outside the working directories while [`permissions.blockReadsOutsideWorkingDirectories`](</docs/en/settings-reference#permissions-blockreadsoutsideworkingdirectories>) is on: recognized file-reading Bash commands prompt even in auto mode and `bypassPermissions` mode, and so does any [unsandboxed retry](</docs/en/sandboxing#the-unsandboxed-retry-escape-hatch>) that needs approval to run outside the sandbox. Requires Claude Code v2.1.257 or later. A command the shell parser can’t trace, such as one that changes directory more than once or runs a subshell, prompts the same way even when it names no outside path. This prompt doesn’t apply when the command runs in the [sandbox](</docs/en/sandboxing>) and the sandbox enforces the block. * Writes outside the working directories while [`permissions.blockWritesOutsideWorkingDirectories`](</docs/en/settings-reference#permissions-blockwritesoutsideworkingdirectories>) is on: Claude Code refuses `Write`, `Edit`, and `NotebookEdit` calls there, apart from [some of its own files](</docs/en/settings-reference#what-the-write-block-refuses-and-what-stays-writable>). The key doesn’t limit shell commands, MCP tools, or the programs hooks run, so use [sandboxing](</docs/en/sandboxing>) to limit where shell commands write. Requires Claude Code v2.1.314 or later. -## - -​ - -Common setups +## Common setups Permission modes decide whether Claude asks before an action, and the [Bash sandbox](</docs/en/sandboxing>) and outer [isolation boundaries](</docs/en/sandbox-environments>) decide what an action can reach once it runs. Each row below pairs a goal with the flags or settings that get you there and the isolation it needs, as a starting point. Available modes lists what runs without a prompt in each mode. @@ -54,11 +42,7 @@ The Bash sandbox and auto mode work independently and combine, with the exceptions listed under [Sandbox modes](</docs/en/sandboxing#sandbox-modes>). For the full interaction, see [How sandboxing relates to permissions and permission modes](</docs/en/sandboxing#how-sandboxing-relates-to-permissions-and-permission-modes>) and [How isolation relates to permission modes](</docs/en/sandbox-environments#how-isolation-relates-to-permission-modes>). -## - -​ - -Which mode a session starts in +## Which mode a session starts in When you start a new session in a terminal, Claude Code takes the permission mode from the first of these that applies: @@ -82,11 +66,7 @@ If your `~/.claude/settings.json` sets a `defaultMode` other than `auto` and no other settings file sets one, your sessions keep starting in that mode. On Pro, Max, Ultra, and Team plans, and in sessions that [don’t fetch feature flags](</docs/en/env-vars#features-that-need-feature-flag-fetching>), Claude Code asks once whether to change the setting to auto mode. The question appears in the terminal or in the VS Code extension, and if you decline, your setting stays as it is. -### - -​ - -Tool calls denied in `claude -p` and Agent SDK runs +### Tool calls denied in `claude -p` and Agent SDK runs In Claude Code v2.1.302 or later, `claude -p` and [Agent SDK](</docs/en/agent-sdk/permissions#permission-modes>) runs with no permission mode set start in Manual mode. This mode appears as `default` in SDK options and settings. Calls needing approval are denied unless you approve them with an allow rule, hook, `canUseTool` callback, or `--permission-prompt-tool`. To get these calls approved, add allow rules or start in auto mode: @@ -113,11 +93,7 @@ Before v2.1.302, these runs could start in auto mode if they didn’t [fetch feature flags](</docs/en/env-vars#features-that-need-feature-flag-fetching>), for example on a [third-party provider](</docs/en/third-party-integrations>) or with `DISABLE_TELEMETRY`. -### - -​ - -Start in a different permission mode +### Start in a different permission mode You can set the starting permission mode for one session, or as a default for every session on a machine, in a project, or in an organization. When more than one settings file sets `permissions.defaultMode`, [settings precedence](</docs/en/settings#settings-precedence>) decides, so a project or managed value outranks `~/.claude/settings.json`. To change the permission mode of a session that’s already running, see Switch permission modes. @@ -138,11 +114,7 @@ The next session you start shows `⏸ manual mode on` in the status bar. -### - -​ - -Permission modes with the HIPAA configuration +### Permission modes with the HIPAA configuration In an organization with the [HIPAA configuration](</docs/en/hipaa-setup>) applied, the built-in `auto` default doesn’t apply. A terminal or VS Code session starts in Manual mode when nothing else chooses its starting permission mode. A terminal session also shows `Auto mode isn't the default for your organization · Shift+Tab to switch`, and the VS Code extension shows no notice. [Check how developers sign in and connect](</docs/en/hipaa-setup#check-how-developers-sign-in-and-connect>) lists the sessions this applies to. Auto mode and `bypassPermissions` stay available: @@ -151,11 +123,7 @@ * **Remove auto mode** : set [`permissions.disableAutoMode`](</docs/en/settings-reference#disableautomode>) to `"disable"` in managed settings * **Block`bypassPermissions`**: set [`permissions.disableBypassPermissionsMode`](</docs/en/settings-reference#permissions-disablebypasspermissionsmode>) to `"disable"` in managed settings -## - -​ - -Switch permission modes +## Switch permission modes Each interface has its own control for switching permission modes during a session and its own way of choosing the permission mode new sessions start in. Select your interface to see its controls. @@ -222,11 +190,7 @@ claude remote-control --permission-mode acceptEdits -## - -​ - -Auto-approve file edits with acceptEdits mode +## Auto-approve file edits with acceptEdits mode `acceptEdits` mode lets Claude create and edit files in your working directory without prompting. The status bar shows `⏵⏵ accept edits on` while this mode is active. In addition to file edits, `acceptEdits` mode auto-approves common filesystem Bash commands: `mkdir`, `touch`, `rm`, `rmdir`, `mv`, `cp`, and `sed`. Except for `touch`, these commands are also auto-approved when prefixed with safe environment variables such as `LANG=C` or `NO_COLOR=1`, or process wrappers such as `timeout`, `nice`, or `nohup`. Like file edits, auto-approval applies only to paths inside your working directory or `additionalDirectories`. These still prompt: @@ -240,11 +204,7 @@ claude --permission-mode acceptEdits -## - -​ - -Analyze before you edit with plan mode +## Analyze before you edit with plan mode Plan mode tells Claude to research and propose changes without making them. Claude reads files, runs shell commands to explore, and writes a plan, but does not edit your source. Except in interactive terminal sessions with bypass permissions available, edits stay blocked until you approve the plan. What happens to a shell command during planning depends on the session, and the first of these cases that matches applies: @@ -256,13 +216,9 @@ claude --permission-mode plan -Press `Shift+Tab` again to leave plan mode without approving a plan. - -### - -​ - -Review and approve a plan +With no approval prompt open, press `Shift+Tab` again to leave plan mode. At the approval prompt, press `Esc` first, since pressing `Shift+Tab` there approves the plan. + +### Review and approve a plan When the plan is ready, Claude presents it and asks how to proceed. From that prompt you can choose: @@ -272,19 +228,11 @@ Approving a plan exits plan mode and switches the session to the permission mode each approve option describes, so Claude starts editing. To plan again, cycle back to plan mode with `Shift+Tab`, or prefix your next prompt with `/plan`. Press `Ctrl+G` to open the proposed plan in your default text editor and edit it directly before Claude proceeds. When [`showClearContextOnPlanAccept`](</docs/en/settings-reference#showclearcontextonplanaccept>) is enabled, the list gains a first option that approves the plan and clears the planning context. Accepting a plan also gives the session a [generated title](</docs/en/sessions#name-your-sessions>) based on the plan, unless you’ve already named the session. -### - -​ - -Set plan mode as the default +### Set plan mode as the default To make plan mode the default for a project’s terminal sessions, set `defaultMode` to `plan` in `.claude/settings.json`, placed as the example under Start in a different permission mode shows. Conversations the [VS Code extension](</docs/en/vs-code>) starts don’t read project settings for the starting permission mode. There, set `claudeCode.initialPermissionMode` to `plan` in your VS Code user settings instead. -## - -​ - -Eliminate permission prompts with auto mode +## Eliminate permission prompts with auto mode Auto mode lets Claude execute without routine permission prompts. A separate classifier model reviews actions before they run, blocking anything that escalates beyond your request, targets unrecognized infrastructure, or appears driven by hostile content Claude read. Explicit [ask rules](</docs/en/permissions#manage-permissions>) still force a prompt. With Claude Code v2.1.283 or later, auto mode is the built-in starting permission mode for interactive terminal and VS Code sessions on every plan and provider. On earlier versions, it’s the built-in starting permission mode only on Pro, Max, Ultra, and Team plans. The classifier also reviews each message Claude sends to another agent with [`SendMessage`](</docs/en/tools-reference>), whether plain text or a structured [agent team](</docs/en/agent-teams>) message, before Claude Code delivers it, both in auto mode and in plan mode while the classifier reviews commands; the send review requires Claude Code v2.1.222 or later. By default, the classifier doesn’t review recognized `rm` and `rmdir` critical-path removals, such as `rm -rf /` or `rm -rf ~`. Critical paths covers what happens to them in each permission mode. Auto mode also nudges Claude to keep working without stopping for clarifying questions, though Claude still asks when your prompt or a skill explicitly relies on it. For stronger autonomous behavior in a mode that still prompts you, set the [Proactive output style](</docs/en/output-styles>) instead. @@ -299,11 +247,7 @@ If Claude Code reports auto mode as unavailable, first check these requirements and whether any settings file sets [`disableAutoMode`](</docs/en/settings-reference#disableautomode>). Anthropic may also have turned auto mode off server-side, or the server may have rejected auto mode for your account. A session that received either answer keeps auto mode off until the session ends, so start a new session later. A separate message that names a model and says auto mode “cannot determine the safety” of an action means a classifier request failed. That failure is usually transient, but on Amazon Bedrock it can repeat until your account can invoke the named model. See the [error reference](</docs/en/errors#auto-mode-cannot-determine-the-safety-of-an-action>) for the causes and what to do. If you set `defaultMode: "auto"` in [settings](</docs/en/settings-reference#all-settings>) and a terminal session starts in Manual mode with no error, the setting is likely in `.claude/settings.json` or `.claude/settings.local.json`. `auto` doesn’t take effect from those files. Move it to `~/.claude/settings.json`. For a conversation the VS Code extension started, check the extension’s own list in Switch permission modes instead. -### - -​ - -Auto mode on Bedrock, Agent Platform, or Foundry +### Auto mode on Bedrock, Agent Platform, or Foundry On [Amazon Bedrock](</docs/en/amazon-bedrock>), [Google Cloud’s Agent Platform](</docs/en/google-vertex-ai>), [Microsoft Foundry](</docs/en/microsoft-foundry>), and signed-in [Claude apps gateway](</docs/en/claude-apps-gateway>) sessions, auto mode is available by default. If you don’t set a permission mode there, interactive sessions start in auto mode, and `claude -p` or Agent SDK runs start in Manual mode, whose config value is `default`: @@ -312,11 +256,7 @@ Only Claude Sonnet 5 or later, Opus 4.7 or later, Haiku 5.5, and the Fable models are supported on these providers. On any other model, the session starts in Manual instead. Auto mode with Haiku 5.5 on these providers requires Claude Code v2.1.293 or later. To prevent developers from using auto mode, set `disableAutoMode` to `"disable"` in [managed settings](</docs/en/managed-settings>). This removes `auto` from the `Shift+Tab` cycle, and a session started with `--permission-mode auto` starts in Manual instead. A session already running in auto mode leaves it when the setting reaches that session from an [admin-deployed source](</docs/en/managed-settings#which-managed-source-claude-code-uses>), and shows `auto mode disabled by settings`. Before v2.1.251, a running session kept auto mode until it ended. -### - -​ - -Server-side classifier review +### Server-side classifier review In auto mode, Claude Code can ask the server to check the actions that the decision order sends for review, as part of the session’s model requests, in place of sending its own classifier requests. These sessions ask: @@ -336,11 +276,7 @@ To skip asking the server and always use Claude Code’s own classifier requests, set [`CLAUDE_CODE_AUTO_MODE_SERVER=0`](</docs/en/env-vars>). On a direct connection to the Anthropic API, the variable requires Claude Code v2.1.281 or later. Setting it to `1` there turns server review on in a session that doesn’t have it yet, unless you’ve also set `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1`. If you set `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1` and leave `CLAUDE_CODE_AUTO_MODE_SERVER` unset, Claude Code also stops asking the server, except as [Disable pre-release capabilities](</docs/en/llm-gateway-protocol#disable-pre-release-capabilities>) describes. -### - -​ - -Default classifier model +### Default classifier model By default, classifier requests go to Claude Sonnet 5. If `/status` shows `Auto mode server` as `Enabled`, they’re sent only for calls outside the server’s review. Find the first row in this table that matches your session. You get that row’s model in place of Sonnet 5. @@ -352,11 +288,7 @@ If Sonnet 5 or the model in `ANTHROPIC_DEFAULT_SONNET_MODEL` is unavailable from your provider or excluded by your organization’s [model policy](</docs/en/model-config#restrict-model-selection>), Claude Code uses a fallback model. That’s your session’s model, or an Opus model in a [Fable session](</docs/en/model-config#work-with-fable>). -### - -​ - -Choose the classifier model +### Choose the classifier model With Claude Code v2.1.302 or later, set [`CLAUDE_CODE_AUTO_MODE_MODEL`](</docs/en/env-vars>) to a full model ID to run the classifier on a model other than the default. Your cloud provider’s own full model IDs work too. This `~/.claude/settings.json` example sets Claude Sonnet 4.6: @@ -366,11 +298,7 @@ } } -#### - -​ - -When your model doesn’t review +#### When your model doesn’t review Situation| What happens| What to do ---|---|--- @@ -381,11 +309,7 @@ If several situations apply, go by the first listed. -#### - -​ - -Check which model the classifier used +#### Check which model the classifier used From your shell, start an auto mode session with [`--debug-file`](</docs/en/cli-reference#cli-flags>): @@ -399,11 +323,7 @@ * **`Enabled`** : the server is set to review this session’s calls. * **`Disabled`** : this check hasn’t tested your model yet. Make sure the permission mode is auto and no [permission rule](</docs/en/permissions#manage-permissions>) matches `curl`, then run the check again with the [sandbox](</docs/en/sandboxing>) off. -### - -​ - -What the classifier blocks by default +### What the classifier blocks by default The classifier trusts your working directory and the remotes that were configured for it when the session started. A remote added or repointed during the session with `git remote add` or `git remote set-url` isn’t trusted, and everything else is treated as external until you [configure trusted infrastructure](</docs/en/auto-mode-config>). **Blocked by default** : @@ -474,11 +394,7 @@ Sandboxed commands don’t get network access by default. Claude names the hosts a command needs on the command itself, the classifier reviews them with the command, and an approved list opens those hosts for that one command alone. [Per-command allowed domains](</docs/en/sandboxing#per-command-allowed-domains-in-auto-mode>) covers what a list can and can’t open and what happens when a command reaches for an unlisted host. Run `claude auto-mode defaults` to print the full rule lists as JSON. If routine actions get blocked, an administrator can add trusted repos, buckets, and services via the `autoMode.environment` setting: see [Configure auto mode](</docs/en/auto-mode-config>). Pushing to any branch of the repository you’re working in and creating a pull request that matches your request run without a prompt, unless the push or pull request falls under the blocked list, such as secrets or sensitive data leaving the repository, or a pull request that targets a different repository or organization. To require a human checkpoint before these commands while staying in auto mode, add `permissions.ask` rules, which match the command [as written](</docs/en/permissions#bash-rule-limits>): see [Common boundaries](</docs/en/auto-mode-config#common-boundaries>). -### - -​ - -The first read outside the working directories +### The first read outside the working directories While [`permissions.blockReadsOutsideWorkingDirectories`](</docs/en/settings-reference#permissions-blockreadsoutsideworkingdirectories>) is off, file reads other than [reads from network paths](</docs/en/permissions#network-paths>) run without a prompt in auto mode, including reads outside the [working directories](</docs/en/permissions#working-directories>). The first time Claude uses the Read, Grep, or Glob tool on a path outside them, Claude Code asks whether to allow that read. The prompt doesn’t appear in non-interactive `-p` runs or background sessions; reads there run as before. Whatever you answer, Claude keeps working: @@ -487,19 +403,11 @@ * **No, and ask again next time** : the read is refused, and the next read outside the working directories prompts again * **Yes, but ask again next time** : the read runs, nothing is saved, and the next read outside the working directories prompts again -### - -​ - -Boundaries you state in conversation +### Boundaries you state in conversation The classifier treats boundaries you state in the conversation as a block signal. If you tell Claude “don’t push” or “wait until I review before deploying”, the classifier blocks matching actions even when the default rules would allow them. A boundary stays in force until you lift it in a later message. Claude’s own judgment that a condition was met does not lift it. Boundaries are not stored as rules. The classifier re-reads them from the transcript on each check, so a boundary can be lost if [context compaction](</docs/en/costs#reduce-token-usage>) removes the message that stated it. For a hard guarantee, add a [deny rule](</docs/en/permissions#permission-rule-syntax>) instead. -### - -​ - -Approvals you state in conversation +### Approvals you state in conversation If you tell Claude that a blocked action is allowed, the classifier reads that as your approval and can clear the block. How you worded it decides whether the action runs, and how far the approval reaches: @@ -507,11 +415,7 @@ * **Expect it to cover one action** : an approval covers the destructive action you named, so a later action is blocked again unless you granted the approval as standing. To stop approving a routine pattern one action at a time, add it to [`autoMode.allow`](</docs/en/auto-mode-config#override-the-block-and-allow-rules>). * **Some blocks stay in place** : [the classifier’s precedence order](</docs/en/auto-mode-config#override-the-block-and-allow-rules>) sets out which blocks your approval can reach. To run a step it won’t clear, leave auto mode and answer the permission prompt. -### - -​ - -When auto mode falls back +### When auto mode falls back When auto mode can’t approve your session’s actions, what happens depends on the case: @@ -521,19 +425,11 @@ * **No verdict from the server** : under server-side classifier review, Claude Code denies an action the server gives no verdict for, and can stop the turn after ten responses in a row with no verdict. See [The server returned no safety verdict](</docs/en/errors#the-server-returned-no-safety-verdict>). * **A mode switch during a check** : if you switch permission modes while a classifier check is pending, Claude Code discards a verdict the new mode wouldn’t have requested. You’re prompted for approval instead, or the action is auto-denied in `dontAsk` mode. -#### - -​ - -Repeated-block thresholds +#### Repeated-block thresholds The thresholds of 3 blocks in a row and 20 blocks total are not configurable. The total counter persists for the session and resets only when its own limit triggers a fallback. Claude Code doesn’t count a denial toward either threshold when a safety check separate from auto mode refuses the classifier’s own request. A [non-interactive](</docs/en/headless>) `-p` run without a [`--permission-prompt-tool`](</docs/en/cli-reference#cli-flags>) has no prompt to fall back to. When repeated blocks reach a threshold, the action doesn’t run and Claude keeps working. Claude Code doesn’t stop the run. Repeated blocks usually mean the classifier is missing context about your infrastructure. Use `/feedback` to report false positives, or have an administrator [configure trusted infrastructure](</docs/en/auto-mode-config>). -### - -​ - -How auto mode evaluates actions +### How auto mode evaluates actions The following sections cover the order Claude Code evaluates an action in, how the classifier reviews subagent work, and what classifier calls add in cost and latency. @@ -579,11 +475,7 @@ Claude Code’s classifier requests can run on a model other than your `/model` selection. See which model they run on.On Enterprise plans and on accounts that use the Claude API, [Claude Platform on AWS](</docs/en/claude-platform-on-aws>), Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry, classifier calls count toward your token usage. Each check sends a portion of the transcript plus the pending action, adding a round-trip before execution. Reads and working-directory edits outside protected paths skip the classifier, so the overhead comes mainly from shell commands and network operations. Where the server reviews the actions as part of the session’s model requests, there are no separate classifier calls to count; see Server-side classifier review.Sandboxed network access adds no per-connection classifier requests. The classifier judges [the hosts a command names](</docs/en/sandboxing#per-command-allowed-domains-in-auto-mode>) together with the command in one review, and Claude Code checks each connection against the approved list without calling the classifier again. -## - -​ - -Allow only pre-approved tools with dontAsk mode +## Allow only pre-approved tools with dontAsk mode If you set `dontAsk` mode, Claude Code auto-denies every tool call that would otherwise prompt you, though a [mod](</docs/en/plugins/mods/overview>) you installed can still approve some of those calls. To check which calls a mod can approve, see [Extend permissions with hooks](</docs/en/permissions#precedence-among-rules-hooks-and-mods>). Claude still runs actions that need no approval in Manual mode, such as file reads inside your working directories and [read-only Bash commands](</docs/en/permissions#read-only-commands>). Actions matching your `permissions.allow` rules and calls approved by a [PreToolUse hook](</docs/en/permissions#extend-permissions-with-hooks>) run too. Use this mode for CI pipelines or restricted environments where you pre-define what Claude may do; the session never waits for input. The status bar shows `⏵⏵ don't ask on` in this mode. Claude Code denies calls matching your explicit [`ask` rules](</docs/en/permissions#manage-permissions>) rather than prompting. It also denies the built-in `AskUserQuestion` tool even if your allow rules match it, and does the same to connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>) in sessions where that setting reaches Claude Code. It denies MCP tools marked [`_meta["anthropic/requiresUserInteraction"]`](</docs/en/mcp#require-approval-for-a-specific-tool>) the same way, because their approval card needs an answer this mode never collects. An allow rule or `PreToolUse` hook can’t approve these: @@ -594,11 +486,7 @@ claude --permission-mode dontAsk -## - -​ - -Skip all checks with bypassPermissions mode +## Skip all checks with bypassPermissions mode `bypassPermissions` mode disables permission prompts and safety checks so tool calls execute immediately, including writes to protected paths. Even in `bypassPermissions` mode, each of the actions no mode auto-approves gets a prompt or a denial, though you can turn off the prompt for dangerous `rm` commands. Reading [another organization’s public artifact](</docs/en/artifacts#read-an-artifact-shared-with-you>) needs your approval, and this mode doesn’t ask for it, so Claude can’t read one. The Remove-Item in PowerShell denies also apply in this mode. Two [cross-session messaging](</docs/en/cross-session-messaging>) safeguards still apply in this mode, and in interactive terminal plan-mode sessions where bypass permissions are available: @@ -634,11 +522,7 @@ `bypassPermissions` offers no protection against prompt injection or unintended actions. For background safety checks with far fewer permission prompts, use auto mode instead. Administrators can block this mode by setting `permissions.disableBypassPermissionsMode` to `"disable"` in [managed settings](</docs/en/managed-settings>). -### - -​ - -Bypass permissions ignored in a background session +### Bypass permissions ignored in a background session This notice means the [background session](</docs/en/agent-view>) didn’t find your acceptance of the bypass permissions warning in user or managed settings, so it ignored the bypass request made at launch: @@ -646,19 +530,11 @@ Add `"skipDangerousModePermissionPrompt": true` to `~/.claude/settings.json`, then start a new background session. -### - -​ - -`claude agents` shows the bypass permissions warning that interactive sessions skip +### `claude agents` shows the bypass permissions warning that interactive sessions skip If [`claude agents`](</docs/en/agent-view#dispatch-defaults>) shows the bypass permissions warning although your interactive sessions skip it, check whether `skipDangerousModePermissionPrompt` is set in `.claude/settings.local.json` or a `--settings` file. Interactive sessions count the key there as your acceptance of the warning, and `claude agents` doesn’t. Whether or not you find it there, accept the warning to add the key to `~/.claude/settings.json`, where `claude agents` looks for it. -## - -​ - -Protected paths +## Protected paths A small set of paths holds repository state and Claude’s own configuration, so each mode has its own rule for writes to them: @@ -710,11 +586,7 @@ * A file you passed to [`--settings`](</docs/en/cli-reference#cli-flags>), `--mcp-config`, or `--agents` when you started the session * The file that your user, project, or local [settings file](</docs/en/settings#settings-files-and-who-they-affect>) points to when the settings file is itself a symbolic link, for example into a dotfiles repository. In the modes that route protected-path writes to the classifier, a write to this file prompts you instead, even when an allow rule matches. If the file’s own path is also that of a settings file, such as `.claude/settings.json` in another folder, the write goes to the classifier as other protected-path writes do -## - -​ - -Critical paths +## Critical paths Critical paths are the directories Claude Code protects from `rm` and `rmdir` commands, such as the filesystem root, your home directory, and your working directory. Claude Code checks these commands before they run, and no [allow rule](</docs/en/permissions#manage-permissions>) approves one whose target it recognizes as a critical path. The check can miss some commands, so it doesn’t replace an operating-system control such as [sandboxing](</docs/en/sandboxing>). A critical-path removal is an `rm` or `rmdir` command whose target Claude Code recognizes as a critical path. No [`PreToolUse` hook](</docs/en/permissions#extend-permissions-with-hooks>) that returns `"allow"` approves one either. An allow rule or `PreToolUse` hook can’t approve one even in the permission modes that skip other prompts. @@ -728,11 +600,7 @@ What happens to a removal that Claude Code recognizes depends on your permission mode. `Remove-Item` and the `cmd` removal built-ins have their own checks, covered in Remove-Item in PowerShell. -### - -​ - -Which paths are critical +### Which paths are critical Claude Code treats an `rm` or `rmdir` target as a critical path when it is any of the following: @@ -745,11 +613,7 @@ For mounted drive paths such as `/mnt/c` or `/Volumes/USB`, see The mounted drive prompt. The checks on the home directory’s 8.3 short name and on the `\\?\C:\` and `\\localhost\C$` spellings require Claude Code v2.1.292 or later. -### - -​ - -Other targets that count as critical paths +### Other targets that count as critical paths Claude Code also treats the following `rm` and `rmdir` targets as critical paths. The last column says why each one counts. @@ -767,11 +631,7 @@ To turn off the check on a target that is only command substitution output, set [`CLAUDE_CODE_DISABLE_SUBSTITUTION_RM_PROMPT=1`](</docs/en/env-vars#variables>) in the environment that launches Claude Code. -### - -​ - -Removals inside nested commands and inline scripts +### Removals inside nested commands and inline scripts Claude Code also looks inside these constructs: @@ -782,11 +642,7 @@ To turn off the check on a critical path typed directly in a `-c` script, such as `~`, set [`CLAUDE_CODE_DISABLE_INLINE_SHELL_RM_PROMPT=1`](</docs/en/env-vars#variables>) in the environment that launches Claude Code. -### - -​ - -Rewrite a flagged command +### Rewrite a flagged command How to rewrite a command so it passes the check depends on which of the other targets it uses: @@ -797,11 +653,7 @@ For a glob or trailing slash under a variable, the prompt names the flagged `rm` and says how to rewrite it so the check passes. -### - -​ - -The `Dangerous rm operation not ruled out` prompt +### The `Dangerous rm operation not ruled out` prompt The full reason reads: @@ -813,19 +665,11 @@ You get the prompt or denial a critical-path removal gets in your permission mode, `bypassPermissions` included, though you can turn off that prompt in `bypassPermissions` mode. You can’t approve the command with a `Bash` or `Bash(*)` allow rule, sandbox [auto-allow mode](</docs/en/sandboxing#auto-allow-mode>), or a `PreToolUse` hook returning `"allow"`. Read the command, then approve the prompt or, after a denial, run it in your shell. -### - -​ - -The mounted drive prompt +### The mounted drive prompt The mounted drive prompt appears on macOS, Linux, and WSL when a recursive `rm` targets a listed mounted drive path, such as `/mnt/c` or `/Volumes/USB/build`. Its reason reads `Dangerous rm operation on mounted drive path: <path>`. A `/*` target gets the prompt without the recursive flag, since Claude Code reads `rm /Volumes/USB/build/*` as a removal of `/Volumes/USB/build`. Even with an allow rule for `rm`, Claude Code handles the command as a critical-path removal: a prompt or a denial depending on your permission mode. Approve the prompt to let the `rm` run, or turn the prompt off. -#### - -​ - -Paths that get the mounted drive prompt +#### Paths that get the mounted drive prompt Match the target of your recursive `rm` or `/*` removal against these path shapes, where each placeholder such as `<drive>` or `<name>` stands for exactly one path segment: @@ -839,11 +683,7 @@ For a recursive or non-recursive `rm` on `/Volumes`, `/media`, or `/mnt` itself, you see the critical path reason `Dangerous rm operation on critical path: <path>` instead. A relative target counts from your working directory, so `rm -rf build` while you work in `/Volumes/USB` targets `/Volumes/USB/build` and gets the prompt. -#### - -​ - -Turn off the mounted drive prompt +#### Turn off the mounted drive prompt To stop getting the mounted drive prompt while prompts from other causes stay, start Claude Code with [`CLAUDE_CODE_DISABLE_MOUNTED_DRIVE_RM_PROMPT=1`](</docs/en/env-vars#variables>) in its environment. For example, set the variable in [your shell](</docs/en/env-vars#set-variables-in-your-shell>) and start `claude` from it: @@ -855,11 +695,7 @@ * **Variable in a settings file** : Claude Code [ignores the variable in a settings file’s `env` block](</docs/en/settings-reference#variables-claude-code-ignores-in-env>), whichever kind of settings file, so set the variable where you start `claude` instead * **Session started without the variable** : start `claude` again from an environment where the variable is set, since a running session doesn’t pick it up -#### - -​ - -Removals that still prompt with the mounted drive prompt off +#### Removals that still prompt with the mounted drive prompt off In Manual mode with an allow rule for `rm`, an `rm` on a mounted drive path can still prompt, without the `Dangerous rm operation on mounted drive path` reason: @@ -867,11 +703,7 @@ * **Target with a`*`**: `rm -rf build/*` gets a prompt. Approve that prompt to run the command, or ask Claude to name each target without a `*` * **Target that is a critical path** : `/mnt` itself and your working directory itself stay critical paths, so `rm -rf` on either gets a prompt. Approve that prompt to let the `rm` run -### - -​ - -Critical-path removals in each permission mode +### Critical-path removals in each permission mode What Claude Code does with a critical-path removal depends on your permission mode: @@ -885,11 +717,7 @@ If an explicit [ask rule](</docs/en/permissions#manage-permissions>) matches the command, Claude Code asks you instead, even in `auto` mode and without a time limit. In modes that ask, a [`PermissionRequest` hook](</docs/en/hooks#permissionrequest>) can answer the prompt. To run these removals with no prompt in `bypassPermissions` mode, see Turn off the critical-path removal prompt. -### - -​ - -Time limits and denials in auto and bypassPermissions modes +### Time limits and denials in auto and bypassPermissions modes In `auto` and `bypassPermissions` modes, the terminal prompt for a critical-path removal shows a two-minute countdown: @@ -918,11 +746,7 @@ ] } -### - -​ - -Turn off the critical-path removal prompt in bypassPermissions mode +### Turn off the critical-path removal prompt in bypassPermissions mode To run Bash `rm` and `rmdir` commands that target critical paths with no prompt in `bypassPermissions` mode, start Claude Code with [`CLAUDE_CODE_EVEN_MORE_DANGEROUSLY_SKIP_PERMISSIONS=1`](</docs/en/env-vars#variables>) in its environment. This requires Claude Code v2.1.311 or later. Claude Code reads the variable from the launch environment only and [ignores it in a settings file’s `env` block](</docs/en/settings-reference#variables-claude-code-ignores-in-env>). For example, set it in [your shell](</docs/en/env-vars#set-variables-in-your-shell>) and start `claude` from there: @@ -945,11 +769,7 @@ Removals run with no prompt only in `bypassPermissions` mode itself, not in plan mode, and only for what the critical-path check flags in the Bash and [Monitor](</docs/en/tools-reference#monitor-tool>) tools. That includes commands Claude Code can’t fully parse, which also run with no prompt. -#### - -​ - -Startup notices about the critical-path removal prompt +#### Startup notices about the critical-path removal prompt To check whether `CLAUDE_CODE_EVEN_MORE_DANGEROUSLY_SKIP_PERMISSIONS` is working, read the line Claude Code prints at startup. In a `-p` run, it’s on stderr. In an Agent SDK app, pass the [`stderr` option](</docs/en/agent-sdk/typescript#options>) to read it. The line says one of these: @@ -959,11 +779,7 @@ A missing line doesn’t mean the prompt is on: an Agent SDK app with no `stderr` option sees no line, and removals can still run with no prompt. Otherwise, check that you set the variable in the launch environment, that the session can enter `bypassPermissions` mode, and that `claude` isn’t inside another session. Some sessions start without the variable. If you see one of these lines and didn’t set the variable, find where it’s set, such as your shell profile, and remove it. -#### - -​ - -Why the critical-path removal prompt stays on +#### Why the critical-path removal prompt stays on If `CLAUDE_CODE_EVEN_MORE_DANGEROUSLY_SKIP_PERMISSIONS` has no effect and removals keep their usual prompt or denial, check for causes such as these: @@ -977,11 +793,7 @@ * **Managed settings can’t be read** : Claude Code hasn’t successfully read your [managed settings](</docs/en/managed-settings>) sources. If server-managed settings keep failing to load, see [Remote managed settings failed to load](</docs/en/errors#remote-managed-settings-failed-to-load>). For any other failure that isn’t a registry query, ask whoever manages that source to fix it * **The Windows registry can’t be queried** : on Windows and in WSL, the variable needs an answer from the registry, even when [WSL doesn’t use it for settings](</docs/en/settings-reference#wslinheritswindowssettings>). The query can fail all session on a non-English Windows, in WSL with interop off, or in a container on a WSL2 kernel. If interop is off, turn it on. Otherwise, run those removals yourself -### - -​ - -Remove-Item in PowerShell +### Remove-Item in PowerShell When you enable the [PowerShell tool](</docs/en/tools-reference#powershell-tool>), Claude Code gives `Remove-Item` and the `cmd` built-ins `rd`, `rmdir`, `del`, and `erase` their own checks, separate from the `rm` critical-path list. For `Remove-Item`, the outcome depends on the target, and the first matching case applies: @@ -991,11 +803,7 @@ The system-paths case also applies to `rd`, `rmdir`, `del`, and `erase` when Claude runs them through `cmd`, as in `cmd /c rd /s /q C:\Users`. By default, Claude Code denies such a command in every mode, without asking you. This `cmd` check requires Claude Code v2.1.283 or later. When judging a `cmd` target, Claude Code treats a PowerShell variable that follows literal text as empty. That makes `cmd /c rd /s /q "C:\$name"` a removal of `C:\`, so it is denied too. A trailing wildcard counts as the folder it empties, so `cmd /c del /q C:\*` is denied and `cmd /c del /q dist\*` in your project is not. To turn the `cmd` check off, set [`CLAUDE_CODE_DISABLE_POWERSHELL_CMD_RM_DENY=1`](</docs/en/env-vars#variables>) in the environment that launches Claude Code. Claude Code ignores this variable in a settings file’s `env` block. `Remove-Item` on a system path stays denied either way. -## - -​ - -See also +## See also * [Permissions](</docs/en/permissions>): allow, ask, and deny rules; managed policies * [Configure auto mode](</docs/en/auto-mode-config>): tell the classifier which infrastructure your organization trusts
modified Configure permissions View current →
Show diff (161 lines)
--- a/permissions.md +++ b/permissions.md @@ -1,10 +1,6 @@ The Claude Agent SDK provides permission controls to manage how Claude uses tools. Use permission modes and rules to define what’s allowed automatically, and the [`canUseTool` callback](</docs/en/agent-sdk/user-input>) to handle everything else at runtime. -## - -​ - -How permissions are evaluated +## How permissions are evaluated If you load a plugin that contains a [mod](</docs/en/plugins/mods/overview>), see [where a mod’s decisions fit among rules and hooks](</docs/en/permissions#precedence-among-rules-hooks-and-mods>). @@ -62,11 +58,7 @@ * **Hooks:** run custom code to allow, deny, or modify tool requests. See [Control execution with hooks](</docs/en/agent-sdk/hooks>). * **canUseTool callback:** prompt users for approval at runtime, when no earlier step resolves the call. See [Handle approvals and user input](</docs/en/agent-sdk/user-input>). -## - -​ - -Allow and deny rules +## Allow and deny rules When you set `allowedTools` and `disallowedTools` (TypeScript) or `allowed_tools` and `disallowed_tools` (Python), Claude Code adds their entries to the allow and deny rule lists in the permission evaluation flow. Any other tool not listed in `allowed_tools` is still available to Claude, and a call to it that needs approval falls through to the permission mode. @@ -102,11 +94,7 @@ You can also configure allow, deny, and ask rules declaratively in `.claude/settings.json`. These rules are read when the `project` setting source is enabled, which it is for default `query()` options. If you set `setting_sources` (TypeScript: `settingSources`) explicitly, include `"project"` for them to apply. See [Permission settings](</docs/en/settings-reference#permission-settings>) for the rule syntax. For when allow rules in a project’s `.claude/settings.json` apply, see [Project allow rules and workspace trust](</docs/en/permissions#project-allow-rules-and-workspace-trust>). -### - -​ - -Path patterns in rules +### Path patterns in rules Scoped rules for `Read` and `Edit` take a path pattern. `Edit(path)` rules govern all built-in tools that write files, including `Write` and `NotebookEdit`, so write a path rule for any of them as `Edit(path)`. If you write a path rule as `Write(path)` or `NotebookEdit(path)`, it [matches no call](</docs/en/permissions#path-rules-that-never-match>) and has no effect. In `allowed_tools` and `disallowed_tools`, start a path pattern with `//` for an absolute path, or with a single `/` for a path inside the session’s working directory: @@ -115,19 +103,11 @@ For other ways to start a path pattern, see [Read and Edit rules](</docs/en/permissions#read-and-edit>). -## - -​ - -Permission modes +## Permission modes Permission modes provide global control over how Claude uses tools. You can set the permission mode when calling `query()` or change it dynamically during streaming sessions. With Claude Code v2.1.302 or later, your app starts in `default` mode unless you set a permission mode or it gets one from [`permissions.defaultMode`](</docs/en/settings-reference#permissions-defaultmode>) in its settings files. In `default` mode, Claude Code denies any tool call needing approval unless you approve it through an allow rule, hook, `canUseTool` callback, or permission prompt tool. If tool calls are denied, see [Tool calls denied in `claude -p` and Agent SDK runs](</docs/en/permission-modes#which-mode-a-non-interactive-run-starts-in>). -### - -​ - -Available modes +### Available modes The SDK supports these permission modes: @@ -142,11 +122,7 @@ **Subagent inheritance:** If your main session is in [plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>), a subagent whose [`AgentDefinition`](</docs/en/agent-sdk/typescript#agentdefinition>) sets `permissionMode: "acceptEdits"` still runs in plan mode. That subagent’s `Edit` and `Write` calls on your source files still go to your `canUseTool` callback. Plan mode holds for the subagents you define too, so that handing work to one doesn’t get around reviewing the plan first.The subagent inherits `plan`, `acceptEdits`, `auto`, or `bypassPermissions` from the main session, and under a `default`\- or `dontAsk`-mode main session it runs in the mode you set. Even then, Claude Code never applies a `"bypassPermissions"` value, and applies an `"auto"` value only when [auto mode is available](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) to that subagent. The `bypassPermissions` exception requires Claude Code v2.1.267 or later.Subagents may have different system prompts and less constrained behavior than your main agent, so inheriting `bypassPermissions` grants them full, autonomous system access. The [actions no mode auto-approves](</docs/en/permission-modes#actions-no-mode-auto-approves>) still apply. -### - -​ - -Set permission mode +### Set permission mode You can set the permission mode once when starting a query, or change it dynamically while the session is active. @@ -242,17 +218,9 @@ main(); -### - -​ - -Mode details - -#### - -​ - -Accept edits mode (`acceptEdits`) +### Mode details + +#### Accept edits mode (`acceptEdits`) Auto-approves file operations so Claude can edit code without prompting. Other tools (like Bash commands that aren’t filesystem operations) still require normal permissions. **Auto-approved operations:** @@ -268,11 +236,7 @@ **Use when:** you trust Claude’s edits and want faster iteration, such as during prototyping or when working in an isolated directory. -#### - -​ - -Don’t ask mode (`dontAsk`) +#### Don’t ask mode (`dontAsk`) Converts any permission prompt into a denial, without calling `canUseTool`, though a [mod](</docs/en/plugins/mods/overview>) you installed can still approve [some of those calls](</docs/en/permissions#precedence-among-rules-hooks-and-mods>). Tools pre-approved by `allowed_tools`, `settings.json` allow rules, or a hook run as normal. Calls that need no approval in `default` mode also run as normal, such as file reads inside your working directories and calls to `Agent`. These calls are denied even when an allow rule matches: @@ -284,11 +248,7 @@ If your `PreToolUse` hook returns `allow` for a recognized critical-path removal, a read from a network path, or a call to a tool marked `always_ask`, the call is still denied. The check that recognizes these removals [can miss some commands](</docs/en/permission-modes#critical-paths>). **Use when:** you run a headless agent and want a hard deny for each call that would otherwise prompt. -#### - -​ - -Bypass permissions mode (`bypassPermissions`) +#### Bypass permissions mode (`bypassPermissions`) Auto-approves tool uses without prompting, except the [actions no mode auto-approves](</docs/en/permission-modes#actions-no-mode-auto-approves>). Hooks still execute and can block operations if needed. On Linux and macOS, Claude Code refuses to start in this mode as root or under `sudo` outside a [recognized sandbox](</docs/en/permission-modes#skip-all-checks-with-bypasspermissions-mode>), and the query fails before the first turn. @@ -298,11 +258,7 @@ * Connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>), tools that require user interaction, recognized [critical-path removals](</docs/en/permission-modes#critical-paths>), and Bash commands flagged [`Dangerous rm operation not ruled out`](</docs/en/permission-modes#dangerous-rm-operation-not-ruled-out>) still fall through to your `canUseTool` callback. The check that recognizes critical-path removals [can miss some commands](</docs/en/permission-modes#critical-paths>), and you can [turn off the critical-path removal prompt](</docs/en/permission-modes#turn-off-the-critical-path-removal-prompt-in-bypasspermissions-mode>). Outside a [cloud session](</docs/en/claude-code-on-the-web>), calls to custom tools your application [marks `always_ask`](</docs/en/agent-sdk/custom-tools#require-approval-for-specific-tools>) fall through to the callback too. * The [cross-session messaging safeguards](</docs/en/permission-modes#skip-all-checks-with-bypasspermissions-mode>) still apply. -#### - -​ - -Plan mode (`plan`) +#### Plan mode (`plan`) Claude explores the codebase and produces a plan. During planning, edits made with Claude’s file tools outside [protected paths](</docs/en/permission-modes#protected-paths>) reach your `canUseTool` callback, even when an allow rule matches or a `PreToolUse` hook returns `allow`. [`AskUserQuestion`](</docs/en/agent-sdk/user-input#handle-clarifying-questions>) calls reach your callback too, even when an allow rule names the tool. When [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) is available, Claude Code sends these calls during planning to [auto mode’s classifier](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>) for review instead of to your callback, when no allow rule approves them: @@ -326,11 +282,7 @@ **Use when:** you want Claude to produce a plan first, such as during code review or before a large change. -#### - -​ - -Auto mode (`auto`) +#### Auto mode (`auto`) A classifier model reviews actions such as shell commands and network requests before they run, and allows or blocks each one it reviews. For the models and providers auto mode requires and the order it evaluates actions in, see [Eliminate permission prompts with auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>). If you switch a session that’s in auto mode to a model that auto mode doesn’t support, using [`set_model()`](</docs/en/agent-sdk/python#claudesdkclient>), [`setModel()`](</docs/en/agent-sdk/typescript#query-object>), or [`applyFlagSettings()`](</docs/en/agent-sdk/typescript#applyflagsettings>), the session changes to `default` mode: @@ -339,11 +291,7 @@ The change to `default` mode after a `set_model()`, `setModel()`, or `applyFlagSettings()` call requires Claude Code v2.1.299 or later. -## - -​ - -Related resources +## Related resources For the other steps in the permission evaluation flow:
modified Platforms and integrations View current →
--- a/platforms.md +++ b/platforms.md @@ -1,10 +1,6 @@ Claude Code runs the same underlying engine everywhere, but each surface is tuned for a different way of working. This page helps you pick the right platform for your workflow and connect the tools you already use. -## - -​ - -Where to run Claude Code +## Where to run Claude Code Choose a platform based on how you like to work and where your project lives. @@ -19,11 +15,7 @@ The CLI is the most complete surface for terminal-native work: scripting and the Agent SDK are CLI-only. Third-party providers also work in [VS Code](</docs/en/vs-code#use-third-party-providers>) and in [JetBrains](</docs/en/feature-availability#features-available-on-every-provider>), which runs the CLI in your IDE’s terminal. Enterprise [Desktop](</docs/en/desktop>) deployments support Google Cloud’s Agent Platform, and Desktop supports [gateway providers](</docs/en/llm-gateway-connect#desktop-app>); for Amazon Bedrock or Microsoft Foundry, use the CLI or an IDE extension, or [Claude Desktop on 3P](<https://claude.com/docs/third-party/claude-desktop/overview>), which runs the Code tab on those providers. Desktop and the IDE extensions trade some CLI-only features for visual review and tighter editor integration. The web runs in the cloud, so tasks keep going after you disconnect. Mobile is a thin client into those same cloud sessions or into a local session via Remote Control, and can send tasks to Desktop with Dispatch. You can mix surfaces on the same project. Configuration, project memory, and MCP servers are shared across the local surfaces. -## - -​ - -Connect your tools +## Connect your tools Integrations let Claude work with services outside your codebase. @@ -38,11 +30,7 @@ For integrations not listed here, [MCP servers](</docs/en/mcp>) and [connectors](</docs/en/desktop#connect-external-tools>) let you connect almost anything: Linear, Notion, Google Drive, or your own internal APIs. -## - -​ - -Work when you are away from your terminal +## Work when you are away from your terminal Claude Code offers several ways to work when you’re not at your terminal. They differ in what triggers the work, where Claude runs, and how much you need to set up. @@ -57,17 +45,9 @@ If you’re not sure where to start, [install the CLI](</docs/en/quickstart>) and run it in a project directory. If you’d rather not use a terminal, [Desktop](</docs/en/desktop-quickstart>) gives you the same engine with a graphical interface. -## +## Related resources -​ - -Related resources - -### - -​ - -Platforms +### Platforms * [CLI quickstart](</docs/en/quickstart>): install and run your first command in the terminal * [Desktop](</docs/en/desktop>): visual diff review, parallel sessions, computer use, and Dispatch @@ -77,11 +57,7 @@ * [Projects](</docs/en/claude-projects>): one conversation where Claude coordinates many cloud sessions for a body of work and reports back * [Mobile](</docs/en/mobile>): the Claude app for [iOS](<https://apps.apple.com/us/app/claude-by-anthropic/id6473753684>) and [Android](<https://play.google.com/store/apps/details?id=com.anthropic.claude>) for starting and monitoring tasks while away from your computer -### - -​ - -Integrations +### Integrations * [Chrome](</docs/en/chrome>): automate browser tasks with your logged-in sessions * [Computer use](</docs/en/computer-use>): let Claude open apps and control your screen on macOS @@ -91,11 +67,7 @@ * [Slack](</docs/en/slack>): send tasks from team chat and get PRs back, on Pro, Max, and Ultra plans * [Claude Tag](<https://claude.com/docs/claude-tag>): run `@Claude` as your organization’s shared identity on Team and Enterprise plans -### - -​ - -Remote access +### Remote access * [Dispatch](</docs/en/desktop#sessions-from-dispatch>): message a task from your phone and it can spawn a Desktop session * [Remote Control](</docs/en/remote-control>): drive a running session from your phone or browser
modified Test plugins with evals View current →
Show diff (624 lines)
--- a/plugin-evals.md +++ b/plugin-evals.md @@ -8,11 +8,7 @@ Every eval run and every judge grader is a real model call on your account, counted against your plan’s usage or your API bill, so check the requirements first. Then create your first eval suite, or go to Run evals in CI if you already have one. -## - -​ - -Requirements +## Requirements To run plugin evals you need: @@ -21,43 +17,23 @@ * A plugin directory with a `plugin.json` or `.claude-plugin/plugin.json` manifest, or a [skills-directory plugin](</docs/en/plugins/loading#plugins-shared-through-a-repository>). * The same authentication and model provider your normal Claude Code sessions use. Eval runs, judge-scored graders, and `claude plugin eval init` call the model with your credentials, so they count against your plan’s usage limits or your API bill. When the command reports a cost, the figure is a [list-price estimate](</docs/en/costs>) of those calls. If you run Claude Code on Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry, run the suite from a shell that exports the same provider variables as your normal sessions, because each run inherits them from that shell as the `env` field describes. -## - -​ - -How an eval run works +## How an eval run works An eval suite lives in a directory called `evals/` inside your plugin, laid out as Write and refine cases shows. Each case is its own subdirectory with a prompt and one or more graders. The prompt is something a person using your plugin might type, such as a request one of its skills should handle. -### - -​ - -What happens in a run +### What happens in a run For each run of a case, Claude Code starts a fresh, isolated [non-interactive session](</docs/en/headless>) with only your plugin loaded, sends the prompt, and lets Claude work until it finishes or hits the case’s turn or time limit. Each grader then checks the final reply, the transcript, or a file Claude created, and passes or fails. -### - -​ - -How a case is scored +### How a case is scored One run of a non-deterministic agent tells you little, so each case runs three times by default. A run’s score is the fraction of its graders that passed, weighted if you set weights, and the case’s score is the mean across its runs. A case passes when its score meets the `--threshold`, `1.0` by default. In model calls, a suite makes roughly cases × runs agent runs with the plugin and the same number again for the no-plugin baseline, plus three short judge calls per `llm` or `baseline` grader per run. -### - -​ - -The no-plugin baseline +### The no-plugin baseline A high score on its own doesn’t tell you the plugin helped, because Claude might do as well without it. To separate the two, a case’s runs are repeated with no plugin loaded, and you get two scores, `WITH` and `W/OUT`. Their difference, `Δ`, is what the plugin contributed. If a case scores 1.0 both with and without the plugin, the plugin isn’t what made it pass. The two sets of runs are called the with-arm and the without-arm; Score against the no-plugin baseline covers which cases run the with-arm only and how graders are scored across the two arms. -## - -​ - -Create your first eval suite +## Create your first eval suite This walkthrough writes one case for your own plugin, runs it, and reads the result. Before you start, make sure you have: @@ -110,11 +86,7 @@ Replace `<case-name>` with one of the directory names under `evals/`. -## - -​ - -Write and refine cases +## Write and refine cases The cases `claude plugin eval init` writes are plain files you can open, change, and add to. A case is a directory under the plugin’s eval directory that contains a `prompt.md`, a `case.yaml`, or both. Give each case at least one grader, as a `graders/<name>.md` file or a `graders:` entry in `case.yaml`, because a case without one fails to load. To group cases, nest them under a directory that isn’t itself a case; anything inside a case directory, such as `graders/` and fixture files, belongs to that case. This is the layout `claude plugin eval init` writes and the one to use for new suites. The eval suite reference has the complete tree, including mocks and results: @@ -132,11 +104,7 @@ │ └── ... └── results/ # written by each run; add to .gitignore -### - -​ - -Write a case manually +### Write a case manually Having Claude write the cases with `claude plugin eval init` is the recommended path. To write one yourself instead, start from a blank template. The following command writes a case named `first-case` with a placeholder `prompt.md` and one placeholder grader, and runs nothing: @@ -175,27 +143,15 @@ This passes when Claude invoked that skill at least once during the run, including by its namespaced `plugin-name:skill-name` form. Grader types lists the other checks available, such as matching a regex or confirming a file was created. With both files saved, run the case the way the quickstart does, with `claude plugin eval .` from the plugin root. -### - -​ - -Set run limits and tools in prompt.md +### Set run limits and tools in prompt.md Set a case’s `max_turns`, `timeout_seconds`, `model`, `tags`, and the `allowed_tools` it may use in `prompt.md` frontmatter; the prompt.md frontmatter reference lists every field and its default. Claude receives the body exactly as you wrote it. `@path` mentions in it aren’t expanded into file attachments, so if Claude needs to read a file, grant a tool for it in `allowed_tools`. -### - -​ - -Choose and weight graders +### Choose and weight graders A grader’s frontmatter sets its `type`, and optionally a `weight` that makes it count for more of the run’s score and an `arm` that controls how it’s scored against the baseline. Of the six types, `regex`, `tool_used`, `tool_order`, and `file_exists` are computed from the transcript and files and cost nothing, while `llm` and `baseline` call a judge model and add to the run’s cost. There are no custom-code graders. Grader types lists each type’s options and pass condition, and what a grader can look at lists the values `target` and `focus` accept. By default, the judge for `llm` and `baseline` graders is the model Claude Code uses for background tasks. Pass `--judge-model sonnet` or a full model ID to choose the judge yourself. -#### - -​ - -Choose graders that give a stable signal +#### Choose graders that give a stable signal An `llm` grader asks a model for a verdict, so its answer can differ between runs, and it differs more the longer the text it has to read. These habits keep a suite’s scores steady enough to trust: @@ -204,11 +160,7 @@ * If a case’s `tool_used: Skill` grader passes but `Δ` is negative, suspect the judge before the plugin. A small judge model can mark a correct answer wrong because it’s formatted differently from what the rubric describes. Re-run with `--judge-model sonnet`, and tighten the rubric so formatting doesn’t decide the verdict. * To check that a build or test passed inside the run, have the prompt ask Claude to run it and write the outcome to a file, grade that file, and assert the command ran with a `tool_used` grader whose `input_match` names the command. -### - -​ - -Score against the no-plugin baseline +### Score against the no-plugin baseline When a plugin is under test, a case normally runs in two arms. The with-arm is its runs with the plugin loaded, and the without-arm is the same number of runs with no plugin at all. The summary and report show both scores and `Δ`, the with-arm score minus the without-arm score. In these situations a case runs the with-arm only, so it gets no `W/OUT` score or `Δ`: @@ -228,11 +180,7 @@ * **`arm: both`** : set `arm: both` on a grader to score it in both arms regardless, which is what you want for a “must not invoke the skill” check with `min: 0` and `max: 0`. * **`--ablation none`** : under `--ablation none` nothing is excluded, so the same suite can produce a different absolute score in the two modes. -### - -​ - -Use a different eval directory +### Use a different eval directory If `evals/` is already taken by another tool, keep the suite in a different directory. You can record that directory in the plugin’s `plugin.json` so every run and every collaborator uses it, or pass it on the command line for a single run: @@ -241,19 +189,11 @@ If you set both, the flag’s directory is used. Give a relative path of plain directory names such as `qa` or `quality/evals`. An absolute path or one containing `..` isn’t accepted: as a flag value it’s an error, while an unusable manifest value prints a `Warning:` line and the run uses `evals/` instead. Cases, results, and `init` output all move to that directory. -## - -​ - -Set up fixtures and mocks +## Set up fixtures and mocks A case can need more than a prompt: files or a git repository in the workspace, an earlier conversation to continue, or answers from the MCP servers your plugin connects to. Each of those is set up beside the case so runs stay repeatable. -### - -​ - -Seed the workspace or conversation +### Seed the workspace or conversation Each run starts in an empty workspace. When a case needs more than the prompt, add a `case.yaml` beside `prompt.md` with a `context` block: @@ -272,11 +212,7 @@ A scaffold script starts in the empty workspace with a small fixed environment: your shell’s `PATH`, `HOME` set to the run’s temporary home directory, `TMPDIR`, and a few constants such as `TERM=dumb`. Nothing else from your shell reaches it, and neither do the case’s `EVAL_*` variables. If the script exits non-zero or runs longer than 120 seconds, that run scores 0 with a `scaffold failed` error. Use the script for files and git state only, since project configuration it writes isn’t loaded. -### - -​ - -Mock MCP servers +### Mock MCP servers You can evaluate a plugin whose skills call MCP tools without the real service behind them. Put one Markdown file per tool under `evals/mocks/<server>/<tool>.md` for the whole suite, or under a case’s own `mocks/` directory for one case, where `<server>` is the server’s name in your plugin’s [MCP configuration](</docs/en/plugins/components#mcp-servers>). A run never starts your plugin’s real MCP servers unless you ask. Claude Code registers a substitute server under each server’s own name. Tools with a mock file answer from it and are allowed without an `--allow-tools` grant, and a tool with no mock file isn’t available to Claude. A server with no mocks at all appears in the case’s `mocked:` progress line as `plugin_<plugin>_<server>[not started: no mock]`. The file’s body is what the tool returns to Claude. This mock substitutes for a `create_issue` tool on a server named `tracker`, checks the input Claude sends, and echoes the title back. Save it as `evals/mocks/tracker/create_issue.md`: @@ -300,27 +236,15 @@ * **`--allow-real-servers`** : start the real process for each server you haven’t mocked, and keep answering mocked tools from their files * **`--mocks off`** : ignore `mocks/` entirely and start every server the plugin declares -#### - -​ - -Replay agent mock answers +#### Replay agent mock answers A `type: agent` mock answers with a call to the `--judge-model`, so its output varies between runs and changes if you change the judge. When a run completes without an error or abort, Claude Code saves each answer an agent mock gave under the results directory in `mock-recordings/`. Open `ADOPT.txt` there to see each recording and the `.replay/<server>/` directory to copy it into, beside the mock that produced it. After you copy a recording there, later runs answer the identical call from it with no model call. Commit `mocks/.replay/` with the rest of `mocks/` so CI runs are repeatable. -## - -​ - -Run evals +## Run evals Once a suite exists, `claude plugin eval` runs it. You choose which plugin and cases run with the target argument, grant any tools the cases need beyond the read-only set with `--allow-tools`, and control run count, models, cost, and output with the other options. -### - -​ - -Choose what to evaluate +### Choose what to evaluate Most of the time you run `claude plugin eval .` from the plugin root, which runs every case in the suite with the plugin you’re standing in loaded. To run a single case file, or to evaluate a plugin you installed rather than one you’re developing, pass a different target: @@ -334,11 +258,7 @@ Add `--case <glob>` to filter by case name and `--tag <tag>` to keep cases with any of the given tags. Put the target before `--tag`, `--allow-tools`, and `--json`. The first two take a list and `--json` takes an optional path, so each of them reads a target that follows as its own value. -### - -​ - -Grant tools +### Grant tools Runs never stop to ask for permission. Built-in tools that need a grant you didn’t give, such as `Bash`, `Write`, `Edit`, `WebFetch`, and `WebSearch`, are removed from the session, so Claude can’t call them at all. A run allows only the read-only tools the case lists in `allowed_tools`, from `Read`, `Glob`, `Grep`, `NotebookRead`, `Skill`, `AskUserQuestion`, `Agent`, `TodoWrite`, and the task tools `TaskCreate`, `TaskGet`, `TaskList`, `TaskUpdate`, and `TaskStop`, plus whatever you grant with `--allow-tools`. That grant applies to every case in the run. To let cases use `Bash`, `Write`, `Edit`, `WebFetch`, or `WebSearch`, grant them yourself: @@ -346,11 +266,7 @@ When a case asked for a tool you didn’t grant, the progress output lists it as `not granted`. Tools on a mocked MCP server need no grant. Tools on a real plugin MCP server need both the server started, with `--allow-real-servers` or `--mocks off`, and a grant by name, such as `--allow-tools "mcp__plugin_my-plugin_github__*"`; a plugin’s MCP tools are named `mcp__plugin_<plugin>_<server>__<tool>`. When you grant `Bash` in any form, every command runs under Claude Code’s [OS-level sandbox](</docs/en/sandboxing>). Writes are confined to the run’s workspace, your home directory and Claude Code configuration are unreadable, and network access is limited to domains you grant with `--allow-tools "WebFetch(domain:example.com)"`. If you grant Bash or PowerShell on a machine with no sandbox backend, Claude Code refuses each run rather than running it unconfined, and the case shows a run error and usually scores 0. Native Windows has no backend, so run shell-granting suites under WSL2; on Linux, install `bubblewrap` and `socat` first. See the [sandboxing prerequisites](</docs/en/sandboxing>). -### - -​ - -Command options +### Command options This table covers the options for run count, models, scoring, cost, tool grants, mocks, and output. Run `claude plugin eval --help` for the complete list, which also includes `--case`, `--tag`, `--eval-dir`, `--no-scaffold`, `--report`, and `--verbose`. @@ -374,11 +290,7 @@ `--publish-report`| | Publish the report even where it would stay local by default, such as a run a Claude Code session started `--keep-temp`| Off| Keep every run’s sandbox directory and print its path, for debugging what Claude produced -### - -​ - -Run evals in CI +### Run evals in CI In your CI job, run the suite with `--json` to write the result for archiving, and fail the build on the exit code. Pass `--trust-plugin` so the job never waits at the first-run trust prompt, pin both models so scores are comparable over time, keep the report local, and set a cost ceiling as an upper limit: @@ -409,19 +321,11 @@ To keep costs predictable, give quick every-change suites only graders that don’t call a judge, use `--ablation none` where you don’t need `Δ`, and leave `partial: true` documents and runs with `skippedPaidGraders` out of any trend you chart. -## - -​ - -Read the results +## Read the results Every run with at least one case writes a `results/<timestamp>/` directory inside the eval directory, containing `aggregate-result.json` and `report.html`. For a path target that’s under the plugin; for a plugin you named, it’s under your current directory, as the target table shows. The summary table, the JSON, and the report all render the same result data. -### - -​ - -HTML report +### HTML report `report.html` is a single self-contained file that makes no external requests, so you can attach it to a CI job or open it from disk. This example is the top of a report for a three-case suite run with `--threshold 0.8`; the cost shown is a list-price estimate and varies with the model and the number of cases: Read it from the top down: @@ -432,11 +336,7 @@ If you’re signed in with a claude.ai subscription and [artifacts](</docs/en/artifacts>) are available for your account, Claude Code also publishes the report as a private artifact and prints `Published: <url>`. Pass `--no-publish` to keep it local. If no `Published:` line appears, such as with API-key authentication, the local file is the report. A run that a Claude Code session started, such as when you ask Claude to run the suite for you, also stays local, and its `Report:` line says `kept local`. Add `--publish-report` to that command to publish it. -### - -​ - -JSON result +### JSON result `aggregate-result.json`, and `--json` output, is a versioned document with `schemaVersion: 1` for CI scripts to parse. Field names are camelCase and new fields are added without renaming existing ones, so write your script to ignore fields it doesn’t recognize. These are the fields a gating script usually reads. The document also carries the suite configuration, every grader definition, and per-run grader results with explanations and evidence: @@ -454,19 +354,11 @@ `cases[].arms.with[].skippedPaidGraders`| `true` when the cost ceiling skipped this run’s judge graders, so its score isn’t comparable `costUsd`, `durationSeconds`, `claudeVersion`| Estimated cost at list price including judge calls, wall-clock seconds, and the Claude Code version that ran the suite -## - -​ - -What a run can access +## What a run can access `claude plugin eval` loads the target plugin’s skills, hooks, and agents and runs its eval suite on your machine, as you. Pointing it at a plugin is the same trust decision as `claude --plugin-dir`, so only evaluate plugins you trust. The isolation described in this section limits what the agent under test can reach; it isn’t a boundary against the plugin’s own code, and a suite that passes says nothing about whether the plugin is safe. -### - -​ - -Trust the plugin directory +### Trust the plugin directory The first time you run `claude plugin eval` against a directory, Claude Code asks `Trust this plugin directory?` before it loads anything from it, unless you already accepted the trust prompt there in an interactive `claude` session. Inside a git repository, answering yes trusts the whole repository, for interactive sessions too. When stdin or stdout isn’t a terminal, or under `--json`, the run can’t ask and is refused with exit 1; pass `--trust-plugin` to assert the trust yourself, only for a plugin you’d run on your own machine. A target you name rather than give as a path, meaning an installed plugin or a skills-directory plugin, skips the prompt. Some parts of the plugin and suite run only when you pass their flag for that run: @@ -476,11 +368,7 @@ A case’s `allowed_tools` and a skill’s own `allowed-tools` frontmatter can’t widen any of them. When the plugin includes hooks you didn’t write, or you start its real MCP servers, treat its scores as advisory unless you ran it in an isolated environment such as a container or CI runner, since hooks and servers run outside the agent’s sandbox and could modify the files the graders read. -### - -​ - -How runs are isolated +### How runs are isolated Each run gets a temporary home directory, working directory, and Claude Code configuration, and the agent under test runs there as a `claude -p` child process with only your plugin loaded. Keep these consequences in mind when you write cases: @@ -490,11 +378,7 @@ * **The case definitions are hidden from the agent.** A run can’t read the eval directory, so Claude can’t see the case’s prompt, its graders, or sibling cases. * **No network sandbox outside shell commands.** Shell commands you grant run under the sandbox’s network rules. A `WebFetch(domain:…)` grant reaches that domain directly, and the plugin’s own hooks and any real MCP servers you start can reach any host. -## - -​ - -Eval suite reference +## Eval suite reference Everything an eval suite can contain lives under the plugin’s eval directory, `evals/` unless you configured another. A directory counts as a case when it holds a `prompt.md` or a `case.yaml`, and a case without at least one grader fails to load with an `invalid case.yaml` error that names `graders`. This tree shows every file `claude plugin eval` reads or writes in the eval directory: @@ -518,11 +402,7 @@ ├── report.html └── mock-recordings/ # agent-mock answers from clean runs, with ADOPT.txt -### - -​ - -prompt.md frontmatter +### prompt.md frontmatter `prompt.md` frontmatter accepts these fields. An unknown key is an error: @@ -542,11 +422,7 @@ `append_system_prompt`| | Text appended to the child session’s system prompt `env`| `{}`| Extra environment variables for the child session. Keys must match `EVAL_[A-Z0-9_]*`; any other key fails the run. The run inherits only an allowlist from your shell: basics such as `PATH` and locale, proxy and certificate settings, the variables that select and authenticate your model provider, most `ANTHROPIC_*` and `CLAUDE_CODE_*` configuration, and `EVAL_*`. To pass the plugin anything else, such as a toolchain setting, export it as an `EVAL_*` variable -### - -​ - -case.yaml fields +### case.yaml fields `case.yaml` is an alternative or companion to `prompt.md`: it describes a case in YAML and adds the fields that point at other files. It requires `schema_version: "1.1"` and `name`. The `prompt.md` fields `description`, `tags`, `plugins`, `runs`, and `expected_outcome` go at the top level; `model`, `max_turns`, `timeout_seconds`, `allowed_tools`, `append_system_prompt`, and `env` go under `execution:`. When both files exist, `prompt.md` frontmatter overrides the matching `case.yaml` fields, the `prompt.md` body is the prompt, and `graders/*.md` are added after any graders listed in `case.yaml`. These fields exist only in `case.yaml`: @@ -558,11 +434,7 @@ `execution.prompt`| The prompt, when you keep the whole case in `case.yaml` and omit `prompt.md` `graders`| A list of graders, each with a `name` plus the same keys a `graders/*.md` file takes in frontmatter. For `llm` graders, put the rubric in `criteria` -### - -​ - -Grader frontmatter +### Grader frontmatter Every grader file under `graders/` takes these keys in frontmatter, plus the options for its type. The grader’s name is the filename without `.md`: @@ -572,11 +444,7 @@ `weight`| `1`| Relative weight in the run’s score. Any positive number `arm`| unset| `with-only` excludes the grader from scoring in a two-arm run; `both` forces a grader Claude Code would otherwise exclude to be scored in both arms -#### - -​ - -What a grader can look at +#### What a grader can look at `regex` graders take a `target` and `llm` graders take a `focus`. Both accept the same values: @@ -588,11 +456,7 @@ `{ source: file, path: <path> }`| The contents of one file in the workspace after the run. Use this to grade what the plugin produced. A PNG, JPEG, GIF, or WebP file is shown to an `llm` judge as an image. An `llm` judge refuses other binary files such as `.pptx` or PDF; render them to an image or write them out as text and grade that `mock_calls`| Each call Claude made to a mocked MCP tool, with its input and the mock’s answer -#### - -​ - -Grader types +#### Grader types Each grader type below lists its options and when it passes: @@ -605,11 +469,7 @@ `llm`| `criteria`, `focus`| A judge model votes PASS on the rubric in at least two of three votes. In the `.md` layout the file body is the criteria `baseline`| `baseline_file`, `criteria`| A judge finds the run satisfies the criteria at least as well as the reference transcript at `baseline_file`, a `.jsonl` in the case directory -### - -​ - -Mock files +### Mock files A `<tool>.md` file under `mocks/<server>/` answers one tool. Its body is the tool result, with `{{input.<field>}}` and `{{file:fixtures/<name>}}` substitutions. Its frontmatter accepts these keys: @@ -627,11 +487,7 @@ A case’s own `mocks/` directory uses the same layout and overrides the suite’s mocks file by file. -#### - -​ - -Regex patterns in expect +#### Regex patterns in expect A `/regex/` value in `expect:` uses a small dialect that Claude Code checks when it loads the suite: @@ -642,43 +498,23 @@ A pattern outside the dialect, such as one with a group, alternation, a backreference, lookaround, or another flag, stops the case from loading: the case scores 0 and its error names the pattern. To allow several exact values, write a list of literals instead of an alternation. Each pattern checks values only up to a maximum length, and a longer value counts as a violation. Quantifiers can lower that length, and a leading `^` raises it, so anchor patterns with `^` and keep quantifiers few. -## - -​ - -Troubleshooting +## Troubleshooting These are the problems authors encounter most often, keyed on what you see. -### - -​ - -”plugin eval is currently in early access” +### ”plugin eval is currently in early access” Your build predates general availability of the command. Run `claude update`, then run the command again in a fresh session. -### - -​ - -”plugin eval is currently unavailable” +### ”plugin eval is currently unavailable” Anthropic has switched the command off server-side. Nothing on your machine turns it back on; run `claude update` and try again in a fresh session later. -### - -​ - -”is not a trusted plugin directory, and this run cannot stop to ask you about it” +### ”is not a trusted plugin directory, and this run cannot stop to ask you about it” This is the first run against a directory Claude Code doesn’t trust yet, and it can’t ask you because stdin or stdout isn’t a terminal or you passed `--json`. Run `claude plugin eval <dir>` once in a terminal and answer the prompt, or pass `--trust-plugin` if you trust the plugin’s code and suite. See What a run can access. -### - -​ - -“is too old for claude plugin eval” +### “is too old for claude plugin eval” The `git` on your `PATH` is older than 2.31, so `claude plugin eval` stopped before running any case and exited 1 with a message naming your version: @@ -686,11 +522,7 @@ For each run, Claude Code switches off git hooks, credential helpers, and other programs a repository’s git configuration can start. It does so through environment configuration that git reads only from version 2.31. An older git ignores that configuration, so the suite stops rather than scoring runs where those programs could execute. Install git 2.31 or later and run the suite again. Before v2.1.283, `claude plugin eval` didn’t check the git version, and on an older git the suite ran with those programs left on. -### - -​ - -“cannot be evaluated where sessions load it” +### “cannot be evaluated where sessions load it” You ran `claude plugin eval` in your shell with the name of a plugin installed from a marketplace you [added from a local path](</docs/en/plugins/loading#in-place-and-copied-plugins>). No session could load the plugin from that marketplace now, so the command refuses with this message and exits with code 1. @@ -698,85 +530,45 @@ The sentence after `no session could load it now.` names what failed. Run `claude plugin marketplace list` in your shell and fix what the message names. For example, restore the marketplace directory or put the plugin’s entry back in its catalog. To evaluate the plugin’s source without the marketplace, pass its directory as the target, such as `claude plugin eval ./plugins/formatter`. -### - -​ - -”No eval cases found” +### ”No eval cases found” No `<case>/prompt.md` or `<case>/case.yaml` exists beneath the eval directory in effect, or your `--case` and `--tag` filters matched no case. Run from the plugin root, or run `claude plugin eval init` to create a suite. -### - -​ - -The baseline arm shows no plugin, or delta is zero +### The baseline arm shows no plugin, or delta is zero If the summary has no `W/OUT` column, or a case fails with “ablation requested but no plugin resolved”, the usual cause is that no plugin was found for the case. If every case resumes a transcript through `context.history_file`, the missing column is expected instead, because those cases run one arm by default. Otherwise, add `plugins: ["../.."]` to the case, giving the path from the case directory to the plugin directory. If the plugin did load and `Δ` is still near zero with your `tool_used: Skill` grader failing, that’s usually a real finding, meaning the skill’s `description` doesn’t trigger on the prompt’s phrasing. Adjust the description and re-run the same suite. -### - -​ - -”Agent type ’…’ not found” for one of your plugin’s agents +### ”Agent type ’…’ not found” for one of your plugin’s agents By default each case runs both with your plugin and without it, and the runs without it are the no-plugin baseline. When Claude dispatches one of your plugin’s agents in a baseline run, the Agent tool call fails with `Agent type '<plugin>:<agent-name>' not found. Available agents: ...`. The list names only agents that exist without the plugin, such as the [built-in subagents](</docs/en/sub-agents#built-in-subagents>). The error is expected, since `Δ` compares your plugin’s runs against the baseline. In the JSON result, the baseline runs are under `cases[].arms.without`. In runs with your plugin loaded, a case that lists `Agent` in `allowed_tools` can dispatch one of your plugin’s agents by its namespaced name, such as `my-plugin:code-reviewer` for the `code-reviewer` agent in a plugin named `my-plugin`. To skip the baseline runs, pass `--ablation none`. -### - -​ - -Everything scores zero although the right files were produced +### Everything scores zero although the right files were produced Your graders target `files`, the list of created paths, when you meant the file’s contents. Use `{ source: file, path: <path> }` as the `target` or `focus`. Separately, `file_exists` counts only files created during the run, so a file the scaffold created or that Claude only edited is invisible to it; grade its contents, or use `tool_used` on `Edit`. -### - -​ - -A regex over the trace doesn’t match text I can see +### A regex over the trace doesn’t match text I can see * **Wrong target** : the default `target` is `last_message`, not the trace. * **JSON escaping** : when you do target `trace`, it’s JSON per line, so quotes appear as `\"`. * **Regex syntax** : regexes use JavaScript syntax, so put `i` in `flags` rather than writing `(?i)`. -### - -​ - -Tools are denied, MCP tools are missing, or Bash won’t run +### Tools are denied, MCP tools are missing, or Bash won’t run Anything beyond the read-only set needs your grant, such as `--allow-tools Bash Write`. Your personal MCP servers never load in a run. The plugin’s own servers don’t start unless you opt in, and their tools then also need an `--allow-tools "mcp__plugin_<plugin>_<server>__*"` grant; a mocked tool needs neither. -### - -​ - -The run exits 1 but the results look fine +### The run exits 1 but the results look fine When every case scored at or above `--threshold` and the command still exits 1, a line on stderr names the cause, even under `--json`. For example, a case file failed to load, or runs ended on an API error. For the other causes, see the exit codes. The default `--threshold` is 1.0, so the command exits 1 when any case scores below perfect. Set a threshold that matches the score you require. -### - -​ - -`--json output path must end in .json` +### `--json output path must end in .json` You put the target after `--json`, so it was read as the output path. Put the target first, as in `claude plugin eval . --json`, or give `--json` an explicit `.json` path. -### - -​ - -A grader shows passed: false under a run that scored 1.0 +### A grader shows passed: false under a run that scored 1.0 That grader is excluded from the score by design in a two-arm run, and its `scored` field is `false`. See Score against the no-plugin baseline. -### - -​ - -“ended on an API error and scored 0 without grading” +### “ended on an API error and scored 0 without grading” This stderr warning means the API answered at least one run’s last request with an HTTP error, such as a rate limit or a plan usage limit. Such a run scores 0 with no grader results, and the command exits non-zero whatever the scores and `--threshold` are. To fix it, find each affected run’s error and resolve the cause it reports, then run the suite again: @@ -785,35 +577,19 @@ The count includes baseline runs too. Their scores never decide whether a case passes, so every case can pass while the command still fails. In a two-arm run, the affected case’s `W/OUT` and `Δ` print as `—`. For a usage or rate limit, see Runs fail with a usage-limit or rate-limit error. Before v2.1.299, such a run was graded on what it had produced. -### - -​ - -Runs fail with a usage-limit or rate-limit error partway through +### Runs fail with a usage-limit or rate-limit error partway through Runs that end with a usage-limit or rate-limit error score 0 without grading, and the command exits non-zero. The suite still finishes and isn’t marked `partial`. Re-run after the limit resets, with `--runs 1` or a `--case` filter if you need to stay under it. -### - -​ - -“mock call budget exceeded” +### “mock call budget exceeded” Every `type: agent` mock in a run draws on one call budget of four times the case’s `max_turns`, which is 40 calls at the default of 10. Calls answered from `.replay/` recordings count too, and the case’s `mock budget` progress line prints the budget. A call past it aborts the run with score 0 and this reason, so raise `max_turns` in the case for a skill that makes many calls to agent mocks. -### - -​ - -Runs time out or hit the turn cap +### Runs time out or hit the turn cap The defaults are 10 turns and 300 seconds. Raise `max_turns` and `timeout_seconds` in the case for tasks that need more, and use `--max-cost-usd` as the cost ceiling rather than tight per-run limits. -## - -​ - -See also +## See also * [Create a plugin](</docs/en/plugins/create>): build the plugin you’re testing, and load it with `--plugin-dir` during development * [Plugin commands reference](</docs/en/plugins/cli-reference#plugin-eval>): the `plugin eval` and `plugin eval init` command entries. The manifest’s [`experimental.evals`](</docs/en/plugins/manifest-reference#fields>) key is on the manifest reference
modified Plugins in the SDK View current →
Show diff (162 lines)
--- a/plugins.md +++ b/plugins.md @@ -7,11 +7,7 @@ For complete information on plugin structure and how to create plugins, see [Plugins](</docs/en/plugins/overview>). -## - -​ - -Loading plugins +## Loading plugins Load plugins by providing their local file system paths in your options configuration. The `type` field must be `"local"`, the only value the SDK accepts. The SDK supports loading multiple plugins from different locations. To use a plugin distributed through a [marketplace](</docs/en/plugins/overview>) or remote repository, download it first and provide the local directory path. For the directory layout a plugin needs, see the Plugin structure reference below. @@ -51,11 +47,7 @@ asyncio.run(main()) -### - -​ - -Path specifications +### Path specifications Plugin paths can be: @@ -64,19 +56,11 @@ The path should point to the plugin’s root directory: the parent of `skills/`, `agents/`, `hooks/`, `commands/`, or `.claude-plugin/`. -### - -​ - -Reload plugins in a running session +### Reload plugins in a running session To apply a change to a plugin’s skills, commands, agents, or hooks without starting a new session, call [`reloadPlugins()`](</docs/en/agent-sdk/typescript#query-object>) on the TypeScript SDK’s `Query` object. The Python SDK doesn’t expose an equivalent method; send [`/reload-plugins`](</docs/en/plugins/cli-reference#reload-plugins>) as a prompt in the session instead. -### - -​ - -Add plugins to a running session +### Add plugins to a running session In the TypeScript SDK, call [`reloadPlugins()`](</docs/en/agent-sdk/typescript#load-more-plugin-folders-with-addplugins>) on the `Query` object that `query()` returned, and list the plugin directory in that call’s `addPlugins` option. Each `addPlugins` entry is a `{ type: "local", path }` object with an absolute `path`. Requires TypeScript Agent SDK v0.3.301 or later. In this example, `q` is the `Query` object that `query()` returned. The example adds one plugin directory to the running session and, after `reloadPlugins()` returns, prints the path of every plugin in the session: @@ -88,11 +72,7 @@ If the plugin loaded, the printed list includes `/home/user/plugins/another-plugin`. If that path is missing from the list, or `reloadPlugins()` rejects, see [When `reloadPlugins()` doesn’t load the `addPlugins` folders](</docs/en/agent-sdk/typescript#when-reloadplugins-doesnt-load-the-addplugins-folders>) for the causes. -## - -​ - -Verifying plugin installation +## Verifying plugin installation When plugins load successfully, they appear in the system initialization message. You can verify that your plugins are available: @@ -148,11 +128,7 @@ asyncio.run(main()) -## - -​ - -Use plugin skills +## Use plugin skills Skills from plugins are automatically namespaced with the plugin name to avoid conflicts. To invoke one directly, send `/plugin-name:skill-name` as the prompt. @@ -196,11 +172,7 @@ If you installed a plugin via the CLI (for example, `/plugin install my-plugin@marketplace`), you can still use it in the SDK by providing its installation path. Check `~/.claude/plugins/` for CLI-installed plugins. -## - -​ - -Complete example +## Complete example Here’s a full example demonstrating plugin loading and usage: @@ -278,11 +250,7 @@ if __name__ == "__main__": asyncio.run(run_with_plugin()) -## - -​ - -Plugin structure reference +## Plugin structure reference A plugin directory typically contains a `.claude-plugin/plugin.json` manifest file. The manifest is optional. When omitted, Claude Code auto-discovers components from the directory layout. The directory can include: @@ -302,11 +270,7 @@ The `commands/` directory holds skills as flat Markdown files. Use `skills/` for new plugins. Claude Code supports both locations. -## - -​ - -Multiple plugin sources +## Multiple plugin sources Combine plugins from different locations: @@ -323,17 +287,9 @@ The SDK doesn’t expand tilde paths like `~/plugins`. If a plugin path doesn’t exist, the SDK skips that plugin and the session continues, so check the `plugins` list in the init message to confirm each plugin loaded. -## - -​ - -Troubleshooting - -### - -​ - -Plugin not loading +## Troubleshooting + +### Plugin not loading If your plugin doesn’t appear in the init message’s `plugins` list, check its [`plugin_errors`](</docs/en/agent-sdk/typescript#sdksystemmessage>) field for the reason, then work through these checks: @@ -342,11 +298,7 @@ 3. **Check file permissions** : ensure the plugin directory is readable 4. **Confirm the directory exists** : the SDK skips a nonexistent path, and the plugin doesn’t appear in the init message’s `plugins` list -### - -​ - -Skills not appearing +### Skills not appearing If plugin skills don’t work: @@ -354,11 +306,7 @@ 2. **Check init message** : verify the skill appears in the `skills` list with the correct namespace 3. **Validate skill files** : ensure each skill has a `SKILL.md` file in its own subdirectory under `skills/`, for example `skills/my-skill/SKILL.md` -## - -​ - -See also +## See also * [Plugins](</docs/en/plugins/overview>) \- Complete plugin development guide * [Plugins reference](</docs/en/plugins/manifest-reference>) \- Technical specifications
modified How Claude Code uses prompt caching View current →
Show diff (387 lines)
--- a/prompt-caching.md +++ b/prompt-caching.md @@ -1,10 +1,6 @@ Prompt caching makes Claude Code faster and more cost-efficient. Without caching, the API would reprocess your full history on every turn. With caching, it reuses what it already processed, bills the re-read at the [cached token rate](<https://platform.claude.com/docs/en/about-claude/pricing>), and fully processes only what changed. Claude Code handles prompt caching for you, unless you disable it. It is still useful to know how prompt caching works, because some actions invalidate the cache and make the next response slower and more expensive while it rebuilds. This page covers which actions those are, why some settings wait for a restart to apply, and how to check cache performance when usage looks high. -## - -​ - -How the cache is organized +## How the cache is organized Each time you send a message in Claude Code, it makes a new API request. The model doesn’t remember anything between requests, so Claude Code re-sends the full context: the system prompt, your project context, every prior message and tool result, and your new message. New content is appended at the end, which means most of each request is identical to the one before it. Prompt caching is how the API avoids reprocessing the part that didn’t change. The API caches by matching the start of each request, called the prefix, against content it recently processed. On a normal turn, the prefix is the entire previous request and only the latest exchange is new. The match is exact, so a change anywhere in the prefix recomputes everything after it. There is no per-file or per-segment caching. See [how prompt caching works](<https://platform.claude.com/docs/en/build-with-claude/prompt-caching#how-prompt-caching-works>) in the API reference for the underlying mechanism. To get the most out of prefix matching, Claude Code orders each request so content that rarely changes between turns comes first: @@ -14,18 +10,14 @@ Project context| CLAUDE.md, auto memory, unscoped rules| Session starts, or after `/clear` or `/compact` Conversation| Your messages, Claude’s responses, tool results| Every turn -A change to the conversation layer leaves the system prompt and project context cached. A change to the system prompt invalidates everything, because all later content now sits behind a different prefix. The third column gives common triggers rather than an exhaustive list, and the sections below cover the full set. The prefix-match rule explains most of the behaviors on this page. [Plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>) and [skill loading](</docs/en/skills>), for example, append their instructions as conversation messages, so the cached prefix stays intact. Two settings don’t appear in the layer table but still affect what stays cached: +An addition to the conversation layer leaves the system prompt and project context cached. A change to the system prompt invalidates everything, because all later content now sits behind a different prefix. The third column gives common triggers rather than an exhaustive list, and the sections below cover the full set. The prefix-match rule explains most of the behaviors on this page. [Plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>) and [skill loading](</docs/en/skills>), for example, append their instructions as conversation messages, so the cached prefix stays intact. Two settings don’t appear in the layer table but still affect what stays cached: * **Model** : each model has its own cache. Switching models recomputes the entire request even when the content is identical. See Switching models below. * **Effort level** : on most models, each effort level has its own cache, so changing effort mid-session recomputes the entire request. With an API key or a Claude subscription, the cache stays intact by default on Fable 5.1 and later, Opus 5.5, Sonnet 5.5, and Haiku 5.5. See Changing effort level below. Pick your model and effort level at the top of a session, then save `/compact` for natural breaks between tasks. The fewer changes you make mid-task, the higher your cache hit rate. -### - -​ - -Where the cache lives +### Where the cache lives Caching happens server-side, in whichever infrastructure serves your model. Where that is depends on how you authenticate: @@ -42,11 +34,7 @@ For what each provider stores and processes, see [data usage](</docs/en/data-usage>). Wherever the cache lives, entries expire after a period of inactivity, and Cache lifetime below covers the TTL and how to extend it. -## - -​ - -Actions that invalidate the cache +## Actions that invalidate the cache These actions can cause the next request to miss part or all of the cache. You see a one-time slower, more expensive turn, after which the new prefix is cached. Most of them are avoidable mid-task once you know they have a cost. A model switch can feel free until you notice the slower turn that follows. @@ -60,27 +48,15 @@ * Accumulating many images * Upgrading Claude Code -### - -​ - -Switching models +### Switching models Each model has its own cache. Switching with [`/model`](</docs/en/model-config#setting-your-model>) means the next request reads the entire conversation history with no cache hits, even though the content is identical. When you run `/model` at the terminal, Claude Code asks you to confirm the switch only while the cache is still warm and the new model isn’t the one that produced the last response. The cache stays warm for one cache TTL after Claude Code last sent a request in this conversation or Claude last responded. Once that time passes, the cache has expired, so Claude Code switches without asking. Before v2.1.238, Claude Code didn’t check the cache TTL and asked even after the cache had expired. You can also require this confirmation or skip it with a [PreModelSwitch hook](</docs/en/hooks#premodelswitch-decision-control>). The [`opusplan` model setting](</docs/en/model-config#opusplan-model-setting>) resolves to Opus during plan mode and Sonnet during execution, so each plan-mode toggle is a model switch and starts a fresh cache. [Automatic model fallback](</docs/en/model-config#automatic-model-fallback>) on Fable models, Opus 5.5, Sonnet 5.5, and Opus 5 is also a model switch. When a safety classifier flags a request in a category that has a fallback model and Claude Code re-runs the request on that model, the session continues there. When a skill or command’s frontmatter names a [`model`](</docs/en/skills#frontmatter-reference>) other than the session’s current model, that turn is also a model switch: the next request reads the entire conversation history with no cache hits. The session model resumes on your next prompt. A `context: fork` skill sets the [forked subagent’s model](</docs/en/skills#run-skills-in-a-subagent>) instead. -### - -​ - -Changing effort level +### Changing effort level On most models, changing the [effort level](</docs/en/model-config#adjust-effort-level>) mid-session means the next request reads the entire conversation history with no cache hits. While the cache is still warm, Claude Code asks you to confirm the change first. With an API key or a Claude subscription, changing effort keeps the cache on Fable 5.1 and later, Opus 5.5, Sonnet 5.5, and Haiku 5.5. Claude Code [applies the new level](</docs/en/model-config#when-a-new-effort-level-starts>) without asking. On Amazon Bedrock, Google Cloud’s Agent Platform, or a [Claude apps gateway](</docs/en/claude-apps-gateway>), or when you set [`CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS`](</docs/en/llm-gateway-protocol#disable-pre-release-capabilities>) or your organization has a HIPAA configuration, it works as on most models. Before v2.1.260, changing effort on Fable 5.1 with an API key or a Claude subscription also invalidated the cache. -### - -​ - -Turning on fast mode +### Turning on fast mode [Fast mode](</docs/en/fast-mode>) and standard speed keep separate caches, so after you turn fast mode on or off, the next request can’t use what the other speed cached. The first time you turn fast mode on in a conversation, the next request reads the whole conversation so far uncached at [fast mode rates](</docs/en/fast-mode#understand-the-cost-tradeoff>). To keep that cost small, turn it on at the start of a session. @@ -89,11 +65,7 @@ Each later toggle reads uncached whatever the speed you switch to doesn’t have cached. Speed changes Claude Code makes on its own, such as the [fallback to standard speed](</docs/en/fast-mode#handle-rate-limits>) after a rate limit and the return to fast mode later, count as toggles too. -### - -​ - -Connecting or removing an MCP server +### Connecting or removing an MCP server Tool definitions sit in the system prompt layer, so the cache invalidates when the set of tool definitions in the request changes between turns. Toggling the [advisor tool](</docs/en/advisor>) is an exception: its definition sits after the cache breakpoint, so enabling or disabling `/advisor` keeps the cached prefix intact. Whether an [MCP server](</docs/en/mcp>) change does this depends on whether [tool search](</docs/en/mcp#scale-with-mcp-tool-search>) defers the session’s MCP tools, the default on supported models: @@ -113,43 +85,23 @@ When you resume a conversation whose tools load into the prefix, one of its MCP servers can still be connecting as the first request goes out. If the transcript recorded that server’s tool definitions, that request includes them as recorded, so it doesn’t change when the server finishes connecting with the same tools. Editing your MCP config does not by itself change the cache. The new config takes effect only after a restart, which is when the server connects or disconnects. -### - -​ - -Enabling or disabling a plugin +### Enabling or disabling a plugin When you enable or disable a [plugin](</docs/en/plugins/overview>), what the change costs depends on which component types the plugin provides. The cases below cover each component type, when Claude Code applies the change, and what happens when you disable a plugin again in the same session. -#### - -​ - -Plugin components that keep the cache +#### Plugin components that keep the cache Claude Code never invalidates the cache for a plugin’s skills, commands, agents, hooks, monitors, or themes. It appends their content after the existing conversation, so the next request pays for that content and still reads everything before it from the cache. -#### - -​ - -Plugins that provide MCP servers +#### Plugins that provide MCP servers When you enable or disable a plugin that provides [MCP servers](</docs/en/plugins/components#mcp-servers>), Claude Code follows the same rules as when you connect or remove an MCP server. -#### - -​ - -Code intelligence plugins +#### Code intelligence plugins When you enable a [code intelligence plugin](</docs/en/plugins/code-intelligence>), Claude gets the [LSP tool](</docs/en/tools-reference#lsp-tool-behavior>). -#### - -​ - -When plugin changes apply +#### When plugin changes apply A change you make in the `/plugin` menu goes through [`/reload-plugins`](</docs/en/plugins/cli-reference#reload-plugins>), which Claude Code runs for you when you close the menu. You pay the cost, whether appended announcements or a full re-read, on the first turn after the change applies. Claude Code can also apply a change on its own: @@ -160,62 +112,38 @@ When `/reload-plugins` runs and the reload would trigger a full re-read, Claude Code shows a warning and doesn’t apply the reload. Run `/reload-plugins --force` to apply it anyway. `/reload-plugins` also runs in sessions without an interactive terminal, such as the desktop app, the Agent SDK, and [non-interactive mode](</docs/en/headless>) with `-p`, when you type it into the session directly. Requires Claude Code v2.1.260 or later. In those sessions the reload applies everything except plugin MCP server changes, which [take effect in your next session](</docs/en/plugins/cli-reference#reload-plugins>) and so never cost a full re-read mid-session. -#### - -​ - -Plugins you enable and then disable in one session +#### Plugins you enable and then disable in one session When you disable a plugin you enabled earlier in the session, Claude Code restores the previous request shape. If that prefix is still within its cache lifetime, the next request reads the older cache entry instead of rebuilding. -### - -​ - -Denying an entire tool +### Denying an entire tool If you add a bare tool name like `Bash` or `WebFetch` as a [deny rule](</docs/en/permissions#manage-permissions>), Claude can’t call that tool from your next request on, whether you add the rule through `/permissions` or by [editing a settings file directly](</docs/en/settings#when-edits-take-effect>). That includes a rule you add through `/permissions` in the middle of a turn. When [tool search](</docs/en/mcp#scale-with-mcp-tool-search>) is active, which is the default on supported models, the request’s tool definitions don’t change and the cached prefix survives. When tool search is unavailable or disabled, Claude Code removes the definition from the next request, which invalidates the cache, and so does removing the rule later. Only a deny rule that matches in the tool-name position blocks a tool this way: a bare tool name, the equivalent `Bash(*)` form, or a [tool-name glob](</docs/en/permissions#tool-name-wildcards>) like `"*"`. A glob that matches only MCP tools, such as `"mcp__*"`, blocks those tools the same way. Scoped deny rules like `Bash(rm *)`, and all allow and ask rules, don’t change which tools Claude sees. Claude Code checks them when Claude attempts a call, leaving the prefix intact. -### - -​ - -Compacting the conversation - -[Compaction](</docs/en/context-window#what-survives-compaction>) replaces your message history with a summary. By design, this invalidates the conversation layer: the next request has a new, shorter history that doesn’t share a prefix with the old one. The system prompt and project context layers can stay cached: +### Compacting the conversation + +[Compaction](</docs/en/context-window#what-survives-compaction>) replaces your message history with a summary. By design, this invalidates the conversation layer: the next request has a new, shorter history that doesn’t share a prefix with the old one. * **System prompt** : the next request reads this layer from the cache, unless a resumed conversation kept a system prompt that is now out of date. The first time that conversation is compacted, Claude Code switches it to the current prompt, and the next request rebuilds this layer’s cache once. - * **Project context** : Claude Code reloads this layer from disk. The next request reads it from the cache only if CLAUDE.md and memory are unchanged since the session started. - -To produce the summary, Claude Code sends a separate request. The request repeats your conversation’s system prompt, tools, and the history being summarized. It ends with a summarization instruction. While the cache is warm, that request reads your prefix from the cache. A mid-session `/compact` then costs a fraction of what the context size suggests and spends most of its time generating the summary. After a break longer than the cache lifetime, there is no cache left to read, so the summarization request reprocesses that history as uncached input. This is why `/compact` costs the most when you [resume an old session](</docs/en/sessions#resume-a-session>). In both the warm and cold cases, the turn after compaction rebuilds the conversation cache for only the much shorter summary, so that turn isn’t the slow part. + * **Project context** : Claude Code reloads this layer from disk. It’s cached together with the conversation, so after `/compact` or automatic compaction its cache is rebuilt even if its files are unchanged. + +To produce the summary, Claude Code sends a separate request. The request repeats your conversation’s system prompt, tools, and the history being summarized. It ends with a summarization instruction. While the cache is warm, that request reads your prefix from the cache. A mid-session `/compact` then costs a fraction of what the context size suggests and spends most of its time generating the summary. After a break longer than the cache lifetime, there is no cache left to read, so the summarization request reprocesses that history as uncached input. This is why `/compact` costs the most when you [resume an old session](</docs/en/sessions#resume-a-session>). In both the warm and cold cases, the turn after compaction rebuilds the conversation cache for only the much shorter history, so that turn isn’t the slow part. Compaction works in your favor when the context you discard is content you no longer need. To choose when its overhead happens, run `/compact` at a natural break in your work, such as between tasks, instead of waiting for auto-compaction to trigger mid-task. If you’ve gone down a path you want to abandon entirely, `/rewind` to an earlier turn instead. Rewinding truncates back to a prefix that is already cached, rather than building a new one as compaction does. If you leave a long conversation idle while it is on the one-hour TTL, Claude Code can compact it. To turn idle compaction off, set [`idleCompaction`](</docs/en/settings-reference#idlecompaction>) to `false`, which requires Claude Code v2.1.290 or later. -### - -​ - -Accumulating many images +### Accumulating many images The API limits how many images and PDFs each request can carry. For the current numbers, see [Request limits](<https://platform.claude.com/docs/en/build-with-claude/vision#request-limits>) in the API docs. Claude Code also caps the total size of the images and PDFs in a request, so large screenshots reach the limit with fewer images than small ones. When the next request would pass either limit, Claude Code removes a batch of the oldest images and PDFs from what it sends, which leaves room for more before it needs to remove any again. Claude can no longer see the removed images. If Claude needs one of them again, share it again. Removing images changes the messages that held them, so the next request reprocesses the conversation from the earliest of those messages onward. Because Claude Code removes a batch at a time, you see one slower turn per batch rather than one with each new screenshot. -### - -​ - -Upgrading Claude Code +### Upgrading Claude Code A new Claude Code version typically updates the system prompt or tool definitions, so the first conversation you start after an upgrade builds its cache from the top. [Auto-update](</docs/en/setup#auto-updates>) downloads new versions in the background but applies them on the next launch, never mid-session, so you see this as an uncached first turn after restarting rather than a surprise during a session. Set `DISABLE_AUTOUPDATER=1` to control when upgrades apply. For what it costs to resume a conversation you started before the upgrade, see Resuming a session. -## - -​ - -Actions that keep the cache +## Actions that keep the cache These actions either append to the end of the conversation or don’t touch the request at all. Some of them, such as editing CLAUDE.md, keep the cache for the same reason the change doesn’t reach the running session until `/clear`, `/compact`, or a restart. @@ -228,83 +156,43 @@ * Rewinding the conversation * Spawning a subagent -### - -​ - -Editing files in your repository +### Editing files in your repository File contents enter context only when Claude reads them, and reads append to the conversation. Editing a file Claude previously read does not retroactively change the earlier read in history. Instead, Claude Code appends a [`<system-reminder>`](</docs/en/glossary#system-reminder>) noting the file changed, and Claude re-reads it if needed. -### - -​ - -Editing CLAUDE.md mid-session +### Editing CLAUDE.md mid-session Your project-root and user-level CLAUDE.md files are read once at session start and held in memory. Editing them mid-session does not invalidate the cache, but the edit also doesn’t apply. Claude keeps working with the version that was loaded at session start. The new content loads on the next `/clear`, `/compact`, or restart. [Nested CLAUDE.md files in subdirectories](</docs/en/memory>) and [rules with `paths:` frontmatter](</docs/en/memory#path-specific-rules>) load later, on demand. Editing one yourself before it loads does take effect. After it loads, the content is part of the conversation history, so a mid-session edit doesn’t retroactively change it. -### - -​ - -Changing permission mode +### Changing permission mode Switching between [permission modes](</docs/en/permission-modes>), such as from Manual to accept edits, does not change the system prompt or tool definitions, so mode changes are cache-safe. The exception is plan mode with the [`opusplan`](</docs/en/model-config#opusplan-model-setting>) model setting, which switches the model between Opus and Sonnet as you enter or leave plan mode. That makes the mode toggle a model switch. -### - -​ - -Changing output style +### Changing output style When you switch [output styles](</docs/en/output-styles>) mid-session with [`/output-style`](</docs/en/output-styles#change-your-output-style>), `/config`, or the `outputStyle` setting, Claude uses the new style starting with your next message. Claude Code delivers the new style’s instructions as a message in the conversation, so that request still reads the system prompt and the earlier conversation from the cache. Before v2.1.251, a mid-session style switch kept the cache but didn’t apply until you ran `/clear` or started a new session. -### - -​ - -Invoking skills and commands +### Invoking skills and commands [Skills](</docs/en/skills>) and [commands](</docs/en/commands>) inject their instructions as user messages at the point of invocation. Nothing earlier in the conversation changes. A skill or command whose frontmatter names a `model` can be a model switch for that turn. -### - -​ - -Running `/recap` +### Running `/recap` [`/recap`](</docs/en/interactive-mode#session-recap>) generates a summary for display in your terminal. Unlike `/compact`, it appends the summary as command output rather than replacing your message history, so the cached prefix stays intact. -### - -​ - -Rewinding the conversation +### Rewinding the conversation [`/rewind`](</docs/en/checkpointing>) truncates your conversation back to an earlier turn. The remaining history is the same content the cache was built from at that point, and the system prompt and project context layers are unchanged, so the next request hits the earlier cache entry. Every turn since then has read through that prefix, which kept the entry warm even if the original turn was longer ago than the TTL. Restoring file checkpoints alongside the conversation has no separate effect on the cache. File contents enter context only when Claude reads them, the same as editing files in your repository. -## - -​ - -Resuming a session +## Resuming a session When you [resume a session](</docs/en/sessions#resume-a-session>), Claude Code sends the whole conversation again, and the request reads from the cache whatever part of its prefix is unchanged and still within the cache lifetime. The layer table at the top of this page says what changes each layer. The system prompt would change after a Claude Code upgrade or with different [`--append-system-prompt`](</docs/en/cli-reference#system-prompt-flags>) text on the resume. By default, the resumed conversation keeps the system prompt it started with, so its history still sits behind the same prompt, and the change takes effect once the conversation is compacted or in a new conversation. [System prompt flags in resumed conversations](</docs/en/cli-reference#system-prompt-flags-in-resumed-conversations>) covers the cases where Claude Code rebuilds the prompt on every request instead. -## - -​ - -Cache lifetime +## Cache lifetime Cached prefixes expire after a period of inactivity. Each request that hits the cache resets the timer, so the cache stays warm as long as you keep working. After a long enough gap, the next request recomputes the full input and re-establishes the cache, which is why the first turn back after stepping away can be noticeably slower. The time to live (TTL) controls how long a gap the cache survives. The API offers two: a five-minute TTL, and a [one-hour TTL](<https://platform.claude.com/docs/en/build-with-claude/prompt-caching#1-hour-cache-duration>) that keeps the cache warm through longer breaks but [charges a higher rate for cache writes](<https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pricing>). The longer TTL helps when you leave a session idle and come back to it, because you skip the reprocessing an expired prefix costs. It costs more on short bursts of work that never idle past five minutes, where the higher write rate applies and the longer cache lifetime goes unused. -### - -​ - -Which TTL each request gets +### Which TTL each request gets Claude Code decides the TTL per request, and every request falls in one of two fixed buckets: @@ -320,11 +208,7 @@ Once you go over your plan’s usage limit and Claude Code draws on [usage credits](<https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans>), you are billed for that usage, so Claude Code drops the main conversation to the five-minute TTL, which charges a lower rate for cache writes. To keep the one-hour TTL there, choose the TTL yourself. -### - -​ - -Choose the TTL yourself +### Choose the TTL yourself You can set a TTL for either bucket. Each control takes `5m` or `1h`, and Claude Code ignores any other value. @@ -346,11 +230,7 @@ * **[Claude apps gateway](</docs/en/claude-apps-gateway>)** : ask your administrator to request the one-hour TTL in a [gateway policy](</docs/en/claude-apps-gateway-config#one-hour-prompt-cache>) * **Amazon Bedrock** : prompt caching support, minimum cacheable prefix length, and one-hour TTL availability all vary by model. If cache token counts stay at zero, check [supported models, regions, and limits](<https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html#prompt-caching-models>) in the Amazon Bedrock documentation. -## - -​ - -Cache scope +## Cache scope In Claude Code, the cache is effectively scoped to one machine and directory. The system prompt embeds your auto memory paths, and the conversation opens with an announcement of the working directory, platform, shell, and OS version. Two sessions in different directories therefore build different prefixes and miss each other’s cache. @@ -359,11 +239,7 @@ The underlying API cache is broader. Caches are isolated between organizations, and on some providers, [between workspaces within an organization](<https://platform.claude.com/docs/en/build-with-claude/prompt-caching#cache-storage-and-sharing>). Within those boundaries, two requests share a cache only when their model, speed, and prefix match. For Agent SDK callers running fleets of automated processes, see [improve prompt caching across users and machines](</docs/en/agent-sdk/modifying-system-prompts#improve-prompt-caching-across-users-and-machines>) to move the auto memory location out of the system prompt. -## - -​ - -Check cache performance +## Check cache performance Cache performance shows up as two token counts the API reports on every response. The most direct way to watch them live is a [statusline script](</docs/en/statusline>) that reads the `current_usage` object: @@ -374,11 +250,7 @@ A high read-to-creation ratio means caching is working well. If creation stays high turn after turn, something is changing in your prefix. The actions that invalidate the cache section lists the usual causes. For a per-session summary, run `/usage`. After the main conversation’s first response, Claude Code adds a [`Prompt cache (main)` line](</docs/en/costs#prompt-cache-statistics>) to the Session block, showing the session’s hit ratio, miss count, and whether the cache is warm right now. A status line script can read the same numbers from the [`prompt_cache` object](</docs/en/statusline#prompt-cache-fields>). Both require Claude Code v2.1.251 or later. The `Prompt cache (main)` line also names the likely cause of the last miss when Claude Code can identify one, for example `likely cause: tool definitions changed`. The likely-cause text requires Claude Code v2.1.260 or later. For visibility across an organization, the OpenTelemetry exporter reports cache read and creation tokens per user and session. See [Monitor usage](</docs/en/monitoring-usage>) for the metric and event attribute reference. -## - -​ - -Subagents and the cache +## Subagents and the cache A [subagent](</docs/en/sub-agents>) starts its own conversation with its own system prompt and tool set, separate from the parent’s. Its first request doesn’t read the parent’s cache, because the two prefixes differ, and it warms a cache of its own across its turns. Subagents fall outside the main-conversation TTL bucket, so they get five minutes even on a subscription until you choose a longer one. The parent’s cache is unaffected. From the parent’s side, the subagent’s call and result append to the conversation, leaving the parent’s prefix intact. A [fork](</docs/en/sub-agents#fork-the-current-conversation>), by contrast, inherits the parent’s system prompt, tools, and conversation history exactly, so its first request reads the parent’s cache. Other requests can also read a prefix that an earlier request cached: @@ -387,11 +259,7 @@ * **Resumed subagents** : when Claude [resumes a subagent](</docs/en/sub-agents#resume-subagents>), the resumed run’s first request can read the cache the original run warmed. * **Workflow fan-outs** : in a [workflow fan-out](</docs/en/workflows#prompt-caching-in-a-fan-out>) of same-prefix agents, Claude Code holds all but the first for up to 5 seconds by default, so their first requests can read the prefix that the first agent cached. -## - -​ - -Disable prompt caching +## Disable prompt caching Disabling caching is occasionally useful when debugging caching behavior with a specific model or provider. To turn it off, set one of these environment variables to `1`: @@ -405,11 +273,7 @@ `DISABLE_PROMPT_CACHING_HAIKU` applies to the default Haiku model, the model the `haiku` alias resolves to. It disables caching wherever that model runs, including the main conversation when it is your main model. Covering the main conversation requires Claude Code v2.1.283 or later. The variable also covers a background model you set with the deprecated `ANTHROPIC_SMALL_FAST_MODEL` variable, when that model differs from your main model. A different Haiku version that you pin as your main model keeps caching; set `DISABLE_PROMPT_CACHING` to disable caching for it. `DISABLE_PROMPT_CACHING_SONNET` and `DISABLE_PROMPT_CACHING_OPUS` each apply to the model the `sonnet` or `opus` alias resolves to. If you set any other Sonnet or Opus model ID as your main model, that model keeps caching. For example, a session on `claude-sonnet-5` keeps caching while `sonnet` resolves to `claude-sonnet-5-5`. To disable caching for that model, set `DISABLE_PROMPT_CACHING`. To set caching policy across an organization, put any of these or the TTL variables in the `env` block of [managed settings](</docs/en/managed-settings>). For normal use, leave caching enabled. -## - -​ - -Related resources +## Related resources * [Lessons from building Claude Code: Prompt caching is everything](<https://claude.com/blog/lessons-from-building-claude-code-prompt-caching-is-everything>): the design rationale for plan mode, deferred tool loading, and compaction * [Explore the context window](</docs/en/context-window>): what loads into context and when
modified Prompt library View current →
--- a/prompt-library.md +++ b/prompt-library.md @@ -1,10 +1,6 @@ This is a library of prompts to copy into Claude Code. Use it to explore ways of working you haven’t tried, or when you’re not sure where to start. The prompts are collected from various Anthropic guides, including [Common workflows](</docs/en/common-workflows>), [Best practices](</docs/en/best-practices>), and [How Anthropic teams use Claude Code](<https://claude.com/blog/how-anthropic-teams-use-claude-code>). They’re starting points rather than scripts. Open **Why this works** under any prompt to see the pattern behind it so you can write your own. -## - -​ - -What makes these prompts work +## What makes these prompts work The prompts above share a few patterns. Recognizing them helps you adapt any prompt here to your own task. **Describe the outcome, not the steps.** Say what you want and let Claude find the files. The prompt below works without naming a single file path. @@ -32,11 +28,7 @@ For more on each pattern, see [best practices](</docs/en/best-practices>). -## - -​ - -Where these come from +## Where these come from These prompts are based on patterns from published Anthropic resources. Each card links to its source: @@ -47,10 +39,6 @@ For video walkthroughs of these patterns, see the free [Claude Code in Action](<https://academy.claude.com/courses/claude-code-in-action>) course on [Claude Academy](<https://academy.claude.com/>). -## - -​ - -Related resources +## Related resources The prompts on this page are starting points. Once one works for your project, the next step is making it repeatable: save it as a [skill](</docs/en/skills>) so anyone on your team can run it as a `/command`, and record the conventions Claude learned in [CLAUDE.md](</docs/en/memory>) so every session starts with that context instead of Claude relearning it. For larger or riskier changes, [plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>) shows you the file list before any edits happen. If you’re introducing Claude Code across a team, see [administration](</docs/en/admin-setup>) for managed settings and policy, and [costs and usage](</docs/en/costs>) for how this work is billed on your plan.
modified Publish and distribute a plugin View current →
Show diff (194 lines)
--- a/publish.md +++ b/publish.md @@ -7,11 +7,7 @@ Start with Choose how to distribute to compare the distribution options. If you already know your route, go to Prepare your plugin for release, then follow your route’s section for what to tell your users and how they receive your updates. -## - -​ - -Choose how to distribute +## Choose how to distribute Choose a distribution option based on who needs to install the plugin: @@ -23,11 +19,7 @@ Auto-update is a per-marketplace setting on the user’s side that fetches new versions in the background. -## - -​ - -Prepare your plugin for release +## Prepare your plugin for release The name, the version, validation, and an install from a marketplace decide whether a release works for the people who install it. Check them before the first release and again before each later one. @@ -65,7 +57,7 @@ Fill in the metadata users see -Set `description`, `author`, `homepage`, and `repository` in `plugin.json`, and add a `README.md` at the plugin root. `homepage` must parse as a URL. The [manifest reference](</docs/en/plugins/manifest-reference#fields>) lists every field. +Set `description`, `author`, `homepage`, and `repository` in `plugin.json`, and add a `README.md` at the plugin root. `homepage` must parse as a URL. For what each field accepts, see the [manifest reference](</docs/en/plugins/manifest-reference#fields>). 6 @@ -73,11 +65,7 @@ If you have an eval suite, run `claude plugin eval` in your shell. It runs the plugin’s test cases and scores the results, which catches regressions when you change the plugin. See [Test plugins with evals](</docs/en/plugin-evals>). -## - -​ - -Share a plugin without a marketplace +## Share a plugin without a marketplace If the plugin is in a git repository, people can clone it and load the checkout, or start Claude Code from their shell with `--plugin-url` pointed at a `.zip` you attach to a release. To get your next version they pull or download again. If it isn’t in a repository, send them the directory or a `.zip` of it. They load it in one of two ways: @@ -86,27 +74,15 @@ Adding a `.claude-plugin/marketplace.json` to that same repository is what lets people install by name and update with a command; see Publish through your own marketplace. -### - -​ - -Ship a plugin with your own tool +### Ship a plugin with your own tool If you maintain a CLI or SDK, publish the plugin in a marketplace and have your installer or post-install message run or print the two commands a user needs: `claude plugin marketplace add <source>`, then `claude plugin install <name>@<marketplace>`. For in-session discovery when someone uses your tool, see [Recommend your plugin from your CLI](</docs/en/plugins/cli-hints>). -## - -​ - -Publish through your own marketplace +## Publish through your own marketplace Your own marketplace is a `.claude-plugin/marketplace.json` file that lists your plugin, added to a git repository. Once the file is in the repository, the plugin is published, with no submission form. You can keep the file in the plugin’s own repository or in a separate one. -### - -​ - -Add the marketplace file to your repository +### Add the marketplace file to your repository To publish from the plugin’s own repository, save the marketplace file beside `plugin.json` in `.claude-plugin/`, with one entry whose `source` is `"./"`, the repository root. Give the entry the same `name` as `plugin.json`, per [Keep the entry name and the manifest name the same](</docs/en/plugins/create-marketplace#keep-the-entry-name-and-the-manifest-name-the-same>): @@ -122,19 +98,11 @@ Replace `your-marketplace` with a name that other authors are unlikely to pick, because a user [can’t have two marketplaces with the same name](</docs/en/plugins/marketplace-reference#marketplace-file>). 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. -### - -​ - -Control who can install +### Control who can install Anyone who can clone the repository can install from it, so if the repository is private, the marketplace is private too. For hosts other than a git repository, see [Host a marketplace](</docs/en/plugins/host-marketplace>). To reach everyone at a company, including people who don’t use git, see [Roll out to a whole company](</docs/en/plugins/host-marketplace#roll-out-to-a-whole-company>). -### - -​ - -Tell users how to install +### Tell users how to install Tell your users to add the marketplace and then install the plugin from their shell, replacing the source and names with yours: @@ -143,11 +111,7 @@ * Or do both from inside a session: `/plugin install deploy-helper --marketplace your-org/your-marketplace`. Requires Claude Code v2.1.275 or later. See [Add a marketplace and install in one command](</docs/en/plugins/install#add-a-marketplace-and-install-in-one-command>) * Or do both from the shell in one command: `claude plugin install deploy-helper --marketplace your-org/your-marketplace`. Requires Claude Code v2.1.292 or later -### - -​ - -Ship updates to users +### Ship updates to users Users receive a release when they ask for it or when auto-update is on for your marketplace: @@ -156,11 +120,7 @@ [Install plugins](</docs/en/plugins/install>) covers the user-side commands, and [when auto-update runs](</docs/en/plugins/loading#when-auto-update-runs>) covers the timing. -## - -​ - -Submit to Anthropic’s directory +## Submit to Anthropic’s directory [Anthropic’s directory](<https://claude.ai/directory>) is the catalog people browse on claude.ai and in Cowork to add plugins and connectors. One listing there reaches people on claude.ai, in Cowork, and in Claude Code. You submit from the developer portal at [claude.ai/directory/manage](<https://claude.ai/directory/manage>), and [Submit a plugin](<https://claude.com/docs/plugins/submit#submit-a-plugin>) on claude.com walks through the portal. Anthropic’s official marketplace, `claude-plugins-official`, doesn’t take submissions through the directory portal. If you work with an Anthropic partner contact, ask them about an official-marketplace listing. To submit a plugin: @@ -195,57 +155,29 @@ * [Submit your plugin, and your MCP server as a connector](<https://claude.com/docs/directory/publish#submit-your-plugin-and-your-mcp-server-as-a-connector>): what you can submit * [Move an earlier submission to the developer portal](<https://claude.com/docs/directory/publish#move-an-earlier-submission-to-the-developer-portal>): what to do if you submitted a plugin through one of the earlier submission forms, before the portal existed -### - -​ - -How a listed plugin reaches Claude Code users +### How a listed plugin reaches Claude Code users A person who installs your plugin from the directory on claude.ai has it on their account, and Claude Code loads it as `<name>@synced`. [Plugins synced from claude.ai](</docs/en/plugins/loading#synced-plugins>) covers what they see and how they turn it off. -## +## Ship updates, renames, and removals -​ - -Ship updates, renames, and removals - -### - -​ - -Release a new version +### Release a new version If you publish through your own marketplace and your `plugin.json` sets `version`, increment it and push. Users who run `claude plugin update` or have auto-update on then receive the new version, as described under Ship updates to users. For a directory listing, see [Update a published plugin](<https://claude.com/docs/plugins/submit#update-a-published-plugin>). -### - -​ - -Tag a release +### Tag a release Tag the release in git when other plugins declare a version range on yours, because those ranges resolve against tags. Otherwise you don’t need a tag. To tag, run `claude plugin tag` in your shell from the plugin directory. It creates a `{name}--v{version}` tag. Add `--push` to send the tag to `origin`. The [`plugin tag` reference](</docs/en/plugins/cli-reference#plugin-tag>) lists its flags. -### - -​ - -Rename or remove a plugin +### Rename or remove a plugin Never change a published plugin’s `name`. After a rename, users who already installed it lose the plugin, because their install is recorded under the old name. A `renames` entry in your marketplace file migrates them instead. Change `displayName` when you want a different label. If a rename is unavoidable, use the marketplace file’s `renames` map so that existing installs migrate instead of failing with [`Plugin "<name>" not found in marketplace`](</docs/en/plugins/troubleshooting#plugin-not-found-in-marketplace>). To remove a plugin from the marketplace, or for the full `renames` details, see [Rename or remove a plugin](</docs/en/plugins/host-marketplace#rename-or-remove-a-plugin>) on the hosting page. The [marketplace reference](</docs/en/plugins/marketplace-reference#top-level-fields>) has the field. -## - -​ - -Declare dependencies +## Declare dependencies If your plugin needs another plugin from the same marketplace to be enabled, list it in the `dependencies` array of `plugin.json`. Each entry is a bare name or an object with a semver `version` range. When a user installs your plugin, Claude Code installs and enables the dependency too. [Plugin dependencies](</docs/en/plugins/dependencies>) covers the range syntax, cross-marketplace dependencies, and how users prune dependencies they no longer need. -## - -​ - -Next steps +## Next steps * [Host and maintain a marketplace](</docs/en/plugins/host-marketplace>): release new versions and keep users up to date * [Plugin dependencies](</docs/en/plugins/dependencies>): declare and version the plugins yours relies on
modified Agent SDK reference - Python View current →
Show diff (2069 lines)
--- a/python.md +++ b/python.md @@ -1,8 +1,4 @@ -## - -​ - -Installation +## Installation Install the package into a virtual environment. On recent Debian, Ubuntu, and Homebrew Python installs, running `pip install` against system Python fails with `error: externally-managed-environment`. @@ -12,11 +8,7 @@ For uv, Windows PowerShell, and API key setup, see [Setup in the Agent SDK quickstart](</docs/en/agent-sdk/quickstart#setup>). -## - -​ - -Choosing between `query()` and `ClaudeSDKClient` +## Choosing between `query()` and `ClaudeSDKClient` The Python SDK provides two ways to interact with Claude Code: @@ -34,19 +26,11 @@ Use `ClaudeSDKClient` for interactive applications such as chat interfaces, or when the next action depends on Claude’s response. -## - -​ - -Functions +## Functions Signature blocks and bare `async for` / `async with` fragments on this page are illustrative. To run them, wrap the body in `async def main(): ...` and call `asyncio.run(main())`. -### - -​ - -`query()` +### `query()` Creates a new session for each interaction with Claude Code by default. Returns an async iterator that yields messages as they arrive. Each call to `query()` starts fresh with no memory of previous interactions unless you pass `continue_conversation=True` or `resume` in `ClaudeAgentOptions`. See [Sessions](</docs/en/agent-sdk/sessions>). @@ -57,11 +41,7 @@ transport: Transport | None = None ) -> AsyncIterator[Message] -#### - -​ - -Parameters +#### Parameters Parameter| Type| Description ---|---|--- @@ -69,19 +49,11 @@ `options`| `ClaudeAgentOptions | None`| Optional configuration object (defaults to `ClaudeAgentOptions()` if None) `transport`| `Transport | None`| Optional custom transport for communicating with the CLI process -#### - -​ - -Returns +#### Returns Returns an `AsyncIterator[Message]` that yields messages from the conversation. -#### - -​ - -Example - With options +#### Example - With options import asyncio from claude_agent_sdk import query, ClaudeAgentOptions @@ -97,11 +69,7 @@ asyncio.run(main()) -### - -​ - -`tool()` +### `tool()` Decorator for defining MCP tools with type safety. @@ -112,11 +80,7 @@ annotations: ToolAnnotations | None = None ) -> Callable[[Callable[[Any], Awaitable[dict[str, Any]]]], SdkMcpTool[Any]] -#### - -​ - -Parameters +#### Parameters Parameter| Type| Description ---|---|--- @@ -125,11 +89,7 @@ `input_schema`| `type | dict[str, Any]`| Schema defining the tool’s input parameters. See Input schema options `annotations`| `ToolAnnotations`` | None`| Optional MCP tool annotations providing behavioral hints to clients -#### - -​ - -Input schema options +#### Input schema options 1. **Simple type mapping** (recommended): @@ -164,19 +124,11 @@ In the simple mapping and TypedDict forms, wrap a type in `Annotated[type, "description"]` to set the field’s description. -#### - -​ - -Returns +#### Returns A decorator function that wraps the tool implementation and returns an `SdkMcpTool` instance. -#### - -​ - -Example +#### Example from claude_agent_sdk import tool from typing import Any @@ -185,11 +137,7 @@ async def greet(args: dict[str, Any]) -> dict[str, Any]: return {"content": [{"type": "text", "text": f"Hello, {args['name']}!"}]} -#### - -​ - -`ToolAnnotations` +#### `ToolAnnotations` Behavioral hints for a tool, passed as the `annotations` argument of `tool()`. `ToolAnnotations` extends the MCP SDK’s `mcp.types.ToolAnnotations` with a `maxResultSizeChars` field, and you can write each hint in camelCase or snake_case: `ToolAnnotations(readOnlyHint=True)` and `ToolAnnotations(read_only_hint=True)` are equivalent. To read a hint back from the object, use the spelling your installed `mcp` package declares: `.readOnlyHint` on `mcp` 1.x and `.read_only_hint` on 2.x, while `.maxResultSizeChars` works on both. You can also pass a plain `mcp.types.ToolAnnotations` wherever the SDK accepts annotations. The snake_case names and the typed `maxResultSizeChars` field require Python Agent SDK 0.2.140 or later. Versions 0.1.31 through 0.2.139 re-export `mcp.types.ToolAnnotations` unchanged. On versions 0.1.55 through 0.2.139 you can still pass `maxResultSizeChars` as a keyword argument: the MCP class accepts extra fields, and the SDK forwards the value to Claude Code. All fields are optional. Clients shouldn’t rely on the hints for security decisions. @@ -214,11 +162,7 @@ async def search(args: dict[str, Any]) -> dict[str, Any]: return {"content": [{"type": "text", "text": f"Results for: {args['query']}"}]} -### - -​ - -`create_sdk_mcp_server()` +### `create_sdk_mcp_server()` Create an in-process MCP server that runs within your Python application. @@ -228,11 +172,7 @@ tools: list[SdkMcpTool[Any]] | None = None ) -> McpSdkServerConfig -#### - -​ - -Parameters +#### Parameters Parameter| Type| Default| Description ---|---|---|--- @@ -240,19 +180,11 @@ `version`| `str`| `"1.0.0"`| Server version string `tools`| `list[SdkMcpTool[Any]] | None`| `None`| List of tool functions created with `@tool` decorator -#### - -​ - -Returns +#### Returns Returns an `McpSdkServerConfig` object that can be passed to `ClaudeAgentOptions.mcp_servers`. -#### - -​ - -Example +#### Example from claude_agent_sdk import tool, create_sdk_mcp_server, ClaudeAgentOptions @@ -276,11 +208,7 @@ allowed_tools=["mcp__calc__add", "mcp__calc__multiply"], ) -### - -​ - -`list_sessions()` +### `list_sessions()` Lists past sessions with metadata. Filter by project directory or list sessions across all projects. Synchronous; returns immediately. @@ -291,11 +219,7 @@ include_worktrees: bool = True ) -> list[SDKSessionInfo] -#### - -​ - -Parameters +#### Parameters Parameter| Type| Default| Description ---|---|---|--- @@ -304,11 +228,7 @@ `offset`| `int`| `0`| Number of sessions to skip from the start of the sorted results. Use with `limit` for pagination `include_worktrees`| `bool`| `True`| When `directory` is inside a git repository, include sessions from all worktree paths -#### - -​ - -Return type: `SDKSessionInfo` +#### Return type: `SDKSessionInfo` Property| Type| Description ---|---|--- @@ -323,11 +243,7 @@ `tag`| `str | None`| User-set session tag (see `tag_session()`) `created_at`| `int | None`| Session creation time in milliseconds since epoch -#### - -​ - -Example +#### Example Print the 10 most recent sessions for a project. Results are sorted by `last_modified` descending, so the first item is the newest. Omit `directory` to search across all projects. @@ -336,11 +252,7 @@ for session in list_sessions(directory="/path/to/project", limit=10): print(f"{session.summary} ({session.session_id})") -### - -​ - -`get_session_messages()` +### `get_session_messages()` Retrieves messages from a past session. Synchronous; returns immediately. @@ -351,11 +263,7 @@ offset: int = 0 ) -> list[SessionMessage] -#### - -​ - -Parameters +#### Parameters Parameter| Type| Default| Description ---|---|---|--- @@ -364,11 +272,7 @@ `limit`| `int | None`| `None`| Maximum number of messages to return `offset`| `int`| `0`| Number of messages to skip from the start -#### - -​ - -Return type: `SessionMessage` +#### Return type: `SessionMessage` Property| Type| Description ---|---|--- @@ -379,11 +283,7 @@ `parent_tool_use_id`| `str | None`| For subagent messages, the id of the spawning `Agent` tool-use block. `None` for main-session messages and older sessions `parent_agent_id`| `str | None`| For messages from a [nested subagent](</docs/en/sub-agents#let-subagents-spawn-their-own-subagents>), the agent id of the parent subagent. `None` for main-session messages, top-level subagent messages, and older sessions. Requires Python Agent SDK 0.2.140 or later -#### - -​ - -Example +#### Example from claude_agent_sdk import list_sessions, get_session_messages @@ -393,11 +293,7 @@ for msg in messages: print(f"[{msg.type}] {msg.uuid}") -### - -​ - -`get_session_info()` +### `get_session_info()` Reads metadata for a single session by ID without scanning the full project directory. Synchronous; returns immediately. @@ -406,11 +302,7 @@ directory: str | None = None, ) -> SDKSessionInfo | None -#### - -​ - -Parameters +#### Parameters Parameter| Type| Default| Description ---|---|---|--- @@ -419,11 +311,7 @@ Returns `SDKSessionInfo`, or `None` if the session is not found. -#### - -​ - -Example +#### Example Look up a single session’s metadata without scanning the project directory. Useful when you already have a session ID from a previous run. @@ -433,11 +321,7 @@ if info: print(f"{info.summary} (branch: {info.git_branch}, tag: {info.tag})") -### - -​ - -`rename_session()` +### `rename_session()` Renames a session by appending a custom-title entry. Repeated calls are safe; the most recent title wins. Synchronous. @@ -447,11 +331,7 @@ directory: str | None = None, ) -> None -#### - -​ - -Parameters +#### Parameters Parameter| Type| Default| Description ---|---|---|--- @@ -461,11 +341,7 @@ Raises `ValueError` if `session_id` is not a valid UUID or `title` is empty; `FileNotFoundError` if the session cannot be found. -#### - -​ - -Example +#### Example Rename the most recent session so it’s easier to find later. The new title appears in `SDKSessionInfo.custom_title` on subsequent reads. @@ -475,11 +351,7 @@ if sessions: rename_session(sessions[0].session_id, "Refactor auth module") -### - -​ - -`tag_session()` +### `tag_session()` Tags a session. Pass `None` to clear the tag. Repeated calls are safe; the most recent tag wins. Synchronous. @@ -489,11 +361,7 @@ directory: str | None = None, ) -> None -#### - -​ - -Parameters +#### Parameters Parameter| Type| Default| Description ---|---|---|--- @@ -503,11 +371,7 @@ Raises `ValueError` if `session_id` is not a valid UUID or `tag` is empty after sanitization; `FileNotFoundError` if the session cannot be found. -#### - -​ - -Example +#### Example Tag a session, then filter by that tag on a later read. Pass `None` to clear an existing tag. @@ -523,11 +387,7 @@ if session.tag == "needs-review": print(session.summary) -### - -​ - -`fork_session()` +### `fork_session()` Copies a session’s transcript into a new session so you can take the conversation in another direction while the original stays unchanged. To branch from an earlier point in the conversation, pass `up_to_message_id`. Synchronous. @@ -538,11 +398,7 @@ title: str | None = None, ) -> ForkSessionResult -#### - -​ - -Parameters +#### Parameters Parameter| Type| Default| Description ---|---|---|--- @@ -557,11 +413,7 @@ * `ValueError`: the session has no messages, or `up_to_message_id` matches no message in the transcript * `FileNotFoundError`: the session cannot be found -#### - -​ - -Example +#### Example Fork the most recent session under a new title, then resume the fork. The original session keeps its own history. @@ -572,17 +424,9 @@ forked = fork_session(sessions[0].session_id, title="Try the OAuth approach") print(forked.session_id) # pass as ClaudeAgentOptions(resume=...) to continue the fork -## - -​ - -Classes - -### - -​ - -`ClaudeSDKClient` +## Classes + +### `ClaudeSDKClient` **Maintains a conversation session across multiple exchanges.** This is the Python equivalent of how the TypeScript SDK’s `query()` function works internally - it creates a client object that can continue conversations. See the comparison with `query()`. @@ -604,11 +448,7 @@ async def get_server_info(self) -> dict[str, Any] | None async def disconnect(self) -> None -#### - -​ - -Methods +#### Methods Method| Description ---|--- @@ -629,11 +469,7 @@ `get_server_info()`| Get the server’s initialization info, including available commands and output styles `disconnect()`| Disconnect from Claude -#### - -​ - -Context Manager Support +#### Context Manager Support The client can be used as an async context manager for automatic connection management: @@ -650,11 +486,7 @@ > **Important:** When iterating over messages, avoid using `break` to exit early as this can cause asyncio cleanup issues. Instead, let the iteration complete naturally or use flags to track when you’ve found what you need. -#### - -​ - -Example - Continuing a conversation +#### Example - Continuing a conversation import asyncio from claude_agent_sdk import ClaudeSDKClient, AssistantMessage, TextBlock, ResultMessage @@ -691,11 +523,7 @@ asyncio.run(main()) -#### - -​ - -Example - Streaming input with ClaudeSDKClient +#### Example - Streaming input with ClaudeSDKClient `query()` also accepts an async iterable of user message dicts, so you can assemble the prompt at send time or include content blocks such as images. Claude Code starts responding to the first yielded message as soon as it arrives, without waiting for the iterable to finish, and `receive_response()` stops at the `ResultMessage` that ends that response. Put everything Claude should read before answering into one message, as this generator does, and pair each `query()` call with its own `receive_response()` loop. @@ -731,11 +559,7 @@ asyncio.run(main()) -#### - -​ - -Example - Using interrupts +#### Example - Using interrupts import asyncio from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions, ResultMessage @@ -773,11 +597,7 @@ **Buffer behavior after interrupt:** `interrupt()` sends a stop signal but does not clear the message buffer. Messages already produced by the interrupted task, including its `ResultMessage`, remain in the stream. You must drain them with `receive_response()` before reading the response to a new query. If you send a new query immediately after `interrupt()` and call `receive_response()` only once, you’ll receive the interrupted task’s messages, not the new query’s response. -#### - -​ - -Example - Advanced permission control +#### Example - Advanced permission control import asyncio from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions @@ -821,19 +641,11 @@ asyncio.run(main()) -## - -​ - -Types +## Types **`@dataclass` vs `TypedDict`:** This SDK uses two kinds of types. Classes decorated with `@dataclass` (such as `ResultMessage`, `AgentDefinition`, `TextBlock`) are object instances at runtime and support attribute access: `msg.result`. Classes defined with `TypedDict` (such as `ThinkingConfigEnabled`, `McpStdioServerConfig`, `SyncHookJSONOutput`) are **plain dicts at runtime** and require key access: `config["budget_tokens"]`, not `config.budget_tokens`. The `ClassName(field=value)` call syntax works for both, but only dataclasses produce objects with attributes. -### - -​ - -`SdkMcpTool` +### `SdkMcpTool` Definition for an SDK MCP tool created with the `@tool` decorator. @@ -853,11 +665,7 @@ `handler`| `Callable[[T], Awaitable[dict[str, Any]]]`| Async function that handles tool execution `annotations`| `ToolAnnotations`` | None`| Optional tool annotations (for example `readOnlyHint`, `destructiveHint`, `openWorldHint`, `maxResultSizeChars`) -### - -​ - -`Transport` +### `Transport` Abstract base class for custom transport implementations. Use this to communicate with the Claude process over a custom channel (for example, a remote connection instead of a local subprocess). @@ -897,11 +705,7 @@ Import: `from claude_agent_sdk import Transport` -### - -​ - -`ClaudeAgentOptions` +### `ClaudeAgentOptions` Configuration dataclass for Claude Code queries. @@ -1009,11 +813,7 @@ `load_timeout_ms`| `int`| `60000`| Per-call timeout for `session_store.load()` and `list_subkeys()` during resume materialization, in milliseconds `task_budget`| `TaskBudget | None`| `None`| API-side token budget. Sent as `output_config.task_budget` with the `task-budgets-2026-03-13` beta header. Pass `{"total": <int>}`. -#### - -​ - -Handle slow or stalled API responses +#### Handle slow or stalled API responses The CLI subprocess reads several environment variables that control API timeouts and stall detection. Pass them through `ClaudeAgentOptions.env`: @@ -1032,11 +832,7 @@ * `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS`: stall watchdog for subagents. While the stream watchdog is on, the default is `CLAUDE_STREAM_IDLE_TIMEOUT_MS` plus 5 minutes, which comes to `600000` unless you raise that variable. With the stream watchdog off, the default is `600000`. Before v2.1.257, the default was always `600000`. The timer resets on each stream event. On a stall, Claude Code aborts the subagent and reports the stall to the parent. For a background subagent, it also marks the task failed and attaches any partial result. * `CLAUDE_ENABLE_STREAM_WATCHDOG` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: stream watchdog that aborts the request when headers have arrived but the response body stops streaming. The watchdog is on by default for all providers; set `CLAUDE_ENABLE_STREAM_WATCHDOG=0` to disable it. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. After the abort, [Automatic retries](</docs/en/errors#automatic-retries>) covers what Claude Code does, based on how far the response had progressed. While the watchdog waits out a response that a gateway behind `ANTHROPIC_BASE_URL` holds open with keep-alive pings, a host that sets `include_partial_messages` keeps receiving `ping` `StreamEvent` messages. Read those frames as liveness rather than timing the session out on silence. Before v2.1.257, the frames stopped 5 minutes after the last real stream event. -### - -​ - -`OutputFormat` +### `OutputFormat` Configuration for structured output validation. Pass this as a `dict` to the `output_format` field on `ClaudeAgentOptions`: @@ -1051,11 +847,7 @@ `type`| Yes| Must be `"json_schema"` for JSON Schema validation `schema`| Yes| JSON Schema definition for output validation -### - -​ - -`SystemPromptPreset` +### `SystemPromptPreset` Configuration for using Claude Code’s preset system prompt with optional additions. @@ -1074,11 +866,7 @@ `exclude_dynamic_sections`| No| Move per-user context, such as the auto memory location, from the system prompt into the first user message. Improves prompt-cache reuse across users and machines. See [Modify system prompts](</docs/en/agent-sdk/modifying-system-prompts#improve-prompt-caching-across-users-and-machines>) `snapshot`| No| Set to `False` to rebuild the system prompt on every request instead of [reusing the prompt the session recorded on its first request](</docs/en/agent-sdk/modifying-system-prompts#change-the-prompt-of-an-existing-session>). Requires `claude-agent-sdk` v0.2.153 or later -### - -​ - -`SystemPromptCustom` +### `SystemPromptCustom` A custom system prompt in object form, equivalent to passing a string as `system_prompt`, that can also set `snapshot`. Requires `claude-agent-sdk` v0.2.153 or later. @@ -1093,11 +881,7 @@ `prompt`| Yes| The system prompt text. Passed to the CLI as a command-line argument, so the command-line length limits apply `snapshot`| No| Same as `SystemPromptPreset.snapshot`, applied to `prompt` -### - -​ - -`SystemPromptFile` +### `SystemPromptFile` Configuration for loading a custom system prompt from a file instead of passing it as a string. The SDK maps this to the CLI [`--system-prompt-file`](</docs/en/cli-reference#system-prompt-flags>) flag. Use the file form when the prompt is large: the SDK passes a string `system_prompt` on the CLI subprocess argv, which is subject to OS command-line length limits before the SDK sends any API request. On Linux a single argument longer than roughly 128 KB fails at process spawn with `Argument list too long`. On Windows the whole command line is capped at roughly 32 KB, so the string form fails at a lower threshold. @@ -1110,11 +894,7 @@ `type`| Yes| Must be `"file"` to load the prompt from disk `path`| Yes| Path to a file containing the system prompt -### - -​ - -`SettingSource` +### `SettingSource` Controls which filesystem-based configuration sources the SDK loads settings from. @@ -1126,19 +906,11 @@ `"project"`| Shared project settings (version controlled)| `.claude/settings.json` `"local"`| Local project settings, gitignored when Claude Code saves a setting to it| `.claude/settings.local.json` -#### - -​ - -Default behavior +#### Default behavior When `setting_sources` is omitted or `None` and `skills` is not set, `query()` loads the same filesystem settings as the Claude Code CLI: user, project, and local. With `skills` set, the `setting_sources` row describes the current default. Endpoint-managed policy is loaded in all cases; server-managed settings are fetched when the session authenticates with an organization credential on an [eligible configuration](</docs/en/server-managed-settings#platform-availability>). For more information, see [What settingSources does not control](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>). -#### - -​ - -Why use setting_sources +#### Why use setting_sources **Disable filesystem settings:** @@ -1203,11 +975,7 @@ To load CLAUDE.md project instructions, include `"project"` in `setting_sources`. See [Modify system prompts](</docs/en/agent-sdk/modifying-system-prompts#claude-md-files-for-project-level-instructions>) for how CLAUDE.md loading interacts with the system prompt options. -#### - -​ - -Settings precedence +#### Settings precedence When multiple sources are loaded, settings are merged with this precedence (highest to lowest): @@ -1217,11 +985,7 @@ Programmatic options such as `agents`, `allowed_tools`, and `settings` override user, project, and local filesystem settings. Managed policy settings take precedence over programmatic options. -### - -​ - -`AgentDefinition` +### `AgentDefinition` Configuration for a subagent defined programmatically. @@ -1259,11 +1023,7 @@ `AgentDefinition` field names use camelCase, such as `disallowedTools`, `permissionMode`, and `maxTurns`. These names map directly to the wire format shared with the TypeScript SDK. This differs from `ClaudeAgentOptions`, which uses Python snake_case for the equivalent top-level fields such as `disallowed_tools` and `permission_mode`. Because `AgentDefinition` is a dataclass, passing a snake_case keyword raises a `TypeError` at construction time. -### - -​ - -`PermissionMode` +### `PermissionMode` Permission modes for controlling tool execution. @@ -1276,11 +1036,7 @@ "auto", # A model classifier reviews actions such as shell commands and network requests ] -### - -​ - -`EffortLevel` +### `EffortLevel` Effort levels for guiding thinking depth. @@ -1292,11 +1048,7 @@ "max", # Maximum effort ] -### - -​ - -`CanUseTool` +### `CanUseTool` Type alias for tool permission callback functions. @@ -1317,11 +1069,7 @@ To check those calls, use a [`PreToolUse` hook](</docs/en/agent-sdk/hooks>), which runs for them too. An allow rule doesn’t pre-approve the [actions no mode auto-approves](</docs/en/permission-modes#actions-no-mode-auto-approves>); see [How permissions are evaluated](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) for which of them reach the callback and what happens in `dontAsk` and `auto` mode. -### - -​ - -`ToolPermissionContext` +### `ToolPermissionContext` Context information passed to tool permission callbacks. @@ -1349,21 +1097,13 @@ `display_name`| `str | None`| Short noun phrase for the tool action, such as `Read file`, suitable for button labels `description`| `str | None`| Human-readable subtitle for the permission UI -### - -​ - -`PermissionResult` +### `PermissionResult` Union type for permission callback results. PermissionResult = PermissionResultAllow | PermissionResultDeny -### - -​ - -`PermissionResultAllow` +### `PermissionResultAllow` Result indicating the tool call should be allowed. @@ -1381,11 +1121,7 @@ If you return `PermissionResultAllow` with more than 4,096 items in `updated_permissions`, Claude Code treats the result as invalid and denies the tool call. Each `PermissionUpdate` counts as one item, and so does each entry in its `rules` or `directories` list. The denial message ends with `updatedPermissions may hold at most 4096 updates, rules and directories in all.` To avoid the denial, return 4,096 items or fewer. -### - -​ - -`PermissionResultDeny` +### `PermissionResultDeny` Result indicating the tool call should be denied. @@ -1401,11 +1137,7 @@ `message`| `str`| `""`| Message explaining why the tool was denied `interrupt`| `bool`| `False`| Whether to interrupt the current execution -### - -​ - -`PermissionUpdate` +### `PermissionUpdate` Configuration for updating permissions programmatically. @@ -1436,11 +1168,7 @@ `directories`| `list[str] | None`| Directories for add/remove directory operations `destination`| `Literal[...] | None`| Where to apply the permission update -### - -​ - -`PermissionRuleValue` +### `PermissionRuleValue` A rule to add, replace, or remove in a permission update. @@ -1449,11 +1177,7 @@ tool_name: str rule_content: str | None = None -### - -​ - -`ToolsPreset` +### `ToolsPreset` Preset tools configuration for using Claude Code’s default tool set. @@ -1461,11 +1185,7 @@ type: Literal["preset"] preset: Literal["claude_code"] -### - -​ - -`ThinkingConfig` +### `ThinkingConfig` Controls extended thinking behavior. A union of three configurations: @@ -1503,11 +1223,7 @@ print(config["budget_tokens"]) # 20000 # config.budget_tokens would raise AttributeError -### - -​ - -`TaskBudget` +### `TaskBudget` API-side task budget in tokens, used with the `task_budget` field in `ClaudeAgentOptions`. @@ -1520,11 +1236,7 @@ Because this is a `TypedDict`, pass it as a plain dict, such as `ClaudeAgentOptions(task_budget={"total": 50000})`. -### - -​ - -`SdkBeta` +### `SdkBeta` Literal type for SDK beta features. @@ -1534,11 +1246,7 @@ On the Claude API, the `context-1m-2025-08-07` beta is retired for Claude Sonnet 4.5 and Claude Sonnet 4. If you still pass it with either model, requests that exceed the standard 200K-token context window return an error, so remove it from `betas`. To run a session with a 1M-token context window, set `model` to a model that [runs with the 1M window by default](</docs/en/model-config#extended-context>), such as `claude-sonnet-5-5` or `claude-opus-5-5`. For a model that reaches 1M only through its `[1m]` variant, append the suffix to the model ID, as in `claude-opus-4-6[1m]`. -### - -​ - -`McpSdkServerConfig` +### `McpSdkServerConfig` Configuration for SDK MCP servers created with `create_sdk_mcp_server()`. @@ -1547,11 +1255,7 @@ name: str instance: Any # MCP Server instance -### - -​ - -`McpServerConfig` +### `McpServerConfig` Union type for MCP server configurations. @@ -1559,11 +1263,7 @@ McpStdioServerConfig | McpSSEServerConfig | McpHttpServerConfig | McpSdkServerConfig ) -#### - -​ - -`McpStdioServerConfig` +#### `McpStdioServerConfig` class McpStdioServerConfig(TypedDict): type: NotRequired[Literal["stdio"]] # Optional for backwards compatibility @@ -1571,33 +1271,21 @@ args: NotRequired[list[str]] env: NotRequired[dict[str, str]] -#### - -​ - -`McpSSEServerConfig` +#### `McpSSEServerConfig` class McpSSEServerConfig(TypedDict): type: Literal["sse"] url: str headers: NotRequired[dict[str, str]] -#### - -​ - -`McpHttpServerConfig` +#### `McpHttpServerConfig` class McpHttpServerConfig(TypedDict): type: Literal["http"] url: str headers: NotRequired[dict[str, str]] -### - -​ - -`McpServerStatusConfig` +### `McpServerStatusConfig` The configuration of an MCP server as reported by `get_mcp_status()`. This is the union of all `McpServerConfig` transport variants plus an output-only `claudeai-proxy` variant for servers proxied through claude.ai. @@ -1611,22 +1299,14 @@ `McpSdkServerConfigStatus` is the serializable form of `McpSdkServerConfig` with only `type` (`"sdk"`) and `name` (`str`) fields; the in-process `instance` is omitted. `McpClaudeAIProxyServerConfig` has `type` (`"claudeai-proxy"`), `url` (`str`), and `id` (`str`) fields. -### - -​ - -`McpStatusResponse` +### `McpStatusResponse` Response from `ClaudeSDKClient.get_mcp_status()`. Wraps the list of server statuses under the `mcpServers` key. class McpStatusResponse(TypedDict): mcpServers: list[McpServerStatus] -### - -​ - -`McpServerStatus` +### `McpServerStatus` Status of a connected MCP server, contained in `McpStatusResponse`. @@ -1649,11 +1329,7 @@ `scope`| `str` (optional)| Configuration scope `tools`| `list` (optional)| Tools provided by this server, each with `name`, `description`, and `annotations` fields -### - -​ - -`ContextUsageResponse` +### `ContextUsageResponse` Response from `ClaudeSDKClient.get_context_usage()`. The response includes the payload Claude Code renders for the `/context` command in an interactive session. Alongside the token counts, that payload carries display fields such as `color` and `gridRows` that Claude Code uses to draw the `/context` usage grid. Claude Code builds this payload by sending several requests to the [token-counting](<https://platform.claude.com/docs/en/build-with-claude/token-counting>) API. These requests don’t appear in the message stream, so cost tracking that reads the stream won’t see them. On the Anthropic API, token counting isn’t billed. @@ -1680,11 +1356,7 @@ Each `ContextUsageCategory` entry carries `name`, `tokens`, `color`, and an optional `isDeferred` flag. `totalTokens` is the session’s current context usage, and `maxTokens` is the window that usage is measured against. That window is the model’s context window, or the lower auto-compaction window when one applies, and `rawMaxTokens` carries the same value as `maxTokens`. `apiUsage` holds the usage from the latest API response, not a running total for the session. Claude Code leaves the optional `deferredBuiltinTools`, `systemTools`, and `systemPromptSections` keys unset, so expect them to be absent even though the type declares them. -### - -​ - -`SdkPluginConfig` +### `SdkPluginConfig` Configuration for loading plugins in the SDK. @@ -1706,17 +1378,9 @@ For complete information on creating and using plugins, see [Plugins](</docs/en/agent-sdk/plugins>). -## - -​ - -Message Types - -### - -​ - -`Message` +## Message Types + +### `Message` Union type of all possible messages. @@ -1730,11 +1394,7 @@ | ConversationResetMessage ) -### - -​ - -`UserMessage` +### `UserMessage` User input message. @@ -1756,11 +1416,7 @@ The SDK passes `tool_use_result` through from the CLI unmodified. For a tool on an external MCP server whose result contains `resource_link` blocks, the dict has a `resourceLinks` key holding a list of dicts with the keys of the TypeScript [`SDKMcpResourceLink`](</docs/en/agent-sdk/typescript#sdkmcpresourcelink>) type. Claude receives each link as a line of text in the tool result. To render the files the server returned, read `resourceLinks` instead of parsing that text. The `resourceLinks` key requires Python Agent SDK 0.2.150 or later and Claude Code v2.1.257 or later; the CLI bundled with that SDK version satisfies the Claude Code requirement. The CLI omits the key when the result has no links and on results from subagents. The CLI keeps at most 50 links per result and stops adding links once the list reaches 64 KiB of serialized JSON. A tool you define in-process with `tool()` never produces the key, because the SDK flattens its `resource_link` blocks to text before the CLI sees the result. -### - -​ - -`AssistantMessage` +### `AssistantMessage` Assistant response message with content blocks. @@ -1788,11 +1444,7 @@ `session_id`| `str | None`| ID of the session this message belongs to `uuid`| `str | None`| Unique message identifier within the session transcript -### - -​ - -`AssistantMessageError` +### `AssistantMessageError` Possible error types for assistant messages. @@ -1807,11 +1459,7 @@ The underlying CLI process can emit error types this Literal doesn’t list, such as `max_output_tokens`. The SDK passes the value through unmodified, so treat strings outside this list the way you treat `unknown`. The TypeScript [`SDKAssistantMessageError`](</docs/en/agent-sdk/typescript#sdkassistantmessage>) type lists the full set of values the CLI can emit. -### - -​ - -`SystemMessage` +### `SystemMessage` System message with metadata. @@ -1822,11 +1470,7 @@ Subtypes that have no dataclass of their own arrive as `SystemMessage`. To follow the session between turns, set [`CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS=1`](</docs/en/env-vars#variables>) and read `message.data["state"]` on each message whose `subtype` is `session_state_changed`. [`SDKSessionStateChangedMessage`](</docs/en/agent-sdk/typescript#sdksessionstatechangedmessage>) lists the states it can carry. Iterate with `receive_messages()` to read them: `receive_response()` stops at the `ResultMessage`, and a `session_state_changed` message can follow that result. -### - -​ - -`ResultMessage` +### `ResultMessage` Final result message with cost and usage information. @@ -1892,11 +1536,7 @@ `provider`| `str`| API provider that served this model, such as `firstParty`, `bedrock`, `vertex`, `foundry`, `anthropicAws`, `mantle`, or `gateway`. Not always present. `costBasis`| `str`| Price table that priced this model’s latest request: `list` for list price, `managed` for a [`modelPricing`](</docs/en/settings-reference#modelpricing>) table, or `unknown` when neither matched the model ID. Not always present, and not declared on the TypedDict, so read it with `.get()`. Requires Claude Code v2.1.246 or later. -### - -​ - -`StreamEvent` +### `StreamEvent` Stream event for partial message updates during streaming. Only received when `include_partial_messages=True` in `ClaudeAgentOptions`. Import via `from claude_agent_sdk.types import StreamEvent`. @@ -1914,11 +1554,7 @@ `event`| `dict[str, Any]`| The raw Claude API stream event data `parent_tool_use_id`| `str | None`| Always `None`. Stream events are emitted for the main session only. For subagent attribution, use complete messages such as `AssistantMessage` -### - -​ - -`RateLimitEvent` +### `RateLimitEvent` Emitted when rate limit status changes (for example, from `"allowed"` to `"allowed_warning"`). Use this to warn users before they hit a hard limit, or to back off when status is `"rejected"`. @@ -1934,11 +1570,7 @@ `uuid`| `str`| Unique event identifier `session_id`| `str`| Session identifier -### - -​ - -`RateLimitInfo` +### `RateLimitInfo` Rate limit state carried by `RateLimitEvent`. @@ -1969,11 +1601,7 @@ `overage_disabled_reason`| `str | None`| Why overage is unavailable, if status is `"rejected"` `raw`| `dict[str, Any]`| Full raw dict from the CLI, including fields not modeled above -### - -​ - -`ConversationResetMessage` +### `ConversationResetMessage` Emitted when the conversation is replaced without ending the connection, such as after `/clear`. See [Track costs in streaming input mode](</docs/en/agent-sdk/cost-tracking#track-costs-in-streaming-input-mode>) for how a reset affects the running totals on later `ResultMessage` objects. Requires Python Agent SDK 0.2.137 or later. @@ -1989,11 +1617,7 @@ `uuid`| `str`| Unique message identifier `session_id`| `str`| ID of the session that was reset. Messages after the reset carry a new `session_id` -### - -​ - -`TaskStartedMessage` +### `TaskStartedMessage` Emitted when a background task starts. A background task is anything tracked outside the main turn, such as a backgrounded Bash command, a Monitor watch, a subagent spawned via the Agent tool, or a remote agent. This naming is unrelated to the `Task`-to-`Agent` tool rename. @@ -2015,11 +1639,7 @@ `tool_use_id`| `str | None`| Associated tool use ID `task_type`| `str | None`| Which kind of background task, such as `"local_bash"` for background Bash and Monitor watches, `"local_agent"` for subagents, `"mcp_task"` for [background MCP tool calls](</docs/en/mcp#automatic-backgrounding-of-long-tool-calls>), or `"remote_agent"` -### - -​ - -`TaskUsage` +### `TaskUsage` Token and timing data for a background task. @@ -2028,11 +1648,7 @@ tool_uses: int duration_ms: int -### - -​ - -`TaskProgressMessage` +### `TaskProgressMessage` Emitted periodically with progress updates for a running background task. @@ -2056,11 +1672,7 @@ `tool_use_id`| `str | None`| Associated tool use ID `last_tool_name`| `str | None`| Name of the last tool the task used -### - -​ - -`TaskNotificationMessage` +### `TaskNotificationMessage` Emitted when a background task completes, fails, or is stopped. Background tasks include `run_in_background` Bash commands, Monitor watches, and background subagents. @@ -2088,17 +1700,9 @@ When the CLI [moves a long MCP tool call to the background](</docs/en/mcp#automatic-backgrounding-of-long-tool-calls>), the tool result for that call holds only a placeholder and the call’s real result arrives in this message. On a `"completed"` notification for such a call, the CLI adds a `resource_links` key listing the files the tool returned by reference, with the same entries and limits as the `resourceLinks` key on `UserMessage.tool_use_result`. The `resource_links` key requires Python Agent SDK 0.2.150 or later and Claude Code v2.1.257 or later; the CLI bundled with that SDK version satisfies the Claude Code requirement. The dataclass has no field for `resource_links`. Read it from the `data` dict the message inherits from `SystemMessage`: `message.data.get("resource_links")`. Match the notification to the call with `tool_use_id`. The CLI omits the key when the result had no links and on notifications for tasks that aren’t MCP tool calls. -## - -​ - -Content Block Types - -### - -​ - -`ContentBlock` +## Content Block Types + +### `ContentBlock` Union type of all content blocks. @@ -2111,11 +1715,7 @@ | ServerToolResultBlock ) -### - -​ - -`TextBlock` +### `TextBlock` Text content block. @@ -2123,11 +1723,7 @@ class TextBlock: text: str -### - -​ - -`ThinkingBlock` +### `ThinkingBlock` Thinking content block (for models with thinking capability). @@ -2136,11 +1732,7 @@ thinking: str signature: str -### - -​ - -`ToolUseBlock` +### `ToolUseBlock` Tool use request block. @@ -2150,11 +1742,7 @@ name: str input: dict[str, Any] -### - -​ - -`ToolResultBlock` +### `ToolResultBlock` Tool execution result block. @@ -2164,19 +1752,11 @@ content: str | list[dict[str, Any]] | None = None is_error: bool | None = None -## - -​ - -Error Types +## Error Types The types below define what your code catches. For entries keyed to the error messages these types raise, with the cause and fix for each, see [Troubleshooting](</docs/en/agent-sdk/troubleshooting>). -### - -​ - -`ClaudeSDKError` +### `ClaudeSDKError` Base exception class for all SDK errors. @@ -2185,11 +1765,7 @@ When a single-shot `query()` ends with an error result, for example a turn-limit error, the SDK raises a `ResultError`. -### - -​ - -`CLINotFoundError` +### `CLINotFoundError` Raised when Claude Code CLI is not installed or not found. @@ -2203,22 +1779,14 @@ cli_path: Optional path to the CLI that was not found """ -### - -​ - -`CLIConnectionError` +### `CLIConnectionError` Raised when connection to Claude Code fails. class CLIConnectionError(ClaudeSDKError): """Failed to connect to Claude Code.""" -### - -​ - -`ProcessError` +### `ProcessError` Raised when the Claude Code process fails. @@ -2229,11 +1797,7 @@ self.exit_code = exit_code self.stderr = stderr -### - -​ - -`ResultError` +### `ResultError` Raised when the Claude Code process exits because the run ended with an error result message, such as a turn-limit error or an API error. `ResultError` subclasses `ProcessError`, so an existing `except ProcessError` handler also catches it. Its attributes carry the fields of that result message, so you can branch on why the run failed without parsing the message text. Requires Python Agent SDK 0.2.140 or later. @@ -2248,11 +1812,7 @@ To tell failures apart, check `data["stop_reason"]` first, then `terminal_reason`, then `subtype`. A declined response has `stop_reason` `"refusal"`, usually with `subtype` `"success"`; its `terminal_reason` doesn’t single it out and can read `"completed"` or `"api_error"`. A failed final request has `subtype` `"success"` and its cause in `terminal_reason`, such as `"api_error"` for an API error. When the run hits a limit you set, such as `max_turns` or `max_budget_usd`, you get an `error_*` subtype. -### - -​ - -`CLIJSONDecodeError` +### `CLIJSONDecodeError` Raised when JSON parsing fails. @@ -2266,19 +1826,11 @@ self.line = line self.original_error = original_error -## - -​ - -Hook Types +## Hook Types For a comprehensive guide on using hooks with examples and common patterns, see the [Hooks guide](</docs/en/agent-sdk/hooks>). -### - -​ - -`HookEvent` +### `HookEvent` Supported hook event types. @@ -2297,11 +1849,7 @@ The TypeScript SDK supports additional hook events not yet available in Python. See the [hook availability table](</docs/en/agent-sdk/hooks#available-hooks>) for per-SDK support. -### - -​ - -`HookCallback` +### `HookCallback` Type definition for hook callback functions. @@ -2315,22 +1863,14 @@ Returns a `HookJSONOutput`. -### - -​ - -`HookContext` +### `HookContext` Context information passed to hook callbacks. class HookContext(TypedDict): signal: Any | None # Future: abort signal support -### - -​ - -`HookMatcher` +### `HookMatcher` Configuration for matching hooks to specific events or tools. @@ -2352,11 +1892,7 @@ To decide what `on_failure` covers, see [Block the action when a callback fails](</docs/en/agent-sdk/hooks#block-the-action-when-a-callback-fails>). -### - -​ - -`HookInput` +### `HookInput` Union type of all hook input types. The actual type depends on the `hook_event_name` field. @@ -2373,11 +1909,7 @@ | PermissionRequestHookInput ) -### - -​ - -`BaseHookInput` +### `BaseHookInput` Base fields present in all hook input types. @@ -2394,11 +1926,7 @@ `cwd`| `str`| Current working directory `permission_mode`| `str` (optional)| Current permission mode -### - -​ - -`PreToolUseHookInput` +### `PreToolUseHookInput` Input data for `PreToolUse` hook events. @@ -2419,11 +1947,7 @@ `agent_id`| `str` (optional)| Subagent identifier, present when the hook fires inside a subagent `agent_type`| `str` (optional)| Subagent type, present when the hook fires inside a subagent -### - -​ - -`PostToolUseHookInput` +### `PostToolUseHookInput` Input data for `PostToolUse` hook events. @@ -2446,11 +1970,7 @@ `agent_id`| `str` (optional)| Subagent identifier, present when the hook fires inside a subagent `agent_type`| `str` (optional)| Subagent type, present when the hook fires inside a subagent -### - -​ - -`PostToolUseFailureHookInput` +### `PostToolUseFailureHookInput` Input data for `PostToolUseFailure` hook events. Called when a tool execution fails. @@ -2475,11 +1995,7 @@ `agent_id`| `str` (optional)| Subagent identifier, present when the hook fires inside a subagent `agent_type`| `str` (optional)| Subagent type, present when the hook fires inside a subagent -### - -​ - -`UserPromptSubmitHookInput` +### `UserPromptSubmitHookInput` Input data for `UserPromptSubmit` hook events. @@ -2492,11 +2008,7 @@ `hook_event_name`| `Literal["UserPromptSubmit"]`| Always “UserPromptSubmit” `prompt`| `str`| The submitted prompt -### - -​ - -`StopHookInput` +### `StopHookInput` Input data for `Stop` hook events. @@ -2509,11 +2021,7 @@ `hook_event_name`| `Literal["Stop"]`| Always “Stop” `stop_hook_active`| `bool`| Whether the stop hook is active -### - -​ - -`SubagentStopHookInput` +### `SubagentStopHookInput` Input data for `SubagentStop` hook events. @@ -2532,11 +2040,7 @@ `agent_transcript_path`| `str`| Path to the subagent’s transcript file `agent_type`| `str`| Type of the subagent -### - -​ - -`PreCompactHookInput` +### `PreCompactHookInput` Input data for `PreCompact` hook events. @@ -2551,11 +2055,7 @@ `trigger`| `Literal["manual", "auto"]`| What triggered the compaction `custom_instructions`| `str | None`| Custom instructions for compaction -### - -​ - -`NotificationHookInput` +### `NotificationHookInput` Input data for `Notification` hook events. @@ -2572,11 +2072,7 @@ `title`| `str` (optional)| Notification title `notification_type`| `str`| Type of notification -### - -​ - -`SubagentStartHookInput` +### `SubagentStartHookInput` Input data for `SubagentStart` hook events. @@ -2591,11 +2087,7 @@ `agent_id`| `str`| Unique identifier for the subagent `agent_type`| `str`| Type of the subagent -### - -​ - -`PermissionRequestHookInput` +### `PermissionRequestHookInput` Input data for `PermissionRequest` hook events. Allows hooks to handle permission decisions programmatically. @@ -2616,21 +2108,13 @@ `agent_id`| `str` (optional)| Subagent identifier, present when the hook fires inside a subagent `agent_type`| `str` (optional)| Subagent type, present when the hook fires inside a subagent -### - -​ - -`HookJSONOutput` +### `HookJSONOutput` Union type for hook callback return values. HookJSONOutput = AsyncHookJSONOutput | SyncHookJSONOutput -#### - -​ - -`SyncHookJSONOutput` +#### `SyncHookJSONOutput` Synchronous hook output with control and decision fields. @@ -2650,11 +2134,7 @@ Use `continue_` (with underscore) in Python code. It is automatically converted to `continue` when sent to the CLI. -#### - -​ - -`HookSpecificOutput` +#### `HookSpecificOutput` A discriminated union of event-specific `TypedDict` output types. The `hookEventName` field determines which fields are valid. For full details on available fields per hook event, see [Control execution with hooks](</docs/en/agent-sdk/hooks#outputs>). @@ -2701,11 +2181,7 @@ | PermissionRequestHookSpecificOutput ) -#### - -​ - -`AsyncHookJSONOutput` +#### `AsyncHookJSONOutput` Async hook output that defers hook execution. @@ -2715,11 +2191,7 @@ Use `async_` (with underscore) in Python code. It is automatically converted to `async` when sent to the CLI. -### - -​ - -Hook Usage Example +### Hook Usage Example This example registers two hooks: one that blocks dangerous Bash commands like `rm -rf /`, and another that logs all tool usage for auditing. With its [`Bash` matcher](</docs/en/agent-sdk/hooks#matchers>), the security hook runs on Bash tool calls. The logging hook has no matcher, so it runs on every tool call. @@ -2770,19 +2242,11 @@ asyncio.run(main()) -## - -​ - -Tool Input/Output Types +## Tool Input/Output Types Documentation of input/output schemas for built-in Claude Code tools. While the Python SDK doesn’t export these as types, they represent the structure of tool inputs and outputs in messages. Each output shown is the value you read from `UserMessage.tool_use_result` for that tool. Key names appear exactly as Claude Code emits them. A key annotated `| None` with a “present when” or “optional” comment is omitted when it doesn’t apply. -### - -​ - -Agent +### Agent **Tool name:** `Agent`. The previous name `Task` is still accepted as an alias when this tool is available to the session. The `tools` list in the init `SystemMessage` reports this tool as `Task` for backward compatibility. **Input:** @@ -2878,11 +2342,7 @@ Returns the result from the subagent. The output is discriminated on the `status` field: `"completed"` for finished tasks, `"async_launched"` for background tasks, and `"remote_launched"` for tasks Claude Code dispatched to a cloud session, where `sessionUrl` links to that session and `taskId` identifies it. If Claude Code [kept the subagent’s isolated worktree](</docs/en/worktrees#isolate-subagents-with-worktrees>), `worktreePath` on the `completed` variant is where to find it, and `worktreeBranch` is its branch when Claude Code created the worktree with git. On the `completed` variant, `resolvedModel` names the model the subagent started on, which can differ from the requested `model` input when [`availableModels`](</docs/en/model-config#restrict-model-selection>) or another override applies. This field requires Claude Code v2.1.174 or later. On the `async_launched` variant, `resolvedModel` names the model in use when the agent moved to the background, so a swap that happened before backgrounding is reflected there. The `modelsUsed` field on both variants lists the models used in order, with consecutive repeats collapsed; it’s set only when the model was swapped mid-run. `modelsUsed` and the backgrounding-time `resolvedModel` behavior require Claude Code v2.1.212 or later. Claude Code fills `usage` and `totalTokens` from the subagent’s final API request, not from the whole run. When present, `thinking_tokens` under `output_tokens_details` in `usage` is the number of that request’s output tokens that were thinking tokens. The `output_tokens_details` key requires Python SDK v0.2.136 or later, which bundles Claude Code v2.1.228. The `fallback_credit` key requires Python SDK v0.2.162 or later, which bundles Claude Code v2.1.285. -### - -​ - -AskUserQuestion +### AskUserQuestion **Tool name:** `AskUserQuestion` Asks the user clarifying questions during execution. See [Handle approvals and user input](</docs/en/agent-sdk/user-input#handle-clarifying-questions>) for usage details. **Input:** @@ -2932,11 +2392,7 @@ "afkTimeoutMs": int | None, # Set when the dialog auto-resolved after this many milliseconds of user inactivity; absent when the user answered } -### - -​ - -Bash +### Bash **Tool name:** `Bash` For what sets the foreground ceiling, see [Timeout and output limits](</docs/en/tools-reference#timeout-and-output-limits>). For the background time limit, see [Time limit for background commands](</docs/en/tools-reference#time-limit-for-background-commands>). **Input:** @@ -2957,11 +2413,7 @@ "backgroundTaskId": str | None, # ID of the background task if command is running in background } -### - -​ - -Monitor +### Monitor **Tool name:** `Monitor` Runs a background source and delivers each event to Claude so it can react without polling: `command` runs a script and emits one event per stdout line, and `ws` opens a WebSocket and emits one event per text frame. Provide exactly one of `command` or `ws`. The `ws` source requires Claude Code v2.1.195 or later. When Monitor runs a command, it follows the same permission rules as Bash. See the [Monitor tool reference](</docs/en/tools-reference#monitor-tool>) for WebSocket permissions, behavior, and provider availability. **Input:** @@ -2980,11 +2432,7 @@ "persistent": bool | None, # False: every watch has a deadline } -### - -​ - -Edit +### Edit **Tool name:** `Edit` **Input:** @@ -3024,11 +2472,7 @@ } | None, } -### - -​ - -Read +### Read **Tool name:** `Read` **Input:** @@ -3113,11 +2557,7 @@ "source": "seeded" | None, # Present when the earlier copy came from a CLAUDE.md or memory file loaded at startup rather than a Read call } -### - -​ - -Write +### Write **Tool name:** `Write` **Input:** @@ -3154,11 +2594,7 @@ "userModified": bool | None, # Optional; whether the user edited the proposed content before accepting it } -### - -​ - -Glob +### Glob **Tool name:** `Glob` **Input:** @@ -3180,11 +2616,7 @@ `totalMatches` and `countIsComplete` require Claude Code v2.1.191 or later. -### - -​ - -Grep +### Grep **Tool name:** `Grep` **Input:** @@ -3223,11 +2655,7 @@ Grep returns this dict shape in each output mode. Which optional keys are present depends on `output_mode`. `totalFiles` requires Claude Code v2.1.208 or later. `totalLines` requires Claude Code v2.1.210 or later. -### - -​ - -NotebookEdit +### NotebookEdit **Tool name:** `NotebookEdit` **Input:** @@ -3254,11 +2682,7 @@ "updated_file": str, # Notebook content after the edit } -### - -​ - -WebFetch +### WebFetch **Tool name:** `WebFetch` **Input:** @@ -3279,11 +2703,7 @@ "url": str, # URL that was fetched } -### - -​ - -WebSearch +### WebSearch **Tool name:** `WebSearch` **Input:** @@ -3301,11 +2721,7 @@ "durationSeconds": float, # Search duration in seconds } -### - -​ - -TodoWrite +### TodoWrite **Tool name:** `TodoWrite` @@ -3317,7 +2733,7 @@ * `TaskUpdate` * `TaskList` -Wherever the tools are available, Claude Code provides the four Task tools, or `TodoWrite` instead when you set `CLAUDE_CODE_ENABLE_TASKS=0`.This default set applies in Claude Code v2.1.268 and later, which the TypeScript Agent SDK bundles from v0.3.268.See [Model availability](</docs/en/agent-sdk/todo-tracking#model-availability>) to opt in. +Wherever the tools are available, Claude Code provides the four Task tools, or `TodoWrite` instead when you set `CLAUDE_CODE_ENABLE_TASKS=0`. This default set applies in Claude Code v2.1.268 and later, which the TypeScript Agent SDK bundles from v0.3.268.See [Model availability](</docs/en/agent-sdk/todo-tracking#model-availability>) to opt in. **Input:** @@ -3350,11 +2766,7 @@ ], } -### - -​ - -TaskCreate +### TaskCreate **Tool name:** `TaskCreate` **Input:** @@ -3371,11 +2783,7 @@ "task": {"id": str, "subject": str}, # Created task with assigned ID } -### - -​ - -TaskUpdate +### TaskUpdate **Tool name:** `TaskUpdate` **Input:** @@ -3401,11 +2809,7 @@ "statusChange": {"from": str, "to": str} | None, } -### - -​ - -TaskGet +### TaskGet **Tool name:** `TaskGet` **Input:** @@ -3426,11 +2830,7 @@ } | None, # None when the ID is not found } -### - -​ - -TaskList +### TaskList **Tool name:** `TaskList` **Input:** @@ -3450,19 +2850,11 @@ ], } -### - -​ - -TaskOutput +### TaskOutput Removed in Claude Code v2.1.277. Previously retrieved output from a running or completed background task, with `BashOutput` accepted as an alias; Claude reads a background task’s output file with `Read` instead. A `disallowed_tools` entry or a deny rule that still names either name is ignored without a warning. -### - -​ - -TaskStop +### TaskStop **Tool name:** `TaskStop`. You can still use the previous names `KillShell` and `KillBash` in permission rules, in hook matchers, and in the `tools`, `allowed_tools`, and `disallowed_tools` options. **Input:** @@ -3480,11 +2872,7 @@ "command": str | None, # The command or description of the stopped task } -### - -​ - -ExitPlanMode +### ExitPlanMode **Tool name:** `ExitPlanMode` **Input:** @@ -3504,11 +2892,7 @@ "requestId": str | None, # Optional ID of that approval request } -### - -​ - -ListMcpResources +### ListMcpResources **Tool name:** `ListMcpResourcesTool` **Input:** @@ -3528,11 +2912,7 @@ } ] -### - -​ - -ReadMcpResource +### ReadMcpResource **Tool name:** `ReadMcpResourceTool` **Input:** @@ -3555,11 +2935,7 @@ "error": str | None, # Present when the server couldn't read the resource } -## - -​ - -Build a continuous conversation interface +## Build a continuous conversation interface The following example keeps one `ClaudeSDKClient` connected across turns, so Claude remembers earlier messages. Type `new` to disconnect and reconnect for a fresh session, or `exit` to end the conversation. @@ -3635,11 +3011,7 @@ asyncio.run(main()) -## - -​ - -Error handling +## Error handling The following example wraps a `query()` call in handlers for four of the error types the SDK raises. This example catches `ResultError`, which requires Python Agent SDK 0.2.140 or later. @@ -3678,17 +3050,9 @@ asyncio.run(main()) -## - -​ - -Sandbox Configuration - -### - -​ - -`SandboxSettings` +## Sandbox Configuration + +### `SandboxSettings` Configuration for sandbox behavior. Use this to enable command sandboxing and configure network restrictions programmatically. @@ -3715,11 +3079,7 @@ To keep sandboxed commands from writing to a file, list its absolute path under [`denyWrite`](</docs/en/settings-reference#sandbox-filesystem-denywrite>) in your sandbox settings, such as `"filesystem": {"denyWrite": ["/home/user/project/.env"]}`. The SDK forwards `filesystem` to Claude Code along with the declared `SandboxSettings` fields. Once the sandbox starts, it blocks writes to each absolute path you listed. -#### - -​ - -Example usage +#### Example usage import asyncio @@ -3748,11 +3108,7 @@ **Unix socket security** : The `allowUnixSockets` option can grant access to system services that reach outside the sandbox. For example, allowing `/var/run/docker.sock` effectively grants full host system access through the Docker API, bypassing sandbox isolation. Only allow Unix sockets that are strictly necessary and understand the security implications of each. -### - -​ - -`SandboxNetworkConfig` +### `SandboxNetworkConfig` Network-specific configuration for sandbox mode. These settings apply to sandboxed Bash commands when `enabled` is `True` in the parent `SandboxSettings`. They do not restrict the WebFetch tool, which uses [permission rules](</docs/en/permissions#webfetch>) instead. @@ -3781,21 +3137,13 @@ The built-in sandbox proxy enforces the network allowlist based on the requested hostname. By default, the proxy doesn’t terminate or inspect TLS traffic, so techniques such as [domain fronting](<https://en.wikipedia.org/wiki/Domain_fronting>) can potentially bypass the allowlist. See [Sandboxing security limitations](</docs/en/sandboxing#security-limitations>) for details and [Secure deployment](</docs/en/agent-sdk/secure-deployment#traffic-forwarding>) for configuring a TLS-terminating proxy. -### - -​ - -`SandboxIgnoreViolations` +### `SandboxIgnoreViolations` Violations to leave out of the sandbox’s violation report. Each key matches part of a command, or `*` for every command, and each value lists text to match in a violation line: `{"*": ["/etc/hosts"]}` hides violations that mention `/etc/hosts`. A matching access is still blocked. See [`sandbox.ignoreViolations`](</docs/en/settings-reference#sandbox-ignoreviolations>). SandboxIgnoreViolations = dict[str, list[str]] -### - -​ - -Permissions Fallback for Unsandboxed Commands +### Permissions Fallback for Unsandboxed Commands When `allowUnsandboxedCommands` is enabled, the model can request to run commands outside the sandbox by setting `dangerouslyDisableSandbox: True` in the tool input. These requests fall back to the existing permissions system, meaning your `can_use_tool` handler is invoked, allowing you to implement custom authorization logic. Your `excludedCommands` entries instead take a call out of the sandbox with no model involvement; [`sandbox.excludedCommands`](</docs/en/settings-reference#sandbox-excludedcommands>) covers when an entry applies. The following example logs each unsandboxed request and denies it unless your own authorization logic allows it: @@ -3857,11 +3205,7 @@ Commands running with `dangerouslyDisableSandbox: True` have full system access. Ensure your `can_use_tool` handler validates these requests carefully.If `permission_mode` is set to `bypassPermissions` and `allowUnsandboxedCommands` is enabled, the model can autonomously execute commands outside the sandbox without approval prompts, apart from the [actions no mode auto-approves](</docs/en/permission-modes#actions-no-mode-auto-approves>). This combination effectively allows the model to escape sandbox isolation silently. -## - -​ - -See also +## See also * [SDK overview](</docs/en/agent-sdk/overview>) \- General SDK concepts * [TypeScript SDK reference](</docs/en/agent-sdk/typescript>) \- TypeScript SDK documentation
modified Quickstart View current →
Show diff (116 lines)
--- a/quickstart.md +++ b/quickstart.md @@ -4,20 +4,12 @@ 2. Create a file with some buggy code 3. Run an agent that finds and fixes the bugs automatically -## - -​ - -Prerequisites +## Prerequisites * **Node.js 18.14+** or **Python 3.10+** * An **Anthropic account**. If you don’t have one, [sign up here](<https://platform.claude.com/>). -## - -​ - -Setup +## Setup 1 @@ -105,11 +97,7 @@ Unless previously approved, Anthropic does not allow third party developers to offer claude.ai login or rate limits for their products, including agents built on the Claude Agent SDK. Use the API key authentication methods described in this document instead. -## - -​ - -Create a buggy file +## Create a buggy file This quickstart walks you through building an agent that can find and fix bugs in code. First, you need a file with some intentional bugs for the agent to fix. Create `utils.py` in the `my-agent` directory and paste the following code: @@ -127,11 +115,7 @@ 1. `calculate_average([])` crashes with division by zero 2. `get_user_name(None)` crashes with a TypeError -## - -​ - -Build an agent that finds and fixes bugs +## Build an agent that finds and fixes bugs Create `agent.py` if you’re using the Python SDK, or `agent.ts` for TypeScript. Use `agent.mts` instead if your existing project uses CommonJS: @@ -197,11 +181,7 @@ This example uses streaming to show progress in real-time. If you don’t need live output (for example, for background jobs or CI pipelines), you can collect all messages at once. See [Streaming vs. single-turn mode](</docs/en/agent-sdk/streaming-vs-single-mode>) for details. -### - -​ - -Run your agent +### Run your agent Your agent is ready. Run it with the following command: @@ -231,11 +211,7 @@ If you see an authentication error such as `Not logged in` or `Invalid API key`, make sure you’ve set the `ANTHROPIC_API_KEY` environment variable in the shell where you run your agent. The SDK doesn’t load `.env` files automatically.For the causes and fixes behind these and other authentication errors, see [Authentication errors](</docs/en/errors#authentication-errors>) in the Error reference. -### - -​ - -Try other prompts +### Try other prompts Now that your agent is set up, try some different prompts: @@ -243,11 +219,7 @@ * `"Add type hints to all functions in utils.py"` * `"Create a README.md documenting the functions in utils.py"` -### - -​ - -Customize your agent +### Customize your agent You can modify your agent’s behavior by changing the options. Here are a few examples: **Add web search capability:** @@ -305,11 +277,7 @@ With `Bash` enabled, try: `"Write unit tests for utils.py, run them, and fix any failures"` Each of these snippets sets fields on the same options object. For more information, see [Configure your agent](</docs/en/agent-sdk/configuration>). -## - -​ - -Key concepts +## Key concepts **Tools** control what your agent can do: @@ -321,11 +289,7 @@ **Permission modes** control how much human oversight you want. The SDK evaluates the active mode together with your allow and deny rules in a fixed order, described in [How permissions are evaluated](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>). For the full list of modes, their behavior, and when to use each, see [Permission mode in How the agent loop works](</docs/en/agent-sdk/agent-loop#permission-mode>). -## - -​ - -Next steps +## Next steps Now that you’ve created your first agent, learn how to extend its capabilities and tailor it to your use case:
modified Mods reference View current →
Show diff (352 lines)
--- a/reference.md +++ b/reference.md @@ -2,11 +2,7 @@ The complete reference is Claude Code’s [TypeScript declarations for mods](<https://github.com/anthropics/claude-code/blob/main/mods/types/claude-code.d.ts>), which describe every event, method, and element, with examples. The copy on GitHub can be older than the Claude Code version you have installed. When the two disagree, trust [the copy Claude Code writes for your version](</docs/en/plugins/mods/create#get-the-types-for-your-build>). -## - -​ - -Files +## Files A mod is a plugin directory with these files: @@ -20,11 +16,7 @@ `register` receives `on` and `options`. `options` holds the values of the [`userConfig`](</docs/en/plugins/components#user-configuration>) fields the manifest declares, with defaults filled in. -## - -​ - -The hook function +## The hook function A mod registers each of its hooks, which are event handlers, by calling `on` inside `register`. `on` takes the event’s name, an optional [matcher](</docs/en/plugins/mods/events#filter-which-events-a-hook-handles>), which is a filter on the event’s fields, and the hook, as in `on('tool.call', { tool: 'Bash' }, async ($, e, next) => next(e))`. `on` returns a registration with one method, `.catch(handler)`, which sets the hook’s [error handler](</docs/en/plugins/mods/events#handle-a-hook-that-fails>). @@ -40,19 +32,11 @@ `next.error`| In a `.catch` handler only. `kind` is `throw` or `timeout`, and `message` is the error’s text. `next.called`| In a `.catch` handler only. `true` when the hook had called `next`. -## - -​ - -Events +## Events Events are grouped by what they concern, each with when it fires and what a hook on it can return. Hooks on `turn.step` and `process.spawn` are async generators, and other hooks are async functions. The last column of each table uses shorthand. `next(e)` passes the event on unchanged. `next({ ...e, text })` passes on a copy with the named field changed, as in `next({ ...e, text: e.text.trim() })`. An object answers the event without calling `next`, and a word such as `reason` stands for a string you write, as in `{ deny: 'Use the file tools.' }`. -### - -​ - -Tools +### Tools Tool events fire around each tool call Claude makes, from the description Claude reads to the decision on whether the call runs: @@ -62,11 +46,7 @@ [`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.| `next(e)` or `{ decision }`, with `decision` set to `allow`, `ask`, or `deny` and an optional `reason` `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. Add `breakPromptCache: true` to send a changed description on the next turn. -#### - -​ - -Agent and organization fields on `tool.check` +#### Agent and organization fields on `tool.check` In a `tool.check` hook, read these fields to tell a subagent’s call from the main conversation’s, and to see whether your organization requires approval for a connector tool: @@ -75,19 +55,11 @@ On `tool.check`, `e.agentId` and `e.ceiling` require Claude Code v2.1.290 or later. -#### - -​ - -The `e.isReadOnly` field on `tool.check` +#### The `e.isReadOnly` field on `tool.check` In a `tool.check` hook, `e.isReadOnly` is `true` when the tool reports this call as read-only. Otherwise the field is absent, not `false`. The value is the tool’s own report, so read [Check whether a tool call is read-only](</docs/en/plugins/mods/events#check-whether-a-tool-call-is-read-only>) before you approve a call on this field alone. On `tool.check`, `e.isReadOnly` requires Claude Code v2.1.304 or later. -### - -​ - -Prompts and what Claude reads +### Prompts and what Claude reads Prompt events cover the text the user types and the text Claude Code sends to Claude on its own, such as the system prompt and reminders: @@ -105,11 +77,7 @@ [`skill.prompt`](</docs/en/plugins/mods/events#rewrite-or-add-to-a-prompt>)| A skill’s text is expanded for Claude| `{ text }` `attribution.text`| Claude Code composes commit or pull request attribution text| `{ text }` -#### - -​ - -Source and frontmatter fields on `skill.prompt` +#### Source and frontmatter fields on `skill.prompt` In a `skill.prompt` hook, you can read these fields along with the skill’s name in `e.skill` and the text Claude reads in `e.text`: @@ -123,19 +91,11 @@ A hook can pass a changed `text` or `frontmatter` to `next`: the hooks after it read both, and Claude reads the final `text`. A hook that changes any other field [fails](</docs/en/plugins/mods/events#handle-a-hook-that-fails>). On `skill.prompt`, `e.source`, `e.pluginName`, `e.path`, `e.frontmatter`, and `e.frontmatterProblem` require Claude Code v2.1.299 or later. -#### - -​ - -Send a changed system prompt section or tool description with `breakPromptCache` +#### Send a changed system prompt section or tool description with `breakPromptCache` To change a section or a tool description in a running conversation, call `$.ui.invalidate('prompt.section')` or `$.ui.invalidate('tool.describe')` so your hook runs again. Return `{ text, breakPromptCache: true }` or `{ description, breakPromptCache: true }` from it. Without the field, Claude keeps reading the text [saved with the conversation](</docs/en/cli-reference#system-prompt-flags-in-resumed-conversations>) for a section or a tool loaded upfront until a new conversation or a [compaction](</docs/en/prompt-caching#compacting-the-conversation>). The changed text reaches Claude on the next turn, and the [prompt cache](</docs/en/prompt-caching>) starts over, so that turn is slower and more expensive. The field requires Claude Code v2.1.321 or later. From v2.1.299 until v2.1.321, a running conversation got the changed text on the next turn. -### - -​ - -Commands and configuration +### Commands and configuration Event| Fires when| A hook can return ---|---|--- @@ -145,20 +105,12 @@ `config.describe`| Once for each `/config` row| `{ label, description, isHidden }` [`settings.read`](</docs/en/plugins/mods/events#settings-read-hook>)| A mod calls [`$.settings.read`](</docs/en/plugins/mods/api#reach-files-processes-and-the-network>), or Claude Code builds the session’s merged settings. Requires Claude Code v2.1.304 or later on Claude Code’s own read and for `e.layers`| `next(e)`, `{ value }`, or `{ deny: reason }` -#### - -​ - -`e.layers` and `e.source` on `settings.read` +#### `e.layers` and `e.source` on `settings.read` * **`e.layers`** : one `{ source, settings }` object for each source in use that holds settings, lowest [precedence](</docs/en/settings#settings-precedence>) first. See [What a `settings.read` hook receives](</docs/en/plugins/mods/events#settings-read-receives>). * **`e.source`** : the one source a mod asked for, as in `$.settings.read({ source: 'policy' })`. Absent on Claude Code’s own read and on a read of the merged settings -### - -​ - -Turns +### Turns Turn events follow one answer from start to finish, including each request to the model within it: @@ -168,11 +120,7 @@ [`turn.step`](</docs/en/plugins/mods/events#follow-a-turn>)| One request is about to go to the model| `yield* next(e)`, or `next({ ...e, model })`, `next({ ...e, effort })` [`turn.complete`](</docs/en/plugins/mods/events#follow-a-turn>)| A turn ended| `next(e)`, or `{ text }` to show a line under the answer -### - -​ - -Session +### Session Session events mark the session starting, ending, compacting, and exchanging messages with other sessions: @@ -186,11 +134,7 @@ `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)` -### - -​ - -Subagents +### Subagents Subagent events fire when a subagent type is offered to Claude and when a subagent or an agent-team teammate is about to start: @@ -203,11 +147,7 @@ The event for a resumed run requires Claude Code v2.1.299 or later. Before v2.1.299, your `agent.spawn` hook didn’t run when a subagent resumed. On those versions, to refuse the `SendMessage` calls that resume a subagent, match that tool in a [`tool.call`](</docs/en/plugins/mods/events#guard-or-change-a-tool-call>) hook. -### - -​ - -Interface +### Interface Interface events fire when Claude Code draws a render site and when the user uses a control a mod drew. [Draw in the interface](</docs/en/plugins/mods/interface>) shows what a `ui.render` hook returns: @@ -221,11 +161,7 @@ [`ui.message`](</docs/en/plugins/mods/interface#build-a-tree-from-elements>)| A `Client` element posts data to its mod [`ui.fault`](</docs/en/plugins/mods/interface#redraw-when-something-changes>)| A `Client` element your mod drew failed to load, draw, or run. `e.phase` is `load`, `render`, or `run`, and `e.reason` is the error message. Requires Claude Code v2.1.289 or later. -### - -​ - -Other mods +### Other mods These events let a mod act on other mods as they load, to refuse one or change the mods API it receives: @@ -236,11 +172,7 @@ When another mod’s hook calls a method on a namespace you added in `engine.create`, your method’s `$` calls run in that hook’s context until every hook on that event returns. For example, a relative path resolves against that hook’s working directory, and `$.prompt.submit` rejects while the turn is waiting on that hook. Calls your method makes after that run in your mod’s own context. -### - -​ - -Telemetry +### Telemetry Telemetry events fire for the usage records Claude Code logs: @@ -248,27 +180,15 @@ ---|---|--- `telemetry.log`, `telemetry.mark`| A telemetry record is about to be logged, or one use of a feature is marked. In a mod you install, give a telemetry hook the filter `{ to: 'collector' }`, as in `on('telemetry.log', { to: 'collector' }, hook)`. Without the filter, the mod fails `claude plugin validate`. `*` doesn’t match these events.| `next(e)`, or `{ deny: reason }` -### - -​ - -Settings hook events +### Settings hook events Each [settings hook event](</docs/en/hooks#hook-events>) is an event named `classic.<Event>`, such as `classic.Stop` or `classic.PostToolUse`. `e` is the hook’s stdin JSON. -### - -​ - -Mods API calls +### Mods API calls Every mods API method is also an event, named for its namespace and method, such as `fs.read`, `model.complete`, or `ui.open`. A hook on one intercepts calls from the mods that run after it, and can return `next(e)`, `{ deny: reason }`, or `{ value }`. -## - -​ - -Mods API methods +## Mods API methods The mods API is the `$` argument every hook receives. Its methods are grouped in namespaces, such as `$.ui`. This table lists each namespace’s methods by name, so `open` in the `$.ui` row is the call `$.ui.open(...)`. The guides show the common ones in use, and [the types for your build](</docs/en/plugins/mods/create#get-the-types-for-your-build>) document every method with an example. @@ -297,11 +217,7 @@ `$.audio`| `play`, `speak` `$.telemetry`| `log`, `mark`. A record is sent only when Claude Code or a built-in mod makes the call. -## - -​ - -Render sites +## Render sites A render site is an extension point in Claude Code’s interface. Each row is a value of `e.component` in a `ui.render` hook, with the fields of `e.props` and the apps that render it. `e.surface` names the app that’s drawing, such as `terminal`, `desktop`, or `vscode`. [Change what Claude Code already draws](</docs/en/plugins/mods/interface#change-what-claude-code-already-draws>) shows what a hook can do at a site, with an example of each choice. Rendering in the VS Code extension requires extension version 2.1.299 or later. A session that [doesn’t fetch feature flags](</docs/en/env-vars#features-that-need-feature-flag-fetching>) needs 2.1.304 or later. [Draw in the VS Code extension](</docs/en/plugins/mods/interface#draw-in-the-vs-code-extension>) lists what the extension draws differently. @@ -331,11 +247,7 @@ A tree taller than the pane scrolls as a whole. -## - -​ - -Elements +## Elements Elements are the building blocks of a tree a `ui.render` hook returns, and you get them from `$.ui.resolve(e)`. [Build a tree from elements](</docs/en/plugins/mods/interface#build-a-tree-from-elements>) shows the common ones with how the terminal draws them, and the [interface gallery](</docs/en/plugins/mods/gallery>) has screenshots of most. A check mark means the app can draw the element. @@ -381,11 +293,7 @@ * **`Input` and `Select`**: `autoFocus`, and `rows` on an `Input` * **`Svg`** : `isInteractive` -### - -​ - -`Box` border styles +### `Box` border styles To draw a border around a `Box`, set its `borderStyle` to one of these names, as in `borderStyle: 'round'`. Each row says what the terminal draws for that name and shows the top edge of the border. @@ -404,11 +312,7 @@ A `Box` whose `borderStyle` names anything else, such as `'rounded'`, draws with no border. -### - -​ - -`Box` spacing steps +### `Box` spacing steps The `Box` spacing props are `gap`, `columnGap`, `rowGap`, `padding`, `margin`, and the one-side and one-axis forms of `padding` and `margin`, such as `paddingX` and `marginTop`. Each takes a number of terminal cells such as `gap: 1`, or a step name such as `gap: 'md'`. In the terminal and the VS Code extension, each step is this many cells: @@ -422,11 +326,7 @@ If you set `gap`, `padding`, or `margin` to a step, the step applies across and down at once. For example, in the terminal and the VS Code extension, `padding: 'md'` is two cells at each side and one row above and below. Step names require Claude Code v2.1.299 or later. On an earlier release, a tree that uses a step name doesn’t draw. -### - -​ - -`Text` typography props +### `Text` typography props Set `size`, `weight`, `mono`, or `tabular` on a `Text` to ask the app drawing your tree for a text size, a weight, a monospaced typeface, or equal-width digits. Before you rely on a prop, check what the terminal and the VS Code extension do with it. If an app ignores a prop you set, your tree still draws there, with the text as if you’d left that prop out. @@ -439,19 +339,11 @@ These four props require Claude Code v2.1.299 or later. On an earlier release, a tree that sets `size`, `weight`, `mono`, or `tabular` doesn’t draw. -#### - -​ - -Replace `bold` with `weight` +#### Replace `bold` with `weight` `bold` on a `Text` is deprecated in favor of `weight` and still works. To replace it on a `Text` with no `weight`, change `bold: true` to `weight: 'semibold'` for the same result on Claude Code v2.1.299 or later. On a release earlier than v2.1.299, a tree that sets `weight` doesn’t draw. If you set both `bold` and `weight` on a `Text`, `bold` has no effect. -## - -​ - -Limits +## Limits Hooks and mods API calls run under time and size limits. Claude Code skips a hook that exceeds a time limit. A tree over the nesting, element, `Raster` cell, or `Image` byte limit [isn’t drawn](</docs/en/plugins/mods/troubleshoot#a-pane-or-band-is-empty>). @@ -489,11 +381,7 @@ Command, tool, subagent type, and pane names, and the `id` of a placed row or a backdrop| Letters, digits, `_`, and `-`, up to 64 characters One `claude plugin test` test| 5 seconds unless the test sets `timeoutMs` -## - -​ - -Settings and environment variables +## Settings and environment variables These are the settings and environment variables that affect mods. The Where column says which settings file or environment each one is read from: @@ -511,11 +399,7 @@ `sec-default@builtin` is a guard built into Claude Code, listed as `cc-plugin-sec-default` in `/plugin` and the debug log. [Where it loads](</docs/en/plugins/mods/admin#know-what-happens-by-default>), it runs ahead of every mod a person installs. If managed `prependPlugins` is set, the guard loads only when that list names it, at the position listed. Its source is in the [`mods/sec-default` directory of the Claude Code repository](<https://github.com/anthropics/claude-code/tree/main/mods/sec-default>). -## - -​ - -Commands +## Commands These commands and flags load, inspect, and test a mod. The `claude` commands run in your shell and the `/` commands at the Claude Code prompt. In the table, `<directory>` stands for a path you type, as in `claude plugin validate ./first-mod`. Square brackets mark an optional argument.
modified Recommend plugins for your org View current →
Show diff (150 lines)
--- a/relevance.md +++ b/relevance.md @@ -10,11 +10,7 @@ * **Marketplace operators** : read how suggestions work, then add relevance to a plugin entry and validate your marketplace * **Administrators** : enable suggestions in managed settings -## - -​ - -Understand how plugin relevance works +## Understand how plugin relevance works Each plugin entry in `marketplace.json` can include a `relevance` object. The object names a topic and one or more signals. A signal is a pattern that Claude Code tests against the current session, such as the working directory or files Claude has read. Signal matching happens locally on the user’s machine and adds no network traffic. Claude Code doesn’t report which signals matched or their values to Anthropic or to the marketplace operator. When a signal matches and the plugin isn’t already installed, Claude Code suggests the plugin in these places: @@ -24,11 +20,7 @@ Preview what the user sees shows the exact text of each and how often they repeat. Claude Code never installs the plugin automatically. The user always confirms. The spinner tip and the session-start notification both stop appearing when the user or project sets [`spinnerTipsEnabled`](</docs/en/settings-reference#spinnertipsenabled>) to `false`, or when a [`spinnerTipsOverride`](</docs/en/settings-reference#spinnertipsoverride>) with `excludeDefault` replaces the built-in tips. The Discover-tab pin isn’t affected by either setting. -## - -​ - -Add relevance to a plugin entry +## Add relevance to a plugin entry Add a `relevance` object to the plugin’s entry in your `marketplace.json`. The following example declares that the `terraform-helpers` plugin is relevant when Claude reads a `.tf` file or runs `terraform`: @@ -53,19 +45,11 @@ While none of its signals match, the plugin keeps its normal position in the Discover list and doesn’t appear as a spinner tip. To check the block before publishing, validate your marketplace. -## - -​ - -Field reference +## Field reference The `relevance` object and its nested `signals` object accept the fields in the following tables. Older clients still load a marketplace that uses `relevance` fields they don’t recognize, because unknown fields under `relevance` and `relevance.signals` are ignored at load time. A recognized field whose value exceeds its limit in the field reference invalidates the whole plugin entry, and users can’t install that plugin from the marketplace until you fix it; `claude plugin validate` reports the same limits. -### - -​ - -`relevance` +### `relevance` Field| Type| Description ---|---|--- @@ -74,11 +58,7 @@ The `topic` is often the product name, for example `Terraform`. Use a domain such as `design` when the plugin name doesn’t sound natural as a topic. -### - -​ - -`relevance.signals` +### `relevance.signals` The `signals` object accepts the following fields. @@ -92,11 +72,7 @@ The `filesRead` and `manifestDeps` signals also match against files Claude has written or edited this session and against the project’s auto-loaded `CLAUDE.md` memory files. -#### - -​ - -Working directory matching +#### Working directory matching `cwd` is the only signal that can match at session start, before the user sends a first message. Claude Code matches each `cwd` pattern as follows: @@ -104,19 +80,11 @@ * Matching is forward-slash normalized and case-insensitive. * Every pattern matches the directory itself and everything under it, so `infra`, `infra/`, and `infra/**` behave identically. -#### - -​ - -Command name matching +#### Command name matching Claude Code records one command name for each shell command Claude runs: the first token after any leading environment variable assignments and `sudo`. Compound commands contribute only their leading command, so `cd infra && terraform plan` records `cd`, not `terraform`. -#### - -​ - -Manifest dependency matching +#### Manifest dependency matching Each `manifestDeps` entry pairs two JavaScript `RegExp` source strings: @@ -142,11 +110,7 @@ In this example, the `file` pattern uses `[/\\\\]` so it matches both forward-slash and backslash path separators, and `\\.` so the dot is literal. In JSON, each backslash in the regular expression is written twice. -## - -​ - -Validate your marketplace +## Validate your marketplace In your shell, run `claude plugin validate` against your marketplace directory to check the `relevance` block before publishing: @@ -160,11 +124,7 @@ Each finding prints with the path of the field it concerns, and the output ends with `Validation passed`, `Validation passed with warnings`, or `Validation failed`. -## - -​ - -Enable suggestions in managed settings +## Enable suggestions in managed settings In the terminal, users see no suggestions from a marketplace until an administrator allowlists it in [managed settings](</docs/en/plugins/org>), even when its `marketplace.json` declares `relevance`. To allowlist a marketplace, edit your managed settings as follows: @@ -191,11 +151,7 @@ "pluginSuggestionMarketplaces": ["claude-plugins-official"] } -## - -​ - -Preview what the user sees +## Preview what the user sees When a plugin’s `relevance` signal matches during a session, the tip below the spinner reads: @@ -213,11 +169,7 @@ * Neither the spinner tip nor the session-start notification repeats once the plugin is installed. * The Discover tab pins the plugin the first time the user opens the tab while the plugin’s signals match. Claude Code records that in `~/.claude.json`, so every later time the user opens `/plugin` on that machine, the plugin appears in normal order. -## - -​ - -See also +## See also * [Host a marketplace](</docs/en/plugins/host-marketplace>): run the marketplace that hosts your plugins * [Marketplace reference](</docs/en/plugins/marketplace-reference#plugin-entries>): every field a plugin entry accepts
modified Continue local sessions from any device with Remote Control View current →
Show diff (477 lines)
--- a/remote-control.md +++ b/remote-control.md @@ -9,11 +9,7 @@ Remote Control is a Claude Code feature. For conversations in other Claude products, see the [Claude Help Center](<https://support.claude.com>). -## - -​ - -Requirements +## Requirements Before using Remote Control, confirm that your environment meets these conditions: @@ -29,11 +25,7 @@ * If you set only `DISABLE_TELEMETRY` or `DO_NOT_TRACK`, Remote Control stays available unless your organization requires Trusted Devices. If it does, unset the variable to use Remote Control. Using Remote Control with either variable set requires Claude Code v2.1.283 or later, or v2.1.304 or later in the Claude Desktop app. * **Workspace trust** : in a directory you haven’t trusted yet, `claude remote-control` prints what trusting it turns on and asks `Trust <directory>? [y/N]` before it starts. Answering `y` saves the choice, except in your home directory, where trust is never saved and the question returns on every run. When its standard input or output isn’t a terminal, the command can’t ask and exits with a [`Workspace not trusted`](</docs/en/errors#workspace-not-trusted-when-starting-remote-control>) error. -## - -​ - -Start a Remote Control session +## Start a Remote Control session You can start a Remote Control session from the CLI, the [Claude Desktop app](</docs/en/desktop>), or the VS Code extension. The CLI offers three invocation modes; the Desktop app and VS Code use the `/remote-control` command. @@ -67,13 +59,14 @@ `--capacity <N>`| Maximum number of concurrent sessions. Default is 32. Cannot be used with `--spawn=session`. `--[no-]create-session-in-dir`| Pre-create one session in the current directory when the server starts, so you have somewhere to type immediately. In `worktree` mode this session stays in the current directory while on-demand sessions get isolated worktrees. On by default. If you pass `--no-create-session-in-dir` to start with none, Claude Code archives the server’s sessions when you stop it, so there’s nothing to resume. `--permission-mode <mode>`| Set the starting [permission mode](</docs/en/permission-modes>) for the server’s sessions, such as `acceptEdits`. Accepts `manual` as an alias for `default`; an unrecognized mode stops the server at startup and lists the valid modes. +`--settings <file>`| Apply a JSON settings file to the server’s sessions, at the same [precedence](</docs/en/settings#settings-precedence>) as `claude --settings`. Give a file path, not a JSON string. Requires Claude Code v2.1.321 or later. `--chrome` / `--no-chrome`| Turn [Chrome integration](</docs/en/chrome>) on or off in the sessions the server creates, so Claude can use Chrome on your machine while you work from another device. Without either flag, the session the server pre-creates and any session you start yourself from claude.ai/code or the Claude app begin with Chrome off, even if you [enabled Chrome by default](</docs/en/chrome#enable-chrome-by-default>). A session the server starts for one of your [project](</docs/en/claude-projects>) threads follows that setting instead, except in `bypassPermissions` mode. Requires Claude Code v2.1.273 or later. `-d`, `--debug[=<filter>]`| Turn on debug logging for the server, optionally filtered by category. Pass a filter only in the `=` form, such as `--debug=api,hooks`. Requires Claude Code v2.1.282 or later. `--debug-file <path>`| Write debug logs to the given file. `--verbose`| Show detailed connection and session logs. `--sandbox`, `--no-sandbox`| Removed in v2.1.300. If you pass either flag, the server [exits with an error](</docs/en/errors#sandbox-is-not-supported-by-claude-remote-control>) instead of starting. -If you pass a global `claude` flag before `remote-control`, or a wrapper script adds one, Claude Code doesn’t carry the flag over to the sessions the server creates. Claude Code lets the flag through only when dropping it is known not to change what those sessions can do, such as `--verbose` or `--model`. For any other flag, such as `--settings`, Claude Code [refuses to start](</docs/en/errors#not-carried-over-to-the-sessions-remote-control-starts>) and names the flag to remove.To sandbox the sessions the server starts, turn on [sandboxing](</docs/en/sandboxing>) in a settings file.To print the `remote-control` flags in your terminal, run `claude remote-control --help`. Before v2.1.302, without an eligible sign-in the command returned one of the errors under Troubleshooting instead. +If you pass a global `claude` flag before `remote-control`, or a wrapper script adds one, Claude Code doesn’t carry the flag over to the sessions the server creates. The server still starts with some flags, such as `--verbose` or `--model`. With any other flag, the server [doesn’t start](</docs/en/errors#not-carried-over-to-the-sessions-remote-control-starts>). To pass a settings file, put `--settings` after `remote-control`.To sandbox the sessions the server starts, turn on [sandboxing](</docs/en/sandboxing>) in a settings file.To print the `remote-control` flags in your terminal, run `claude remote-control --help`. Before v2.1.302, without an eligible sign-in the command returned one of the errors under Troubleshooting instead. To start a normal interactive Claude Code session with Remote Control enabled, use the `--remote-control` flag (or `--rc`): @@ -107,11 +100,7 @@ Once the session connects, find it in the session list at [claude.ai/code](<https://claude.ai/code>). To disconnect, run `/remote-control` again.To turn Remote Control on for every session by default instead, see Enable Remote Control for all sessions. -### - -​ - -Check connection status +### Check connection status In an interactive session, while Remote Control is connected, the terminal shows an `/rc active` indicator that links to the session on claude.ai. The indicator is hidden when the terminal is too narrow to fit it. To see the session URL and a QR code for connecting from another device, run `/remote-control` again to open the status panel. The panel also lets you disconnect Remote Control while your local session keeps running. If the connection fails in an interactive session, the indicator changes to show the failure, and Claude Code shows the reason in a notification and adds it to the conversation. Run `/remote-control` to reconnect, unless the reason says the session changed somewhere else: @@ -121,11 +110,7 @@ If `/remote-control` opens a dialog that says `Remote Control isn't connected.`, follow the step the dialog gives, such as running `/login` or selecting **Continue** and trying again. -### - -​ - -Connect from another device +### Connect from another device Once a Remote Control session is active, you have a few ways to connect from another device: @@ -142,11 +127,7 @@ If you didn’t set an explicit name, Claude Code updates the title to reflect your prompt once you send one. When you rename a session from claude.ai or the Claude app, Claude Code also updates the local title shown in `claude --resume`. If you don’t have the Claude app yet, run `/mobile` inside Claude Code to show a QR code for [claude.ai/mobile](<https://claude.ai/mobile>), which opens the right app store for your phone. -### - -​ - -What connected devices see +### What connected devices see A connected device shows the conversation in your terminal as it happens. These cases go beyond ordinary messages: @@ -159,22 +140,14 @@ * **Effort level** : when you set the [effort level](</docs/en/model-config#adjust-effort-level>) from a connected device, with `/effort` or the device’s effort control, Claude Code applies it to the session on your machine. If you pinned a level with `CLAUDE_CODE_EFFORT_LEVEL`, the session keeps that level, and Claude Code refuses a different pick from the effort control. Picking a level from the effort control requires Claude Code v2.1.234 or later on your machine. * **Reconnecting after a connection failure** : run `/remote-control` to reconnect. If compaction rewrote the conversation or you switched conversations with `/resume` in the meantime, Claude Code archives the server session it was using instead of leaving it in the session list. You can still find that session among your [archived sessions](</docs/en/claude-code-on-the-web#find-an-archived-session>) at claude.ai/code. Switching conversations while a device is still connected doesn’t archive the session. -### - -​ - -Fork a session from your browser +### Fork a session from your browser To try a different direction without interrupting a session, open it at [claude.ai/code](<https://claude.ai/code>) and select **Fork** in the session’s menu, or fork from an earlier message in the transcript. The fork opens as a new session in your session list and continues the conversation from that point while the original keeps running. Forking requires Claude Code v2.1.277 or later on your machine. A `claude remote-control` server started with `--spawn session` has room only for its one session, so it can’t run a fork. Claude Code declines the fork in cases such as these: * The session is busy. Fork when it’s idle. * The session is hosted by the VS Code extension or another app built on the [Agent SDK](</docs/en/agent-sdk/overview>). -### - -​ - -Enable Remote Control for all sessions +### Enable Remote Control for all sessions Remote Control only activates when you explicitly run `claude remote-control`, `claude --remote-control`, or `/remote-control`, unless auto-connect is turned on. To turn auto-connect on for every interactive session, run `/config` inside Claude Code and set **Enable Remote Control for all sessions**. The toggle takes three values: @@ -189,22 +162,14 @@ To turn auto-connect on from a settings file instead, set [`remoteControlAtStartup`](</docs/en/settings-reference#remotecontrolatstartup>) to `true` in your user `~/.claude/settings.json` or in [managed settings](</docs/en/managed-settings>). In project or local settings (`.claude/settings.json`, `.claude/settings.local.json`), Claude Code honors a `false` and turns auto-connect off for that repository. It ignores a `true`, so you can’t use a checked-in file to turn on Remote Control for everyone who opens the repository. Auto-connect signs in with your own claude.ai account, so a session it starts appears only in your own account’s Claude apps and grants no one else access. With this setting on, each interactive Claude Code process registers one remote session. If you run multiple instances, each one gets its own remote session. To run multiple concurrent sessions from a single process, use server mode instead. -#### - -​ - -Auto-connect with `DISABLE_TELEMETRY` or `DO_NOT_TRACK` set +#### Auto-connect with `DISABLE_TELEMETRY` or `DO_NOT_TRACK` set With only `DISABLE_TELEMETRY` or `DO_NOT_TRACK` set, your sessions don’t auto-connect through your organization’s admin default or Claude Code’s own default. If something else makes Remote Control unavailable for you, such as [`CLAUDE_CODE_DISABLE_FEATURE_FLAGS`](</docs/en/env-vars#variables>) or an LLM gateway, start with Requirements instead. Before you turn auto-connect on with only `DISABLE_TELEMETRY` or `DO_NOT_TRACK` set, confirm that your Claude Code version meets the requirement for these variables. Then check whether your organization requires Trusted Devices: * **Not required** : set **Enable Remote Control for all sessions** to `true` in `/config`. * **Required** : Remote Control isn’t available while `DISABLE_TELEMETRY` or `DO_NOT_TRACK` is set. Unset whichever of the two variables you set. If your sessions still don’t auto-connect, set **Enable Remote Control for all sessions** to `true` in `/config`. -### - -​ - -Resume sessions after stopping the server +### Resume sessions after stopping the server When you stop `claude remote-control` with Ctrl+C, the sessions it was serving stop responding from your phone or browser. As long as you weren’t running another `claude remote-control` in the same directory and didn’t start this one with `--no-create-session-in-dir`, Claude Code doesn’t archive them. To bring them back, run one of these commands in the same directory: @@ -214,30 +179,18 @@ These commands work for about four hours after the server stopped. After that, run `claude remote-control` to start a new session. If you archived a session in the meantime, `--continue` and `--session-id` unarchive it on Claude Code v2.1.228 or later. To bring back a session you started with `claude --remote-control` or `/remote-control`, resume the conversation with `claude --continue` or `claude --resume`. For the permission mode that the resumed conversation starts in, see [permission mode on resume](</docs/en/sessions#permission-mode-on-resume>). If Remote Control doesn’t reconnect, see Couldn’t reconnect to your Remote Control session. If you resume the conversation in a second terminal while the first one still has Remote Control on, Claude Code prints a `Remote Control not started here` notice in the second terminal and leaves Remote Control off there instead of taking the session away from the first. Run `/remote-control` in the second terminal to move Remote Control to it. When you resume a conversation in Claude Desktop or an IDE extension that had Remote Control on, Claude Code reattaches it to the existing claude.ai session instead of adding a new one to the session list. -### - -​ - -Set the default spawn mode for a project +### Set the default spawn mode for a project If `claude remote-control` prints `Spawn mode: <mode> (saved for this folder; press w to change)` at startup, the server is starting in a spawn mode saved earlier for this project. The saved mode comes from a choice you made in your own terminal. If `claude remote-control` asked `Spawn mode for this project:` there, Claude Code kept what you answered: `1` for `same-dir` or `2` for `worktree`. If you pressed `w` while it ran, Claude Code kept the mode you switched to, even on a run you started with `--spawn same-dir` or `--spawn worktree`. * While the server runs in `same-dir` or `worktree` mode, press `w` in the server’s terminal to switch to the other one. Switching requires a git repository or a `WorktreeCreate` hook. * To use a different mode for one run, pass `--spawn <mode>`. -## - -​ - -Connection and security +## Connection and security Your local Claude Code session makes outbound HTTPS requests only and never opens inbound ports on your machine. When you start Remote Control, it registers with the Anthropic API and polls for work. When you connect from another device, the server routes messages between the web or mobile client and your local session over a streaming connection. All traffic travels through the Anthropic API over TLS, the same transport security as any Claude Code session. The connection uses multiple short-lived credentials, each scoped to a single purpose and expiring independently. While Remote Control is connected, the session transcript, including your messages, Claude’s responses, and tool activity, is stored on Anthropic servers. The stored transcript keeps the conversation in sync across your devices and lets the session reconnect after a network drop. Execution and filesystem access stay on your machine, and stored transcripts are retained under the [Data usage](</docs/en/data-usage>) policy. To turn Remote Control off entirely, use the [`disableRemoteControl`](</docs/en/settings-reference#disableremotecontrol>) setting. Organizations with [Zero Data Retention](</docs/en/zero-data-retention>) enabled, or with the [HIPAA configuration](</docs/en/hipaa-setup>) applied, can’t enable Remote Control. -## - -​ - -Trusted Devices +## Trusted Devices Trusted Devices is currently in beta. Features and functionality may evolve as the experience is refined.Trusted Devices is available on Pro, Max, Ultra, Team, and Enterprise plans and is off by default. On Team and Enterprise plans, an Owner turns it on for the organization. On Pro, Max, and Ultra plans, you turn on **Require trusted devices** yourself in your settings, on the Cowork or Account page. @@ -248,11 +201,7 @@ Biometric checks run on the device through the operating system or browser, the same mechanism as passkey sign-in. Anthropic never receives or stores fingerprints, face data, or any other biometric information. Only the device’s public key and basic metadata such as display name, platform, and enrollment time are stored. The setting applies to Remote Control in Claude Code and to Computer access in [Cowork](<https://claude.com/docs/cowork/overview>). This page covers the Claude Code side. Regular Claude chat, Claude Code in the terminal, and API usage are unaffected. -### - -​ - -Enable Trusted Devices for a Team or Enterprise organization +### Enable Trusted Devices for a Team or Enterprise organization An Owner enables the setting from the claude.ai organization settings. @@ -274,11 +223,7 @@ The first time a member views or steers a new Remote Control session from a browser, phone, or desktop app after the setting is enabled, they are prompted to enroll that device. Letting them know ahead of time avoids confusion. -### - -​ - -What members see +### What members see Enrollment is a one-time step per device. After that, the only visible change is an occasional biometric prompt. @@ -288,19 +233,11 @@ * **No platform authenticator** : members on a machine without Face ID, Touch ID, or Windows Hello can use a hardware security key, or sign in again instead of stepping up. * **In the terminal** : the machine running Claude Code receives its own credential automatically when the developer signs in to the CLI. There is no separate enrollment step in the terminal. -### - -​ - -Manage enrolled devices +### Manage enrolled devices Members can review and revoke their own devices from account settings. Open [claude.ai/settings/account](<https://claude.ai/settings/account#trusted-devices>) and find the **Trusted devices** section to see every enrolled device with its name, platform, and enrollment date. Removing a device revokes its credential immediately, and the device can re-enroll later after a fresh sign-in. Credentials also expire on their own if not renewed, so an unused device drops off the trusted list automatically. For a lost or stolen device, the member removes it from this page. If the member cannot sign in, an admin can use **Sign out everywhere** in the admin console to revoke every session and enrolled device for that member, after which the member re-enrolls the devices they still hold. -## - -​ - -Remote Control vs cloud sessions +## Remote Control vs cloud sessions Remote Control and [cloud sessions](</docs/en/claude-code-on-the-web>) both use the claude.ai/code interface. The key difference is where the session runs: Remote Control executes on your machine, so your local MCP servers, tools, and project configuration stay available. A cloud session executes on cloud infrastructure, Anthropic-managed by default. Use Remote Control when you’re in the middle of local work and want to keep going from another device. Use a cloud session when you want to start a task without any local setup, work on a repo you don’t have cloned, or run multiple tasks in parallel. A [project](</docs/en/claude-projects>) combines the two: its threads run in the cloud, and it uses Remote Control to [run a thread on your computer](</docs/en/claude-projects#run-a-thread-on-your-own-computer>) when you ask for one there. Claude Code offers several ways to work when you’re not at your terminal. They differ in what triggers the work, where Claude runs, and how much you need to set up. @@ -313,11 +250,7 @@ [Self-hosted environments](</docs/en/self-hosted-environments>)| Start a [cloud session](</docs/en/claude-code-on-the-web>) and pick your organization’s environment| Your organization’s infrastructure| [Deploy runners](</docs/en/self-hosted-environments-quickstart>), on Team and Enterprise plans| Cloud sessions that must run inside your network [Scheduled tasks](</docs/en/scheduled-tasks>)| Set a schedule| [CLI](</docs/en/scheduled-tasks>), [Desktop](</docs/en/desktop-scheduled-tasks>), or [cloud](</docs/en/routines>)| Pick a frequency| Recurring automation like daily reviews -## - -​ - -Mobile push notifications +## Mobile push notifications When Remote Control is active, Claude can send push notifications to your phone. A push can arrive when a long-running task finishes or when Claude needs a decision from you. You can also request a push in your prompt, for example `notify me when the tests finish`. Beyond the two on/off toggles below, there is no per-event configuration. To set up mobile push notifications: @@ -353,11 +286,7 @@ Claude Code skips mobile push notifications while you are typing in or focused on the connected terminal. To extend this to any time you are at the machine, even in another window, set [`CLAUDE_CLIENT_PRESENCE_FILE`](</docs/en/env-vars>) to a marker file path: notifications are skipped while the file exists. Configure a screen-lock listener or similar tool to create the file when your screen unlocks and delete it when your screen locks. -## - -​ - -Limitations +## Limitations * **One remote session per interactive process** : outside of server mode, each Claude Code instance supports one remote session at a time. Use server mode to run multiple concurrent sessions from a single process. * **Local process must keep running** : Remote Control runs as a local process. If you close the terminal, quit the Desktop app or VS Code that runs the session on your machine, or otherwise stop the `claude` process, the session goes offline until you bring it back. If you run `claude` from a terminal on a remote machine, start it inside `tmux` or `screen` to keep the session running after you disconnect from SSH. @@ -381,11 +310,7 @@ * `/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 +## 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>). @@ -414,17 +339,9 @@ 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".` -## - -​ - -Troubleshooting - -### - -​ - -“Remote Control disconnected” or “Can’t reach” +## Troubleshooting + +### “Remote Control disconnected” or “Can’t reach” At [claude.ai/code](<https://claude.ai/code>) or in the Desktop app, **Remote Control disconnected** or a **Can’t reach** message means your browser or app lost contact with Claude Code on your computer. Neither message tells you whether Claude or a subagent you were watching is still working on your computer. On that computer, check the state Claude Code is in and follow the matching step to reconnect: @@ -432,11 +349,7 @@ * **Claude Code is running and shows no failure** : an interactive session reconnects by itself once the machine is awake and online, so you don’t need to act. If you used `claude remote-control`, see **Extended network outage** under Limitations * **Claude Code isn’t running** : start it again and bring the session back -### - -​ - -”Remote Control requires a claude.ai subscription” +### ”Remote Control requires a claude.ai subscription” You’re not signed in with a claude.ai account, or another credential is taking precedence over your login. The message takes one of these forms: @@ -446,62 +359,34 @@ Run `claude auth login` and choose the claude.ai option. If the message names `ANTHROPIC_API_KEY` or `ANTHROPIC_AUTH_TOKEN`, remove it wherever it’s set: your shell environment or the `env` block of a [settings file](</docs/en/settings-reference#env>). If it names `apiKeyHelper`, remove that setting. -### - -​ - -”Remote Control requires a full-scope login token” +### ”Remote Control requires a full-scope login token” You’re authenticated with a long-lived token from `claude setup-token` or the `CLAUDE_CODE_OAUTH_TOKEN` environment variable. These tokens can only make model requests, so they can’t establish Remote Control sessions. Run `claude auth login` to authenticate with a full-scope session token instead. -### - -​ - -”Unable to determine your organization for Remote Control eligibility” +### ”Unable to determine your organization for Remote Control eligibility” Your cached account information is stale or incomplete. Run `claude auth login` to refresh it. -### - -​ - -”Remote Control isn’t enabled for this account” +### ”Remote Control isn’t enabled for this account” Claude Code checked Remote Control availability for the account you’re signed in with and the check came back off. The usual cause is cached entitlements that are out of date after a plan change. Run `claude auth logout` then `claude auth login` to refresh them, and update Claude Code if you’re on an old version. Run `claude doctor` to see which individual eligibility check failed. Environment-variable conflicts, unreachable checks, and your organization’s Remote Control setting each produce their own message, so this error means the account-level check itself. Before v2.1.239, this message read “Remote Control is not yet enabled for your account”. -### - -​ - -”Couldn’t verify Remote Control eligibility” +### ”Couldn’t verify Remote Control eligibility” Claude Code could not reach the feature-flag service to check whether Remote Control is enabled for your account, typically because you are offline or a proxy is blocking the request. Retry once you have network access, or run `claude doctor` for details. The related message “Couldn’t verify your organization’s Remote Control policy” means Claude Code hit an error reading that policy, and has the same fix. -### - -​ - -”Remote Control requires feature-flag evaluation” +### ”Remote Control requires feature-flag evaluation” An [environment variable](</docs/en/env-vars#features-that-need-feature-flag-fetching>) that turns off feature-flag evaluation is set, and the full message names the variable Claude Code found. On versions before 2.1.154, the same configuration produces “Remote Control is not yet enabled for your account” instead. What to do depends on the variable the message names: * **`CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`, `CLAUDE_CODE_DISABLE_FEATURE_FLAGS`, or `DISABLE_GROWTHBOOK`**: unset the variable wherever it’s set, in your shell environment or in the `env` block of a [`settings.json` file](</docs/en/settings-reference#all-settings>). * **`DISABLE_TELEMETRY` or `DO_NOT_TRACK`**: on a Pro, Max, Ultra, Team, or Enterprise plan with `CLAUDE_CODE_DISABLE_FEATURE_FLAGS` and `DISABLE_GROWTHBOOK` unset, Remote Control stays available with these variables set, unless your organization requires Trusted Devices. If it does, unset the variable wherever it’s set to use Remote Control. On v2.1.154 through v2.1.282, you see this message with either variable set, so update Claude Code to a version that meets the requirement for these variables. -### - -​ - -”Remote Control is only available when using Claude via api.anthropic.com” +### ”Remote Control is only available when using Claude via api.anthropic.com” The session isn’t talking to the Anthropic API directly, which Remote Control requires. This happens on Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry. It also happens when [`ANTHROPIC_BASE_URL`](</docs/en/env-vars>) points at a host other than `api.anthropic.com`, such as an [LLM gateway](</docs/en/llm-gateway>) or proxy, even if you sign in with claude.ai. See the [error reference](</docs/en/errors#remote-control-requires-the-anthropic-api>) for the full cause list. The message names what routed the session away from the Anthropic API, such as `CLAUDE_CODE_USE_BEDROCK` or a custom `ANTHROPIC_BASE_URL`. If you have an eligible claude.ai login, unset the named variable, remove it from the `env` key in [settings](</docs/en/settings>) if you set it there, and restart the session. -### - -​ - -“Remote Control is disabled by your organization’s policy” +### “Remote Control is disabled by your organization’s policy” A policy blocks Remote Control. Check these causes in order: @@ -514,11 +399,7 @@ Before v2.1.281, this message also appeared when Claude Code hadn’t loaded your organization’s policy on this machine, for example after starting offline. Later versions report that state as `Couldn't verify your organization's policy for remote control` instead. -### - -​ - -“Remote Control was turned off by your organization’s policy” +### “Remote Control was turned off by your organization’s policy” Your organization’s policy stopped allowing Remote Control while a session was connected, so Claude Code disconnected it. What happens to the session depends on how you started Remote Control: @@ -527,11 +408,7 @@ To find one of these sessions again, open your [archived sessions](</docs/en/claude-code-on-the-web#find-an-archived-session>) at claude.ai/code. Remote Control doesn’t reconnect on its own. To turn it back on after your organization allows it again, run `/remote-control` in the session or `claude remote-control` in your shell. Either command fails with `Remote Control is disabled by your organization's policy` until Claude Code on this machine has fetched the changed policy. An open session fetches it about once an hour. To find out what is blocking Remote Control, match the full text the command prints against that entry. -### - -​ - -“Couldn’t verify your organization’s policy for remote control” +### “Couldn’t verify your organization’s policy for remote control” Claude Code couldn’t fetch your organization’s policy and has no saved copy on this machine to use instead, so it keeps Remote Control off until it can confirm that your organization allows it. This usually happens when you start Claude Code offline or before a VPN connects, or when a proxy interferes with the request. On a slow connection it can also appear while the first request is still in flight. The message takes one of these forms: @@ -540,11 +417,7 @@ Restore your network connection, then run `/remote-control` or run the command again. Each attempt checks for the policy again, so you don’t need to restart Claude Code. If the message keeps appearing, run `claude doctor` and read its `Organization policy` line, which says why the policy didn’t load. Before v2.1.281, this state showed `Remote Control is disabled by your organization's policy` instead. -### - -​ - -”Remote credentials fetch failed” +### ”Remote credentials fetch failed” Claude Code could not obtain a short-lived credential from the Anthropic API to establish the connection. Re-run with `--verbose` to see the full error: @@ -556,11 +429,7 @@ * Network or proxy issue: a firewall or proxy may be blocking the outbound HTTPS request. Remote Control requires access to the Anthropic API on port 443. * Session creation failed: if you also see `Session creation failed — see debug log`, the failure happened earlier in setup. Check that your subscription is active. -### - -​ - -“working folder not found” +### “working folder not found” In the terminal running `claude remote-control`, `Session failed: working folder not found:` followed by a quoted path means a session couldn’t start because no folder exists at that path. @@ -569,59 +438,31 @@ Before v2.1.318, a session that failed this way showed `Session failed: spawn error:` and an `ENOENT` message that named a program file instead of the missing folder. -### - -​ - -“The program file this Remote Control started from is gone” +### “The program file this Remote Control started from is gone” This warning in the terminal running `claude remote-control` means the program file the server started from is missing, and new sessions run the newer version that replaced it. To move the server to that version too, stop it and run `claude remote-control` again. If Claude Code is installed on network storage, restart the server now and follow [Install on network storage](</docs/en/setup#install-on-network-storage>). Otherwise, new sessions start without a restart. When the program file is gone and Claude Code finds no newer version to run, new sessions fail. The terminal shows an error such as `Session failed: spawn error:` followed by an `ENOENT` message. Stop the server, [install Claude Code](</docs/en/setup#install-claude-code>) again if `claude` doesn’t run in your shell, and run `claude remote-control` again. Before v2.1.318, new sessions failed this way even with a newer version installed. -### - -​ - -“Couldn’t reconnect to your Remote Control session” +### “Couldn’t reconnect to your Remote Control session” When you resume a conversation with `claude --resume` or `claude --continue`, Claude Code reconnects to the Remote Control session recorded in that conversation. This message means the reconnection failed for a reason that may be temporary, such as a network interruption or a server error, so Claude Code can’t confirm whether the remote session still exists. Run `/remote-control` to retry the connection, or start a new session with `claude --remote-control` to create a new Remote Control session. Your local session keeps running without Remote Control in the meantime. -### - -​ - -“Previous session is unavailable — run /remote-control to start a new one” +### “Previous session is unavailable — run /remote-control to start a new one” Claude Code couldn’t bring back the previous Remote Control session and stopped instead of starting a new one on its own. You can see this message after you resume a conversation with `claude --resume` or `claude --continue`, or after Claude Code [reconnects on its own following a disconnect](</docs/en/errors#remote-control-couldnt-refresh-your-login>). Run `/remote-control` to start a new Remote Control session under the current login; your local session keeps running without Remote Control in the meantime. The related message `Remote Control could not verify the signed-in account — run /remote-control to reconnect` has the same fix. If you run `/remote-control` after `Previous session is unavailable` without restarting Claude Code first, Claude Code leaves the conversation’s earlier messages out of the new session. -### - -​ - -”Remote Control got an unexpected server response” +### ”Remote Control got an unexpected server response” The Remote Control server accepted a request but replied in a form this version of Claude Code couldn’t read, while creating the remote session or fetching its credentials. Retrying on the same version fails the same way. Run `claude update`, then run `/remote-control` to reconnect. -### - -​ - -”Your organization requires Trusted Devices for Remote Control, but this device is not enrolled” +### ”Your organization requires Trusted Devices for Remote Control, but this device is not enrolled” Your organization has Trusted Devices enabled and this machine has not enrolled yet. Run `/login` in Claude Code. Enrollment happens as part of sign-in, and there is no separate enrollment command. -### - -​ - -”session expired for trusted-device check” +### ”session expired for trusted-device check” Your sign-in is more than 18 hours old. Run `/login` in Claude Code, or confirm with Face ID, Touch ID, Windows Hello, or a passkey when claude.ai or the mobile app prompts you. See Trusted Devices. -## - -​ - -Related resources +## Related resources * [Use Claude Code in the cloud](</docs/en/claude-code-on-the-web>): run sessions in the cloud instead of your machine, configured through [cloud environments](</docs/en/cloud-environments>) * [Cross-session messaging](</docs/en/cross-session-messaging>): let Claude message your sessions on other machines or your [cloud sessions](</docs/en/claude-code-on-the-web>)
modified Automate work with scheduled tasks View current →
Show diff (389 lines)
--- a/routines.md +++ b/routines.md @@ -17,11 +17,7 @@ Team and Enterprise Owners can turn off scheduled tasks for all members with the **Scheduled tasks (Was Routines)** or **Routines** toggle at [**Organization settings > Capabilities > Remote sessions**](<https://claude.ai/admin-settings/capabilities>). When the toggle is off, existing scheduled tasks stop running and members can’t create new ones. If your Enterprise organization manages your access with [custom roles](<https://support.claude.com/en/articles/13930452>), you also need a role that includes the scheduled tasks permission. An Owner can add it in a role’s **Remote sessions** section at [**Organization settings > Roles**](<https://claude.ai/admin-settings/roles>). -## - -​ - -Example use cases +## Example use cases Each example pairs a trigger type with the kind of work scheduled tasks are suited to: unattended, repeatable, and tied to a clear outcome. @@ -32,11 +28,7 @@ * **Docs drift** : a schedule trigger runs weekly. The scheduled task scans merged PRs since the last run, flags documentation that references changed APIs, and opens update PRs against the docs repository for an editor to review. * **Library port** : a GitHub trigger runs on `pull_request.closed` filtered to merged PRs in one SDK repository. The scheduled task ports the change to a parallel SDK in another language and opens a matching PR, keeping the two libraries in step without a human re-implementing each change. -## - -​ - -Create a scheduled task +## Create a scheduled task Create a scheduled task from the web at [claude.ai/code/routines](<https://claude.ai/code/routines>), from the Desktop app, or from the CLI. All three surfaces write to the same cloud account, so a scheduled task you create in one shows up in the others immediately. In the Desktop app’s **Code** tab, click **Scheduled** in the sidebar or in the sidebar’s **More** menu, then **New task** , and continue with Create from the web. Scheduled tasks run autonomously as full Claude Code cloud sessions. The session runs shell commands, uses [skills](</docs/en/skills>), and calls any connectors you include. Outside a [project](</docs/en/claude-projects#what-threads-pick-up-from-your-repositories>)’s threads, those skills include the ones committed to the cloned repository. You don’t choose a permission mode when you create the task: see Permission prompts during a run for when a run stops to wait for you. What a scheduled task can reach is determined by: @@ -46,11 +38,7 @@ Scope each of those to what the task needs. Scheduled tasks belong to your individual claude.ai account. They are not shared with teammates, and their runs count against your account’s usage and limits. Anything a scheduled task does through your connected GitHub identity or connectors appears as you. Commits and pull requests carry your GitHub user, and Slack messages, Linear tickets, or other connector actions use your linked accounts for those services. -### - -​ - -Create from the web +### Create from the web 1 @@ -125,19 +113,11 @@ Click **Create**. The dialog closes and the new task’s detail page opens. The task runs the next time one of its triggers matches. To start a run immediately, click **Run now** on the detail page.To see what a run did, click it in the **History** list on the detail page. The run opens as a full session, a new one for each run, where you can see what Claude did, review changes, and create a pull request. -#### - -​ - -Dialog with Repositories and Environment in the main view +#### Dialog with Repositories and Environment in the main view Follow the steps to create from the web, and fill in each field in the dialog’s main view rather than under **Advanced settings**. This dialog creates only Claude Code tasks. Select the repository before you add a GitHub event trigger, because that trigger is unavailable until a repository is selected. -#### - -​ - -Full-page form +#### Full-page form In the Desktop app, if a menu with **Local** and **Cloud** opens, select **Cloud**. A page titled **New routine** or **New scheduled task** opens. Fill in its fields: @@ -148,11 +128,7 @@ If **Create** is unavailable, hover over it to see what the form still needs. Click **Create** , and the task’s detail page opens. -### - -​ - -Create from the CLI +### Create from the CLI Run `/schedule` in any session to create a scheduled task conversationally. You can also pass a description directly, for a recurring task like `/schedule daily PR review at 9am` or a one-off like `/schedule clean up feature flag in one week`. Claude walks through the same information the web dialog collects, then saves the task to your account. The command is also available under the alias `/routines`. A successful start looks like a conversation: Claude asks follow-up questions about the schedule, repositories, and prompt before saving. If Claude instead replies that you need to authenticate or that it can’t connect to your remote claude.ai account, no scheduled task was created; see Troubleshooting. A task you create with `/schedule` has a schedule trigger. You can also add the other trigger types: @@ -161,19 +137,11 @@ A scheduled task with no schedule trigger, such as one started only by API calls or GitHub events, has no next run time. The CLI shows none when Claude saves or updates it. -## - -​ - -Configure triggers +## Configure triggers A scheduled task starts when one of its triggers matches. Add or remove a task’s triggers at any time in the **Trigger** row of the task’s edit dialog. When a task has two or more triggers, each one has a trash icon in that dialog. To remove a schedule or GitHub event trigger, click its trash icon, then **Save changes**. To remove an API trigger, delete its token instead. -### - -​ - -Add a schedule trigger +### Add a schedule trigger A schedule trigger runs the task on a recurring cadence, or once at a specific future time. In the task’s creation or edit dialog on the web, pick a preset frequency such as hourly, daily, or weekly: @@ -182,11 +150,7 @@ * **Time zone** : when you pick a preset frequency, enter the time in your local time zone. * **Cron expression time zone** : when the expression is five fields alone, write the hours in UTC, so `0 9 * * 1-5` runs at 9:00 AM UTC on weekdays. If the field opens with a `CRON_TZ=` prefix, keep it and write the hours in its zone, or delete it and write them in UTC. -#### - -​ - -Schedule a one-off run +#### Schedule a one-off run A one-off schedule runs the task a single time at a specific timestamp. For example, use it to: @@ -202,11 +166,7 @@ One-off runs count against the same hourly limit as other scheduled runs. See Usage and limits for details. -### - -​ - -Add an API trigger +### Add an API trigger An API trigger gives a scheduled task a dedicated HTTP endpoint. POSTing to the endpoint with the task’s bearer token starts a new session and returns a session URL. Use this to wire Claude Code into alerting systems, deploy pipelines, internal tools, or anywhere you can make an authenticated HTTP request. Add an API trigger on the web, either while you create the task or later with the steps below. You can’t add an API trigger or manage its token from the CLI. @@ -239,11 +199,7 @@ * **Turn off API access** : click **Delete token** , the trash icon next to **Regenerate**. This removes the API trigger * **Rotate the token** : click **Regenerate**. The previous token stops working, and the **Token generated** dialog shows the new one once -#### - -​ - -Trigger a scheduled task +#### Trigger a scheduled task Send a POST request to the `/fire` endpoint with the bearer token in the `Authorization` header. The request body accepts an optional `text` field for run-specific context such as an alert body or a failing log, passed to the task alongside its saved prompt. The value is freeform text and is not parsed: if you send JSON or another structured payload, the task receives it as a literal string. The `text` value doesn’t reach the routine as a bare message. It arrives wrapped in a `<routine-fire-payload>` block that labels it as untrusted data and tells Claude not to follow instructions inside it unless the routine’s own prompt says to. The same wrapping applies to text supplied with **Run now** in the web UI. This means a routine’s saved prompt must opt in to acting on fire text: write the prompt to reference the payload explicitly, for example “Investigate the alert described in the routine-fire-payload block”, or the routine treats the text as inert context. Anyone holding the bearer token can send `text`, so the wrapper makes fire text from a leaked token arrive labeled as untrusted data rather than as direct instructions to your routine. The example below triggers a scheduled task from a shell. The task ID and token shown are placeholders: replace them with the URL and token you copied when adding the API trigger, or the request fails with a `401` authentication error: @@ -266,19 +222,11 @@ The `/fire` endpoint ships under the `experimental-cc-routine-2026-04-01` beta header. Request and response shapes, rate limits, and token semantics may change while the feature is in research preview. Breaking changes ship behind new dated beta header versions, and the two most recent previous header versions continue to work so that callers have time to migrate. -#### - -​ - -API reference +#### API reference For the full API reference, including all error responses, validation rules, and field limits, see [Trigger a routine through the API](<https://platform.claude.com/docs/en/api/claude-code/routines-fire>) in the Claude Platform documentation. The `/fire` endpoint is available to claude.ai users only and is not part of the Claude Platform API surface. -### - -​ - -Add a GitHub trigger +### Add a GitHub trigger A GitHub trigger starts a new session automatically when a matching event occurs on a connected repository. Claude Code doesn’t reuse sessions across events, so two PR updates produce two independent sessions. @@ -309,11 +257,7 @@ Change the repository if needed, choose an event from the supported events list, and optionally add filters. Then click **Save changes** at the bottom of the dialog to apply the trigger. -#### - -​ - -Supported events +#### Supported events Choose an event from any of the following categories. Within each category you can pick a specific action, such as `pull_request.opened`, or react to all actions in the category. @@ -323,11 +267,7 @@ Release| A release is created, published, edited, or deleted Issue| An issue is opened, edited, closed, reopened, labeled, assigned, or otherwise updated -#### - -​ - -Filter pull requests +#### Filter pull requests Use filters to narrow which pull requests start a new session. All filter conditions must match for the scheduled task to trigger. The available filter fields are: @@ -348,19 +288,11 @@ * **Ready-for-review only** : is draft is `false`. Skips drafts so the task only runs when the PR is ready for review. * **Label-gated backport** : labels include `needs-backport`. Triggers a port-to-another-branch task only when a maintainer tags the PR. -## - -​ - -Manage scheduled tasks +## Manage scheduled tasks Click a scheduled task in the list to open its detail page. The detail page shows the task’s repositories, connectors, prompt, schedule, API tokens, GitHub triggers, and a list of past runs. -### - -​ - -View and interact with runs +### View and interact with runs Click any run to open it as a full session. From there you can see what Claude did, review changes, create a pull request, or continue the conversation. Each run session works like any other session: use the dropdown menu next to the session title to rename, archive, or delete it. Under **History** on the task’s detail page, each finished run’s row ends with **Error** if the run failed, **Cancelled** if it was cancelled, and neither word if it succeeded. The **Status** filter names the same three outcomes **Failed** , **Cancelled** , and **Succeeded**. These outcomes say how the session ended, not whether Claude completed the work your prompt describes, so open the run and read its transcript to see what happened. @@ -370,11 +302,7 @@ If a warning appears under **History** , see “The last run” warnings. -### - -​ - -Edit and control scheduled tasks +### Edit and control scheduled tasks From the detail page you can: @@ -383,19 +311,11 @@ * Open the menu next to the task’s name and select **Edit** to change the name, prompt, repositories, environment, connectors, or any of the task’s triggers. The **Edit scheduled task** dialog opens with the same layout as the creation dialog. To add a trigger, click **+** in the **Trigger** row. Click **Save changes** to apply your edits. API token actions take effect immediately, without **Save changes**. * Open the same menu and select **Delete** to delete the task. -### - -​ - -Manage scheduled tasks from the CLI +### Manage scheduled tasks from the CLI Run `/schedule list` to see your scheduled tasks, `/schedule update` to change one, or `/schedule run` to start one immediately. You can also ask about a scheduled task’s run history, for example `/schedule why did my nightly review do nothing this morning?`. Claude lists the task’s recent runs with their status and a link to open each run on the web. It also reads a run’s log to explain what happened, including tool errors, permission denials, and the final result. Requires Claude Code v2.1.227 or later. -### - -​ - -Repositories and branch permissions +### Repositories and branch permissions Scheduled tasks need GitHub access to clone repositories. When you create a scheduled task from the CLI with `/schedule`, Claude checks whether your account has GitHub access for the repository you ran it from. If it doesn’t, Claude adds a setup note naming how to grant it. @@ -403,11 +323,7 @@ If your GitHub connection is missing or expired when a run is due, the scheduled task skips runs until you reconnect, for up to 72 hours. Reconnect GitHub within that window and the task resumes on its own. After 72 hours without a connection, the task turns off, and you turn it back on after reconnecting GitHub. Each repository you add is cloned on every run. Claude starts from the repository’s default branch unless your prompt specifies otherwise. If a GitHub pull request event triggers the run and the pull request’s repository is the task’s first repository, that repository starts from the pull request’s head commit instead. Claude pushes its work to a branch prefixed with `claude/` unless your prompt directs it to push to another branch. To control which branches a run can push to, use branch protection rules or rulesets on GitHub. For runs on Anthropic-managed infrastructure, and for self-hosted runs that push through [Anthropic’s git proxy](</docs/en/self-hosted-environments-deploy#use-the-anthropic-git-proxy>), GitHub applies them to the GitHub access you connected, so a rule that access can bypass doesn’t block a run’s push. A self-hosted run that pushes with the git credentials your deployment provides is checked against those instead. See [Configure git](</docs/en/self-hosted-environments-deploy#configure-git>). -### - -​ - -Connectors +### Connectors Scheduled tasks can use your connected MCP connectors to read from and write to external services during each run. For example, a task that triages support requests might read from a Slack channel and create issues in Linear. Connectors are the [claude.ai integrations](</docs/en/mcp#use-mcp-servers-from-claude-ai>) on your account. MCP servers you added locally in the CLI with `claude mcp add` are stored on your machine rather than your claude.ai account, so they do not appear in the connectors list. To use one of those servers in a scheduled task: @@ -416,11 +332,7 @@ When you create a scheduled task, all of your currently connected connectors are included by default. Remove any that aren’t needed to limit which tools Claude has access to during the run. You can also add connectors directly from the task’s creation or edit dialog. To manage or add connectors outside of that dialog, visit [claude.ai/customize/connectors](<https://claude.ai/customize/connectors>) or use `/schedule update` in the CLI. -### - -​ - -Permission prompts during a run +### Permission prompts during a run For a task that runs in your organization’s self-hosted environment, see [Permissions and tool approval](</docs/en/self-hosted-environments-configuration#permissions-and-tool-approval>). @@ -431,19 +343,11 @@ If auto mode is unavailable, such as when your organization turned it off or the task’s model doesn’t support it, the run keeps the permission mode it launched in. To answer a waiting prompt, open the run from the task’s detail page. In a [project](</docs/en/claude-projects>), a run can continue a thread rather than start a new session. That run keeps whatever permission mode the thread is in at the time. When that thread was made, it started in auto mode unless auto mode was unavailable. To answer a prompt waiting in that thread, see [Unblock a thread waiting on approval](</docs/en/claude-projects#unblock-a-thread-waiting-on-approval>). -### - -​ - -When a run publishes an artifact without asking +### When a run publishes an artifact without asking During a run in auto mode, Claude publishes an [artifact](</docs/en/artifacts>) without asking you once the classifier allows the publish. You’re still asked first when, for example, the publish matches an [ask rule](</docs/en/permissions#manage-permissions>). A new artifact is visible only to you until you [share it](</docs/en/artifacts#share-an-artifact>). The Accept edits rules that follow don’t apply in auto mode. When a scheduled task’s job is to keep a page current, give it an artifact you already published. -#### - -​ - -Artifacts in Accept edits mode +#### Artifacts in Accept edits mode When a scheduled task’s schedule or **Run now** starts a run, Claude can publish a new [artifact](</docs/en/artifacts>) without asking. The new artifact is visible only to you until you [share it](</docs/en/artifacts#share-an-artifact>). If the publish declares runtime capabilities for the page, such as [connector calls](</docs/en/artifacts#pull-live-data-with-mcp-connectors>) or [file downloads](</docs/en/artifacts#offer-a-file-download>), Claude asks first. In those runs, Claude republishes an existing artifact without asking only when all of these hold: @@ -457,13 +361,9 @@ In every other case, including a run that an API or GitHub trigger starts, Claude asks first. -### - -​ - -Environments and network access - -Each scheduled task uses a [cloud environment](</docs/en/cloud-environments>) that controls network access, environment variables, and setup scripts. The task inherits the environment’s network policy on every run. The **Default** environment uses **Limited** access with **Allow package managers** checked, so its runs reach the [default allowlist](</docs/en/cloud-environments#default-allowed-domains>). A request to a blocked host fails with `403` and `x-deny-reason: host_not_allowed`. MCP connector traffic is routed through Anthropic’s servers, so the connectors you add to the task work without adding their hosts to **Allowed domains**. Remove any connectors you don’t need under Connectors. To allow additional domains on one of your own environments, follow these steps. An [organization-shared environment](</docs/en/cloud-environments#organization-shared-environments>) opens read-only here, so an Owner changes its network access from the **Cloud environments** page in [admin settings](<https://claude.ai/admin-settings>) instead. +### Environments and network access + +Each scheduled task uses a [cloud environment](</docs/en/cloud-environments>) that controls network access, environment variables, and setup scripts. The task inherits the environment’s network policy on every run. The **Default** environment uses **Limited** access with **Allow package managers** checked, so its runs reach the [default allowlist](</docs/en/cloud-environments#default-allowed-domains>). A request to a blocked host fails with [an error such as a `403` or `ENOTFOUND`](</docs/en/errors#host-not-allowed-in-a-cloud-session>). MCP connector traffic is routed through Anthropic’s servers, so the connectors you add to the task work without adding their hosts to **Allowed domains**. Remove any connectors you don’t need under Connectors. To allow additional domains on one of your own environments, follow these steps. An [organization-shared environment](</docs/en/cloud-environments#organization-shared-environments>) opens read-only here, so an Owner changes its network access from the **Cloud environments** page in [admin settings](<https://claude.ai/admin-settings>) instead. 1 @@ -497,11 +397,7 @@ See [Network access](</docs/en/cloud-environments#network-access>) for details on access levels and the default allowlist. -## - -​ - -Usage and limits +## Usage and limits Scheduled tasks draw down subscription usage the same way interactive sessions do. See your current consumption at [claude.ai/settings/usage](<https://claude.ai/settings/usage>). Separately from subscription usage, each way of starting a run has an hourly limit: @@ -515,11 +411,7 @@ None of these hourly limits has overage. When a scheduled task hits your subscription usage limit, organizations with usage credits turned on can keep running scheduled tasks on metered overage. Without usage credits, additional runs are rejected until your usage window resets. Turn on usage credits at [claude.ai/settings/usage](<https://claude.ai/settings/usage>). On Team and Enterprise plans, an admin turns them on for the organization at [claude.ai/admin-settings/usage](<https://claude.ai/admin-settings/usage>). While your subscription is paused, your scheduled tasks are put on hold and don’t run. Once your subscription is active again, turn them back on. -## - -​ - -Where the name routines still appears +## Where the name routines still appears Scheduled tasks were previously called routines, and these places keep the earlier name. Each one refers to the same feature: @@ -529,17 +421,9 @@ * **API** : the `/fire` endpoint path, its beta header, its response `type`, the `<routine-fire-payload>` tag, and the [Trigger a routine through the API](<https://platform.claude.com/docs/en/api/claude-code/routines-fire>) reference page * **Organization settings** : the **Scheduled tasks (Was Routines)** or **Routines** toggle -## - -​ - -Troubleshooting - -### - -​ - -`/schedule` returns “Unknown command” +## Troubleshooting + +### `/schedule` returns “Unknown command” The CLI hides `/schedule` when one of its requirements isn’t met: the command menu shows `No commands match "/schedule"` while you type. Submitting it returns `Unknown command: /schedule`, except in the cases below that note a different answer. The cause is usually one of the following: @@ -552,19 +436,11 @@ If the cause is your CLI sign-in or being inside a cloud session, you can still create and manage scheduled tasks at [claude.ai/code/routines](<https://claude.ai/code/routines>). You need a Pro, Max, Ultra, Team, or Enterprise account there. If scheduled tasks or cloud sessions are off for your organization or missing from your roles, you can’t create them on the web either. -### - -​ - -Scheduled tasks are off for your organization +### Scheduled tasks are off for your organization Cloud scheduled tasks are off for your organization, and you can’t change that from your local configuration. Ask your Team or Enterprise Owner whether they can turn on the **Scheduled tasks (Was Routines)** or **Routines** toggle at [**Organization settings > Capabilities > Remote sessions**](<https://claude.ai/admin-settings/capabilities>). -### - -​ - -“The last run” warnings +### “The last run” warnings When a warning under **History** begins with “The last run”, find it in the first column and do what its row says. The warning clears once a later run starts. @@ -579,11 +455,7 @@ ”The last run stopped because a usage limit was reached.”| For when the task’s runs can start again after a usage limit, see Usage and limits ”The last run failed.”| Click **Run now** to try again, or wait for the next run. The failed run has no session to open -## - -​ - -Related resources +## Related resources * [`/loop` and in-session scheduling](</docs/en/scheduled-tasks>): schedule local tasks within an open CLI session * [Desktop scheduled tasks](</docs/en/desktop-scheduled-tasks>): local scheduled tasks that run on your machine with access to local files
modified Choose a sandbox environment View current →
Show diff (160 lines)
--- a/sandbox-environments.md +++ b/sandbox-environments.md @@ -2,11 +2,7 @@ For the broader security model, see [Security](</docs/en/security>). For Agent SDK deployments, see [Secure deployment](</docs/en/agent-sdk/secure-deployment>). -## - -​ - -Compare sandboxing approaches +## Compare sandboxing approaches The first two approaches in the table below run on the host operating system without containers. The rest place Claude Code inside a container or virtual machine. @@ -23,11 +19,7 @@ Sandbox isolation reduces the impact of a breach, but it does not eliminate risk. Any approach that allows network egress can still leak data the agent can read, and any approach that mounts your project directory writable can still modify that code. Review the [security limitations](</docs/en/sandboxing#security-limitations>) before relying on a sandbox as a hard control.Isolation also does not change what is sent to the model. Your prompts and the files Claude reads are transmitted to the Anthropic API or your configured provider with or without a sandbox. See [Data usage](</docs/en/data-usage>) for what Claude Code sends and how to reduce it. -## - -​ - -Choose an approach +## Choose an approach Match your goal to a row below, then read the detail section that follows. @@ -41,19 +33,11 @@ Require isolation for every developer in your organization| Enforce isolation across an organization Work on a native Windows host| A container or VM, or run the Bash sandbox inside WSL2 -### - -​ - -How isolation relates to permission modes +### How isolation relates to permission modes [Permission modes](</docs/en/permission-modes>) decide whether a tool call runs and whether you are prompted first. Isolation restricts what a command can access once it runs. The two work together: when a permission mode lets actions run without asking you, an isolation boundary limits what those actions can reach. When you pass `--dangerously-skip-permissions`, Claude acts without asking you first. The [actions no mode auto-approves](</docs/en/permission-modes#actions-no-mode-auto-approves>) still apply. With no prompts to catch mistakes, the isolation boundary you choose is what protects your system. Always run `--dangerously-skip-permissions` sessions inside a container, a VM, or the sandbox runtime, so that file tools, MCP servers, and hooks are also inside the boundary. On Linux and macOS, Claude Code refuses to start with this flag when running as root, so run the container, VM, or sandbox runtime as a non-root user. [Auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) replaces the prompt with a classifier that reviews actions. The classifier is a per-action control, not an isolation boundary, so an isolation boundary still adds defense in depth for unattended runs, and is not required the way it is for `--dangerously-skip-permissions`. The sandboxed Bash tool on its own constrains only shell commands, so it is not sufficient for fully unattended runs in either mode. You can layer approaches: running the sandboxed Bash tool inside a container or VM gives you OS-level command restrictions on top of the outer environment boundary. For how the Bash sandbox itself interacts with permission rules and modes, see [How sandboxing relates to permissions and permission modes](</docs/en/sandboxing#how-sandboxing-relates-to-permissions-and-permission-modes>). -## - -​ - -Sandboxed Bash tool +## Sandboxed Bash tool This option does not support native Windows. On Windows hosts, use WSL2 or one of the container or VM approaches below. @@ -64,19 +48,11 @@ To put built-in tools, MCP servers, and hooks all behind one OS boundary, run the whole Claude Code process inside the sandbox runtime, the dev container, or a custom container. -## - -​ - -Sandbox runtime +## Sandbox runtime The [`@anthropic-ai/sandbox-runtime`](<https://github.com/anthropics/sandbox-runtime>) package wraps an entire process in the same Seatbelt or bubblewrap isolation that the built-in Bash sandbox uses. Running Claude Code through the runtime constrains the session’s tools, hooks, and MCP servers as well as shell commands. The runtime is a beta research preview, and its configuration format may change as the package evolves. This section covers what you configure and what the runtime enforces on its own. For deploying the runtime in Agent SDK applications, see the [secure deployment guide](</docs/en/agent-sdk/secure-deployment#sandbox-runtime>). -### - -​ - -Set up and launch the runtime +### Set up and launch the runtime On Linux and WSL2, the runtime relies on the same `bubblewrap` and `socat` packages as the built-in sandbox, plus `ripgrep`, which Claude Code bundles but the standalone runtime resolves from your PATH. Install `bubblewrap` and `socat` as described in [Set up Linux and WSL2](</docs/en/sandboxing#set-up-linux-and-wsl2>), and `ripgrep` from your distribution’s package manager. On macOS you need no additional packages. The runtime uses the built-in Seatbelt sandbox there. By default the runtime denies network access and confines writes to a small set of built-in runtime paths, so configure it before launching Claude Code through it. Put your configuration in `~/.srt-settings.json`, or in a file you pass with `--settings`. The package [README](<https://github.com/anthropics/sandbox-runtime>) documents the configuration schema. Allow write access to at least: @@ -105,11 +81,7 @@ Claude Code starts inside the sandbox with the filesystem and network boundaries you configured. The same `srt` command works for sandboxing standalone MCP servers or other helper processes. -### - -​ - -What the runtime blocks on its own +### What the runtime blocks on its own The runtime blocks the highest-risk writes without any configuration from you: @@ -122,43 +94,23 @@ Your write grants still include other paths Claude Code loads configuration from, so deny those with `denyWrite`. A sandboxed session that can write them can persist hooks, permission rules, or MCP servers that run unsandboxed the next time you launch Claude Code. -### - -​ - -After unattended runs +### After unattended runs Review the paths you kept writable. On Linux and WSL2, also review anything the session created. -## - -​ - -Dev containers +## Dev containers A dev container runs Claude Code inside a Docker container that VS Code or a compatible editor manages, with your project mounted in. You can define your own with a `.devcontainer/` directory in your repository. The claude-code repository publishes an [example dev container](</docs/en/devcontainer>) with a default-deny iptables firewall as a starting point. Copy it into your repository and adjust the firewall allowlist, base image, and pinned Claude Code version to fit your environment. Because the firewall blocks unapproved egress, a configuration like this supports running Claude Code with `--dangerously-skip-permissions` for unattended work. -## - -​ - -Custom container +## Custom container You can run Claude Code in any Docker or OCI container image with your own network policies, mounted volumes, and seccomp profiles. This is the most common path for organizations with existing container infrastructure or CI runners. Several managed sandbox and remote execution services can host the container for you. The same checklist applies as for any container you operate: review what is mounted writable, what credentials and tokens are reachable inside it, and what the network egress policy allows. You can layer the built-in Bash sandbox inside the container for per-command restrictions. Unprivileged containers need `enableWeakerNestedSandbox`, described in [Bubblewrap fails to start inside a container](</docs/en/sandboxing#bubblewrap-fails-to-start-inside-a-container>). -## - -​ - -Virtual machine +## Virtual machine A dedicated virtual machine provides the strongest separation, with its own kernel and, in cloud or microVM deployments, its own virtualized hardware. Options include cloud instances, local hypervisors, and microVMs such as Firecracker. Use this approach when your security policy requires kernel-level separation between the agent and the host, or when no host-level approach meets your compliance requirements. [Docker Sandboxes](<https://docs.docker.com/ai/sandboxes/>) provides a microVM with its own Docker daemon and workspace sync, which can run Claude Code on any host with Docker Sandboxes installed. It is a free, standalone product from Docker that does not require Docker Desktop. -## - -​ - -Cloud sessions +## Cloud sessions A [cloud session](</docs/en/claude-code-on-the-web>) runs in an isolated, Anthropic-managed virtual machine. A network proxy enforces a default allowlist, and a separate proxy holds your GitHub token outside the sandbox while issuing scoped credentials for repository access inside it. Sessions your organization routes to a [self-hosted environment](</docs/en/self-hosted-environments>) run on infrastructure you provision instead, where isolation, egress control, and git credentials are your deployment’s responsibility. Use this approach when you want full VM isolation without provisioning infrastructure yourself, or when you are delegating tasks from a device that does not have a local development environment. It requires: @@ -167,11 +119,7 @@ See [Use Claude Code in the cloud](</docs/en/claude-code-on-the-web>) for plan availability and GitHub authentication options. -## - -​ - -Enforce isolation across an organization +## Enforce isolation across an organization Individual developers can opt into any of the sandboxing approaches on this page. What an organization can enforce, and with which tools, depends on the approach: @@ -179,11 +127,7 @@ * **Dev containers** : commit the [example dev container](</docs/en/devcontainer>) to your repositories to standardize the environment across a team. This is a convention rather than an enforcement boundary, because Claude Code does not require a container. If developers should not be able to run Claude Code outside it, enforce that with your organization’s device management or software allowlisting tools. * **Custom containers and VMs** : distribute Claude Code through the approved image and use your organization’s device management or software allowlisting tools to prevent installation outside it. -## - -​ - -See also +## See also These pages cover configuration and policy details for the sandboxing approaches on this page.
modified Configure the sandboxed Bash tool View current →
Show diff (810 lines)
--- a/sandboxing.md +++ b/sandboxing.md @@ -6,11 +6,7 @@ * To compare other isolation approaches such as dev containers, custom containers, and virtual machines, see [Sandbox environments](</docs/en/sandbox-environments>) * To reduce permission prompts for tools other than Bash, see [permission modes](</docs/en/permission-modes>) -## - -​ - -What the sandbox restricts +## What the sandbox restricts While the sandbox is on, the shell commands Claude runs start inside its boundary, and so do the processes they start. The sandbox is off by default. To turn it on, run `/sandbox` in a session, as Get started shows, or set [`sandbox.enabled`](</docs/en/settings-reference#sandbox-enabled>) to `true` in a [settings file](</docs/en/settings>) such as `~/.claude/settings.json`. The table shows what a sandboxed command can reach by default and the settings that change each default. @@ -23,11 +19,7 @@ Claude Code builds the sandbox on the open source [`@anthropic-ai/sandbox-runtime`](<https://github.com/anthropics/sandbox-runtime>) package. -### - -​ - -What runs outside the sandbox +### What runs outside the sandbox The sandbox wraps shell commands. These tools and processes run outside it: @@ -43,11 +35,7 @@ To put the tools, processes, and commands in this section behind one boundary, run the Claude Code process itself in a [container, virtual machine, or the sandbox runtime](</docs/en/sandbox-environments>). -## - -​ - -Get started +## Get started The sandbox is built into Claude Code. What you install depends on your platform: @@ -88,11 +76,7 @@ By default, when the platform doesn’t support the sandbox or the dependency check at startup fails, Claude Code runs commands without sandboxing. To make Claude Code exit at startup instead, set [`sandbox.failIfUnavailable`](</docs/en/settings-reference#sandbox-failifunavailable>) to `true`. Managed deployments that require sandboxing as a security gate can use this setting. -### - -​ - -Confirm commands run inside the sandbox +### Confirm commands run inside the sandbox To check that the sandbox is working, ask Claude to run each line in the table. What you type at the `!` prompt usually runs outside the sandbox, so typing a line yourself doesn’t test it. @@ -103,11 +87,7 @@ If Claude asks to retry a failed command outside the sandbox, decline the retry. If `touch` succeeds and your home directory isn’t one of the directories the sandbox lets commands write to, delete `~/sandbox-probe`. Then run `/sandbox` to check that the sandbox is on and its dependencies are installed. -### - -​ - -Set up Linux and WSL2 +### Set up Linux and WSL2 On Linux and WSL2, the sandbox relies on these packages: @@ -135,11 +115,7 @@ Check your WSL version with `wsl -l -v` from PowerShell. If you see `Sandboxing requires WSL2`, your distribution is running WSL1. Upgrade it to WSL2 or run Claude Code without sandboxing.On WSL2, WSL hands a launch of a Windows binary such as `cmd.exe`, `powershell.exe`, or anything under `/mnt/c/` to the Windows host over a Unix socket, so whether a sandboxed command can launch one follows the sandbox’s [Unix-socket settings](</docs/en/settings-reference#sandbox-network-allowunixsockets>): the optional seccomp filter has to be installed to block the socket in the first place. To allow these launches, set `allowAllUnixSockets`, which opens every Unix socket to sandboxed commands. -#### - -​ - -Add an AppArmor profile for bubblewrap +#### Add an AppArmor profile for bubblewrap Add the profile if Claude Code runs `/usr/bin/bwrap` and either of these happens: @@ -164,19 +140,11 @@ Then restart Claude Code and confirm the sandbox works. -### - -​ - -Sandbox modes +### Sandbox modes Claude Code offers two sandbox modes. In both, the sandbox enforces the same filesystem and network restrictions; the difference is only in whether sandboxed commands are auto-approved or require explicit permission. -#### - -​ - -Auto-allow mode +#### Auto-allow mode Claude Code approves a command automatically, with no prompt, when the command runs inside the sandbox. A command goes through the regular [permission flow](</docs/en/permissions>) when it runs outside the sandbox because it matches `excludedCommands` or because Claude retries it unsandboxed. A sandboxed command that connects to a host you haven’t allowed stays in the sandbox. Hosts outside your allowed domains covers who decides whether the connection goes through. Even in auto-allow mode, the following still apply: @@ -196,19 +164,11 @@ Auto-allow mode works independently of your permission mode setting, with three exceptions: [plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>), an auto mode command that carries per-command allowed domains, and [server-side classifier review](</docs/en/permission-modes#how-the-classifier-evaluates-actions>) of sandboxed commands in auto mode. Even if you’re not in “accept edits” mode, sandboxed Bash commands run automatically when auto-allow is enabled. This means Bash commands that modify files within the sandbox boundaries execute without prompting, even in Manual mode, where the file edit tools would prompt.In plan mode, auto-allow doesn’t widen approvals; see [plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>) for how Claude Code gates commands while you plan. -#### - -​ - -Regular permissions mode +#### Regular permissions mode All Bash commands go through the regular permission flow, even when sandboxed. This provides more control but requires more approvals. -#### - -​ - -The unsandboxed retry escape hatch +#### The unsandboxed retry escape hatch The unsandboxed retry is an escape hatch for commands that fail inside the sandbox, such as tools that are incompatible with it. When the sandbox blocks a network connection, Claude Code names the denied host in the command’s result, so Claude sees what was blocked. Claude analyzes the failure and may retry the command with the `dangerouslyDisableSandbox` parameter. The retried command runs unsandboxed. In an interactive terminal session, who approves it depends on your permission mode: @@ -226,11 +186,7 @@ While commands are refused with a `Sandbox is required` message, Claude Code ignores the `dangerouslyDisableSandbox` parameter and refuses the retry too. -#### - -​ - -Turn off the retry with strict sandbox mode +#### Turn off the retry with strict sandbox mode You can disable the unsandboxed retry by setting `"allowUnsandboxedCommands": false` in your [sandbox settings](</docs/en/settings-reference#sandbox-settings>). With the retry disabled, Claude Code ignores the `dangerouslyDisableSandbox` parameter. While the sandbox is running, commands Claude runs are then sandboxed unless they match an `excludedCommands` entry. To keep Claude Code from running commands unsandboxed when the sandbox can’t start, also set [`failIfUnavailable`](</docs/en/settings-reference#sandbox-failifunavailable>). The `/sandbox` **Overrides** tab shows this setting as **Strict sandbox mode**. A `false` in your user settings, `--settings`, or managed settings holds even when a project’s settings set `true`. A `false` in your user settings doesn’t make the sandbox admin-required, so a project’s other sandbox settings still apply. Before v2.1.285, a project’s `true` overrode a `false` in your user settings. If you or your administrator disable the retry in managed settings or with the `--settings` flag, the sandbox becomes admin-required. Claude Code then ignores the settings in a repository’s files that loosen the sandbox, `excludedCommands` entries included. Repository settings under an admin-required sandbox lists them. Strict sandbox mode applies to the commands Claude runs. Commands you type yourself at the [`!` shell-mode prompt](</docs/en/interactive-mode#shell-mode-with-prefix>) run outside the sandbox unless the session is one of these: @@ -239,19 +195,11 @@ Before v2.1.260, strict sandbox mode sandboxed shell-mode commands in every session. -#### - -​ - -Temporary directories +#### Temporary directories A per-user temp directory is writable inside the sandbox by default, alongside the working directory. Unless you disable filesystem isolation, Claude Code sets `$TMPDIR` to this directory for sandboxed commands, so tools that write temporary files work without extra configuration. Unsandboxed commands inherit your shell’s `$TMPDIR` when it is set, so while filesystem isolation is on, sandboxed and unsandboxed commands resolve `$TMPDIR` to different directories. If your shell leaves `$TMPDIR` unset or empty, an unsandboxed command that references `$TMPDIR` receives your [`CLAUDE_CODE_TMPDIR`](</docs/en/env-vars>) override, or the operating system’s temp directory when you haven’t set one or the override is a long path, so the variable doesn’t expand to an empty string. To pass temporary files between the two, write them under the working directory instead. -## - -​ - -Configure sandboxing +## Configure sandboxing Customize sandbox behavior through your `settings.json` file. See [Settings](</docs/en/settings-reference#sandbox-settings>) for the complete configuration reference. By default, sandboxed commands can write to the current working directory, the per-user temp directory, and any [directories you’ve added](</docs/en/permissions#additional-directories-grant-file-access-not-configuration>) with `--add-dir`, `/add-dir`, or `permissions.additionalDirectories`. If subprocess commands like `kubectl`, `terraform`, or `npm` need to write outside those directories, use `sandbox.filesystem.allowWrite` to grant access to specific paths: @@ -264,7 +212,7 @@ } } -These paths are enforced at the OS level, so all commands running inside the sandbox, including their child processes, respect them. This is the recommended approach when a tool needs write access to a specific location, rather than excluding the tool from the sandbox entirely with `excludedCommands`. When you define the same filesystem array in multiple [settings scopes](</docs/en/settings#settings-precedence>), Claude Code merges them, combining the paths rather than replacing one scope’s array with another’s. Claude Code leaves an entry out of the merge when a lock under Keep developers from widening the policy covers it. If you exclude a source with [`--setting-sources`](</docs/en/cli-reference>) on the CLI or [`settingSources`](</docs/en/agent-sdk/claude-code-features#control-filesystem-settings-with-settingsources>) in the Agent SDK, Claude Code ignores its `sandbox.filesystem` entries, its `Edit` permission rules, and its `Read` deny rules when building the sandbox configuration. Requires Claude Code v2.1.246 or later. When you edit these filesystem lists during a session, Claude Code [applies the change to the running session](</docs/en/settings#when-edits-take-effect>), so the next sandboxed command runs under the new paths. Sandbox filesystem paths use standard conventions: `/tmp/build` is absolute and `~/.kube` is relative to your home directory. This differs from [Read and Edit permission rules](</docs/en/permissions#read-and-edit>), which use `//path` for absolute and `/path` for project-relative. For relative paths, trailing slashes, and wildcards, see [Sandbox path prefixes](</docs/en/settings-reference#sandbox-path-prefixes>). You can also deny write or read access using `sandbox.filesystem.denyWrite` and `sandbox.filesystem.denyRead`, and re-allow specific paths within a denied region using `sandbox.filesystem.allowRead`. When read rules overlap, the rule with the narrower path applies: +These paths are enforced at the OS level, so all commands running inside the sandbox, including their child processes, respect them. This is the recommended approach when a tool needs write access to a specific location, rather than excluding the tool from the sandbox entirely with `excludedCommands`. On Linux and WSL2, an entry for a path that doesn’t exist yet has no effect, so create the path first. When you define the same filesystem array in multiple [settings scopes](</docs/en/settings#settings-precedence>), Claude Code merges them, combining the paths rather than replacing one scope’s array with another’s. Claude Code leaves an entry out of the merge when a lock under Keep developers from widening the policy covers it. If you exclude a source with [`--setting-sources`](</docs/en/cli-reference>) on the CLI or [`settingSources`](</docs/en/agent-sdk/claude-code-features#control-filesystem-settings-with-settingsources>) in the Agent SDK, Claude Code ignores its `sandbox.filesystem` entries, its `Edit` permission rules, and its `Read` deny rules when building the sandbox configuration. Requires Claude Code v2.1.246 or later. When you edit these filesystem lists during a session, Claude Code [applies the change to the running session](</docs/en/settings#when-edits-take-effect>), so the next sandboxed command runs under the new paths. Sandbox filesystem paths use standard conventions: `/tmp/build` is absolute and `~/.kube` is relative to your home directory. This differs from [Read and Edit permission rules](</docs/en/permissions#read-and-edit>), which use `//path` for absolute and `/path` for project-relative. For relative paths, trailing slashes, and wildcards, see [Sandbox path prefixes](</docs/en/settings-reference#sandbox-path-prefixes>). You can also deny write or read access using `sandbox.filesystem.denyWrite` and `sandbox.filesystem.denyRead`, and re-allow specific paths within a denied region using `sandbox.filesystem.allowRead`. When read rules overlap, the rule with the narrower path applies: Example rules| Result ---|--- @@ -286,11 +234,7 @@ If you placed the same configuration in `~/.claude/settings.json`, `.` would resolve to `~/.claude` instead, and project files would remain blocked by the `denyRead` rule. To deny sandboxed commands read access to home directories and mounted volumes while keeping the working directories readable, set [`permissions.blockReadsOutsideWorkingDirectories`](</docs/en/settings-reference#permissions-blockreadsoutsideworkingdirectories>) instead of writing path rules. -### - -​ - -Run commands outside the sandbox with `excludedCommands` +### Run commands outside the sandbox with `excludedCommands` List a command pattern in [`sandbox.excludedCommands`](</docs/en/settings-reference#sandbox-excludedcommands>) to run matching commands outside the sandbox, which means no filesystem restrictions and no network proxy. Use it for a tool that can’t work inside the sandbox and that you trust with your full access. A tool that needs one more directory or one more host may work with `allowWrite` or `allowedDomains`, which keep the command sandboxed. This example takes `docker compose` commands out of the sandbox. Save it in `~/.claude/settings.json` to apply it to all of your projects: @@ -320,11 +264,7 @@ An excluded command runs with your full access. A broad entry such as `docker *` covers everything that tool can do. If you write a pattern that covers an interpreter, a script inside your working directory, or a tool that acts on a file there, as `docker compose` does with its compose file, Claude can write that file and then run it outside the sandbox. A narrower pattern leaves less that Claude can run outside the sandbox. -### - -​ - -Disable filesystem isolation +### Disable filesystem isolation Set `sandbox.filesystem.disabled` to `true` to skip filesystem isolation while keeping network isolation. The example below turns off filesystem isolation while keeping an allowlist of network domains: @@ -344,25 +284,17 @@ With filesystem isolation off and commands auto-allowed, a sandboxed command can write files that later commands run or read, such as shell startup files, executables on `$PATH`, or `~/.claude/settings.json`, and use them to widen its own access on the next run. Set `filesystem.disabled` to `true` only for workloads you trust not to escalate their own access. Locking network domains with `allowManagedDomainsOnly` narrows the risk but doesn’t remove it, since that lock applies only to commands running inside the sandbox. -#### - -​ - -Which settings can disable it +#### Which settings can disable it Because turning filesystem isolation off widens what sandboxed commands can do, Claude Code honors `filesystem.disabled` from these settings sources only: - * User settings, managed settings, and the `--settings` CLI flag can set it. Project settings in `.claude/settings.json` and `.claude/settings.local.json` can’t, so a checked-out project can’t switch filesystem isolation off. - * When managed settings configure `sandbox.filesystem` at all, or list any `sandbox.credentials.files` entry with `"mode": "deny"`, only managed settings can set the key. This keeps developers from turning filesystem isolation off in such a deployment; to turn it off for everyone, set `"disabled": true` in managed settings. - * When [`CLAUDE_CODE_SUBPROCESS_ENV_SCRUB`](</docs/en/env-vars>) is set, Claude Code ignores `filesystem.disabled` from every source, including managed settings, and keeps filesystem isolation on. + * User settings, managed settings, and the `--settings` CLI flag can set it. Project settings in `.claude/settings.json` and `.claude/settings.local.json` can’t set it. + * When managed settings configure `sandbox.filesystem` at all, or list any `sandbox.credentials.files` entry with `"mode": "deny"`, only managed settings can set the key. To turn filesystem isolation off for everyone, set `"disabled": true` in managed settings. + * When [`CLAUDE_CODE_SUBPROCESS_ENV_SCRUB`](</docs/en/env-vars>) is set, Claude Code ignores `filesystem.disabled` from every source, including managed settings. A [valid](</docs/en/settings-reference#invalid-credential-entries-in-managed-settings>) `mask` entry doesn’t lock the key, even when Claude Code falls back to `deny` for it at startup. List a path that can’t be masked, such as a credential directory, as an explicit `deny` entry in managed settings, which locks the key. -#### - -​ - -What changes when filesystem isolation is off +#### What changes when filesystem isolation is off Setting `filesystem.disabled` lifts the protections the filesystem layer itself enforces. Protections that other layers enforce keep applying: @@ -377,11 +309,7 @@ * Sandboxed commands inherit your shell’s `$TMPDIR` instead of the per-user temp directory, because every temp directory is writable and Claude Code no longer redirects commands to the per-user one. On Linux the variable is often unset in the parent shell. The Bash tool guidance tells Claude to create scratch directories with `mktemp -d` instead of relying on `$TMPDIR`. * [`autoAllowBashIfSandboxed`](</docs/en/settings-reference#sandbox-autoallowbashifsandboxed>) still defaults to `true`, so sandboxed commands keep running without prompts. Set it to `false` to prompt for sandboxed commands. -### - -​ - -Protect credentials +### Protect credentials The `sandbox.credentials` setting declares credential files and environment variables to protect from sandboxed commands. Each entry names a file path or an environment variable and a `mode`. The dedicated `credentials` block keeps credential rules grouped together and separate from general filesystem rules. For entries with `"mode": "deny"`, file paths are denied for reads inside the sandbox, the same restriction that `filesystem.denyRead` applies, and environment variables are unset before each sandboxed command runs. The file protection is part of the filesystem layer, so it doesn’t apply if you disable filesystem isolation; the environment variable protection still does. The example below blocks reads of the AWS credentials file and the SSH directory and removes `GITHUB_TOKEN` and `NPM_TOKEN` from the environment of sandboxed commands: @@ -408,11 +336,7 @@ There is no built-in credential deny list, so only the files and variables you list are restricted. `sandbox.credentials` affects sandboxed Bash commands only. To strip credentials from all subprocesses regardless of sandboxing, set [`CLAUDE_CODE_SUBPROCESS_ENV_SCRUB`](</docs/en/env-vars>). -### - -​ - -Mask credentials +### Mask credentials When you mask a credential, Claude Code shows sandboxed commands a per-session placeholder called the sentinel, and the sandbox proxy substitutes the real value on outbound requests to hosts you allow. A `deny` entry under Protect credentials blocks the credential instead. For files on macOS, Claude Code blocks the file instead of masking it. The [`sandbox.credentials`](</docs/en/settings-reference#sandbox-credentials>) reference lists every field. Masking requires the following: @@ -420,11 +344,7 @@ * **An allowed destination** : each `mask` entry can list `injectHosts`, the hosts the real value is allowed to reach. The proxy injects only on connections the domain allowlist admits, so each `injectHosts` host must also be reachable through `network.allowedDomains`. For a `mask` entry with no `injectHosts`, the proxy substitutes the real value on requests to every host in `network.allowedDomains`. * **A trusted settings scope** : masking authorizes the proxy to send your real credential somewhere, so Claude Code honors `mask` entries, `network.tlsTerminate`, [`credentials.allowPlaintextInject`](</docs/en/settings-reference#sandbox-credentials-allowplaintextinject>), `awsPairs`, and `sigv4` only from user settings, managed settings, and the `--settings` flag. It ignores them in a repository’s `.claude/settings.json` or `.claude/settings.local.json`. When your administrator delivers `mask` entries, `network.tlsTerminate`, or `credentials.allowPlaintextInject` through server-managed settings, they count as [settings that need approval](</docs/en/server-managed-settings#security-approval-dialogs>). -#### - -​ - -Mask environment variables +#### Mask environment variables To mask an environment variable, set `"mode": "mask"` on its `credentials.envVars` entry. The command and anything it logs never hold the real credential, but its requests still authenticate. When the same variable is listed with `deny` in any scope, `deny` takes precedence. This example masks two tokens. `GH_TOKEN` is substituted only on requests to `api.github.com`, while `NPM_TOKEN` has no `injectHosts` and is substituted on requests to every host in `network.allowedDomains`: @@ -451,19 +371,11 @@ The proxy matches each `injectHosts` entry against the connection’s bare destination address, ignoring ports, so a bracketed, zone-ID, or differently compressed spelling never matches. `claude doctor` flags entries that can never match with the warning `Sandbox credential injectHosts entries can never match their destination`. This check requires Claude Code v2.1.229 or later. -#### - -​ - -Re-sign AWS requests +#### Re-sign AWS requests AWS requests carry SigV4 signatures over the request contents, so mask `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` together. The proxy detects a SigV4 request by the access key’s sentinel and re-signs the request with the real values, which requires Claude Code v2.1.221 or later. If you mask only the secret, requests are signed with a placeholder the proxy can’t detect, so they fail at AWS. Claude Code links the conventional `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_SESSION_TOKEN` variables into one credential automatically when you mask their whole values. If your AWS credential is in variables with other names, group them with [`credentials.awsPairs`](</docs/en/settings-reference#sandbox-credentials-awspairs>), which requires Claude Code v2.1.224 or later. Streaming uploads, presigned URLs, and SigV4A requests carry signatures the proxy can’t recompute. When one of these requests is signed with a masked pair’s placeholder, the proxy fails it rather than forward a broken signature. Requests signed with unmasked credentials aren’t affected. Use [`credentials.sigv4`](</docs/en/settings-reference#sandbox-credentials-sigv4>), which requires Claude Code v2.1.224 or later, to forward one of these request forms instead. AWS still rejects the request, so the calling tool receives AWS’s own rejection response instead of a proxy error. -#### - -​ - -Mask credential files +#### Mask credential files To mask a credential file, set `"mode": "mask"` on its `credentials.files` entry. Masking files requires Claude Code v2.1.221 or later. What a sandboxed command sees depends on the platform: @@ -498,17 +410,9 @@ `mask` applies to a single file, so list each credential file individually. Claude Code falls back to `deny` for a `mask` entry it can’t mask safely: a directory path, a glob pattern, a file larger than 8 MiB, or a file that isn’t UTF-8 text. -## - -​ - -How sandboxing works - -### - -​ - -Filesystem isolation +## How sandboxing works + +### Filesystem isolation The sandboxed Bash tool restricts file system access to specific directories: @@ -519,11 +423,7 @@ To skip filesystem isolation entirely while keeping network isolation, set `sandbox.filesystem.disabled`. -### - -​ - -Protected paths +### Protected paths Inside the directories that sandboxed commands can write to, the sandbox still denies writes to the files Claude Code loads configuration and code from. A command that could edit those files could grant itself permissions, or add a hook or MCP server that Claude Code runs outside the sandbox. The permission system has its own [protected paths](</docs/en/permission-modes#protected-paths>), which control what Claude Code approves before a tool runs; the sandbox’s list applies to a command that is already running. It covers four groups of paths: @@ -538,27 +438,15 @@ To see most of these paths resolved for your machine, run `/sandbox` and open the **Config** tab, which lists them under **Denied within allowed** , mixed in with your own `denyWrite` entries. If `git merge` or `git checkout` fails with `unable to unlink old` on one of these paths, see A git command fails with `unable to unlink old`. -#### - -​ - -When the sandbox deletes `HEAD`, `objects`, or `refs` +#### When the sandbox deletes `HEAD`, `objects`, or `refs` After a sandboxed command ends, a newer top-level `HEAD`, `objects`, or `refs` entry in your working directory is deleted unless it’s a folder with contents. Newer means the entry wasn’t there when the sandbox last built its configuration: at session start, or after a change such as [`/cd`](</docs/en/commands>). A newer `objects` or `refs` folder with contents is deleted too, with its contents, when a `HEAD` file or symlink was there the last time the sandbox built its configuration. To keep a folder, see A folder named `objects` or `refs` disappears after a command. -#### - -​ - -Denied paths that pass through a symlink +#### Denied paths that pass through a symlink On macOS, when a denied path passes through a symlink, such as a `~/.claude` that is a link into a dotfiles repository, the sandbox also denies the path’s real location. This covers the sandbox’s own denials and your literal `denyWrite` and `denyRead` entries. A `denyWrite` entry that contains `*`, `?`, or `[` is also covered when a folder before the first of those characters is a symlink. For example, `~/.claude/*.json` is also denied under the real location of `~/.claude`. -### - -​ - -Network isolation +### Network isolation A sandboxed command has no direct route to the network: @@ -584,11 +472,7 @@ The built-in proxy enforces the allowlist based on the requested hostname and, by default, does not terminate or inspect TLS traffic. The experimental [`network.tlsTerminate`](</docs/en/settings-reference#sandbox-network-tlsterminate>) setting makes the built-in proxy terminate TLS itself, which `mask` credential entries require. See Security limitations for the implications of the default, and Custom proxy configuration if your threat model requires TLS inspection. -#### - -​ - -Hosts outside your allowed domains +#### Hosts outside your allowed domains When a sandboxed command connects to a host that isn’t in your allowed domains, the command stays in the sandbox and waits for a decision. In an interactive terminal session, the decision depends on your permission mode: @@ -601,27 +485,15 @@ With [`strictAllowlist`](</docs/en/settings-reference#sandbox-network-strictallowlist>) or [`allowManagedDomainsOnly`](</docs/en/settings-reference#sandbox-network-allowmanageddomainsonly>) on, the built-in sandbox proxy refuses the connection in every permission mode. In `bypassPermissions` mode, hosts outside your allowed domains are allowed unless one of them is on. The unsandboxed retry escape hatch covers when a command can leave the sandbox in that mode. A connection to a host in [`deniedDomains`](</docs/en/settings-reference#sandbox-network-denieddomains>) is refused in every permission mode too. -#### - -​ - -Hostnames that resolve to local addresses +#### Hostnames that resolve to local addresses After a hostname passes the allowlist, the sandbox proxy resolves it and refuses the connection when the name resolves only to local addresses. Local addresses include loopback addresses such as `127.0.0.1`, link-local addresses such as the `169.254.169.254` cloud metadata endpoint, and addresses assigned to your own machine. The names `localhost` and `*.localhost` are allowed to resolve to loopback. An allowed intranet hostname that resolves to a private range such as `10.0.0.0/8` connects. To let a name resolve to a refused address, add that IP address to `allowedDomains`, such as `"127.0.0.1:8080"`. The check applies to hostnames. Your allowed domains and permission mode decide a connection to an IP address. The proxy also skips the check for connections it sends through an upstream corporate proxy, because that proxy resolves the name. -#### - -​ - -Per-command allowed domains in auto mode +#### Per-command allowed domains in auto mode In [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) with sandboxing on, Claude names the hosts a command needs on the command itself instead of triggering a network approval for each connection. Each Bash, PowerShell, or [Monitor](</docs/en/tools-reference#monitor-tool>) command that runs in the sandbox can carry a list of hosts beyond the sandbox’s allowlist: a domain such as `registry.npmjs.org`, a wildcard such as `*.pythonhosted.org`, or an IP address, each with an optional `:port`. The classifier reviews the hosts together with the command. Requires Claude Code v2.1.271 or later. An approved list opens those hosts for that one command alone, for as long as it runs. Nothing is added to your session’s allowed hosts or your settings; the next command names its own hosts. A command that carries hosts goes to the classifier instead of being approved by a permission rule or the sandbox’s auto-allow mode. If an [ask rule](</docs/en/permissions#manage-permissions>) forces a prompt for the command, the permission dialog in your terminal lists the hosts beside it, and approving there covers both. A per-command list widens only what the sandbox denies by default. [`deniedDomains`](</docs/en/settings-reference#sandbox-network-denieddomains>) entries still block. When [`strictAllowlist`](</docs/en/settings-reference#sandbox-network-strictallowlist>) or [`allowManagedDomainsOnly`](</docs/en/settings-reference#sandbox-network-allowmanageddomainsonly>) locks the allowlist, Claude Code refuses per-command lists. While per-command lists apply, Claude Code refuses a connection to a host that no approved command listed, without a prompt or a classifier check. The refusal names the host in the command’s result, and Claude re-runs the command with the host added. -#### - -​ - -IPv6 addresses in domain lists +#### IPv6 addresses in domain lists To match an IPv6 address in `allowedDomains`, `deniedDomains`, or a `WebFetch(domain:...)` rule, write the address in brackets: `"[::1]"` matches that address on every port, and `"[::1]:443"` matches it on port 443 only. The bracketed form requires Claude Code v2.1.229 or later. An unbracketed entry such as `::1:443` is ambiguous between an address and an address with a port: @@ -630,11 +502,7 @@ To find ambiguous entries, run `claude doctor` in your terminal and look for the `Sandbox network domain entries have unreliable spellings` warning. Rewrite each ambiguous entry in the bracketed form. -### - -​ - -OS-level enforcement +### OS-level enforcement The sandboxed Bash tool uses operating system security primitives: @@ -644,19 +512,11 @@ You can also run the [`@anthropic-ai/sandbox-runtime`](<https://github.com/anthropics/sandbox-runtime>) package on its own to wrap the Claude Code process. See [Sandbox runtime](</docs/en/sandbox-environments#sandbox-runtime>). -## - -​ - -How sandboxing relates to permissions and permission modes +## How sandboxing relates to permissions and permission modes Sandboxing, [permission rules](</docs/en/permissions>), and [permission modes](</docs/en/permission-modes>) are complementary layers. The sections below cover how the sandbox interacts with each. -### - -​ - -Permission rules +### Permission rules Permission rules and sandboxing control different things: @@ -679,11 +539,7 @@ Paths and domains from both sandbox settings and permission rules are merged into the final sandbox configuration. The [claude-code repository’s examples directory](<https://github.com/anthropics/claude-code/tree/main/examples/settings>) includes starter settings configurations for common deployment scenarios, including sandbox-specific examples. Use these as starting points and adjust them to fit your needs. -### - -​ - -Permission modes +### Permission modes `/sandbox` is not a [permission mode](</docs/en/permission-modes>). Permission modes decide whether a tool call runs and whether you are prompted first, while the sandbox restricts what a Bash command can access once it runs. They differ in what they control and what replaces the per-action prompt: @@ -695,19 +551,11 @@ The sandbox’s auto-allow mode is separate from [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>): auto-allow approves Bash commands because the sandbox boundary contains them, while auto mode uses a classifier to review actions. The two work independently and can be combined, with the exceptions listed under Sandbox modes. To choose an isolation boundary for unattended runs, see [Sandbox environments](</docs/en/sandbox-environments#how-isolation-relates-to-permission-modes>). For a table of common permission mode and sandbox pairings with the flags that start each one, see [Common setups](</docs/en/permission-modes#common-setups>). -## - -​ - -Configure the sandbox for your organization +## Configure the sandbox for your organization Administrators can require sandboxing for every user, keep developers from widening the policy, and route sandbox traffic through a corporate proxy. -### - -​ - -Enforce sandboxing with managed settings +### Enforce sandboxing with managed settings To require the sandbox for every developer, deliver the `sandbox` keys through [managed settings](</docs/en/managed-settings#delivery-mechanisms>), either as a file managed by your MDM or through [server-managed settings](</docs/en/server-managed-settings>) on claude.ai. The following managed settings configuration enables the sandbox, refuses to start Claude Code when the platform is unsupported or a dependency is missing, and prevents the model from retrying commands outside the sandbox: @@ -734,11 +582,7 @@ * **Deliver the configuration by operating system** : deploy it through your MDM or as a [managed settings file](</docs/en/managed-settings#delivery-mechanisms>) on macOS and Linux machines only. [Server-managed settings](</docs/en/server-managed-settings#give-groups-different-settings>) follow the member, not the device. * **Move Windows users into a supported environment** : have them run Claude Code inside WSL2 or a container -### - -​ - -Keep developers from widening the policy +### Keep developers from widening the policy When managed settings set a Boolean key such as `enabled` or `failIfUnavailable`, Claude Code uses the managed value and ignores anything a developer sets locally. For array keys such as `allowRead`, Claude Code merges entries from the scopes the session loads, so a developer can append entries that widen the policy unless a lock covers that key. Unless managed settings set them, a developer’s user settings or `--settings` can turn on the following keys. A repository’s `.claude/settings.json` can too, unless the sandbox is admin-required. Each one weakens the sandbox, so set it to `false` in managed settings if you don’t want it used: @@ -751,11 +595,7 @@ Set `allowManagedReadPathsOnly` to `true` in managed settings so that only `allowRead` entries from managed settings are honored. This prevents developers from widening read access beyond the organization-approved paths. To lock network domains to the managed values the same way, set [`allowManagedDomainsOnly`](</docs/en/settings-reference#sandbox-network-allowmanageddomainsonly>). With `allowManagedDomainsOnly` on, only managed settings can set a proxy port. When managed settings configure `sandbox.filesystem` or list any `sandbox.credentials.files` entry with `"mode": "deny"`, only managed settings can set `filesystem.disabled`, so developers can’t turn filesystem isolation off with that key. A [valid](</docs/en/settings-reference#invalid-credential-entries-in-managed-settings>) `mask` entry doesn’t lock the key. See Which settings can disable it. -#### - -​ - -Repository settings under an admin-required sandbox +#### Repository settings under an admin-required sandbox The sandbox is admin-required while one of these settings is in effect: @@ -780,11 +620,7 @@ The configuration under Enforce sandboxing with managed settings makes the sandbox admin-required. Add the `excludedCommands`, `allowWrite`, and socket entries that your approved tools need to managed settings, because a repository can’t supply them. Requires Claude Code v2.1.285 or later. From v2.1.282 to v2.1.284, the same settings made Claude Code ignore a repository’s `excludedCommands` entries. -#### - -​ - -Locks that apply without an admin-required sandbox +#### Locks that apply without an admin-required sandbox Some settings make Claude Code ignore the repository keys that directly override one restriction, even when the sandbox isn’t admin-required. Each one has this effect only when you set it in a file its row names, and the repository’s other sandbox settings still apply. Requires Claude Code v2.1.285 or later. @@ -796,11 +632,7 @@ These locks change what sandboxed commands can reach. The WebFetch tool and Claude’s file tools still follow a repository’s rules and additional directories. -### - -​ - -Custom proxy configuration +### Custom proxy configuration To inspect, filter, or log sandbox traffic with your own tooling, replace the built-in sandbox proxy with a proxy you run on the same machine. To route sandbox traffic through a corporate proxy elsewhere on your network, set `HTTPS_PROXY` instead, as the **Corporate proxy** entry under Network isolation describes. That way, Claude Code’s allowlist still applies. To direct sandboxed commands to your proxy, set the localhost ports it listens on in [sandbox settings](</docs/en/settings-reference#sandbox-settings>): @@ -823,59 +655,31 @@ Once either port applies, your proxy is responsible for filtering everything sent to it. Claude Code’s own network controls, such as `allowedDomains`, `deniedDomains`, `strictAllowlist`, approval prompts, and the local-address check, stop applying to that traffic. A sandboxed command can connect to either proxy, so if you set only one port, Claude Code’s domain lists on the other proxy don’t limit what the command reaches through yours. -## - -​ - -Troubleshooting +## Troubleshooting Some commands fail inside the sandbox even though they work outside it. Find the heading that matches your symptom or error message. If your organization’s sandbox is admin-required, Claude Code ignores the settings these fixes name in a project’s settings files, so save them in `~/.claude/settings.json`, where they apply in every project. If a fix still has no effect, your organization’s managed settings may set that key. A fix that adds an `excludedCommands` pattern removes the sandbox from the commands the pattern matches. See what an excluded command can do. -### - -​ - -Commands fail with a host-not-allowed error +### Commands fail with a host-not-allowed error Many CLI tools need to reach specific hosts. Approve the host when prompted, or add it to [`allowedDomains`](</docs/en/settings-reference#sandbox-network-alloweddomains>). If your organization locks the allowlist with `allowManagedDomainsOnly`, there’s no prompt, so ask your administrator to add the host. -### - -​ - -`jest` hangs or fails +### `jest` hangs or fails `watchman` is incompatible with the sandbox. Run `jest --no-watchman` instead. -### - -​ - -Go-based CLIs fail TLS verification on macOS +### Go-based CLIs fail TLS verification on macOS Tools such as `gh`, `gcloud`, and `terraform` may fail TLS verification under Seatbelt. To run these tools outside the sandbox, add a pattern for each tool, such as `gh *`, to `excludedCommands`. The tool then runs with your full access and its stored credentials. If you are using `httpProxyPort` with a MITM proxy and custom CA, set [`enableWeakerNetworkIsolation`](</docs/en/settings-reference#sandbox-enableweakernetworkisolation>) to `true` instead. -### - -​ - -`open`, `osascript`, or browser-based auth flows fail with error `-600` on macOS +### `open`, `osascript`, or browser-based auth flows fail with error `-600` on macOS The sandbox blocks Apple Events by default. Set [`allowAppleEvents`](</docs/en/settings-reference#sandbox-allowappleevents>) to `true` in your user, managed, or CLI settings to allow them. Claude Code ignores this key in project settings. Enabling `allowAppleEvents` removes code-execution isolation, since sandboxed commands can then launch other applications unsandboxed with no user prompt, and can send AppleScript commands to running applications, subject to the macOS automation-consent prompt (TCC). Alternatively, add a pattern such as `open *` to `excludedCommands`. Each `open` call then goes through the permission flow, and `open` can launch any file or app, including one Claude wrote. -### - -​ - -`docker` commands fail +### `docker` commands fail `docker` is incompatible with the sandbox. Take the `docker` commands you need out of the sandbox with an `excludedCommands` pattern such as `docker compose *`. Run commands outside the sandbox with `excludedCommands` explains what an excluded `docker` command can reach. A narrower pattern takes fewer commands out of the sandbox. -### - -​ - -Chromium or rootless Podman fails inside the sandbox on Linux +### Chromium or rootless Podman fails inside the sandbox on Linux On Linux and WSL2, commands in the sandbox can’t create user namespaces by default, so tools that rely on them fail: @@ -891,19 +695,11 @@ If you set `allowNestedUserNamespaces` to `true`, you turn off a security boundary: code from a sandboxed command can end up running outside the sandbox.Don’t rely on any of the sandbox’s restrictions, including protected paths and [`credentials.files`](</docs/en/settings-reference#sandbox-credentials-files>) entries, to stop a malicious command. In auto-allow mode, that command can run without a permission prompt. If your organization has a security team, check with them before you turn this setting on. -### - -​ - -`pbcopy`, `xclip`, or `wl-copy` doesn’t update the clipboard +### `pbcopy`, `xclip`, or `wl-copy` doesn’t update the clipboard The `pbcopy`, `xclip`, and `wl-copy` clipboard utilities can fail to reach the system clipboard from inside the sandbox, in which case the text piped to them doesn’t arrive. To put Claude’s output on your clipboard, ask Claude to print it in its response, then run [`/copy`](</docs/en/commands>). `/copy` writes to the clipboard from the Claude Code process rather than from a sandboxed command. When Claude pipes text to one of these tools, adding the tool to [`excludedCommands`](</docs/en/settings-reference#sandbox-excludedcommands>) doesn’t take that call out of the sandbox on its own. -### - -​ - -A git command fails with `unable to unlink old` +### A git command fails with `unable to unlink old` `git merge`, `git checkout`, and similar commands fail with `unable to unlink old` when they need to replace a file the sandbox denies writes to. On Linux and WSL2 the error ends with `Read-only file system`. The file can be in one of these places: @@ -913,35 +709,19 @@ After the failure, Claude may offer to rerun the command outside the sandbox. Approve that retry, or run the git command yourself in another terminal. If you’ve set `allowUnsandboxedCommands` to `false`, Claude can’t offer the retry, so run the command yourself. -### - -​ - -A git command fails with `Unable to create '…/index.lock'` +### A git command fails with `Unable to create '…/index.lock'` If you started Claude Code in a repository’s subdirectory, this error can mean `.git` is outside what sandboxed commands can write to. Start Claude Code from the repository root instead, or from the worktree’s root in a [linked worktree](</docs/en/worktrees>). -### - -​ - -A folder named `objects` or `refs` disappears after a command +### A folder named `objects` or `refs` disappears after a command A top-level `objects` or `refs` folder that appeared during the session can be deleted after a sandboxed command ends. It doesn’t matter whether a command, Claude, or you created it. To keep a folder, leave something in it. If a `HEAD` file or symlink has been at the top level during the session, move it away, then restart every Claude Code session open there. Before v2.1.307, the folder was deleted even with something in it and no `HEAD`. On an earlier version, [update Claude Code](</docs/en/setup#update-claude-code>). -### - -​ - -Bubblewrap fails to start inside a container +### Bubblewrap fails to start inside a container In an unprivileged container, bubblewrap can’t mount a fresh `/proc` filesystem, so sandboxed commands fail with a `bwrap` error such as `Can't mount proc on /newroot/proc: Operation not permitted`. Set [`enableWeakerNestedSandbox`](</docs/en/settings-reference#sandbox-enableweakernestedsandbox>) to `true` so the sandbox bind-mounts the container’s existing `/proc` instead. Only use this setting when the outer container already provides the isolation boundary you need, since the setting exposes process information to sandboxed commands that a fresh `/proc` mount would hide. -### - -​ - -Ubuntu’s AppArmor restriction stops bubblewrap +### Ubuntu’s AppArmor restriction stops bubblewrap On Linux and WSL2, the message `Ubuntu's AppArmor restriction on user namespaces stops bubblewrap here` means that Ubuntu’s AppArmor restriction keeps the sandbox from starting. To get the sandbox to start, lift the restriction in one of these two ways: @@ -950,11 +730,7 @@ Then restart Claude Code and confirm the sandbox works. Until you lift the restriction, commands run without the sandbox under the regular permission flow, or Claude Code refuses to start if [`sandbox.failIfUnavailable`](</docs/en/settings-reference#sandbox-failifunavailable>) is `true`. -### - -​ - -Sandboxed commands fail with `bwrap: setting up uid map: Permission denied` +### Sandboxed commands fail with `bwrap: setting up uid map: Permission denied` On Linux and WSL2, this error or `bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted` can mean that Ubuntu’s AppArmor restriction on user namespaces is stopping bubblewrap. To check, run `sysctl kernel.apparmor_restrict_unprivileged_userns` in your shell: @@ -963,11 +739,7 @@ Before v2.1.310, Claude Code didn’t check for this restriction at startup, so `/sandbox` didn’t report it. -### - -​ - -0-byte read-only files appear at `.claude` settings paths, and “Yes, and don’t ask again” doesn’t save +### 0-byte read-only files appear at `.claude` settings paths, and “Yes, and don’t ask again” doesn’t save On Linux and WSL2, the sandbox holds a write denial on a file that doesn’t exist yet by creating a 0-byte read-only placeholder there while a sandboxed command runs. The sandbox removes the placeholder afterward. A placeholder stays behind in cases such as these: @@ -976,11 +748,7 @@ Later sessions bind the placeholders read-only again on every start, so a settings write such as saving a permission choice fails at a path where a placeholder remains. Run `claude doctor` in your terminal to list the leftover placeholder files. The [`Sandbox mask files left behind at write-deny paths`](</docs/en/errors#stale-sandbox-mask-files-left-by-a-killed-session>) warning names some of them and counts the rest. Delete each file with `rm` while no other Claude Code session is running in that project. Before v2.1.257, Claude Code left the same placeholders behind when a session was killed, without flagging them. -### - -​ - -`git` over SSH fails with the sandbox on +### `git` over SSH fails with the sandbox on On macOS, `git fetch`, `git pull`, and `git push` against an SSH remote fail inside the sandbox even when the host is allowed. On Linux and WSL2, they work once the host is allowed. Claude Code tunnels git’s SSH connection through the sandbox proxy, and the macOS tunnel can’t authenticate to that proxy. On Linux and WSL2, check these if the connection still fails: @@ -1002,11 +770,7 @@ These entries match `git push origin main`. A call that adds a `cd`, uses `git -C`, or contains a command substitution stays sandboxed. The excluded git commands can reach any host, not only the ones in `allowedDomains`. Plain `ssh`, `scp`, and `rsync` over SSH fail for the reason the database client entry gives. -### - -​ - -A database client or other non-HTTP tool fails to reach an allowed host +### A database client or other non-HTTP tool fails to reach an allowed host A tool that ignores the proxy environment variables can’t connect from inside the sandbox, even to a host in `allowedDomains`. A sandboxed command has no direct route to the network, so a tool that opens its own connection fails. Most database drivers, plain `ssh`, and tools that use UDP behave this way. The failure looks like a network or name resolution error: @@ -1026,11 +790,7 @@ The script runs with your full access, and Claude can edit a script that’s inside your working directory, so review it when the prompt appears. -### - -​ - -A command fails to reach a server on localhost +### A command fails to reach a server on localhost By default, a sandboxed command can’t connect directly to a server that’s running on your machine outside the sandbox, such as a dev server or a database in a container. What you can change depends on your platform: @@ -1049,11 +809,7 @@ An `allowedDomains` entry for `localhost` applies to connections that go through the proxy, so it doesn’t change a direct connection. Claude Code sets `NO_PROXY` for sandboxed commands so that they connect to `localhost` directly instead of through the proxy. The entry also exposes every port on your machine’s localhost to a command that does use the proxy. For a development hostname that points at `127.0.0.1`, see An allowed hostname is refused with `resolved to a loopback address`. -### - -​ - -An allowed hostname is refused with `resolved to a loopback address` +### An allowed hostname is refused with `resolved to a loopback address` The sandbox proxy refuses an allowed hostname that resolves to a local address, which affects development names such as `myapp.test` that point at `127.0.0.1`. The command sees a `403` response whose body names the kind of address, such as `Connection to myapp.test blocked: resolved to a loopback address`. Add the IP address the name resolves to alongside the hostname in `allowedDomains`, each with the port your server listens on: @@ -1067,11 +823,7 @@ An IP address entry with no port lets sandboxed commands reach every service listening on that address. Before v2.1.284, the proxy connected to whatever address an allowed hostname resolved to. -### - -​ - -Commands are refused with `Sandbox is required` +### Commands are refused with `Sandbox is required` If you require the sandbox with [`sandbox.failIfUnavailable`](</docs/en/settings-reference#sandbox-failifunavailable>) and it fails in one of these ways after Claude Code starts, each sandboxed command Claude runs is refused with the message shown. The session keeps running, and the refused command doesn’t run unsandboxed: @@ -1086,22 +838,14 @@ In a Linux session with `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB` set, every command runs sandboxed, so excluded commands and commands you type are refused too. -### - -​ - -`/sandbox` fails with `Sandbox settings are overridden by a higher-priority configuration` +### `/sandbox` fails with `Sandbox settings are overridden by a higher-priority configuration` `/sandbox` prints `Error: Sandbox settings are overridden by a higher-priority configuration and cannot be changed locally.` instead of opening its panel when a higher [settings level](</docs/en/settings#settings-precedence>) sets `sandbox.enabled`, `sandbox.autoAllowBashIfSandboxed`, or `sandbox.allowUnsandboxedCommands`. The panel saves your choices to `.claude/settings.local.json`, and a value saved there can’t override those levels. Managed settings and `--settings` rank above local settings. To see which of them this session loaded, run `/status` and read the `Setting sources` line: * **`Command line arguments`** : if you started Claude Code with [`--settings`](</docs/en/settings#change-a-setting-for-one-session>), check whether the file or JSON you passed sets one of those keys. If it does, change the value there, or start Claude Code again without those keys. * **`Enterprise managed settings`** : your organization’s managed settings are loaded. If they set one of those keys, you can’t change that key from `/sandbox` or from any settings file you control, so ask your administrator. -### - -​ - -`/sandbox` prints `Sandbox settings not changed` +### `/sandbox` prints `Sandbox settings not changed` This line means `/sandbox` couldn’t save the choice you made in its panel to your project’s `.claude/settings.local.json`: @@ -1117,19 +861,11 @@ This turns on auto-allow mode. For regular permissions mode, also set [`sandbox.autoAllowBashIfSandboxed`](</docs/en/settings-reference#sandbox-autoallowbashifsandboxed>) to `false`. The change takes effect in your running session at the next shell command Claude runs, and the **Mode** tab of `/sandbox` then marks the mode in effect. -## - -​ - -Limitations +## Limitations Sandboxing reduces risk but is not a complete isolation boundary. Review the limitations below before relying on it as a hard security control. -### - -​ - -Security limitations +### Security limitations * **Network filtering** : the sandbox restricts which domains processes can connect to. By default the built-in proxy does not terminate or inspect TLS on outbound traffic, so the contents of encrypted connections are not examined. The experimental [`network.tlsTerminate`](</docs/en/settings-reference#sandbox-network-tlsterminate>) setting terminates TLS at the proxy for `mask` credential substitution but does not add content filtering. You are responsible for ensuring that only trusted domains are allowed in your policy. @@ -1142,11 +878,7 @@ * **Mach and XPC services on macOS** : sandboxed commands can reach outside the sandbox to each service that you list in [`network.allowMachLookup`](</docs/en/settings-reference#sandbox-network-allowmachlookup>), and the sandbox doesn’t confine what those services do for those commands. * **User namespaces on Linux and WSL2** : by default, sandboxed commands can’t create user namespaces. If you set [`allowNestedUserNamespaces`](</docs/en/settings-reference#sandbox-allownestedusernamespaces>) to `true`, you turn off a security boundary: code from a sandboxed command can end up running outside the sandbox. Before you turn this setting on, read the warning in Chromium or rootless Podman fails inside the sandbox on Linux. -### - -​ - -Scope +### Scope The sandbox isolates shell commands and their child processes. What runs outside the sandbox lists the tools and helper processes it doesn’t cover. Computer use and subagents relate to the sandbox as follows: @@ -1158,11 +890,7 @@ Effective sandboxing requires both filesystem and network isolation. Without network isolation, a compromised agent could exfiltrate sensitive files like SSH keys. Without filesystem isolation, whether from a permissive policy or from disabling the filesystem layer, a compromised agent could backdoor system resources to gain network access. When you widen the defaults, check that an `allowWrite` path, a broad `allowedDomains` entry, or an `excludedCommands` exception does not undo a restriction on the other side. -## - -​ - -See also +## See also * [Sandbox environments](</docs/en/sandbox-environments>): compare the built-in sandbox with dev containers, containers, and VMs * [Security](</docs/en/security>): security features and best practices
modified Run prompts on a schedule View current →
Show diff (211 lines)
--- a/scheduled-tasks.md +++ b/scheduled-tasks.md @@ -7,11 +7,7 @@ Tasks are session-scoped. When you resume with `--resume` or `--continue`, Claude Code restores tasks that haven’t expired, except those listed under Limitations. For scheduling that survives independently of any session, create a [cloud scheduled task](</docs/en/routines>), set up a [Desktop scheduled task](</docs/en/desktop-scheduled-tasks>), or use [GitHub Actions](</docs/en/github-actions>). -## - -​ - -Compare scheduling options +## Compare scheduling options Claude Code offers three ways to schedule recurring or one-off work: @@ -29,11 +25,7 @@ Use **cloud tasks** for work that should run reliably without your machine. Use **Desktop tasks** when you need access to local files and tools. Use **`/loop`** for quick polling during a session. -## - -​ - -Run a prompt repeatedly with /loop +## Run a prompt repeatedly with /loop The `/loop` [bundled skill](</docs/en/commands>) is the quickest way to run a prompt on repeat while the session stays open. Both the interval and the prompt are optional, and what you provide determines how the loop behaves. @@ -50,11 +42,7 @@ * Skills withheld from Claude by a [`skillOverrides`](</docs/en/skills#override-skill-visibility-from-settings>) setting or a `Skill` [deny rule](</docs/en/skills#restrict-claude%E2%80%99s-skill-access>) * [MCP prompts](</docs/en/mcp#use-mcp-prompts-as-commands>) such as `/mcp__github__list_prs` -### - -​ - -Run on a fixed interval +### Run on a fixed interval When you supply an interval, Claude converts it to a cron expression, schedules the job, and confirms the cadence and job ID. @@ -62,11 +50,7 @@ The interval can lead the prompt as a bare token like `30m`, or trail it as a clause like `every 2 hours`. Supported units are `s` for seconds, `m` for minutes, `h` for hours, and `d` for days. Seconds are rounded up to the nearest minute since cron has one-minute granularity. Intervals that don’t map to a clean cron step, such as `7m` or `90m`, are rounded to the nearest interval that does and Claude tells you what it picked. -### - -​ - -Let Claude choose the interval +### Let Claude choose the interval When you omit the interval, Claude chooses one dynamically instead of running on a fixed cron schedule. After each iteration it picks a delay between one minute and one hour based on what it observed: short waits while a build is finishing or a PR is active, longer waits when nothing is pending. The chosen delay and the reason for it are printed at the end of each iteration. The example below checks CI and review comments, with Claude waiting longer between iterations once the PR goes quiet: @@ -76,11 +60,7 @@ Dynamically chosen intervals and the built-in maintenance prompt work on every provider, and with [feature-flag fetching](</docs/en/env-vars#features-that-need-feature-flag-fetching>) turned off. On Amazon Bedrock, Claude Platform on AWS, Google Cloud’s Agent Platform, and Microsoft Foundry, or with fetching turned off, both require Claude Code v2.1.248 or later. -### - -​ - -Run the built-in maintenance prompt +### Run the built-in maintenance prompt When you omit the prompt, Claude uses a built-in maintenance prompt instead of one you supply. On each iteration it works through the following, in order: @@ -94,11 +74,7 @@ Add an interval, for example `/loop 15m`, to run it on a fixed schedule instead. To replace the built-in prompt with your own default, see Customize the default prompt with loop.md. -### - -​ - -Customize the default prompt with loop.md +### Customize the default prompt with loop.md Create a `loop.md` file to replace the built-in maintenance prompt with your own instructions. It defines a single default prompt for bare `/loop`, not a list of separate scheduled tasks, and Claude Code ignores it whenever you supply a prompt on the command line. To schedule additional prompts alongside it, use `/loop <prompt>` or ask Claude directly. Claude looks for the file in two locations and uses the first one it finds. @@ -118,30 +94,18 @@ Edits to `loop.md` take effect on the next iteration, so you can refine the instructions while a loop is running. When no `loop.md` exists in either location, the loop falls back to the built-in maintenance prompt. Keep the file concise: content beyond 25,000 bytes is truncated. -### - -​ - -Stop a loop +### Stop a loop * **Self-paced loop** : while the loop is waiting for its next iteration, press `Esc` to stop it. You can also stop it with `Ctrl+C` while Claude is idle, except in a background session you’ve attached to. A `Pending wakeup cancelled` notice confirms that the loop won’t fire again. * **Fixed-interval loop** : to stop a loop such as `/loop 5m`, ask Claude to cancel it, for example `cancel the deploy check loop`. `Esc` and `Ctrl+C` don’t stop it, or any task you scheduled by asking Claude directly. A loop you don’t cancel ends when seven days elapse. In self-paced mode, Claude can also end the loop on its own once the task is complete. Claude calls the [`ScheduleWakeup` tool](</docs/en/tools-reference>) with `stop: true`, which cancels the pending wakeup immediately. If an iteration ends without either rescheduling or stopping, Claude Code schedules one fallback wakeup about 20 minutes later and ends the loop when that iteration doesn’t reschedule either. -#### - -​ - -Detach without stopping a loop +#### Detach without stopping a loop When you’re [attached to a background session](</docs/en/agent-view#attach-to-a-session>) and Claude is idle, press `Ctrl+C` twice on an empty prompt to detach. A self-paced loop waiting there for its next iteration keeps running, and that iteration starts on schedule. To stop the loop instead, press `Esc` before you detach. Detaching with `Ctrl+C` without stopping the loop requires Claude Code v2.1.295 or later. -## - -​ - -Set a one-time reminder +## Set a one-time reminder For one-shot reminders, describe what you want in natural language instead of using `/loop`. Claude schedules a single-fire task that deletes itself after running. @@ -151,11 +115,7 @@ Claude pins the fire time to a specific minute and hour using a cron expression and confirms when it will fire. -## - -​ - -Manage session-scoped scheduled tasks +## Manage session-scoped scheduled tasks Ask Claude in natural language to list or cancel tasks, or reference the underlying tools directly. @@ -173,27 +133,15 @@ Each scheduled task has an 8-character ID you can pass to `CronDelete`. A session can hold up to 50 scheduled tasks at once. -## - -​ - -How session-scoped scheduled tasks run +## How session-scoped scheduled tasks run The scheduler checks every second for due tasks and enqueues them at low priority. A scheduled prompt fires between your turns, not while Claude is mid-response. If Claude is busy when a task comes due, the prompt waits until the current turn ends. All times are interpreted in your local timezone. A cron expression like `0 9 * * *` means 9am wherever you’re running Claude Code, not UTC. -### - -​ - -Jitter +### Jitter 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, except a task that runs every five minutes, written `*/5 * * * *`. One-shot tasks scheduled on the hour or half hour run a little early. To see when a task is next due, read the row under Claude’s `CronCreate` call in your terminal. The row shows that time after the schedule, for example `next run 10:21 AM`. To check again later, ask Claude to list your tasks and look for `next run` in the rows under the `CronList` call. Next run times in these rows require Claude Code v2.1.299 or later. -#### - -​ - -How late a recurring task runs +#### How late a recurring task runs Unless it runs every five minutes, a recurring task starts each run late by up to half the gap to the next run, and by at most 30 minutes. Your task is one of these three cases: @@ -212,27 +160,15 @@ 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 +#### 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 * * *`. -### - -​ - -Seven-day expiry +### Seven-day expiry Recurring tasks automatically expire 7 days after creation. The task fires one final time, then deletes itself. This bounds how long a forgotten loop can run. If you need a recurring task to last longer, cancel and recreate it before it expires, or use [cloud scheduled tasks](</docs/en/routines>) or [Desktop scheduled tasks](</docs/en/desktop-scheduled-tasks>) for durable scheduling. -## - -​ - -Cron expression reference +## Cron expression reference `CronCreate` accepts standard 5-field cron expressions: `minute hour day-of-month month day-of-week`. All fields support wildcards (`*`), single values (`5`), steps (`*/15`), ranges (`1-5`), and comma-separated lists (`1,15,30`). @@ -247,19 +183,11 @@ Day-of-week uses `0` or `7` for Sunday through `6` for Saturday. Extended syntax like `L`, `W`, `?`, and name aliases such as `MON` or `JAN` is not supported. When both day-of-month and day-of-week are constrained, a date matches if either field matches. This follows standard vixie-cron semantics. -## - -​ - -Disable session-scoped scheduled tasks +## Disable session-scoped scheduled tasks Set `CLAUDE_CODE_DISABLE_CRON=1` in your environment to disable the scheduler entirely. `CronCreate` and `/loop` become unavailable, and any already-scheduled tasks stop firing. While the project’s `.claude/scheduled_tasks.json` file holds tasks, `CronList` and `CronDelete` stay available, so you can still ask Claude to list or cancel them. See [Environment variables](</docs/en/env-vars>) for the full list of disable flags. -## - -​ - -Limitations +## Limitations Session-scoped scheduling has inherent constraints:
modified Securely deploying AI agents View current →
Show diff (271 lines)
--- a/secure-deployment.md +++ b/secure-deployment.md @@ -1,18 +1,10 @@ Claude Code and the Agent SDK can execute code, access files, and interact with external services on your behalf. Unlike traditional software that follows predetermined code paths, these tools generate their actions dynamically based on context and goals. This flexibility is what makes them useful, but it also means their behavior can be influenced by the content they process: files, webpages, or user input. This is sometimes called prompt injection. For example, if a repository’s README contains unusual instructions, Claude Code might incorporate those into its actions in ways the operator didn’t anticipate. This guide covers practical ways to reduce this risk. Not every deployment needs maximum security. A developer running Claude Code on their laptop has different requirements than a company processing customer data in a multi-tenant environment. This guide presents options ranging from Claude Code’s built-in security features to hardened production architectures, so you can choose what fits your situation. -## - -​ - -Threat model +## Threat model Agents can take unintended actions due to prompt injection (instructions embedded in content they process) or model error. Claude models are designed to resist this; see the [model overview](<https://platform.claude.com/docs/en/about-claude/models/overview>) and the system card for the model you deploy for evaluation details. Defense in depth is still good practice though. For example, if an agent processes a malicious file that instructs it to send customer data to an external server, network controls can block that request entirely. -## - -​ - -Built-in security features +## Built-in security features Claude Code includes several security features that address common concerns. See the [security documentation](</docs/en/security>) for full details. @@ -21,27 +13,15 @@ * **Web search summarization** : Search results are summarized rather than passing raw content directly into the context, reducing the risk of prompt injection from malicious web content. * **Sandbox mode** : Bash commands can run in a sandboxed environment that restricts filesystem and network access. See the [sandboxing documentation](</docs/en/sandboxing>) for details. -## - -​ - -Security principles +## Security principles For deployments that require additional hardening beyond Claude Code’s defaults, these principles guide the available options. -### - -​ - -Security boundaries +### Security boundaries A security boundary separates components with different trust levels. For high-security deployments, you can place sensitive resources (like credentials) outside the boundary containing the agent. If something goes wrong in the agent’s environment, resources outside that boundary remain protected. For example, rather than giving an agent direct access to an API key, you could run a proxy outside the agent’s environment that injects the key into requests. The agent can make API calls, but it never sees the credential itself. This pattern is useful for multi-tenant deployments or when processing untrusted content. -### - -​ - -Least privilege +### Least privilege When needed, you can restrict the agent to only the capabilities required for its specific task: @@ -52,11 +32,7 @@ Credentials| Inject via proxy rather than exposing directly System capabilities| Drop Linux capabilities in containers -### - -​ - -Defense in depth +### Defense in depth For high-security environments, layering multiple controls provides additional protection. Options include: @@ -67,11 +43,7 @@ The right combination depends on your threat model and operational requirements. -## - -​ - -Isolation technologies +## Isolation technologies Different isolation technologies offer different tradeoffs between security strength, performance, and operational complexity. @@ -84,11 +56,7 @@ gVisor| Excellent (with correct setup)| Medium/High| Medium VMs (Firecracker, QEMU)| Excellent (with correct setup)| High| Medium/High -### - -​ - -Sandbox runtime +### Sandbox runtime For lightweight isolation without containers, [sandbox-runtime](<https://github.com/anthropics/sandbox-runtime>) enforces filesystem and network restrictions at the OS level. The main advantage is simplicity: no Docker configuration, container images, or networking setup required. The proxy and filesystem restrictions are built in. **How it works:** @@ -104,11 +72,7 @@ For many single-developer and CI/CD use cases, sandbox-runtime raises the bar significantly with minimal setup. The sections below cover containers and VMs for deployments requiring stronger isolation. -### - -​ - -Containers +### Containers Containers provide isolation through Linux namespaces. Each container has its own view of the filesystem, process tree, and network stack, while sharing the host kernel. A security-hardened container configuration might look like this: @@ -155,11 +119,7 @@ `--userns-remap`| Maps container root to unprivileged host user; requires daemon configuration but limits damage from container escape `--ipc private`| Isolates inter-process communication to prevent cross-container attacks -### - -​ - -gVisor +### gVisor Standard containers share the host kernel: when code inside a container makes a system call, it goes directly to the same kernel that runs the host. This means a kernel vulnerability could allow container escape. gVisor addresses this by intercepting system calls in userspace before they reach the host kernel, implementing its own compatibility layer that handles most syscalls without involving the real kernel. If an agent runs malicious code (perhaps due to prompt injection), that code runs in the container and could attempt kernel exploits. With gVisor, the attack surface is much smaller: the malicious code would need to exploit gVisor’s userspace implementation first and would have limited access to the real kernel. To use gVisor with Docker, install the `runsc` runtime and configure the daemon: @@ -187,19 +147,11 @@ For multi-tenant environments or when processing untrusted content, the additional isolation is often worth the overhead. -### - -​ - -Virtual machines +### Virtual machines VMs provide hardware-level isolation through CPU virtualization extensions. Each VM runs its own kernel, creating a strong boundary. A vulnerability in the guest kernel doesn’t directly compromise the host. However, VMs aren’t automatically “more secure” than alternatives like gVisor. VM security depends heavily on the hypervisor and device emulation code. Firecracker is designed for lightweight microVM isolation. It can boot VMs in under 125ms with less than 5 MiB memory overhead, stripping away unnecessary device emulation to reduce attack surface. With this approach, the agent VM has no external network interface. Instead, it communicates through `vsock` (virtual sockets). All traffic routes through vsock to a proxy on the host, which enforces allowlists and injects credentials before forwarding requests. -### - -​ - -Cloud deployments +### Cloud deployments For cloud deployments, you can combine any of the above isolation technologies with cloud-native network controls: @@ -209,19 +161,11 @@ 4. Assign minimal IAM permissions to the agent’s service account, routing sensitive access through the proxy where possible 5. Log all traffic at the proxy for audit purposes -## - -​ - -Credential management +## Credential management Agents often need credentials to call APIs, access repositories, or interact with cloud services. The challenge is providing this access without exposing the credentials themselves. -### - -​ - -The proxy pattern +### The proxy pattern The recommended approach is to run a proxy outside the agent’s security boundary that injects credentials into outgoing requests. The agent sends requests without credentials, the proxy adds them, and forwards the request to its destination. This pattern has several benefits: @@ -230,11 +174,7 @@ 3. The proxy can log all requests for auditing 4. Credentials are stored in one secure location rather than distributed to each agent -### - -​ - -Configuring Claude Code to use a proxy +### Configuring Claude Code to use a proxy Claude Code supports two methods for routing sampling requests through a proxy: **Option 1: ANTHROPIC_BASE_URL (simple but only for sampling API requests)** @@ -247,11 +187,7 @@ Claude Code and the Agent SDK respect these standard environment variables, routing all HTTP traffic through the proxy. For HTTPS, the proxy creates an encrypted CONNECT tunnel: it cannot see or modify request contents without TLS interception. -### - -​ - -Implementing a proxy +### Implementing a proxy You can build your own proxy or use an existing one: @@ -260,30 +196,18 @@ * [Squid](<http://www.squid-cache.org/>): caching proxy with access control lists * [LiteLLM](<https://github.com/BerriAI/litellm>): LLM gateway with credential injection and rate limiting -### - -​ - -Credentials for other services +### Credentials for other services Beyond sampling from the Claude API, agents often need authenticated access to other services, such as git repositories, databases, and internal APIs. There are two main approaches: -#### - -​ - -Custom tools +#### Custom tools Provide access through an MCP server or custom tool that routes requests to a service running outside the agent’s security boundary. The agent calls the tool, but the actual authenticated request happens outside. The tool calls to a proxy which injects the credentials. For example, a git MCP server could accept commands from the agent but forward them to a git proxy running on the host, which adds authentication before contacting the remote repository. The agent never sees the credentials. Advantages: * **No TLS interception** : The external service makes authenticated requests directly * **Credentials stay outside** : The agent only sees the tool interface, not the underlying credentials -#### - -​ - -Traffic forwarding +#### Traffic forwarding For Claude API calls, `ANTHROPIC_BASE_URL` lets you route requests to a proxy that can inspect and modify them in plaintext. But for other HTTPS services (GitHub, npm registries, internal APIs), the traffic is often encrypted end-to-end. Even if you route it through a proxy via `HTTP_PROXY`, the proxy only sees an opaque TLS tunnel and can’t inject credentials. To modify HTTPS traffic to arbitrary services, without using a custom tool, you need a TLS-terminating proxy that decrypts traffic, inspects or modifies it, then re-encrypts it before forwarding. This requires: @@ -297,19 +221,11 @@ Both approaches still require the TLS-terminating proxy and trusted CA certificate. They just ensure traffic actually reaches the proxy. -## - -​ - -Filesystem configuration +## Filesystem configuration Filesystem controls determine what files the agent can read and write. -### - -​ - -Read-only code mounting +### Read-only code mounting When the agent needs to analyze code but not modify it, mount the directory read-only: @@ -332,11 +248,7 @@ Consider copying only the source files needed, or using `.dockerignore`-style filtering. -### - -​ - -Writable locations +### Writable locations If the agent needs to write files, you have a few options depending on whether you want changes to persist: For ephemeral workspaces in containers, use `tmpfs` mounts that exist only in memory and are cleared when the container stops: @@ -348,11 +260,7 @@ If you want to review changes before persisting them, an overlay filesystem lets the agent write without modifying underlying files. Changes are stored in a separate layer you can inspect, apply, or discard. For fully persistent output, mount a dedicated volume but keep it separate from sensitive directories. -## - -​ - -Further reading +## Further reading * [Claude Code security documentation](</docs/en/security>) * [Hosting the Agent SDK](</docs/en/agent-sdk/hosting>)
modified Security View current →
Show diff (184 lines)
--- a/security.md +++ b/security.md @@ -1,22 +1,10 @@ -## +## How we approach security -​ - -How we approach security - -### - -​ - -Security foundation +### Security foundation Your code’s security is paramount. Claude Code is built with security at its core, developed according to Anthropic’s comprehensive security program. Learn more and access resources (SOC 2 Type 2 report, ISO 27001 certificate, etc.) at [Anthropic Trust Center](<https://trust.anthropic.com>). -### - -​ - -Permission-based architecture +### Permission-based architecture A session’s permission mode sets which actions Claude can take without asking you first. Auto mode is the built-in starting permission mode for interactive terminal and VS Code sessions. [Which mode a session starts in](</docs/en/permission-modes#which-mode-a-session-starts-in>) covers earlier versions, other surfaces, and the settings that change the starting permission mode. @@ -25,11 +13,7 @@ You and your organization configure these permissions directly. For detailed permission configuration, see [Permissions](</docs/en/permissions>). -### - -​ - -Built-in protections +### Built-in protections To mitigate risks in agentic systems: @@ -40,36 +24,20 @@ * **Prompt fatigue mitigation** : Support for allowlisting frequently used safe commands per-user, per-codebase, or per-organization * **Accept Edits mode** : Auto-approves file edits and a fixed set of filesystem Bash commands like `mkdir`, `touch`, `rm`, `mv`, `cp`, and `sed` for paths in the working directory. Other Bash commands and out-of-scope paths still prompt -### - -​ - -User responsibility +### User responsibility You’re responsible for reviewing proposed code and commands for safety before approval. -## - -​ - -Protect against prompt injection +## Protect against prompt injection Prompt injection is a technique where an attacker attempts to override or manipulate an AI assistant’s instructions by inserting malicious text. Claude Code includes several safeguards against these attacks: -### - -​ - -Core protections +### Core protections * **Permission system** : In Manual mode, sensitive operations require explicit approval * **Network command approval** : Commands that fetch content from the web such as `curl` and `wget` are not auto-approved by default. In Manual mode they prompt like any other non-read-only Bash command, so you can still approve once or add an explicit allow rule like `Bash(curl *)`. To stop Claude from running them, add them to [`permissions.deny`](</docs/en/permissions#tool-specific-permission-rules>). A deny rule matches the command [as written](</docs/en/permissions#bash-rule-limits>); for network enforcement that doesn’t depend on the command text, see [sandbox network isolation](</docs/en/sandboxing#network-isolation>) -### - -​ - -Privacy safeguards +### Privacy safeguards We have implemented several safeguards to protect your data, including: @@ -79,11 +47,7 @@ For full details, please review our [Commercial Terms of Service](<https://www.anthropic.com/legal/commercial-terms>) (for Team, Enterprise, and API users) or [Consumer Terms](<https://www.anthropic.com/legal/consumer-terms>) (for Free, Pro, Max, and Ultra users) and [Privacy Policy](<https://www.anthropic.com/legal/privacy>). -### - -​ - -Additional safeguards +### Additional safeguards * **Network request approval** : In Manual mode, most tools that make network requests require user approval by default * **Web page summaries** : For most fetches, WebFetch runs a separate model call over the page, and Claude receives that call’s answer instead of the raw page. See [WebFetch tool behavior](</docs/en/tools-reference#webfetch-tool-behavior>) @@ -106,27 +70,15 @@ While these protections significantly reduce risk, no system is completely immune to all attacks. Always maintain good security practices when working with any AI tool. -## - -​ - -MCP security +## MCP security You can connect Claude Code to Model Context Protocol (MCP) servers. Project-scoped servers are defined in `.mcp.json`, which you can check into source control. Servers at [other scopes](</docs/en/mcp#mcp-installation-scopes>) and [claude.ai connectors](</docs/en/mcp#how-connectors-reach-claude-code>) are configured outside the repository, and plugins can add servers too, so reviewing `.mcp.json` doesn’t show every server a session can load. To restrict which servers run in your organization, see [Managed MCP configuration](</docs/en/managed-mcp>). We encourage either writing your own MCP servers or using MCP servers from providers that you trust. You are able to configure Claude Code permissions for MCP servers. Anthropic reviews connectors against its [listing criteria](<https://claude.com/docs/connectors/building/review-criteria>) before adding them to the [Anthropic Directory](<https://claude.ai/directory>), but does not security-audit or manage any MCP server. -## - -​ - -IDE security +## IDE security See [The built-in IDE MCP server](</docs/en/vs-code#the-built-in-ide-mcp-server>) for more information on running Claude Code in an IDE. -## - -​ - -Cloud execution security +## Cloud execution security When you use [cloud sessions](</docs/en/claude-code-on-the-web>), additional security controls are in place. Sessions your organization routes to a [self-hosted environment](</docs/en/self-hosted-environments>) run on your own infrastructure, where isolation, network egress, and git credentials are your deployment’s responsibility. In Anthropic-hosted environments: @@ -140,28 +92,16 @@ For more details on cloud execution, see [Use Claude Code in the cloud](</docs/en/claude-code-on-the-web>); to configure network access for cloud sessions, see [Configure cloud environments](</docs/en/cloud-environments#network-access>). [Remote Control](</docs/en/remote-control>) sessions work differently: the web interface connects to a Claude Code process running on your local machine. All code execution and file access stays local, and session traffic travels through the Anthropic API over TLS; while connected, the session transcript is stored on Anthropic servers to sync the conversation across devices, as described in [Connection and security](</docs/en/remote-control#connection-and-security>). No cloud VMs or sandboxing are involved. The connection uses multiple short-lived, narrowly scoped credentials, each limited to a specific purpose and expiring independently, to limit the blast radius of any single compromised credential. -## +## Security best practices -​ - -Security best practices - -### - -​ - -Working with sensitive code +### Working with sensitive code * Review all suggested changes before approval * Use project-specific permission settings for sensitive repositories * For additional isolation, run the whole Claude Code (local mode) process inside the [sandbox runtime](</docs/en/sandbox-environments#sandbox-runtime>) or a [dev container](</docs/en/devcontainer>) * Regularly audit your permission settings with `/permissions` -### - -​ - -Team security +### Team security * Use [managed settings](</docs/en/settings#where-settings-live>) to enforce organizational standards * Share approved permission configurations through version control @@ -169,11 +109,7 @@ * Monitor Claude Code usage through [OpenTelemetry metrics](</docs/en/monitoring-usage>) * Audit or block settings changes during sessions with [`ConfigChange` hooks](</docs/en/hooks#configchange>) -### - -​ - -Reporting security issues +### Reporting security issues If you discover a security vulnerability in Claude Code: @@ -182,11 +118,7 @@ 3. Include detailed reproduction steps 4. Allow time for us to address the issue before public disclosure -## - -​ - -Related resources +## Related resources * [Security guidance plugin](</docs/en/security-guidance>): have Claude review and fix vulnerabilities in its own code changes during the session * [`/security-review`](</docs/en/commands#all-commands>): run an on-demand security pass over the changes on your current branch
modified Catch security issues as Claude writes code View current →
Show diff (218 lines)
--- a/security-guidance.md +++ b/security-guidance.md @@ -1,21 +1,13 @@ The security guidance plugin makes Claude review its own code changes for common vulnerabilities while it works and fix what it finds in the same session. The plugin catches issues such as injection, unsafe deserialization, and unsafe DOM APIs before the code reaches a pull request, reducing how much security review falls to human reviewers downstream. Once installed, the plugin runs automatically. There is nothing to invoke and no separate command to remember. The plugin is the in-session companion to [Code Review](</docs/en/code-review>), which runs on pull requests. This plugin reduces what reaches the PR. Code Review catches what does. For how the plugin layers with on-demand review and CI scanning, or to scan code you already have rather than changes Claude is writing, see How this fits with other security tools. -## - -​ - -Prerequisites +## Prerequisites * Python 3.7 or later on your `PATH`. The agentic commit review needs Python 3.10 or later, as do all model-backed reviews when Claude Code uses a third-party provider such as Amazon Bedrock or Google Cloud’s Agent Platform. The plugin prefers the versioned interpreters `python3.13` through `python3.10`, then falls back to `python3`, `python`, and `py -3` * A git repository for the directory you work in. The end-of-turn and commit reviews diff against git state and skip silently outside a repository. The per-edit pattern check works anywhere On first run the plugin creates a virtual environment under `~/.claude/security/` and installs the Claude Agent SDK into it, which requires `pip` and network access. If that install fails, or the available Python is older than 3.10, the commit review on first-party authentication falls back to a single-shot review instead of the agentic one; on a third-party provider such as Amazon Bedrock or Google Cloud’s Agent Platform the model-backed reviews need the SDK themselves, so they skip. The plugin shows a one-time notice when an older Python is the cause. -## - -​ - -Install the plugin +## Install the plugin In a terminal Claude Code session, install from the [official Anthropic marketplace](</docs/en/plugins/anthropic-marketplaces>): @@ -34,11 +26,7 @@ Check the install summary. If it reports `Run /reload-plugins to apply.`, see [Apply plugin changes without restarting](</docs/en/plugins/cli-reference#reload-plugins>) to activate the plugin in your current session. -### - -​ - -Enable for your team in local sessions +### Enable for your team in local sessions To turn the plugin on in the local sessions your teammates start in the repository, declare it in the project’s checked-in settings: @@ -52,11 +40,7 @@ Each teammate also [runs `claude plugin install security-guidance@claude-plugins-official --scope project`](</docs/en/plugins/loading#enabled-in-project-settings-but-not-installed>) once per clone. Administrators can enable the plugin organization-wide by setting [`enabledPlugins`](</docs/en/settings-reference#enabledplugins>) in [managed settings](</docs/en/admin-setup>). -## - -​ - -What the plugin checks +## What the plugin checks The plugin reviews Claude’s work at three points, each at a different depth: @@ -66,11 +50,7 @@ You can extend each layer by adding your own rules. Built-in checks cannot be removed individually, but you can disable each layer independently. -### - -​ - -Checks 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: @@ -81,11 +61,7 @@ The check runs after the edit lands and appends the warning to Claude’s context for the next step. Each warning fires once per pattern per file per session, so repeat matches in the same file do not flood the conversation. You can add your own patterns to this layer with a `security-patterns.yaml` file. -### - -​ - -Checks 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: @@ -97,35 +73,19 @@ You see both the finding and Claude’s resolution directly in your session. The review covers up to 30 changed files per turn and fires at most three times in a row before yielding back to you. -### - -​ - -Checks 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. -### - -​ - -Review independence and limits +### Review independence and limits The plugin does not ask the same Claude instance that wrote the code to grade itself. The per-edit check is a deterministic string match with no model involved. The end-of-turn and commit reviews run as a separate Claude call with a fresh context and a security-focused prompt: the reviewer starts from the diff, has no investment in the original approach, and is instructed only to find problems. None of the layers block writes or commits. Findings reach the writing Claude as instructions, Claude addresses them in the conversation, and the review model can miss issues. Treat the plugin as one layer of defense in depth, not a complete security solution. See How this fits with other security tools. -## - -​ - -Add your own rules +## Add your own rules The plugin has two extension points: a Markdown guidance file for the model-backed reviews, and a YAML or JSON patterns file for the per-edit string match. Both are additive. You can add checks but cannot disable built-in ones from these files. -### - -​ - -Add guidance for the model-backed reviews +### Add guidance for the model-backed reviews Create `.claude/claude-security-guidance.md` in your project and describe your threat model and review checklist in plain language. The model-backed reviews load it as additional context alongside the built-in vulnerability checklist. The following example is for a web service with role-gated admin routes and a customer-data logging policy: @@ -139,11 +99,7 @@ These rules are guidance for the reviewer, not deterministic guardrails. The plugin surfaces violations as findings for Claude to fix, but it does not block writes or guarantee every violation is caught. The guidance is additive only: a rule that says to ignore a vulnerability class does not suppress those findings. For hard enforcement, pair the plugin with a [hook that blocks the edit](</docs/en/hooks-guide#block-edits-to-protected-files>) or a CI check. -### - -​ - -Add custom per-edit patterns +### Add custom per-edit patterns Create `.claude/security-patterns.yaml` to add regex or substring rules to the per-edit pattern check. These run as deterministic string matches alongside the built-in patterns: @@ -169,11 +125,7 @@ The plugin also reads `.claude/security-patterns.yml` and `.claude/security-patterns.json` with the same schema. JSON works on any Python install. The YAML forms require PyYAML to be importable, which the plugin does not install for you. The plugin loads up to 50 custom rules and skips regexes that look prone to catastrophic backtracking. -### - -​ - -Rule file lookup locations +### Rule file lookup locations The plugin looks for `claude-security-guidance.md` and `security-patterns.yaml` in the same locations, independently of how the plugin was enabled: @@ -185,19 +137,11 @@ The plugin loads all locations that exist and concatenates them, with a combined cap of 8 KB for the guidance file. Administrators can distribute organization-wide rules by pushing the user-scope file to `~/.claude/` through device management. The same paths apply to `security-patterns.yaml`. -## - -​ - -Usage cost +## Usage cost The per-edit pattern check makes no model call and adds no cost. The end-of-turn and commit reviews each spend additional model usage that counts toward your [usage](</docs/en/costs>) like any other Claude request. The commit review is agentic and may take several model turns per commit. Expect roughly one review call per turn that changes files and one deeper review per commit, both subject to the caps above. By default, both reviews run on a Claude Opus model. Set `SECURITY_REVIEW_MODEL` to choose a different model for the end-of-turn review and `SG_AGENTIC_MODEL` for the commit review. The plugin is available on all plans. -## - -​ - -Disable or uninstall +## Disable or uninstall To turn off individual layers while keeping the rest, set the matching environment variable: @@ -219,11 +163,7 @@ If the plugin was enabled through a project’s `.claude/settings.json`, uninstalling it from `/plugin` writes an override to your `.claude/settings.local.json` rather than editing the checked-in file, so the plugin stays off for you while teammates are unaffected. The same dialog also offers to uninstall the plugin for everyone by removing it from the shared `.claude/settings.json`. If it was enabled through [managed settings](</docs/en/admin-setup>), only an administrator can disable it. -## - -​ - -How the plugin integrates with Claude Code +## How the plugin integrates with Claude Code The plugin is built entirely on [hooks](</docs/en/hooks>), the mechanism for running your own code at specific points in Claude’s loop. It registers: @@ -237,11 +177,7 @@ If you build your own hooks, the [plugin’s source](<https://github.com/anthropics/claude-plugins-official/tree/main/plugins/security-guidance>) is a working example of running a separate model call from a hook and feeding the result back to the session. -## - -​ - -How this fits with other security tools +## How this fits with other security tools The plugin is one layer in a defense-in-depth approach. It catches issues earliest, while code is still in the editor, but it is not a guarantee and does not replace later checks. A typical stack: @@ -255,11 +191,7 @@ To find security issues in code you already have, rather than in changes Claude is writing, ask Claude in a session to review a specific file or directory for vulnerabilities, or use the [Claude Security plugin](</docs/en/claude-security>) for a deeper multi-agent scan of the whole repository; [`/security-review`](</docs/en/commands#all-commands>) covers only the changes on your current branch. Either way, the review reads the source code in your checkout, not a running site or deployed service. -## - -​ - -Troubleshooting +## Troubleshooting The plugin writes runtime diagnostics to `~/.claude/security/log.txt`. Check there first if reviews are not appearing. Common reasons a review layer skips without a message in the conversation: @@ -267,11 +199,7 @@ * The session has no Anthropic authentication and no third-party provider configured: the model-backed reviews skip and only the per-edit pattern check runs * A `security-patterns.yaml` file is present but PyYAML is not importable: the file is ignored. Use `security-patterns.json` instead -## - -​ - -Related resources +## Related resources To go deeper on the pieces this page touches:
modified Self-hosted environments View current →
Show diff (124 lines)
--- a/self-hosted-environments.md +++ b/self-hosted-environments.md @@ -8,11 +8,7 @@ To learn how self-hosting works and when to choose it, read How self-hosted environments work and Why self-host. -## - -​ - -How self-hosted environments work +## How self-hosted environments work Self-hosting has three parts: @@ -24,11 +20,7 @@ The two Claude Code boxes in the diagram are session processes: one runner executing two sessions at once, up to its configured capacity. A runner serves one owner at a time and locks to that owner when it claims its first session, so checked-out code never mixes between owners; Runner lifecycle covers the rule. You can start runners yourself and keep them running, or run the [autoscaling orchestrator](</docs/en/self-hosted-environments-configuration#on-demand-runners>), a second process you host, which starts runners as sessions queue. Either way, you set the environment up once, and it appears in the picker on every supported surface. -## - -​ - -Availability and limitations +## Availability and limitations Check these before planning a rollout: @@ -42,11 +34,7 @@ * **Another git host** : see the [requirements for starting a session with `--environment`](</docs/en/self-hosted-environments-deploy#start-a-session-on-a-repository-outside-github>). * **Billing** : sessions in a self-hosted environment consume your organization’s Claude Code usage the same way sessions in Anthropic-hosted environments do. -## - -​ - -Why self-host +## Why self-host Most teams are better served by Anthropic-hosted environments, which need no infrastructure to run or maintain. Self-hosting is for teams whose network, tooling, or compliance requirements call for keeping session execution on infrastructure they control. If that’s you, plan for the operational ownership it carries: you build and maintain the runner image, operate the fleet, and control its network. In exchange, self-hosting gives you network access, custom tooling, and compliance control: @@ -54,19 +42,11 @@ * **Custom tooling** : pre-install compilers, SDKs, and internal CLIs in your runner image so every session starts ready to build * **Compliance** : repository checkouts and build artifacts stay on infrastructure you control. Session content still goes to `api.anthropic.com`. -## - -​ - -Environments, runners, and sessions +## Environments, runners, and sessions Environments are managed on the **Cloud environments** page in claude.ai admin settings; runners are processes you start and manage on your own infrastructure. -### - -​ - -Key concepts +### Key concepts These terms appear throughout the self-hosted pages: @@ -84,11 +64,7 @@ The minimum fleet size is therefore the number of owners you expect to be active at once, counting users and Claude Tag agents. -### - -​ - -Session lifecycle +### Session lifecycle When a developer starts a session and selects your environment, Anthropic’s control plane places the session on the environment’s queue. From there: @@ -99,11 +75,7 @@ The runner gives each poll request 10 seconds. When a request times out, is lost, or gets a response the runner can’t parse, the runner keeps serving its live sessions and retries after a second or two instead of waiting for the next scheduled poll. For example, an intercepting proxy that answers the poll with its own page produces a response the runner can’t parse. Each time another request fails in one of those ways, the runner doubles the gap before the next retry, up to 20 seconds, and shortens the gap whenever the lease is close to expiring. -### - -​ - -Runner lifecycle +### Runner lifecycle The first session a runner picks up locks the runner to that session’s owner, and the runner runs up to `--capacity` concurrent sessions for that owner. While the runner has active sessions and hasn’t received a shutdown signal or reached its retire time, the runner keeps claiming the locked owner’s queued work. What happens once they finish depends on [`--drain-grace-sec`](</docs/en/self-hosted-environments-reference#runner-cli-flags>): @@ -120,11 +92,7 @@ A turn that outlives the kill is still lost; [Shutdown timing](</docs/en/self-hosted-environments-deploy#shutdown-timing>) covers sizing the margin. Without `--retire-at`, a signal-less host kill is indistinguishable from a crash: the control plane records a lost worker rather than a clean release, and the session requeues to another runner. -### - -​ - -Network paths +### Network paths The runner and its sessions make several kinds of outbound connection, and no inbound connectivity from Anthropic is required: @@ -138,19 +106,11 @@ * **Proxy authentication** : 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>). * **Long-lived responses** : if a runner picks up a session but Claude never answers its first message, your proxy may be the cause. See [A session is picked up, but Claude never answers its first message](</docs/en/self-hosted-environments-deploy#when-a-sessions-first-message-is-never-answered>). -## - -​ - -What stays on your infrastructure +## What stays on your infrastructure Repository checkouts, build artifacts, secrets, and any files a session creates or modifies stay on the machines you provision. The conversation itself, including prompts, responses, and tool results, goes to `api.anthropic.com`, and Anthropic stores the session transcript so you can resume the session from another supported surface. When a 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 conversation still goes to `api.anthropic.com` in the session’s event stream. A self-hosted environment moves session execution into your network. The control plane remains Anthropic-hosted: session orchestration, queueing, and the claude.ai interface continue to run on Anthropic’s infrastructure. -## - -​ - -Get started +## Get started The self-hosted environments pages are organized by what you’re doing:
modified Customize sessions in self-hosted environments View current →
Show diff (517 lines)
--- a/self-hosted-environments-configuration.md +++ b/self-hosted-environments-configuration.md @@ -2,11 +2,7 @@ A [self-hosted environment](</docs/en/self-hosted-environments>) runs Claude Code [cloud sessions](</docs/en/claude-code-on-the-web>) on your own infrastructure, executed by a runner process you deploy. With no configuration, that runner clones the session’s repository, spawns Claude Code, and cleans up. This page is for the platform engineer operating the runners: it covers the extension points for when those defaults don’t fit, from per-session credential provisioning to replacing checkout entirely. Wrappers and hooks run as executable files on the runner host, which is Linux or macOS, and the examples on this page assume a POSIX shell. A few hook environment variables on this page still use `pool`, such as `CLAUDE_RUNNER_POOL_ID`; the CLI flag and env var names use `environment`, such as `--environment-secret-file`. -## - -​ - -Wrapper scripts +## Wrapper scripts Use a wrapper script when each session needs setup the runner can’t do on its own: @@ -41,19 +37,11 @@ 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. You can read the `CLAUDE_CODE_REMOTE_SLACK_*` variables in your wrapper or `command` hook, and in 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 +### Give a default to variables that can be unset If your script uses `set -u`, expand `CCR_SESSION_ACCOUNT_EMAIL`, `CLAUDE_RUNNER_CLIENT_PLATFORM`, `CLAUDE_CODE_REMOTE_SLACK_THREAD_URL`, `CLAUDE_CODE_REMOTE_SLACK_THREAD_TS`, and `CLAUDE_CODE_REMOTE_SLACK_CHANNEL_ID` with a default, such as `"${CCR_SESSION_ACCOUNT_EMAIL:-}"`. Each can be unset, and under `set -u` Bash stops with `unbound variable` when it expands an unset one. -### - -​ - -Quote the arguments and variables your script expands +### Quote the arguments and variables your script expands Quote every argument and variable that the runner passes to your wrapper or `command` hook. Some values contain characters a shell acts on, because they hold JSON, whole sentences, or a [permission rule](</docs/en/permissions#permission-rule-syntax>) such as `Bash(npm run test *)`. @@ -61,11 +49,7 @@ * **Variables** : quote each one, as in `"${CLAUDE_CODE_REMOTE_SLACK_THREAD_URL:-}"`. The Slack thread link, for example, can contain `?` and `&`. * **`eval` and `sh -c` strings**: don’t substitute a value into a string that `eval` or `sh -c` runs, even inside quotes. Have that string reference the variable instead. -### - -​ - -Keep stdin and file descriptor 3 attached +### 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, 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 9 and re-attach it explicitly: @@ -81,22 +65,14 @@ * **File descriptors 4 and 5** : runners on Claude Code v2.1.309 or later reserve them for the child. Don’t close or reuse them in the wrapper. If your wrapper uses either, for example to save stdin, move that use to a descriptor from 6 to 9, which earlier versions leave free too. * **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. -### - -​ - -Pass the system prompt flags through +### Pass the system prompt flags through The system prompt and appended system prompt that Anthropic’s control plane sends for a session reach your wrapper as file paths, not as inline text. The runner writes each prompt to a file in the session’s config directory, `CLAUDE_CONFIG_DIR`, and passes its path in the arguments your wrapper receives, as [`--system-prompt-file <path>` or `--append-system-prompt-file <path>`](</docs/en/cli-reference#system-prompt-flags>). Runners on Claude Code v2.1.281 or later deliver the prompts as files. Before v2.1.281, the runner passed them as `--system-prompt <text>` and `--append-system-prompt <text>`. In your wrapper script or `command` hook, handle these flags as follows: * **Pass them through** : end the wrapper with `exec "$CLAUDE_RUNNER_CLAUDE_BIN" "$@"`, which forwards the file flags along with every other argument. Don’t drop or rewrite them. If a session loses a prompt file flag, it runs without the instructions the control plane sent for it. * **On a runner at v2.1.281 or later, a file flag you append replaces the server’s, never adds to it** : each prompt file flag takes a single value and Claude Code keeps the last occurrence, so if you append `--append-system-prompt-file <path>` after `"$@"`, your file’s contents replace the server’s appended instructions. To add instructions on top of the server’s, put them in the runner image’s `CLAUDE.md`, which the runner seeds into every session’s user-level config. -#### - -​ - -Fix `Argument list too long` at session start +#### Fix `Argument list too long` at session start On Linux, if you join the control plane’s prompt and your own text into one `--append-system-prompt` argument, the runner logs a line like this once the argument reaches 128 KB: @@ -108,11 +84,7 @@ On Linux, if your own text reaches 128 KB, move it to the runner image’s `CLAUDE.md`, because it’s still one argument. On v2.1.281 or v2.1.282, that command exits with `Cannot use both --append-system-prompt and --append-system-prompt-file`. On earlier versions, your text replaces the control plane’s prompt with no error. On any of them, update first, or move your own text to `CLAUDE.md`. -### - -​ - -Provision credentials scoped to the session creator +### Provision credentials scoped to the session creator Use the `decode-token` subcommand to read claims from the session JWT. It reads the token from an argument, from `CLAUDE_CODE_SESSION_ACCESS_TOKEN`, or from stdin, in that order; see [Verify the token inside the session](</docs/en/self-hosted-environments-identity#verify-the-token-inside-the-session>) for what it checks. The example below decodes the creator identity, exchanges it for short-lived AWS credentials, and execs into Claude Code: @@ -130,19 +102,11 @@ Use `jq -re` rather than `jq -r` when the extracted claim gates an auth decision, so an absent claim exits non-zero instead of passing the literal string `null` downstream. Sessions created by an organization service identity, such as bot and agent sessions, carry an `agent:` subject rather than `user:`, so this example refuses them; if your environment serves those sessions, decide explicitly whether the wrapper falls back to a default credential for them instead of exiting. When your credential exchange needs the email instead, read `.act.email` and handle its absence: the token carries it only when the creating surface recorded it, and a [CLI-dispatched session](</docs/en/self-hosted-environments-testing#run-the-test-loop>) can lack it. For the full claim reference and verification from services outside the runner, see [Verify session identity](</docs/en/self-hosted-environments-identity>). -## - -​ - -Lifecycle hooks +## Lifecycle hooks Lifecycle hooks replace stages of the runner’s per-session pipeline with your own scripts. Point the runner at a directory of hooks with `--hooks-dir <path>`, or `SELF_HOSTED_RUNNER_HOOKS_DIR`. The runner looks for executable files with well-known names; any hook that isn’t present falls through to the built-in behavior, so you only write the ones you need. Hooks run with the runner’s own privileges, and session children share that UID, so mount the hooks directory read-only, or bake it into the image, so session code can’t modify it; see the [hardening section](</docs/en/self-hosted-environments-deploy#harden-your-deployment>). These hooks are distinct from [Claude Code hooks](</docs/en/hooks>), which run inside the session; lifecycle hooks run on the runner, around the session. -### - -​ - -checkout +### checkout Runs for each repository each time the runner starts a session, including when the session resumes or is requeued, 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: @@ -160,30 +124,18 @@ 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. -#### - -​ - -Checkout folder names +#### Checkout folder names `CLAUDE_RUNNER_CHECKOUT_PATH` ends in a folder named `<repo-owner>-<repo>`, such as `acme-api`. Two repositories in a session can’t share a folder, even when their names differ only in case. For example, if a session lists `acme/api` and then `Acme/API`, the first gets `acme-api` and the second gets `Acme-API-2`. -#### - -​ - -Get git credentials in the 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 +#### When the hook fails The hook fails when it exits non-zero, or exits 0 without leaving a usable checkout behind: @@ -192,11 +144,7 @@ When the hook succeeds, the runner removes the checkout path after the session ends. -### - -​ - -post-session +### post-session Runs after the Claude Code child has exited and before the runner tears the workspace down. This hook is your only chance to save uncommitted work, because uncommitted tracked changes don’t survive on either path: @@ -257,11 +205,7 @@ 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. Treat any credential your hook gives git as one a session can obtain, and mint it so that it can do no more than this push. Git in your hook reads configuration files that a session can write, and a credential helper or filter driver named in one of them runs with your hook’s privileges. Settings in those files can also change where a push goes, whatever remote you name. For the git settings the runner fixes in your hook and the ones it leaves to those files, see Git configuration inside lifecycle hooks. -#### - -​ - -Hook timing when the runner releases a session +#### Hook timing when the runner releases a session A released session can resume on another runner. On a runner on v2.1.236 or later, what the session was doing at release decides whether it can resume before this hook finishes: @@ -270,11 +214,7 @@ This applies whenever the runner releases a session: at the idle timeout, at the [`--retire-at`](</docs/en/self-hosted-environments-reference#runner-cli-flags>) time, and, on a runner on v2.1.260 or later, at a session’s [`--kill-session-after-min`](</docs/en/self-hosted-environments-reference#runner-cli-flags>) limit. A session whose turn has ended and that holds only background tasks counts as idle here. Before v2.1.236, the runner released the session first and then ran this hook in both cases. During a `SIGTERM` drain, the runner holds the session lease until the hook finishes; see [Shutdown timing](</docs/en/self-hosted-environments-deploy#shutdown-timing>). -### - -​ - -Git configuration inside lifecycle hooks +### Git configuration inside lifecycle hooks The `checkout` and `post-session` hooks run with the session’s access token in their environment, and the git they run reads configuration files that sessions can write, such as `~/.gitconfig` and a checkout’s `.git/config`. Before either hook runs, the runner sets git settings in the hook’s environment, including the ones below, as `GIT_CONFIG_COUNT`/`GIT_CONFIG_KEY_n`/`GIT_CONFIG_VALUE_n` pairs and git environment variables. Git ranks those above every configuration file, and they apply only to the git your hooks run, not to the session’s own git. At startup, the runner prints a `[runner:git] lifecycle hooks:` line that shows the hooks path, allowed protocols, gpg programs, and signing mode in effect. Requires Claude Code v2.1.280 or later. @@ -293,19 +233,11 @@ Git in your hook still reads every setting the runner doesn’t set, such as credential helpers, `url.*.insteadOf` rewrites, and filter drivers, from every configuration file, including the ones sessions can write. A credential helper or filter driver named in one of those files runs as a program with your hook’s privileges, and configuration in those files can still change where a push from your hook goes, including a push to a URL you pass on the command line. Before v2.1.280, the runner set none of these settings, and under `--configure-git` a commit made from a hook failed unless the hook passed `-c commit.gpgsign=false`. -### - -​ - -command +### command Runs after checkout each time a session starts or resumes, in place of the built-in child spawn. The hook receives the same environment as a wrapper script and should `exec` into `"$CLAUDE_RUNNER_CLAUDE_BIN"` the same way. Use the `command` hook to keep all customization in one hooks directory; use `--exec-path` when the wrapper lives elsewhere. If `--exec-path` is also set, the flag takes precedence and the `command` hook is ignored. Always `exec` the runner’s own binary rather than a PATH-resolved `claude`; otherwise you defeat [version pinning](</docs/en/self-hosted-environments-deploy#pin-the-version>). -## - -​ - -On-demand runners +## On-demand runners Instead of running a fixed fleet, you can boot one runner per session. The orchestrator is a separate, stateless subcommand that polls Anthropic for spawn requests, one per session that’s queued with no runner available, and runs your `spawn-runner` hook for each. Your hook submits a workload to your platform: a Kubernetes Job, an EC2 instance, a Nomad dispatch. On-demand runners improve credential hygiene. On a fixed fleet, the environment secret lives on every runner host, which is the same host that runs user sessions. With the orchestrator, the environment secret stays only on the orchestrator host, which never runs user code; each spawned runner receives a single-use work order that registers exactly one runner and then expires. To start the orchestrator, pass the environment secret and a hooks directory containing an executable `spawn-runner` script: @@ -315,11 +247,7 @@ The orchestrator keeps no state between polls, so you can run two or more replicas against the same environment for availability. Each spawn request is claimed server-side by exactly one replica. All replicas must use the same `--expected-spawn-seconds` value; see the hook contract. -### - -​ - -The spawn-runner hook +### The spawn-runner hook The orchestrator runs `${hooks-dir}/spawn-runner` once per spawn request. The hook must submit work asynchronously, without waiting for the runner to boot, and return within `--hook-timeout`, 60 seconds by default. The hook receives: @@ -361,11 +289,7 @@ 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. -#### - -​ - -Fix re-opened sessions that stay Queued or show Failed +#### Fix re-opened sessions that stay Queued or show Failed If re-opened sessions stay **Queued** or show **Failed** , or your hook times out on them, one cause is a hook that names or deduplicates workloads by the session ID. A session is re-opened when its user sends it a message after its runner has exited. For example, take a hook that builds each workload’s name like this: @@ -395,11 +319,7 @@ * **Queued** : the session gets its next spawn request on its own * **Failed** : select **Retry** on it as an Owner, or have its user send it a new message -#### - -​ - -Make on-demand runners exit when idle +#### Make on-demand runners exit when idle By default, a runner your hook starts doesn’t exit when its session’s turn finishes, so the workload you submitted keeps running. To make runners exit, have your hook pass these [runner flags](</docs/en/self-hosted-environments-reference#runner-cli-flags>): @@ -411,11 +331,7 @@ Remove the workload when the runner exits, for example by setting `ttlSecondsAfterFinished` on a Kubernetes Job or by having the VM’s start script delete the VM afterwards. -#### - -​ - -Send a background process’s output to a file +#### Send a background process’s output to a file If your `spawn-runner` hook leaves a process running in the background, send that process’s output to a file that the hook’s user can create. For example, append `>> "$HOME/claude-runner.log" 2>&1` to the command that starts the process, ahead of any `&`. This hook line shows where the redirect goes, with `your-background-command` standing in for the command your hook backgrounds: @@ -431,22 +347,14 @@ * **Activity tab** , in a failed session’s spawn error: `spawn-runner hook timed out after 60000ms`, or the last lines on the hook’s stderr. * **Orchestrator log** : `timed out after 60000ms, sending SIGTERM to process tree`. -#### - -​ - -Exit the hook without waiting for the runner +#### Exit the hook without waiting for the runner If every on-demand runner stops about 60 seconds after its hook starts, and your hook runs again for the same session, check whether the hook waits for the runner. The 60 seconds are the default [`--hook-timeout`](</docs/en/self-hosted-environments-reference#orchestrator-cli-flags>), so if you set your own, runners stop that long after the hook starts. A hook that starts `claude self-hosted-runner` on the orchestrator’s host and waits for it, in the foreground or with `wait`, is still running when `--hook-timeout` ends. The orchestrator then stops the hook and the processes running under it, including that runner and the session’s Claude process, so a turn that’s still running is cut off. * **To confirm that the timeout is what stops your runners** : look in the orchestrator’s log for `timed out after 60000ms, sending SIGTERM to process tree` on every spawn request. The `60000` is your `--hook-timeout` in milliseconds. * **To fix it** : have the hook submit the runner to your platform and exit 0. If you raise `--hook-timeout` instead, the runner only stops later. -#### - -​ - -Keep transient failures retryable in a shell hook +#### 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: @@ -476,11 +384,7 @@ 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. -#### - -​ - -Find out why a spawn request was sent +#### Find out why a spawn request was sent Your hook receives the reason for each spawn request in `CLAUDE_RUNNER_SPAWN_REASON`, so you can log why the hook ran, together with `CLAUDE_RUNNER_SESSION_UUID`. Requires Claude Code v2.1.318 or later on the orchestrator. Read it as `"${CLAUDE_RUNNER_SPAWN_REASON:-}"`, because it can be unset, and start the runner whatever the value is. If your hook branches on it, keep a default branch, because Anthropic can add values. To find the reason for earlier requests, search the log of every orchestrator replica for `session=` and the session’s `CLAUDE_RUNNER_SESSION_UUID`, not its `session_...` ID. The `ok session=` and `nack session=` lines show the value of `CLAUDE_RUNNER_SPAWN_REASON` after `reason=`, or `reason=-` if it was unset: @@ -501,11 +405,7 @@ `server_retry`| Anthropic gave up on the previous request or on starting the session on its runner, and is retrying. Your hook didn’t fail.| Nothing for a single request. If the value keeps appearing, on one session or across many, report it to [your Anthropic account team](</docs/en/self-hosted-environments-deploy#report-an-issue>). `prewarm`| This is a pre-warming request, with no session yet| Nothing -### - -​ - -Stop or restart the orchestrator +### Stop or restart the orchestrator To stop or restart the orchestrator without cutting off running `spawn-runner` hooks, start it with [`--shutdown-drain-sec`](</docs/en/self-hosted-environments-reference#orchestrator-cli-flags>). On `SIGTERM` it then gives running hooks up to the number of seconds you set to finish. To choose the value and set up your process supervisor to match, see Size `--shutdown-drain-sec` and the orchestrator’s stop timeout. This start command allows 70 seconds: @@ -518,11 +418,7 @@ `--shutdown-drain-sec` requires Claude Code v2.1.299 or later. An older version exits at startup with `error: unknown flag --shutdown-drain-sec`. -#### - -​ - -Size `--shutdown-drain-sec` and the orchestrator’s stop timeout +#### Size `--shutdown-drain-sec` and the orchestrator’s stop timeout At default settings, use [`--shutdown-drain-sec 70`](</docs/en/self-hosted-environments-reference#orchestrator-cli-flags>) with a stop timeout of 85 seconds, meaning `terminationGracePeriodSeconds: 85` on Kubernetes or `TimeoutStopSec=85` under systemd. If you changed `--hook-timeout`, scale both: @@ -534,11 +430,7 @@ * **If your hook submits its workload to a platform and exits** : run the orchestrator as the unit’s main process and set `KillMode=mixed`, which sends `SIGTERM` to that process alone. * **If your hook starts runners as processes in the orchestrator’s own unit** : `KillMode=mixed` sends those runners no `SIGTERM`. Instead systemd later sends them `SIGKILL`, so they exit without draining their sessions or running their `post-session` hook. -## - -​ - -Send model requests to Bedrock or Agent Platform +## Send model requests to Bedrock or Agent Platform If your organization needs model requests to go through its own AWS or Google Cloud account, configure the runner for [Amazon Bedrock](</docs/en/amazon-bedrock>) or [Google Cloud’s Agent Platform, formerly Vertex AI](</docs/en/google-vertex-ai>). Every session that runner starts then calls the model in your cloud account, with your cloud credentials. Without this configuration, sessions send model requests to the Anthropic API. The runner still polls Anthropic for sessions, and each session still sends its event stream to `api.anthropic.com`. The event stream carries prompts, responses, and tool results. The plan requirement and the Zero Data Retention exclusion in [Availability and limitations](</docs/en/self-hosted-environments#availability-and-limitations>) still apply. Sessions are routed to an environment, not to a runner, and a requeued or resumed session can run on a different runner. Configure every runner in the environment the same way. Before you start, read what differs on these providers. @@ -601,11 +493,7 @@ A line that sets `CLAUDE_CODE_USE_BEDROCK` or `CLAUDE_CODE_USE_VERTEX` to `1` means the variable reached the session. If both appear, Claude Code uses Amazon Bedrock. No output means neither reached it.The command shows configuration, not traffic. To confirm the requests themselves, look for them in your cloud account’s own metrics or request logs. If the first message fails instead, see troubleshooting for [Amazon Bedrock](</docs/en/amazon-bedrock#troubleshooting>) or [Agent Platform](</docs/en/google-vertex-ai#troubleshooting>). -### - -​ - -What differs from sessions on the Anthropic API +### What differs from sessions on the Anthropic API 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: @@ -618,11 +506,7 @@ * **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>). -## - -​ - -MCP servers +## MCP servers To make [MCP servers](</docs/en/mcp>) available in every session, add them at image build time with the same `claude mcp add` command used on a desktop install. If your runner is a bare process rather than a container, run the same command as the runner’s user on the host, then restart the runner: it reads host config once at startup. The `--scope user` flag is required; the default local scope writes under a per-directory key that the runner doesn’t seed into sessions. For example, in your Dockerfile: @@ -642,11 +526,7 @@ `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 +### 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: @@ -659,11 +539,7 @@ 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. -### - -​ - -Turn off built-in session tools +### Turn off built-in session tools Anthropic’s control plane attaches its own MCP server, named Claude Code Remote, to cloud sessions. Claude uses the server’s tools to create [cloud scheduled tasks](</docs/en/routines>), start and steer other cloud sessions, attach more repositories, and follow pull request activity. To turn off the whole server, add a [server-level deny rule](</docs/en/permissions#mcp>) to your settings. The control plane registers the server under one of three names, depending on how the session was created. Claude Code matches the name in a rule exactly, including case, so write the rule once per name as shown: @@ -679,11 +555,7 @@ A rule that names the whole server covers tools the server gains later too. To turn off one tool and keep the rest, append two more underscores and the tool name to each rule, as in `mcp__Claude_Code_Remote__add_repo`. To block the server from connecting at all rather than removing its tools, add the three names without the `mcp__` prefix as `serverName` entries under [`deniedMcpServers`](</docs/en/managed-mcp#policy-based-control-with-allowlists-and-denylists>) instead. Put the rules in [server-managed settings](</docs/en/server-managed-settings>) to reach sessions with no change to the runner, or in `~/.claude/settings.json` on the runner. On a runner that sends model requests to Bedrock or Agent Platform, use that file, because server-managed settings don’t reach those sessions. Permissions and tool approval explains how settings on the runner reach sessions. To confirm the rules took effect, start a session on the environment and ask Claude to list its MCP tools. Claude Code removes a denied tool from Claude’s context, so the denied tools are absent from its answer. -## - -​ - -Prompt sessions to push their work +## Prompt sessions to push their work Anthropic-hosted sessions run a [`Stop` hook](</docs/en/hooks#stop>), the Claude Code hook that runs when Claude finishes responding, that prompts Claude to commit and push its work. The runner doesn’t install one. Without it, a session that ends with uncommitted changes leaves that work only on the runner’s disk, and the **Create PR** button in claude.ai/code stays inactive until the branch exists on the remote. The reference implementation below has two parts. Merge the settings block into `~/.claude/settings.json` on the runner host, which the runner seeds into every session, and save the script as `~/.claude/hooks/stop-hook-nudge.sh` on the runner host and make it executable: @@ -795,11 +667,7 @@ The Stop hook prompts at most once per turn. If the commit or push fails, the turn still ends. Look for git’s error in the session and fix what it names. On a large checkout, raise `timeout` in the Stop hook settings and restart the runners. The script’s `git status` skips `core.fsmonitor`, so it can take longer than the 10 seconds set there. A hook that times out ends the turn with no prompt. -### - -​ - -Submodules and the Stop hook +### Submodules and the Stop hook The Stop hook checks which commit each submodule is on, not the files inside it: @@ -807,11 +675,7 @@ * **Uncommitted files in a submodule** : Claude isn’t prompted, so that work stays only on the runner’s disk * **Unpushed commits in a submodule** : the Stop hook doesn’t check whether they’re pushed, so the parent can point at a commit that nobody else can fetch -### - -​ - -Replace an earlier copy of the Stop hook script +### Replace an earlier copy of the Stop hook script Search your copy of `stop-hook-nudge.sh` for `GIT_OPTIONAL_LOCKS`. If it’s missing, you have an earlier copy. Replace it with the current script wherever you installed it, then restart the runners. Keep your Stop hook settings, except to raise `timeout` on a large checkout. @@ -820,19 +684,11 @@ Hooks run outside the Bash sandbox, so the current script’s git calls skip some git features that can start a program named in the checkout’s git settings. They don’t skip them all. Don’t count on the sandbox alone, and isolate sessions as [Harden your deployment](</docs/en/self-hosted-environments-deploy#harden-your-deployment>) describes. -## - -​ - -Permissions and tool approval +## Permissions and tool approval A self-hosted session has no terminal attached, so an unanswered permission prompt stalls the turn until the user responds in the UI. Anthropic’s control plane sends each session’s tool list and permission rules with the work payload; the default configuration pre-approves routine tool calls, including `Bash`, and cloud sessions [pre-approve file edits regardless of mode](</docs/en/permission-modes#switch-permission-modes>). A call that nothing pre-approves prompts through the session UI. -### - -​ - -Pin a permission mode from your wrapper +### Pin a permission mode from your wrapper Only pin auto mode on an environment whose session containers run with [default-deny network egress](</docs/en/self-hosted-environments-deploy#default-deny-egress>) and the rest of the [hardening section](</docs/en/self-hosted-environments-deploy#harden-your-deployment>) in place. Routine tool calls, including `Bash` network requests, run without a human in the loop on both the default pre-approved tool set and in auto mode, so the network boundary is what limits where those calls can reach. @@ -843,19 +699,11 @@ Once a client sets a mode, your appended mode no longer applies, even after the session restarts on the runner. claude.ai/code, for example, sets one with the session’s first message when its mode dropdown shows Auto, or when someone picked a mode there. In auto mode, a separate classifier model reviews actions before they run and blocks the ones it rejects. An explicit ask rule still forces a prompt. A call that a [deny rule](</docs/en/permissions#manage-permissions>) blocks stays blocked in every mode. -### - -​ - -Pre-approve specific tools +### Pre-approve specific tools To pre-approve specific tools, append `--allowed-tools` with your rules after `"$@"` in your wrapper script, for example `--allowed-tools "Bash(bazel *) Bash(yarn *) mcp__internal__*"`. List flags such as `--allowed-tools` and `--disallowed-tools` accumulate across occurrences rather than overriding, so your rules apply on top of any rules the control plane sends. To narrow, append `--disallowed-tools`, which denies tools even if another rule allows them. -### - -​ - -How each session’s config is assembled +### 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. Sessions also read these settings files: @@ -870,11 +718,7 @@ When a person starts their own session, Claude Code 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 [cloud scheduled task](</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, add it to your runner image or, outside a [project](</docs/en/claude-projects#what-threads-pick-up-from-your-repositories>) thread, commit it to the repository’s `.claude/skills/`. 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. -### - -​ - -Stop sessions that fail to fetch server-managed settings +### Stop sessions that fail to fetch server-managed settings To keep a session that fetches [server-managed settings](</docs/en/server-managed-settings>) from starting when that fetch fails, set [`forceRemoteSettingsRefresh`](</docs/en/settings-reference#forceremotesettingsrefresh>) to `true` in the [`managed-settings.json`](</docs/en/settings#where-settings-live>) in your runner image. A reply from Anthropic’s API that your organization has no server-managed settings counts as a successful fetch. Before you add the key, check whether the environment runs Claude Tag channel sessions or sends model requests to Bedrock or Agent Platform: @@ -891,11 +735,7 @@ Set the key in that file even if you also set it in the claude.ai admin console. A new session has no [cached copy](</docs/en/server-managed-settings#fetch-and-caching-behavior>) of your server-managed settings, so if you set the key only in the console, the session doesn’t have it yet. If its fetch then fails, the session runs without those settings until a later fetch succeeds. To confirm that a failed settings fetch is why a session didn’t start, look at Claude Code’s last output in the session or the runner’s log. It includes `Your organization requires remote managed settings to load, but they could not be loaded.` -### - -​ - -Repository settings in sessions with several repositories +### Repository settings in sessions with several repositories In a thread in a [project](</docs/en/claude-projects#what-threads-pick-up-from-your-repositories>), no repository’s `.claude/settings.json` takes effect as project settings and no repository’s `.mcp.json` or skills load, wherever the thread starts. To give those threads a skill, add it to your runner image. In any other session with several repositories, Claude Code reads project settings from the directory the session starts in, so at most one repository’s `.claude/settings.json` takes effect as project settings. A hook defined in another repository’s file doesn’t run, a deny rule in it doesn’t apply, and its `env` isn’t set. @@ -904,19 +744,11 @@ Each repository’s `CLAUDE.md` loads wherever the session starts. Outside a project thread, its skills load too. The runner passes every repository to Claude Code as an [additional directory](</docs/en/permissions#additional-directories-grant-file-access-not-configuration>), so Claude Code also reads the `enabledPlugins` and `extraKnownMarketplaces` keys from each repository’s `.claude/settings.json`. To run a hook or apply a permission rule in every session, put it in `~/.claude/settings.json` on the runner host. The runner seeds the host file into every session, wherever the session starts. Write a path in a `Read` or `Edit` rule as a `//` absolute or `~/` home-relative [pattern](</docs/en/permissions#read-and-edit>), because other patterns anchor at the settings source or the current directory. -### - -​ - -Repository-committed permission rules +### Repository-committed permission rules Don’t put a bare `"Edit"`, `"Write"`, or `"NotebookEdit"` entry in a repository-committed `permissions.allow`. A bare file-tool rule matches the tool regardless of path, granting writes anywhere on the host rather than only the workspace, so the runner’s write-scope confine guard flags the session; with [`--confine-repo-settings enforce`](</docs/en/self-hosted-environments-reference#runner-cli-flags>) it refuses to spawn the session instead of logging and continuing. See the [hardening section](</docs/en/self-hosted-environments-deploy#harden-your-deployment>). A repository needs no file-tool rule at all: cloud sessions [pre-approve file edits regardless of mode](</docs/en/permission-modes#switch-permission-modes>). If you do commit a rule, scope it to the workspace, such as `"Edit(/**)"`; a single leading slash is relative to the project root, which is the session’s workspace. Bare file-tool rules are fine in the operator’s host-level `settings.json`, since that file isn’t repository-committed. A `defaultMode` of `auto` is only honored from the image-wide or user-level settings file, so a checked-out repository can’t grant itself auto mode. For which modes cloud sessions accept and the full rule syntax, see [permission modes](</docs/en/permission-modes>). -## - -​ - -What’s next +## What’s next * [Reference](</docs/en/self-hosted-environments-reference>): every CLI flag, environment variable, and metric * [Verify session identity](</docs/en/self-hosted-environments-identity>): validate the session token from services outside the runner
modified Deploy self-hosted environments to production View current →
Show diff (715 lines)
--- a/self-hosted-environments-deploy.md +++ b/self-hosted-environments-deploy.md @@ -2,11 +2,7 @@ A [self-hosted environment](</docs/en/self-hosted-environments>) runs Claude Code [cloud sessions](</docs/en/claude-code-on-the-web>) on runners you deploy inside your network, and in production those sessions execute model-directed code on behalf of everyone who can dispatch a session to the environment. This page is for the operator taking a working environment to production. It works through the deployment in order: what to lock down before connecting real systems, the egress the fleet needs, how sessions authenticate to your git host, the deployment recipes themselves, and what to check when sessions misbehave. -## - -​ - -Harden your deployment +## Harden your deployment A self-hosted runner executes arbitrary, model-directed code on your infrastructure on behalf of everyone who can dispatch a session to its environment. That’s any member of your Anthropic organization, and anyone who can start a [Claude Tag](<https://claude.com/docs/claude-tag/overview>) channel session in a scope an Owner routed to the environment. Work through each item before you connect an environment to production systems: @@ -36,11 +32,7 @@ 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. -## - -​ - -Network requirements +## Network requirements The runner and the session children it spawns make outbound connections to the hosts below. Restrict session-container egress to these hosts and the specific internal services sessions need to reach; Default-deny egress covers how and why. These hosts are always required: @@ -74,38 +66,22 @@ * **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`. If your organization uses single sign-on, that browser can also be redirected through `sso.claude.com`. -### - -​ - -Default-deny egress +### Default-deny egress Deploy runner and session containers in a network segment or namespace whose outbound traffic is limited to the hosts in the network requirements table, your git host, and the specific internal services sessions need to reach. The product can’t verify or enforce this, so apply it at your own network boundary on every environment. Session code is model-directed and can attempt connections to arbitrary hosts; default-deny egress at the network layer bounds where those attempts can land. This applies regardless of permission mode: the default pre-approved tool set already includes `Bash`, so shell egress runs without a prompt even without [auto mode](</docs/en/self-hosted-environments-configuration#permissions-and-tool-approval>). For details on which telemetry each session emits and how to turn it off, see [Telemetry](</docs/en/self-hosted-environments-reference#telemetry>). -### - -​ - -Authenticate to an egress proxy +### Authenticate to an egress proxy Some corporate egress proxies require a `Proxy-Authorization` header on every connection. The token in that header often rotates too fast to write into the proxy URL you set in `HTTPS_PROXY`. Set `HTTPS_PROXY` or `HTTP_PROXY` to your proxy’s URL as usual, then set `--proxy-authorization-command` or `--proxy-authorization-file` to tell the runner where to read the header value from. Both flags require Claude Code v2.1.238 or later. -#### - -​ - -Choose where the `Proxy-Authorization` value comes from +#### Choose where the `Proxy-Authorization` value comes from Pick the flag that matches how you produce the `Proxy-Authorization` token: * **[`--proxy-authorization-command<command>`](</docs/en/self-hosted-environments-reference#runner-cli-flags>)**: choose this for a token you generate on demand. The runner runs the shell command and uses its trimmed stdout as the header value, for example `Bearer <token>`. * **[`--proxy-authorization-file<path>`](</docs/en/self-hosted-environments-reference#runner-cli-flags>)**: choose this for a token another process rotates in place. The runner reads the file and uses its trimmed contents as the header value. -#### - -​ - -Configurations the runner refuses to start with +#### Configurations the runner refuses to start with Each flag also has an environment variable form, listed beside it in the [runner CLI flags reference](</docs/en/self-hosted-environments-reference#runner-cli-flags>). Before the runner contacts your proxy or the control plane, it checks the flags and their variables, and refuses to start in three cases: @@ -113,11 +89,7 @@ * **No proxy URL** : neither `HTTPS_PROXY` nor `HTTP_PROXY` holds an `http://` or `https://` URL. The runner reads both variables in upper or lower case, and doesn’t consult `ALL_PROXY`. * **Either flag passed to the orchestrator subcommand** : `self-hosted-runner orchestrator` doesn’t accept the flags or their environment variables. Pass the flag to each runner the orchestrator starts instead. -#### - -​ - -What the runner changes while a proxy-authorization flag is set +#### What the runner changes while a proxy-authorization flag is set With either flag set, the runner starts a listener of its own and sends proxy traffic from itself, its lifecycle hooks, and its sessions through that listener. The listener adds the `Proxy-Authorization` header on the way to your proxy. @@ -127,11 +99,7 @@ * **Session environment** : a session reaches your proxy only through the listener. In each session’s environment the runner removes `ALL_PROXY`, removes any spelling of `HTTPS_PROXY` or `HTTP_PROXY` that you didn’t set, and pins `NO_PROXY` to the runner’s own value. * **Logs** : the runner never logs the header value. -## - -​ - -Configure git +## Configure git The runner manages repository checkouts but doesn’t configure git identity or credentials by default. You control the runner’s image and process environment, so you control the git config. Choose one of two approaches: @@ -140,11 +108,7 @@ 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. -### - -​ - -Let the runner configure git +### Let the runner configure git Start the runner with `--configure-git`, or set `SELF_HOSTED_RUNNER_CONFIGURE_GIT=1`, to have it write global git config at startup: @@ -155,11 +119,7 @@ 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. -### - -​ - -Ship git config in your image +### Ship git config in your image Git identity is required for any commit. Set it system-wide in your Dockerfile so the config applies regardless of which user the runner process runs as: @@ -183,11 +143,7 @@ RUN git config --system --add safe.directory '*' -### - -​ - -Use the Anthropic git proxy +### Use the Anthropic git proxy 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: @@ -204,11 +160,7 @@ Keep git settings that aren’t secret, such as identity and `safe.directory`, in the system git configuration. -#### - -​ - -Turn the Anthropic git proxy on +#### 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: @@ -224,11 +176,7 @@ 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 +#### 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: @@ -236,11 +184,7 @@ * **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 +#### 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: @@ -253,11 +197,7 @@ After you fix the cause, restart the runners that failed the sessions, then have each creator send a message in their session or an Owner select **Retry**. -#### - -​ - -Turn the Anthropic git proxy off +#### 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. @@ -287,11 +227,7 @@ Restart the runners so that they register without the git proxy. Then start each failed session again. -#### - -​ - -GitHub API access without the GitHub CLI +#### GitHub API access without the GitHub CLI If your runner image doesn’t include the GitHub CLI, Claude Code can provide a built-in `gh`, so Claude can still open pull requests, comment, and read CI results. The built-in `gh` is for runners that use Anthropic-managed git. It supports one command, `gh api`, which calls GitHub’s REST API. Requires Claude Code v2.1.287 or later in the runner image. This command opens a pull request in place of `gh pr create`. The built-in `gh` fills in `{owner}` and `{repo}` for the current repository: @@ -302,19 +238,11 @@ * **`jq`** : install `jq` in the image if you want `--jq` to work * **[`CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`](</docs/en/env-vars>)** : if the session environment sets it, Claude Code doesn’t provide the built-in `gh`, and the session has no `gh` -#### - -​ - -GitHub API access with the GitHub CLI +#### GitHub API access with the GitHub CLI If your runner image includes the GitHub CLI for sessions to use, have your [wrapper script](</docs/en/self-hosted-environments-configuration#provision-credentials-scoped-to-the-session-creator>) mint a short-lived, least-scoped `GH_TOKEN` per session for the session’s creator. When `gh` is on the `PATH` that Claude Code starts with, the session has that `gh` and no built-in `gh`. With the token, that `gh` reaches GitHub with whatever access the token grants and outside Anthropic-managed git, so allow `api.github.com`. With Anthropic-managed git, leave the GitHub CLI out of the image to use the built-in `gh` instead. -#### - -​ - -Trust a private certificate authority with Anthropic-managed git +#### Trust a private certificate authority with Anthropic-managed git This section applies if you set `GIT_SSL_CAINFO` or `GIT_SSL_NO_VERIFY` in the environment of a runner whose sessions use Anthropic-managed git. The handling it describes requires the runner to run Claude Code v2.1.283 or later. When git on the runner must trust a private certificate authority (CA), such as the one a TLS-inspecting proxy signs with, the usual approaches work out as follows: @@ -335,11 +263,7 @@ The per-session certificate file needs a system CA bundle at `/etc/ssl/certs/ca-certificates.crt` or `/etc/pki/tls/certs/ca-bundle.crt` on the runner host. It also needs a `GIT_SSL_CAINFO` file that the runner’s user can read, that holds PEM `CERTIFICATE` blocks, and that is at most 1 MiB. When the runner can’t build the per-session file, it logs a `[runner:warn]` line containing `did not build the certificate file` and the reason. Git then uses your file as it is for Anthropic-managed git. Fix what the line names. For each session that uses Anthropic-managed git, the runner also logs a `[runner:warn]` line that begins `governed git: GIT_SSL_CAINFO is set` or `governed git: GIT_SSL_NO_VERIFY is set`. The line says what the runner did with that variable for its own git, for git inside the session, and for your lifecycle hooks. It ends with whether you need to change anything. -### - -​ - -Add github.com repositories to Claude Tag channel sessions +### Add github.com repositories to Claude Tag channel sessions If Claude can’t add a github.com repository to a Claude Tag channel session, make sure the channel has access to it, even when your runner can clone it. That access comes from settings on GitHub and in your Claude organization, not from your runner’s git credentials. @@ -363,11 +287,7 @@ Then start a new thread in the channel and [name the repository](<https://claude.com/docs/claude-tag/admins/configure-github#how-granted-repositories-reach-a-session>) in your first message. If Claude still can’t add the repository, see [If Claude can’t reach a repository](<https://claude.com/docs/claude-tag/admins/configure-github#if-claude-can%E2%80%99t-reach-a-repository>) for where to check the GitHub link and the repository grant. -### - -​ - -Rewrite git URLs for private networks +### Rewrite git URLs for private networks Repository URLs arrive from the control plane as HTTPS, with the hostname of your git host; for GitHub Enterprise, that’s the hostname you configured for the [GitHub Enterprise integration](</docs/en/github-enterprise-server>) on claude.ai. Two repeatable flags rewrite those URLs before clone: @@ -376,11 +296,7 @@ Host rewriting runs first, so list the internal hostname in `--git-ssh-rewrite` if you need both. For full control over checkout, use a [`checkout` lifecycle hook](</docs/en/self-hosted-environments-configuration#checkout>). -### - -​ - -Start a session on a repository outside GitHub +### Start a session on a repository outside GitHub To run a session on a repository from a git host other than GitHub, start the session from your terminal, in a checkout of that repository. First check the runner’s git credentials, network and git proxy, the repository’s address, and your branch: @@ -395,11 +311,7 @@ When the session is created, the command prints one line of JSON that starts with `{"ok":true`. If the `origin` remote doesn’t fit, the command fails with `requires a git source, but no GitHub remote was detected`. Review and merge on your git host the branches that sessions [push](</docs/en/self-hosted-environments-configuration#prompt-sessions-to-push-their-work>). -## - -​ - -Build the runner image +## Build the runner image Anthropic doesn’t publish a pre-built runner image. Build your own around the `claude` binary, layering in whatever toolchain your repositories need: language runtimes, compilers, package managers, and [MCP](</docs/en/mcp>) sidecars. The recipes below use `--capacity 4`, so one container serves up to four concurrent sessions from the same locked owner. That doesn’t provide the per-session container isolation in the hardening section: before connecting an environment to production systems, either run the recipes at `--capacity 1` with one container per session, or use [on-demand runners](</docs/en/self-hosted-environments-configuration#on-demand-runners>), which also keep the environment secret off session-running hosts. If you add the Anthropic git proxy to one of these recipes, also change `--capacity` to `1`. This Dockerfile is a minimal starting point. It installs `python3` because the [hooks Anthropic’s control plane supplies](</docs/en/self-hosted-environments-configuration#how-each-session%E2%80%99s-config-is-assembled>) to Claude Tag sessions, including the one that has Claude post its reply in Slack, run `python3`. Keep `python3` on `PATH` in any image that serves Claude Tag sessions: @@ -423,11 +335,7 @@ The command substitution looks up the current `stable` release number and passes it as the build argument, so running the same command after a new stable release rebuilds the download layer with the newer binary. To pin a specific release for reproducible builds, pass the version number directly as `CLAUDE_CODE_VERSION`. Replace `stable` with `latest` in the lookup URL when you need a release newer than the stable channel, such as one a [newly launched model requires](</docs/en/model-config>). -## - -​ - -Size CPU and memory for sessions +## Size CPU and memory for sessions Size a runner’s container or host for the sessions it runs rather than for the runner process. The runner itself polls for work, prepares each session’s checkout, runs your [lifecycle hooks](</docs/en/self-hosted-environments-configuration#lifecycle-hooks>), and starts and supervises the session processes. The load comes from the sessions: each one is a Claude Code process plus whatever it starts, such as builds, test suites, package installs, and [MCP servers](</docs/en/mcp>). For one session, start with the following values, stated as Kubernetes requests and limits or your platform’s equivalent, and treat them as a starting point rather than a requirement: @@ -453,11 +361,7 @@ * **CPU** : multiply one session’s CPU request by the sum. To let every session burst at once, multiply its CPU limit instead. Give each runner its own container. Use the same `--base-dir` path in each, on storage that no other runner’s container mounts, so that each runner has its own working directory. -### - -​ - -Give each session its own memory limit +### Give each session its own memory limit To stop one session from ending the others when memory runs out, run each runner at `--capacity 1` under its own memory limit, set to one session’s memory: @@ -466,19 +370,11 @@ When a container or unit reaches its memory limit, the kernel kills processes only inside it. If you set `--capacity` above one, the sessions share one limit. When they reach it, the kernel doesn’t choose by session which processes to kill, so one session’s memory use can end the others. On Kubernetes, you can’t separate the sessions with either value of the kubelet’s `singleProcessOOMKill` setting. You can’t cap a session’s total memory with a memory `ulimit` in your [wrapper script](</docs/en/self-hosted-environments-configuration#wrapper-scripts>) either. The kernel applies a value such as `ulimit -v` to each process separately. -### - -​ - -Leave room under process and thread limits +### Leave room under process and thread limits To size a process and thread limit, measure what one session needs and multiply it by the number of sessions that share the limit. When those sessions reach the limit, the kernel refuses new processes and threads, so commands, builds, and tests in any of them can fail. The refused call returns `EAGAIN`, whose standard message is `Resource temporarily unavailable`. Suppose one session peaks at 300 processes and threads, and four sessions share the limit. Together they need 1,200, and with a limit of 2,400, you leave room for builds that need twice as much. -#### - -​ - -Where to set each limit +#### Where to set each limit Each limit in this table counts threads as well as processes, and `pids.max` is the file that holds a cgroup’s limit: @@ -491,11 +387,7 @@ When you don’t set `TasksMax`, systemd applies `DefaultTasksMax`, which defaults to 15% of the lowest of `kernel.pid_max`, `kernel.threads-max`, and the root cgroup’s `pids.max`. -#### - -​ - -Measure one session’s peak +#### Measure one session’s peak To get the numbers for your own runners, measure one session on its host, which on Kubernetes is the node: @@ -543,20 +435,12 @@ With a higher limit, you leave room for heavier builds, and with a lower one, you stop a fork bomb sooner. -#### - -​ - -Check a `pids.max` limit +#### Check a `pids.max` limit * **Check whether`pids.max` was reached**: search the host’s kernel log, for example with `dmesg`, for a line that contains `cgroup: fork rejected by pids controller in` and a cgroup’s path. The kernel logs it only the first time it refuses a process or thread in that cgroup, so search the whole log. * **See the limit in force** : read `pids.max` in the runner’s cgroup directory and in each directory above it. The lowest value is the limit in force, and `max` means no limit at that level. -## - -​ - -Kubernetes +## Kubernetes The runner serves `GET /healthz` on port 8080 by default, configurable with `--health-port`. After startup, the endpoint returns `200` whenever the process is alive, so the probes below detect a dead process, not a stuck one. To catch a runner that stopped polling, alert on the `last_poll_age_seconds` series from [`/metrics`](</docs/en/self-hosted-environments-reference#prometheus-metrics>). The Deployment below mounts the environment secret from a Kubernetes Secret, points the liveness and readiness probes at `/healthz`, and sets a 90-second termination grace period. See Shutdown timing for why the grace period matters. The manifest sets no CPU or memory `resources` on the runner container. Add a block sized for the capacity you run, as Size CPU and memory for sessions describes. @@ -622,11 +506,7 @@ kubectl create secret generic claude-runner-environment-secret -n claude-runners --from-file=environment-secret=./environment-secret -## - -​ - -Docker Compose +## Docker Compose The Compose service below restarts the runner whenever it exits, which covers both crashes and the normal exit after draining. A Docker restart policy restarts the same container with its writable layer intact, so the runner comes back on a reused filesystem rather than the fresh one the hardening posture recommends; use this recipe for evaluation, and for production either recreate the container per run or use an orchestrator that does. Docker waits longer before each restart of a container that keeps exiting, up to a ceiling, so a runner that can’t start doesn’t keep restarting in a tight loop under this recipe. When the runner exits describes what to check when that happens. @@ -650,11 +530,7 @@ environment-secret: file: ./environment-secret -## - -​ - -Shutdown timing +## Shutdown timing These timings apply to runners. The `claude self-hosted-runner orchestrator` process has its own: see [Size `--shutdown-drain-sec` and the orchestrator’s stop timeout](</docs/en/self-hosted-environments-configuration#size-shutdown-drain-sec-and-the-supervisors-stop-timeout-for-the-orchestrator>). @@ -682,11 +558,7 @@ * **With[`--retire-at`](</docs/en/self-hosted-environments-reference#runner-cli-flags>)**: leave enough time between the retire time and the time the host stops for typical turns to finish, plus the wait for background tasks that [Runner lifecycle](</docs/en/self-hosted-environments#runner-lifecycle>) describes, plus the logged time. Compute the retire time at each launch, for example `date +%s` plus the runner’s intended lifetime. * **With`--defer-shutdown-max-min`**: the stop timeout must also cover the minutes you configure and a further wait before the drain starts, 75 seconds at default settings. Defer the drain past the first signal explains both. The runner logs this longer time at startup too. -### - -​ - -Let running turns finish before a restart +### Let running turns finish before a restart To let running turns finish before a rolling restart, set `--drain-wait-sec`, and raise your stop timeout to at least that wait plus 80 seconds. With the default wait of `0`, a restart cuts off any turn that’s still running, and the session resumes on another runner without its unpushed work. @@ -696,27 +568,15 @@ If the stop timeout runs out during the wait, your host kills the runner with work still running. Its sessions get no `post-session` hook. The runner also doesn’t deregister, so the control plane can take a few minutes and sometimes longer to requeue them. -### - -​ - -Post a status message before a restart +### Post a status message before a restart Before a restart that will interrupt sessions, have an [Owner](</docs/en/cloud-environments#organization-shared-environments>) post a status message on the environment from the [**Cloud environments** admin page](<https://claude.ai/admin-settings/cloud-environments>). At [claude.ai/code](<https://claude.ai/code>), members see the message in their sessions in that environment. Have the Owner set an expiry with the post, or remove the message once the runners are back. -### - -​ - -Defer the drain past the first signal +### Defer the drain past the first signal Set [`--defer-shutdown-max-min <n>`](</docs/en/self-hosted-environments-reference#runner-cli-flags>) if you want a runner you’re restarting to go on serving the sessions it holds for up to `n` minutes, instead of draining them on the first signal. On the first `SIGTERM` or `SIGINT`, the runner stops taking new work and goes on serving the sessions it holds. It keeps polling so that the control plane doesn’t requeue those sessions. Requires Claude Code v2.1.238 or later. -#### - -​ - -What happens to the sessions the runner holds after the first signal +#### What happens to the sessions the runner holds after the first signal In the first two stages that follow the signal, the runner releases sessions, and a released session resumes on a fresh runner when its user sends their next message. Counting from the first signal, the runner moves through three stages: @@ -726,19 +586,11 @@ At any stage, the runner exits 0 as soon as it holds no sessions. A second signal cuts the stages short: the runner drains immediately, as it does on the first signal without `--defer-shutdown-max-min`. Once a drain is under way, the next signal force-exits the runner. That holds whether a second signal or the post-release grace running out started the drain. -#### - -​ - -Size the stop timeout +#### Size the stop timeout Give your host’s stop timeout at least the sum of three parts: the `n` minutes you configure, the post-release grace, and the drain that Shutdown timing describes. With default settings the post-release grace is 75 seconds and the drain takes up to 80 seconds, so allow `n` minutes plus 155 seconds. The runner prints this sum at startup whenever `--defer-shutdown-max-min` is set. If the stop timeout runs out before the runner finishes, the sessions it still holds get no `post-session` hook. The runner doesn’t deregister, so the control plane can take a few minutes and sometimes longer to requeue those sessions. If you can’t give the stop timeout that sum, leave `--defer-shutdown-max-min` unset so the runner drains on the first signal instead. -### - -​ - -What reaches a running post-session hook +### What reaches a running post-session hook The `post-session` hook and the Claude session child each run in their own POSIX process group, separate from the runner’s, so stop mechanisms reach them differently: @@ -749,19 +601,11 @@ When the drain starts, and again on a forced exit, the runner logs how many `post-session` hooks are still running, so you can tell a quiet drain from one that’s mid-snapshot. -## - -​ - -Keep the base directory and capacity identical across runners +## Keep the base directory and capacity identical across runners If a runner dies mid-session, the server requeues the session and another runner in the environment picks it up. That runner derives the checkout path from its own `--base-dir` and `--capacity`: `--capacity 1` checks out directly under `--base-dir`, and a `--capacity` above `1` uses per-session worktrees instead. When runners in the same environment use different values for either flag, the resumed session’s working directory changes, and absolute paths the agent recorded earlier, in edits, tool calls, or its own notes, point at a location that no longer exists. Use the same `--base-dir` and `--capacity` on every runner in an environment, and don’t use a per-host value such as an instance ID or hostname. Pass both flags explicitly, as the Kubernetes and Docker Compose recipes do, so that neither value depends on a default. The base directory defaults to `/workspace`, with the exception the [`--base-dir` reference row](</docs/en/self-hosted-environments-reference#runner-cli-flags>) records. The runner needs write access to it. At startup, before registering, the runner creates the directory and confirms it can write to it, and exits with `cannot create or write to base directory` when it can’t. A runner started as root creates the default `/workspace` itself. For a non-root runner, create the directory and give the runner’s user ownership before starting the runner, or point `--base-dir` at a directory that user already owns. -## - -​ - -Reuse a pre-warmed checkout +## Reuse a pre-warmed checkout 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: @@ -783,19 +627,11 @@ * **With the git proxy, a`reftable` pre-warm loses its refs**: when the runner sanitizes `.git/` before each session, it keeps `.git/refs/` and removes the `.git/reftable/` directory. A clone pre-warmed in git’s `reftable` ref format loses its refs that way, so pre-warm the clone in git’s `files` ref format instead. * **Long clones need no workaround** : the runner bounds each git operation with a 120-second no-progress watchdog and a 30-minute hard cap, not a flat timeout, so a slow cold clone that keeps reporting progress completes. -### - -​ - -Confirm that the runner uses your clone +### Confirm that the runner uses your clone To confirm that the runner uses your clone, start it with [`--log-level debug`](</docs/en/self-hosted-environments-reference#runner-cli-flags>) and start a session on the repository. The runner logs `Prefetched repo found at` and the clone’s path. If it logs `No prefetched repo, fresh init at` instead, it found no usable clone at the path in that line. Check that your clone is at that path, owned by the runner’s user, with a remote named `origin`. If the runner finds your clone and sessions still start slowly, check whether the clone is shallow. -## - -​ - -Pin the version +## Pin the version Each session’s child process runs the runner’s own binary by default, and the runner turns off auto-update inside the sessions it spawns. With that default, 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: @@ -806,22 +642,14 @@ * **If sessions start a different binary** : if you use [`--exec-path`](</docs/en/self-hosted-environments-reference#runner-cli-flags>) or a [`command` hook](</docs/en/self-hosted-environments-configuration#command>) to start a Claude Code binary other than the runner’s own, sessions run that binary’s version. Update that binary when you update the runner. * **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 -## - -​ - -Scale the fleet +## Scale the fleet Your orchestrator decides when to add or remove runners. Because of the [one-owner-per-runner lock](</docs/en/self-hosted-environments#runner-lifecycle>), the minimum replica count is the number of users and Claude Tag agents you expect to be active concurrently; `--capacity` controls parallelism within one owner’s sessions, not across owners. Two scaling approaches are available: * **Fixed fleet** : run a static set of runner replicas and scale on the [Prometheus metrics](</docs/en/self-hosted-environments-reference#prometheus-metrics>) each runner serves * **On-demand runners** : run the `claude self-hosted-runner orchestrator` subcommand, which polls Anthropic for sessions that are queued with no runner available and invokes your `spawn-runner` hook to boot one per session. See [On-demand runners](</docs/en/self-hosted-environments-configuration#on-demand-runners>). -### - -​ - -Release idle sessions on a fixed fleet +### Release idle sessions on a fixed fleet If sessions stay queued on a fixed fleet while every runner is online, idle sessions may be the cause. By default, a session keeps its slot after its turn finishes, and its runner stays locked to that session’s [owner](</docs/en/self-hosted-environments#key-concepts>). Other owners’ sessions can’t use that runner’s free slots. If your team’s [cloud scheduled task](</docs/en/routines>) starts a new session at each run, its idle sessions can fill every slot. To check, read `claude_code_self_hosted_runner_session_idle_seconds` in each runner’s [Prometheus metrics](</docs/en/self-hosted-environments-reference#prometheus-metrics>). Each session a runner holds has its own series: `0` while the session is busy, otherwise the seconds since it went idle. Choose the idle time you’d allow: longer than the pauses people take mid-task, and short enough that each run is released before the scheduled task’s next one starts. Compare the series with it. @@ -836,11 +664,7 @@ * **Runner exits** : a runner that releases its last session starts a normal exit. Have your supervisor restart it on a fresh filesystem, as Harden your deployment describes. * **Sessions that never go idle** : also set [`--kill-session-after-min`](</docs/en/self-hosted-environments-reference#runner-cli-flags>), because some sessions don’t count as idle -### - -​ - -Keep an idle session while its processes run +### Keep an idle session while its processes run To keep an idle session until processes it left on your host finish, such as `nohup` jobs, start the runner with [`--hold-idle-file`](</docs/en/self-hosted-environments-reference#runner-cli-flags>) and keep touching that file from the host. Requires Claude Code v2.1.311 or later. These steps assume a non-root runner on a host. If your runner runs as `root`, its sessions can touch the file themselves, so run it as a dedicated user first. @@ -884,19 +708,11 @@ * **Past the cap** : `--max-hold-min` runs out. To hold longer, raise it * **Forced releases** : you set [`--retire-at`](</docs/en/self-hosted-environments-reference#runner-cli-flags>), [`--defer-shutdown-max-min`](</docs/en/self-hosted-environments-reference#runner-cli-flags>), or [`--kill-session-after-min`](</docs/en/self-hosted-environments-reference#runner-cli-flags>), and that limit arrives. To hold longer, set a later limit -## - -​ - -Known issues and limitations +## Known issues and limitations The following are the limitations in this release, with workarounds where one exists. -### - -​ - -Connector traffic leaves your network +### Connector traffic leaves your network Anthropic calls connector tools from its own infrastructure rather than from your runner. Connector tools are the claude.ai connectors, such as GitHub, Slack, and Linear. When Claude uses a connector in a self-hosted session, that traffic goes through `api.anthropic.com` rather than originating inside your network boundary. To keep a connector out of self-hosted sessions, filter it with the [`allowedMcpServers` and `deniedMcpServers` policy settings](</docs/en/managed-mcp#policy-based-control-with-allowlists-and-denylists>). Claude Code applies these settings to the connectors Anthropic delivers as well as to the servers you seed from the runner host and the servers users add, so if you deploy an allowlist for other servers, Claude Code blocks delivered connectors too. To keep connectors available alongside a URL-based allowlist, add entries that match the Anthropic proxy paths for delivered connectors: @@ -906,11 +722,7 @@ If tool traffic must stay inside your network, run the equivalent tools as local MCP servers on the runner image instead. See [MCP servers](</docs/en/self-hosted-environments-configuration#mcp-servers>). -### - -​ - -Some sessions don’t count as idle +### Some sessions don’t count as idle A session holding a background task that keeps running doesn’t count as idle, so `--release-idle-session-min` won’t release that session’s slot. A session that’s waiting on an approval requested from inside a running tool call also doesn’t count as idle. Set `--kill-session-after-min` alongside it as a hard backstop. `--kill-session-after-min` is a backstop for runaway sessions. On a runner on v2.1.260 or later, a session that reaches the limit isn’t terminated outright. The runner gives it a grace window, 15 minutes by default, which you can change with [`SELF_HOSTED_RUNNER_MAX_LIFETIME_GRACE_MS`](</docs/en/self-hosted-environments-reference#environment-variable-only-settings>): @@ -920,11 +732,7 @@ A released session resumes from a fresh clone, so work it hadn’t pushed is gone either way; see Resumed sessions lose unpushed work. Before v2.1.260, the runner terminated every session at the limit, after waiting at most the grace window for a running turn to finish. Set the flag above your longest expected session, such as `--kill-session-after-min 480` for 8 hours. To free slots from conversations that go idle, use `--release-idle-session-min` instead. -### - -​ - -Resumed sessions lose unpushed work +### Resumed sessions lose unpushed work A session that resumes on a fresh runner loses the work it hadn’t pushed, because that runner clones the repository again from its starting branch. To keep committed work, set [`--push-outcome-on-release`](</docs/en/self-hosted-environments-reference#runner-cli-flags>) on every runner in the environment. 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. A runner without it resumes the session from its starting branch. The push uses the runner host’s own git credentials, including on a runner that uses Anthropic-managed git. @@ -936,30 +744,18 @@ * **Repositories checked out via a[`checkout` lifecycle hook](</docs/en/self-hosted-environments-configuration#checkout>)**: these aren’t pushed. Snapshot them from the [`post-session` hook](</docs/en/self-hosted-environments-configuration#post-session>). * **Commits in a session that someone archives or deletes, or whose runner they release from the session’s menu** : don’t count on the flag’s push. To save them, push `HEAD` to a rescue branch from a [`post-session` hook](</docs/en/self-hosted-environments-configuration#post-session>). The example there pushes only after a snapshot commit, so make yours push even when nothing is uncommitted. -### - -​ - -Additional limitations +### Additional limitations * **A command cut off by a lost runner can run again** : when the session resumes on another runner, Claude sees the interrupted tool call with a result saying its outcome is unknown. * **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. * **When the session resumes** : a [`checkout` hook](</docs/en/self-hosted-environments-configuration#checkout>) runs for the added repository too, with [`CLAUDE_RUNNER_REPO_REF`](</docs/en/self-hosted-environments-configuration#checkout>) empty, so make your hook handle that. * **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. -### - -​ - -Report an issue +### Report an issue For issues with self-hosted environments, contact your Anthropic account team. -## - -​ - -Troubleshooting +## Troubleshooting For guided diagnosis, run the doctor subcommand on the runner host. The doctor subcommand starts an interactive Claude Code session with the runner’s logs and state attached. Sign in with `claude auth login` on that host first so the session can query your environment, its runners, and its queued sessions. Without that sign-in, for example when the host authenticates with an API key, it’s limited to the local health endpoint, metrics, and the runner’s log, and it reads the log only if you started the runner with `--log-file`. @@ -1011,11 +807,7 @@ 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 base directory 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. -### - -​ - -When the runner exits +### When the runner exits Don’t restart an [on-demand runner](</docs/en/self-hosted-environments-configuration#on-demand-runners>), because its work order is single-use. A runner that exits right after it starts needs different handling from one that exits for any other reason. @@ -1025,11 +817,7 @@ 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. For production, have your supervisor restart the runner on a fresh disk, in a new container or VM, as Harden your deployment recommends. -#### - -​ - -Recognize a failed start +#### Recognize a failed start When the runner can’t start, it prints a line that says why, and then it exits. For most causes the line contains `[runner:fatal]`. For some causes the line begins with `error:` instead, including when the runner can’t parse its flags, can’t read the environment secret, or can’t create or write to the base directory. The next line then points to `--help`. Most log lines start with a timestamp and `[self-hosted-runner]`, which the sample below leaves out. For example, a runner started with the Anthropic git proxy and a capacity above one prints a line like this one: @@ -1041,11 +829,7 @@ * **The exit code** : the runner doesn’t set aside an exit code for errors that repeat on every start. It exits with the same code for a configuration error, such as an unsupported combination of flags, and for a failure that can clear by itself, such as the API staying unreachable through the runner’s own retries. Base the decision to wait longer on how soon the runner exited, and read the runner’s output to learn why. * **An environment that looks healthy** : some startup steps run after the runner registers with your environment, such as `--configure-git` and the Anthropic git proxy’s credential setup. If one of those steps fails, the environment can go on listing that runner for a few minutes after the process has exited, and the **Cloud environments** page can read **Healthy** while no runner is picking up work. If sessions stay queued in an environment that looks healthy, check whether your supervisor is restarting the runner. -#### - -​ - -Restart with a wait that grows +#### Restart with a wait that grows How you get a growing wait depends on your supervisor. @@ -1062,11 +846,7 @@ * **A systemd unit** : by default systemd waits the same `RestartSec` before every restart and doesn’t lengthen it, so a unit with `Restart=always` restarts a runner that can’t start at that same interval each time. When the starts come fast enough to reach the unit’s start rate limit, five starts in 10 seconds by default, systemd stops restarting the unit. The unit stays stopped until someone starts it again, which systemd allows once the rate limit’s interval has passed or after `systemctl reset-failed`. Because `RestartSec` applies to every restart, a longer value also delays the restart after a normal exit. Choose a value that balances the two, and alert on the unit’s restart count. * **A shell loop or your own supervisor** : apply the same rule yourself. Start with a wait of five seconds. After each run that ended within a minute, double the wait for the next restart, up to five minutes. After a run that lasted a minute or more, go back to five seconds. -#### - -​ - -Check why the runner keeps exiting +#### Check why the runner keeps exiting When the runner has exited right after starting several times in a row, stop and check these before restarting it again. @@ -1078,11 +858,7 @@ For guided diagnosis on the runner host, run the doctor subcommand. -### - -​ - -A session is picked up, but Claude never answers its first message +### A session is picked up, but Claude never answers its first message If a runner picks up a session but Claude never answers the first message, and your runners reach `api.anthropic.com` through a proxy, the proxy may be the cause. Anthropic sends a session its messages over one streaming response that stays open. If your proxy buffers it, or ends it before passing anything on, the first message never arrives. Other requests from the session still succeed. To fix it, change how the proxy handles this request: @@ -1093,11 +869,7 @@ Then start a new session and check that Claude answers. Raising the runner’s timeouts doesn’t help: you only wait longer before the runner stops the session. -#### - -​ - -Confirm the cause in the runner’s log +#### Confirm the cause in the runner’s log These steps are for runners on Claude Code v2.1.287 or later, at the default `--log-level info`. Older runners log these lines later, or not at all. @@ -1115,19 +887,11 @@ If the log has none of these lines, or the proxy’s log shows nothing wrong, report an issue. -#### - -​ - -Stop the session from trying again +#### Stop the session from trying again The session keeps the message pending, and a runner that can serve the session’s owner picks the session up again. Until you change the proxy, the session waits the same way each time. To stop that, archive the session in claude.ai/code. -## - -​ - -What’s next +## What’s next * [Customize sessions](</docs/en/self-hosted-environments-configuration>): wrapper scripts, lifecycle hooks, on-demand runners, MCP servers, and permissions * [Test end to end](</docs/en/self-hosted-environments-testing>): verify a new runner image from CI before promoting it
modified Verify session identity in self-hosted environments View current →
Show diff (137 lines)
--- a/self-hosted-environments-identity.md +++ b/self-hosted-environments-identity.md @@ -2,19 +2,11 @@ A [self-hosted environment](</docs/en/self-hosted-environments>) lets Claude Code [cloud sessions](</docs/en/claude-code-on-the-web>) run on infrastructure you operate instead of on Anthropic’s. Because the session runs inside your network, Claude can call your internal services directly. Those services need a way to confirm that a request came from a Claude Code session in your environment, and to identify the user or service identity that created that session. Every session in a self-hosted environment receives a signed JSON Web Token (JWT) in the `CLAUDE_CODE_SESSION_ACCESS_TOKEN` environment variable. A session presents the token like any bearer credential; for example, a script Claude runs can call your service with `curl -H "Authorization: Bearer $CLAUDE_CODE_SESSION_ACCESS_TOKEN"`. Anthropic signs the token and publishes the verification keys at a public JWKS endpoint. Your services fetch those keys, verify the signature, and read the claims to decide what access to grant. -## - -​ - -The session token +## The session token Before you write verification code, know what the token establishes and the shape your JWT library will see. -### - -​ - -What the token proves +### What the token proves A valid token establishes some facts and deliberately not others: @@ -26,11 +18,7 @@ * Verify the `aud` claim against your environment ID, the `ccpool_...` value shown with your environment on the [**Cloud environments** admin page](<https://claude.ai/admin-settings/cloud-environments>), to reject tokens issued to any other organization’s environment. * Scope credentials you derive from the token to what a single coding session should be able to do, not to everything the session’s creator can do. See Scope derived credentials. -### - -​ - -Token format +### Token format The value of `CLAUDE_CODE_SESSION_ACCESS_TOKEN` has an `sk-ant-cc-` prefix followed by a standard three-part JWT: @@ -38,19 +26,11 @@ Strip the prefix before passing the value to a JWT library. Tokens issued to Anthropic-hosted cloud sessions carry an `sk-ant-si-` prefix instead and are signed by a different key set, so reject any value that doesn’t start with `sk-ant-cc-`. The signature algorithm is `ES256`, which is ECDSA on the P-256 curve with SHA-256. The token header carries a `kid` that identifies which key in the JWKS signed it. -## - -​ - -Verify the token +## Verify the token Verification runs in one of two places. Services on your network verify the token cryptographically against Anthropic’s published keys, and wrapper scripts inside the session can use the runner binary’s built-in decoder instead. -### - -​ - -Verify the token from your service +### Verify the token from your service Anthropic publishes the verification keys at a public, unauthenticated endpoint: @@ -176,11 +156,7 @@ "creator_sub": act.get("sub"), } -### - -​ - -Verify the token inside the session +### Verify the token inside the session [Wrapper scripts](</docs/en/self-hosted-environments-configuration#wrapper-scripts>) run inside the session, before Claude starts. Instead of calling a JWT library, they can run the runner binary’s `self-hosted-runner decode-token` subcommand. The subcommand reads the token from a positional argument, from `CLAUDE_CODE_SESSION_ACCESS_TOKEN`, or from piped stdin, in that order, then strips the prefix, verifies the signature against the JWKS endpoint, checks expiry, and prints the claims as JSON. The subcommand performs the signature and expiry checks only; it doesn’t check `iss`, `aud`, or `ccr:role`. When your wrapper’s auth decision depends on those claims, read them from the printed JSON and compare them explicitly. This command extracts the creator identity, preferring the email address, then the creator’s `act.sub` subject, `user:<id>` or `agent:<id>`: @@ -188,11 +164,7 @@ 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. -## - -​ - -Claims reference +## Claims reference Read identity from the `ccr:*` namespace and the `act` chain; the flat `account_email`, `organization_uuid`, and `account_uuid` claims are backward-compatibility duplicates that may be removed. Sessions your organization’s service identity creates carry an `agent:` subject in `act.sub` and omit `act.email`, `ccr:account_id`, `account_email`, and `account_uuid`. The two email claims are optional for user-created sessions too. Anthropic records them at session creation only when the creating request’s credentials carry an email, and a session dispatched from the CLI can lack both. Key identity on `act.sub` or `ccr:account_id` rather than on email. Tokens can also carry additional claims beyond this table; ignore claims you don’t recognize. The table below lists the session token claims relevant to verification. @@ -214,11 +186,7 @@ `account_uuid`| string| The creating user’s Anthropic account UUID. `act`| object| [RFC 8693](<https://www.rfc-editor.org/rfc/rfc8693>) delegation chain. See The `act` chain. -### - -​ - -The `act` chain +### The `act` chain The `act` claim records the full delegation path from the user or service identity that created the session down to the [environment](</docs/en/self-hosted-environments#key-concepts>) whose secret admitted the runner, and the identity that created that secret. The creator is the outermost actor, so `act.sub` identifies them directly. @@ -231,11 +199,7 @@ `act.act.act`| The environment. `act.act.act.sub` is `ccr:pool:<pool_id>`. `act.act.act.act`| The identity that created the environment secret the runner registered with. The chain ends here. -## - -​ - -Scope derived credentials +## Scope derived credentials The session token identifies the user or service identity that created the session, but don’t treat it as equivalent to that creator logging in directly. The token sits in an environment variable inside the session, so any code Claude runs, and any tool or MCP server the session starts, can read and present it. Verification is also offline: a token that verifies against the JWKS stays valid until its `exp`, whatever has happened to the session since, and Anthropic doesn’t publish a revocation feed for session tokens. Bound anything you derive from the token accordingly. When your service exchanges the token for internal credentials, issue credentials scoped to what one coding session should reach: @@ -243,11 +207,7 @@ * **Limit lifetime** : bound derived credentials to the token’s `exp`, or shorter. * **Audit as the session** : record the `ccr:session_id` and `jti` alongside the creator identity so you can trace actions back to a specific session. -## - -​ - -Related environment variables +## Related environment variables The creator identity also appears in plain environment variables on two surfaces that never verify the token: @@ -256,11 +216,7 @@ Use the plain variables for orchestrator-side decisions such as selecting a machine image. Use `CLAUDE_CODE_SESSION_ACCESS_TOKEN` when a downstream service needs independent cryptographic proof rather than trusting the runner’s environment. -## - -​ - -What’s next +## What’s next * [Self-hosted environments](</docs/en/self-hosted-environments>): the environment, runner, and session model; the [quickstart](</docs/en/self-hosted-environments-quickstart>) and [Deploy to production](</docs/en/self-hosted-environments-deploy>) hold setup and operations * [Customize sessions](</docs/en/self-hosted-environments-configuration>): wrapper scripts that consume the token, and the `spawn-runner` hook
modified Self-hosted environments quickstart View current →
Show diff (121 lines)
--- a/self-hosted-environments-quickstart.md +++ b/self-hosted-environments-quickstart.md @@ -2,28 +2,16 @@ A [self-hosted environment](</docs/en/self-hosted-environments>) runs Claude Code [cloud sessions](</docs/en/claude-code-on-the-web>) on infrastructure your organization operates, executed by runner processes you deploy. This quickstart stands up your first one, the smallest that works: one runner on a single host, running one test session. There are two steps: create the environment, start a runner, and route a session to it, then message that session from your terminal. You’ll move between two surfaces: claude.ai for creating the environment, checking its status, and routing a session, and a terminal on the host for everything the runner does. By the end you’ll have an environment on the [**Cloud environments** admin page](<https://claude.ai/admin-settings/cloud-environments>), a runner polling for work, and a session running on your host. Before you connect real repositories or internal systems, work through [Deploy to production](</docs/en/self-hosted-environments-deploy>), which covers the security posture, egress control, git credentials, and orchestration. -## +## Prerequisites -​ - -Prerequisites - -### - -​ - -Organization and roles +### Organization and roles The claude.ai side needs: * **Allow self-hosted environments** turned on by an [Owner](</docs/en/cloud-environments#organization-shared-environments>) on the [**Cloud environments** admin page](<https://claude.ai/admin-settings/cloud-environments>); the **New** button doesn’t appear until it is. If you don’t hold the role, someone who does can create the environment and hand you its secret; the runner and terminal steps on this page need no claude.ai role, and where a step checks status in the admin UI, the runner’s own log lines give you the same signal. * The [GitHub connector](<https://claude.ai/admin-settings/connectors>) turned on by an Owner, and each developer’s own [GitHub connection](</docs/en/web-quickstart#connect-github>), so they can pick github.com repositories when they start sessions. -### - -​ - -Host and network +### Host and network The runner host needs: @@ -31,11 +19,7 @@ * 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. An SSH key alone isn’t enough, because the runner clones the repository’s `https://` URL. To clone over SSH instead, see [Rewrite git URLs for private networks](</docs/en/self-hosted-environments-deploy#rewrite-git-urls-for-private-networks>). * A clock synchronized to real time, for example with NTP. -### - -​ - -Software on the runner host +### Software on the runner host Install on the host before you start: @@ -48,19 +32,11 @@ A ready host prints the runner’s usage text, listing flags such as `--environment-secret-file`. On versions older than 2.1.224, the command prints the general `claude --help` output instead. If you see that output, [update Claude Code](</docs/en/setup#update-claude-code>). If you run `claude` from a container image, [rebuild the image](</docs/en/self-hosted-environments-deploy#build-the-runner-image>) with version 2.1.224 or later. -## - -​ - -Set up an environment and runner +## Set up an environment and runner 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 +### 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: @@ -73,11 +49,7 @@ 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 +### 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. @@ -128,11 +100,7 @@ * **After either fix** : start the runner again and watch the failed session instead of starting a new one. If it has failed several times, wait several minutes for the runner to log `Picked up session`. * **To use a different repository instead** : [archive](</docs/en/claude-code-on-the-web#archive-sessions>) or [delete](</docs/en/claude-code-on-the-web#delete-sessions>) the failed session, then start the runner again and start a new session. Otherwise, the runner can pick up the failed session instead of the new one. -### - -​ - -If the runner exits +### If the runner exits If the runner exits during this quickstart, start it again. The runner can exit on its own: @@ -143,11 +111,7 @@ 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>). -## - -​ - -Send a follow-up message to a running session +## Send a follow-up message to a running session Once a session is running on your environment, send it a follow-up from the `claude` CLI on any machine where you’re logged in with `claude auth login`; the command doesn’t need to run from the machine that started the session. The command posts one message: @@ -155,11 +119,7 @@ For `<session-id>`, pass the bare `session_...` or `cse_...` ID or the session’s claude.ai/code URL. A successful send prints `Sent to cloud session.` with the session ID and a view link. Accepted ID forms, JSON output, and the account and policy requirements are on [Send follow-ups from the CLI](</docs/en/claude-code-on-the-web#send-follow-ups-from-the-cli>), since the command works the same against Anthropic-hosted sessions. -## - -​ - -What’s next +## What’s next * [Deploy to production](</docs/en/self-hosted-environments-deploy>): harden the deployment, control egress, configure git credentials, and run the fleet under Kubernetes or Compose * [Customize sessions](</docs/en/self-hosted-environments-configuration>): wrapper scripts, lifecycle hooks, on-demand runners, MCP servers, and permissions
modified Self-hosted environments reference View current →
Show diff (223 lines)
--- a/self-hosted-environments-reference.md +++ b/self-hosted-environments-reference.md @@ -2,11 +2,7 @@ This page is the reference for the two processes you run in a [self-hosted environment](</docs/en/self-hosted-environments>): the runner, which executes Claude Code [cloud sessions](</docs/en/claude-code-on-the-web>) on your hosts, and the optional autoscaling orchestrator, which starts runners as sessions queue. Each has its own flag table. Both run on Linux or macOS hosts, which the defaults such as `/workspace` and `~/.claude` assume. Run `claude self-hosted-runner --help` for the authoritative list on your installed version. Metric series and a few API fields still use `pool` for what these pages call an environment; both terms name the same thing. The environment ID is the `pool_id` field, with the form `ccpool_...`: wherever these pages show a `pool` identifier, it names the environment. CLI flags and environment variables spell it `environment`, such as `--environment-secret-file`; the deprecated `pool` spellings still work, as the `--environment-secret-file` row describes. -## - -​ - -Runner CLI flags +## Runner CLI flags Most flags have a corresponding environment variable. When both are set, the flag takes precedence. Duration flags take minutes or seconds on the CLI, but the paired environment variable is always in milliseconds, indicated by the `_MS` suffix, and the Default column shows the flag’s unit: `--exit-if-unused-min 10` is equivalent to `SELF_HOSTED_RUNNER_IDLE_SHUTDOWN_MS=600000`, and a Helm value like `SELF_HOSTED_RUNNER_STARTUP_TIMEOUT_MS: "15"` means 15 milliseconds, not the 15-minute default. @@ -55,19 +51,11 @@ * **Flag** : startup fails with an error. * **Environment variable** : the runner clamps the value to the timer ceiling rather than rejecting it. -### - -​ - -Session startup timeout +### Session startup timeout If a session lost its slot during a turn such as `/code-review`, update the runner and the child binary to v2.1.309 or later. From v2.1.299 through v2.1.308, the runner released a session, even mid-turn, once the startup timeout passed without a `user` or `assistant` message. With `--startup-timeout-min <n>`, the runner releases a session’s slot when its child hasn’t initialized within `<n>` minutes after cloning. During a turn that begins before the child initializes, the session keeps its slot until `<n>` minutes pass with no line on the child’s [activity channel](</docs/en/self-hosted-environments-configuration#keep-stdin-and-file-descriptor-3-attached>). Once the child initializes, the runner clears that count and `--release-idle-session-min` governs release. To limit a session whose child is alive but stuck, set `--kill-session-after-min`. -### - -​ - -Auto mode rule lists +### 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`: @@ -83,11 +71,7 @@ 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`. -## - -​ - -Orchestrator CLI flags +## Orchestrator CLI flags The `self-hosted-runner orchestrator` subcommand, which spawns [on-demand runners](</docs/en/self-hosted-environments-configuration#on-demand-runners>), accepts `--api-url`, `--environment-secret-file`, `--hooks-dir`, `--health-port`, and `--log-level` with the same defaults as the runner and, where the runner’s flag has one, the same environment variable, except that `--hooks-dir` is required and must contain a `spawn-runner` hook. It also takes its own flags: @@ -100,11 +84,7 @@ `--shutdown-drain-sec <n>`| `0`| On `SIGTERM`, stop polling for spawn requests and give running `spawn-runner` hooks and any unanswered poll up to this many seconds to finish before stopping what’s left. At `0`, stop immediately. Maximum `3600`, which the orchestrator enforces at startup. To choose a value, see [Size `--shutdown-drain-sec` and the orchestrator’s stop timeout](</docs/en/self-hosted-environments-configuration#size-shutdown-drain-sec-and-the-supervisors-stop-timeout-for-the-orchestrator>). Requires Claude Code v2.1.299 or later. `--debug-dir <path>`| unset| Write each spawn request’s work order and hook stderr to disk. Debug only; never set in production. -### - -​ - -SCM connector flags +### SCM connector flags The SCM connector isn’t available, so leave the flags in this section unset. If you set `--scm-connector-host`, the connection doesn’t open, and the orchestrator keeps retrying it. Runners still start as sessions queue. The connector is a standing WebSocket connection from the orchestrator to Anthropic’s control plane. It’s designed to let hosted pre-session flows, such as the repository picker and the branch or ref resolver, reach a GitHub Enterprise Server host that’s only routable from inside your network. See [Network requirements](</docs/en/github-enterprise-server#network-requirements>) on the GitHub Enterprise Server page for what those flows need. @@ -118,11 +98,7 @@ On each connection attempt the orchestrator sends its existing environment secret, and it retries automatically with exponential backoff, capped at 30 seconds plus jitter. -## - -​ - -Environment-variable-only settings +## Environment-variable-only settings These runner settings are read from the environment only and cover behavior most deployments leave at the default: @@ -140,19 +116,11 @@ `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 -## - -​ - -Telemetry +## Telemetry Session children send operational telemetry to Anthropic unless you turn it off. No code or repository content is sent. Set telemetry variables on the runner process; the runner re-asserts them after applying server-provided environment variables, so the operator’s setting always takes precedence. One control is specific to self-hosted environments: `CLAUDE_CODE_BYOC_ENABLE_DATADOG=1` opts in to Datadog operational metrics, which are off by default in self-hosted environments. The general Claude Code telemetry controls, `DISABLE_TELEMETRY`, `DO_NOT_TRACK`, `DISABLE_ERROR_REPORTING`, and `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`, apply to session children as documented in the [environment variable reference](</docs/en/env-vars>). [`CLAUDE_CODE_DISABLE_FEATURE_FLAGS`](</docs/en/env-vars#variables>) is related but different: setting `CLAUDE_CODE_DISABLE_FEATURE_FLAGS=1` disables feature-flag fetching, and telemetry stays on unless `DISABLE_TELEMETRY` is also set. `CLAUDE_CODE_DISABLE_FEATURE_FLAGS` requires Claude Code v2.1.319 or later. `CLAUDE_CODE_ENABLE_TELEMETRY` is unrelated: it enables OpenTelemetry export to your own collector, as described in [Monitoring](</docs/en/monitoring-usage>), and doesn’t control Anthropic’s analytics. -## - -​ - -Health endpoint +## Health endpoint The runner serves `GET /healthz` on the configured health port once it has registered and finished its startup checks. From then on, the response is `200 OK` whenever the process is alive, whatever state the poll loop is in, so an HTTP probe on this endpoint detects a dead process only. The JSON body describes current state: @@ -166,11 +134,7 @@ Alert on `last_poll_age_ms`, but don’t use it in a liveness probe; keep that probe on the HTTP status code. The value is the time since the last successful poll, so it also rises while the runner can’t reach Anthropic. Both `last_poll_at` and `last_poll_age_ms` are `null` until the first poll succeeds. To catch polls that fail from the start, also alert on `claude_code_self_hosted_runner_poll_errors_total`, listed under Prometheus metrics. The orchestrator’s own `/healthz`, on its health port, always returns `200`. The body carries a `connected` field reporting whether the most recent poll succeeded, plus per-state spawn-queue counts in `queue_counts`. To see why `connected` is `false`, read the top-level `last_error` field, which each successful poll resets to `null`. Gate readiness and alerting on `connected` rather than the status code. When the SCM connector is configured, the orchestrator’s `/healthz` body also carries `scm_connector_connected` and a `scm_connector` object with `connected`, `last_connected_at`, `last_error`, `reconnects`, and `requests_forwarded`. Both fields are `null` when `--scm-connector-host` isn’t set. -## - -​ - -Prometheus metrics +## Prometheus metrics Each runner serves Prometheus metrics at `GET /metrics` on the same port as `/healthz`. Key series: @@ -247,11 +211,7 @@ path: /metrics interval: 30s -### - -​ - -Sample alert rules +### Sample alert rules These sample alert rules are a starting point; tune the thresholds for your fleet size: @@ -324,22 +284,14 @@ annotations: summary: "Orchestrator {{ $labels.pod }}: >3 spawn-runner hook failures in 5m" -### - -​ - -Alert on lost runners and waiting sessions +### Alert on lost runners and waiting sessions To be alerted when runners are lost, sessions wait, or the orchestrator is down, load these Prometheus alert rules beside the sample alert rules: * **[Fixed fleet](</docs/en/self-hosted-environments-deploy#scale-the-fleet>)** : `ClaudeRunnersBelowFloor` * **[On-demand runners](</docs/en/self-hosted-environments-configuration#on-demand-runners>)** : `ClaudeOrchestratorSessionsWaiting`, `ClaudeOrchestratorQueueWaitHigh`, and `ClaudeOrchestratorAbsent` -#### - -​ - -Alert when a fixed fleet loses runners +#### Alert when a fixed fleet loses runners `ClaudeRunnersBelowFloor` fires when fewer registered, scraped runners than the floor are left for 10 minutes: @@ -359,11 +311,7 @@ * **Namespace** : replace `claude-runners` in the matcher and in `labels`, and copy the alert for each further namespace. If your targets have no `namespace` label, remove the matcher and the label, or the alert reads 0 and fires. * **`ClaudeRunnerPollStale` and `ClaudeRunnerPollErrors`**: keep them loaded from the sample alert rules, because `ClaudeRunnersBelowFloor` still counts a runner that can’t poll -#### - -​ - -Alert when sessions wait for on-demand runners +#### Alert when sessions wait for on-demand runners `ClaudeOrchestratorSessionsWaiting` fires when the number of sessions waiting for a runner stays above 0 for 10 minutes. `ClaudeOrchestratorQueueWaitHigh` fires when over 1% of queue waits in the last 10 minutes exceeded 160 seconds, and that holds for 5 minutes: @@ -395,11 +343,7 @@ * **Threshold** : if some session is always waiting, raise the `> 0` in `ClaudeOrchestratorSessionsWaiting` above the number you usually see * **`ClaudeOrchestratorDisconnected`** : keep it loaded from the sample alert rules, because `ClaudeOrchestratorSessionsWaiting` stops firing about 2 minutes after the last orchestrator in the namespace disconnects -#### - -​ - -Alert when the orchestrator is down +#### Alert when the orchestrator is down To learn that the [orchestrator](</docs/en/self-hosted-environments-configuration#on-demand-runners>) itself is down, load `ClaudeOrchestratorAbsent`. It fires when no orchestrator in the namespace has been scraped for 5 minutes: @@ -418,19 +362,11 @@ * **Prometheus servers that don’t scrape the orchestrator** : leave the alert out of their rule files, because on such a server it fires after 5 minutes and stays on * **Don’t rely on the orchestrator’s other alerts** : they read metrics that the orchestrator itself serves. `ClaudeOrchestratorSessionsWaiting`, `ClaudeOrchestratorQueueWaitHigh`, and the orchestrator’s sample alert rules all stop firing within about 10 minutes of the orchestrator going down. -### - -​ - -Pass through session-child metrics +### Pass through session-child metrics Each session runs in its own child process with its own OpenTelemetry metrics; at `--capacity` above one, the runner rewrites how those child metrics are exposed. Setting `OTEL_METRICS_EXPORTER=prometheus` on the runner host and `CLAUDE_CODE_ENABLE_TELEMETRY=1` in the session’s environment, for example from your [wrapper script](</docs/en/self-hosted-environments-configuration#wrapper-scripts>) or the runner’s own environment, which sessions inherit, re-exposes each child’s counter and gauge instruments on the runner’s own `/metrics` endpoint, alongside the runner’s series. The runner rewrites the child’s exporter to push over OTLP to a loopback-only receiver on the health port, tags each series with `session_id` and `client_platform` labels, and evicts a session’s series when that session ends. Histograms don’t pass through, and a child metric whose name would collide with the runner’s own prefix is dropped. At the default `--capacity 1`, the rewrite doesn’t apply: the session’s child binds its own Prometheus endpoint on port 9464 as usual. -#### - -​ - -Join a session’s metrics to the runner’s +#### Join a session’s metrics to the runner’s To see what idle sessions have cost, join the runner’s `claude_code_self_hosted_runner_session_idle_seconds` to Claude Code’s cost metric on `ccr_session_id`. The runner’s metric doesn’t carry that label, so give it one with `label_replace`, as in this query: @@ -446,11 +382,7 @@ * **`session_id`** : on port 9464, that label on Claude Code metrics holds Claude Code’s own [`session.id`](</docs/en/monitoring-usage#standard-attributes>), which matches no runner series. A join on it returns nothing, so join on `ccr_session_id`. * **Claude Code metrics have no`ccr_session_id`**: check that [`OTEL_METRICS_INCLUDE_SESSION_ID`](</docs/en/monitoring-usage#metrics-cardinality-control>) isn’t set to `false` -### - -​ - -Session lifecycle counter semantics +### Session lifecycle counter semantics The `sessions_started_total`, `sessions_completed_total`, `sessions_failed_total`, and `sessions_interrupted_total` counters classify each session by how it ended. Every spawned session child increments `sessions_started_total` at spawn time, and exactly one of the other three increments at exit, so `sessions_started_total` minus the sum of the other three equals the number of session children currently running. @@ -469,11 +401,7 @@ The `orchestrator_*` rows exist only on environments running the [on-demand orchestrator](</docs/en/self-hosted-environments-configuration#on-demand-runners>). On a fixed fleet whose runners outlive their sessions, with `--drain-grace-sec` above `0`, use `sum(rate(claude_code_self_hosted_runner_sessions_started_total[5m]))` for throughput; on a one-shot fleet that series has the same scrape-window problem as the terminal counters, so rely on the queued-sessions count instead. Check backlog on the environment’s **Activity** tab, on the [**Cloud environments** admin page](<https://claude.ai/admin-settings/cloud-environments>): the runners don’t export a queue-depth series. For per-session outcome reporting, use the [`post-session` hook](</docs/en/self-hosted-environments-configuration#post-session>) instead: it fires at every session end where a child process was spawned, apart from abrupt runner termination such as a VM preemption, per the [hook’s own contract](</docs/en/self-hosted-environments-configuration#post-session>). -## - -​ - -What’s next +## What’s next * [Self-hosted environments](</docs/en/self-hosted-environments>): the environment, runner, and session model; the [quickstart](</docs/en/self-hosted-environments-quickstart>) and [Deploy to production](</docs/en/self-hosted-environments-deploy>) hold setup and operations * [Customize sessions](</docs/en/self-hosted-environments-configuration>): wrapper scripts, lifecycle hooks, and on-demand runners
modified Test self-hosted environments end to end View current →
Show diff (160 lines)
--- a/self-hosted-environments-testing.md +++ b/self-hosted-environments-testing.md @@ -2,19 +2,11 @@ In a [self-hosted environment](</docs/en/self-hosted-environments>), Claude Code [cloud sessions](</docs/en/claude-code-on-the-web>) run on a runner image you build and maintain. Before rolling a new image to your production environment, drive a full session against a test environment from a script: create a session, read Claude’s reply, send a follow-up, and read that reply too. This is the shape of a CI smoke test that verifies your runner image, git access, and any custom tools before you promote a change. This recipe assumes you’ve already [set up an environment and a runner](</docs/en/self-hosted-environments-quickstart#set-up-an-environment-and-runner>), and that your CI job starts the runner process on the same host as the test script. A Stop hook you install on the runner writes each turn’s final reply to a local file, and the script reads it from there. If your test runners are on separate infrastructure, see Remote test runners. -## - -​ - -Install the capture hook on your test runner +## Install the capture hook on your test runner The read-back works through a Claude Code [Stop hook](</docs/en/hooks#stop>): when Claude finishes a turn, the hook receives the final assistant message as `last_assistant_message` in its stdin JSON and appends it to `$E2E_REPLY_DIR/<session_id>.txt`. Install it the same way as the [commit-nudge Stop hook](</docs/en/self-hosted-environments-configuration#prompt-sessions-to-push-their-work>), on the runner host’s `~/.claude/`, which the runner seeds into every session. -### - -​ - -Save the hook files +### Save the hook files Save the two files below on the runner host: @@ -58,11 +50,7 @@ jq -r '.last_assistant_message // empty' >> "$E2E_REPLY_DIR/$sid.txt" 2>/dev/null exit 0 -### - -​ - -Before you start the runner +### Before you start the runner The hook has these requirements: @@ -71,11 +59,7 @@ Install this hook only on runners serving your test environment. It writes every session’s final reply to disk whenever `E2E_REPLY_DIR` exists, which is harmless on a throwaway CI runner but not something to carry into a production-environment runner image where the variable might be set by accident. -## - -​ - -Run the test loop +## Run the test loop 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: @@ -87,19 +71,11 @@ 3. Sends a follow-up with `claude -p "<message>" --cloud <session_id> --output-format json` (see [Send a follow-up message to a running session](</docs/en/claude-code-on-the-web#send-follow-ups-from-the-cli>)), which posts a user event to the existing session and exits. 4. Waits for the follow-up’s reply the same way as step 2. -### - -​ - -`--environment` dispatch behavior +### `--environment` dispatch behavior Claude Code creates the session, prints the session ID and a link to it, and exits. The flag takes precedence over the [`remote.defaultEnvironmentId`](</docs/en/settings-reference#remote-defaultenvironmentid>) setting. It doesn’t support `--output-format stream-json`, and can’t be combined with flags that resume, attach to, or preconfigure a session, such as `--resume`, `--continue`, `--teleport`, `--session-id`, or `--init-only`. `--cloud` is rejected with a session ID or URL, and in non-interactive runs when it carries a description. A bare `--cloud` is treated as absent. From a terminal, you can pass the task as the `--cloud` description instead of a positional prompt. -## - -​ - -Example script +## Example script The example script runs on the same machine as the test runner. Before you run it, prepare that machine: @@ -178,11 +154,7 @@ Replace the `TURN1`/`TURN2` prompts and `EXPECT1`/`EXPECT2` sentinels with whatever exercises your setup, such as asking Claude to run one of your custom MCP tools and asserting on its output. -## - -​ - -Remote test runners +## Remote test runners If your test runners are on separate infrastructure, such as a persistent Kubernetes fleet your CI job can’t share a filesystem with, swap the file write in the Stop hook for a POST to an endpoint your driver listens on: @@ -198,43 +170,23 @@ On the driver side, run anything that accepts the POST and holds the reply until the test asks for it, such as a small HTTP listener inside the CI job or a webhook receiver you already run. The hook runs on your infrastructure, so the endpoint only needs to be reachable from your runners. -## - -​ - -Authenticate from CI +## Authenticate from CI Both `claude -p ... --environment` and `claude -p ... --cloud` authenticate with a claude.ai OAuth token; API keys, such as `sk-ant-xxxxx`, aren’t accepted for either call. Two approaches make a token available in CI. -### - -​ - -Long-lived CI host +### Long-lived CI host Run `claude auth login` once interactively on the machine that executes the script, using a dedicated user account for automation. Claude Code stores the token in the OS keychain on macOS, or in `~/.claude/.credentials.json` on Linux and Windows. On a macOS host whose Keychain can’t be written, as is typical in an SSH session where the login Keychain stays locked, Claude Code stores the token in `~/.claude/.credentials.json` there too. See [Credential management](</docs/en/authentication#credential-management>). The CLI refreshes the short-lived access token automatically on each invocation, but the underlying refresh-token grant is capped at 30 days from the initial login, so re-run `claude auth login` interactively on that host every 30 days. -### - -​ - -Ephemeral CI runners +### Ephemeral CI runners There is no long-lived CI token for this today. The scope that grants cloud-session control, `user:sessions:claude_code`, is capped server-side at 30 days, so `claude setup-token`, which mints a one-year inference-only token, doesn’t cover it. The [environment secret](</docs/en/self-hosted-environments-quickstart#set-up-an-environment-and-runner>) isn’t accepted either, since it only authorizes a runner to register with the environment, not to create sessions. To provision a stored login onto an ephemeral runner, set [`CLAUDE_CODE_OAUTH_REFRESH_TOKEN` and `CLAUDE_CODE_OAUTH_SCOPES`](</docs/en/env-vars#variables>) so `claude auth login` exchanges the token without a browser; the same 30-day cap applies to the refresh grant. Contact your Anthropic account team if you need a machine-identity path that isn’t bound to a human account. -## - -​ - -Create a dedicated test environment +## Create a dedicated test environment Create and delete environments programmatically so each CI run gets a clean one; the runner your CI job starts registers into the fresh environment. The create and delete calls below are the same endpoints that the **Cloud environments** admin page on claude.ai uses, and they require the `anthropic-beta: ccr-byoc-2025-07-29` header. -### - -​ - -Mint the admin token +### Mint the admin token `$ADMIN_TOKEN` is a claude.ai OAuth access token for an account that holds an Owner role, minted the same way as Authenticate from CI: @@ -242,11 +194,7 @@ * **Read it fresh each run** : the CLI rotates the access token, and the same 30-day refresh-grant cap applies, so don’t store a copy. * **Pass it via stdin** : as the example does, so the token never lands in curl’s argument list or your build log. -### - -​ - -Create the environment +### Create the environment Capture the response without echoing it: `pool_secret` is a long-lived credential that can register runners into the environment, so store it as a masked CI secret and print only the environment ID. The `-H @-` form that keeps the token out of the process list requires curl 7.55 or later; older curl treats `@-` as a literal header and sends the request without authorization. @@ -261,11 +209,7 @@ Until an [Owner turns on **Allow self-hosted environments**](</docs/en/self-hosted-environments#availability-and-limitations>) for the organization, the call fails with a `403` `permission_error` reading `self-hosted runners are disabled by your organization's policy`. Start a runner on this host with `SELF_HOSTED_RUNNER_ENVIRONMENT_SECRET=$ENVIRONMENT_SECRET`, plus the capture hook and `E2E_REPLY_DIR` per Install the capture hook, then run the test script. -### - -​ - -Delete the environment +### Delete the environment Delete the environment when the run finishes, so each CI run starts clean:
modified Configure server-managed settings View current →
Show diff (271 lines)
--- a/server-managed-settings.md +++ b/server-managed-settings.md @@ -2,11 +2,7 @@ Server-managed settings are available for [Claude for Teams](<https://claude.com/pricing?utm_source=claude_code&utm_medium=docs&utm_content=server_settings_teams#team-&-enterprise>) and [Claude for Enterprise](<https://anthropic.com/contact-sales?utm_source=claude_code&utm_medium=docs&utm_content=server_settings_enterprise>) customers. -## - -​ - -Requirements +## Requirements To use server-managed settings, you need: @@ -14,11 +10,7 @@ * The Owner or Primary Owner role in your Claude organization, to view and edit the configuration * Network access to `api.anthropic.com` -## - -​ - -Choose between server-managed and endpoint-managed settings +## Choose between server-managed and endpoint-managed settings Claude Code supports two approaches for centralized configuration. Server-managed settings deliver configuration from Anthropic’s servers. [Endpoint-managed settings](</docs/en/managed-settings#delivery-mechanisms>) are deployed directly to devices through native OS policies (macOS managed preferences, Windows registry) or managed settings files. @@ -29,11 +21,7 @@ If your devices are enrolled in an MDM or endpoint management solution, endpoint-managed settings provide stronger security guarantees because the settings file can be protected from user modification at the OS level. Endpoint-managed settings don’t reach [cloud sessions](</docs/en/model-config#surface-coverage>) in Anthropic-hosted environments, so organizations whose developers run cloud sessions should configure server-managed settings as well. Sessions in a [self-hosted environment](</docs/en/self-hosted-environments>) also read the managed settings file in the runner image. The settings precedence below says when that file applies. -## - -​ - -Configure server-managed settings +## Configure server-managed settings 1 @@ -83,11 +71,7 @@ Save your changes. Claude Code clients receive the updated settings on their next startup or hourly polling cycle.The editor checks your JSON against the published JSON schema for Claude Code settings. If it finds a problem in JSON that parses, it shows a warning and relabels the save button. The label is **Update with errors** when settings are already saved, and **Add with errors** when no settings are saved yet. That button still saves, because a schema warning doesn’t block the save.The schema [can lag behind the newest releases](</docs/en/settings#edit-a-settings-file>), so the editor can flag a key or value that the [settings reference](</docs/en/settings-reference#all-settings>) documents. Claude Code receives the keys and values you saved and runs its own validation when it loads them. -### - -​ - -Verify settings delivery +### Verify settings delivery To confirm that settings are being applied, ask a user to restart Claude Code. If the configuration includes settings that trigger the security approval dialog, the user sees a prompt describing the managed settings the next time Claude Code fetches them: at the next start, or within an hour in a running interactive session. You can also verify that managed permission rules are active by having a user run `/permissions` to view their effective permission rules. In a session, have the user run `/status`. The [`Setting sources` line](</docs/en/managed-settings#read-the-source-in-/status>) lists `Enterprise managed settings` with `remote` in parentheses when server-managed settings apply. To check the fetch outcome on a specific machine, have the user run `claude doctor` and read the `Managed settings (remote)` line. Requires Claude Code v2.1.248 or later. The line reports one of four outcomes: @@ -98,11 +82,7 @@ While the fetch is still in progress, the line reports that instead. In a running session, `/status` shows the same line after a failed fetch, and for some skipped-fetch causes, such as a third-party provider variable or a custom `ANTHROPIC_BASE_URL` exported in the user’s shell. -### - -​ - -Give groups different settings +### Give groups different settings On an Enterprise plan, you can give each group of members its own configuration instead of one organization-wide configuration. If your organization has [HIPAA enabled](</docs/en/hipaa-setup>), group configurations aren’t available yet. Each group must already exist, either synced from your identity provider through SCIM or as a custom group you manage in the admin console. Each member receives at most one configuration, the same on every device: @@ -143,11 +123,7 @@ A group’s model limits hold only in local sessions. Cloud and remote Cowork sessions use the [`availableModels`](</docs/en/model-config#restrict-model-selection>) list in the catch-all. If you set no catch-all, it comes from your organization-wide configuration, even after you switch to group-based mode. If you leave the key out of the catch-all, members aren’t limited by this list in those sessions. If you use a group’s configuration to set where API requests go, that applies only to Claude Code, not to other tools that call the API. -### - -​ - -Access control +### Access control The following roles can manage server-managed settings: @@ -156,19 +132,11 @@ Restrict access to trusted personnel, as settings changes can apply to all users in the organization. -### - -​ - -Managed-only settings +### Managed-only settings Most [settings keys](</docs/en/settings-reference#all-settings>) work in any scope. A handful of keys are only read from managed settings and have no effect when placed in user or project settings files. See [managed-only settings](</docs/en/managed-settings#managed-only-settings>) for the permission and plugin controls, or read the Scope column of the [All settings](</docs/en/settings-reference#all-settings>) index for the full set. -### - -​ - -Current limitations +### Current limitations Server-managed settings have the following limitations: @@ -176,25 +144,13 @@ * You can’t distribute a [`managed-mcp.json`](</docs/en/managed-mcp>) file through server-managed settings. Deliver the `allowedMcpServers` and `deniedMcpServers` policy keys there instead. On Claude Code v2.1.259 or later, you can also provide remote servers with [`managedMcpServers`](</docs/en/managed-mcp#provide-servers-through-managed-settings>), which accepts `http` and `sse` servers only and doesn’t take exclusive control the way the file does. Claude Code reads a `managed-mcp.json` deployed at its [system path](</docs/en/managed-mcp#exclusive-control-with-managed-mcp-json>) separately from the managed settings tier, so the file still applies when server-managed settings are in effect. * Settings restricted to OS-level policy sources, such as `policyHelper` and `wslInheritsWindowsSettings`, aren’t honored. Deploy them through MDM or a system `managed-settings.json` file instead. A `policyHelper` deployed that way runs only when its source is the one selected under [precedence within the managed tier](</docs/en/managed-settings#precedence-within-the-managed-tier>). -## - -​ - -Settings delivery - -### - -​ - -Settings precedence +## Settings delivery + +### Settings precedence Server-managed settings and [endpoint-managed settings](</docs/en/managed-settings#delivery-mechanisms>) both occupy the highest tier in the Claude Code [settings hierarchy](</docs/en/settings#settings-precedence>). A key you set here takes precedence over the same key in a user’s own settings files or in a `--settings` value, apart from the [exceptions to managed settings precedence](</docs/en/settings#exceptions-to-managed-settings-precedence>). Within the managed tier, Claude Code by default uses the first source that delivers at least one policy key, checking server-managed settings first and then endpoint-managed settings, apart from the exception keys covered next. [How Claude Code combines managed sources](</docs/en/managed-settings#precedence-within-the-managed-tier>) has the full ranking, the carve-out for the control keys, and the opt-in that applies every source. If the selected source is an MDM policy or managed settings file whose [`policyHelper`](</docs/en/settings-reference#policyhelper>) supplies managed settings, the helper’s output replaces that source as the only managed configuration for the run. Claude Code doesn’t consult a `policyHelper` configured in MDM or file-based settings while server-managed settings deliver a policy key. If a later fetch finds the server-managed settings removed, Claude Code runs that helper right away instead of at the next launch. The [`policyHelper`](</docs/en/settings-reference#policyhelper>) entry covers what happens when that run fails. If you clear your server-managed configuration in the admin console with the intent of falling back to an endpoint-managed plist or registry policy, be aware that cached settings persist on client machines until the next successful fetch, and the keys that apply only at the next launch, such as `model`, stay in effect until each client relaunches. Run `/status` to see which managed source is active. -### - -​ - -Per-key exceptions across managed sources +### Per-key exceptions across managed sources These keys are exceptions to the no-merge rule: @@ -206,11 +162,7 @@ * **First-party sign-in keys** : [`forceLoginOrgUUID`](</docs/en/settings-reference#forceloginorguuid>) and the `"claudeai"` and `"console"` values of [`forceLoginMethod`](</docs/en/settings-reference#forceloginmethod>). If you also deploy an MDM policy or managed settings file, set them there and in server-managed settings from claude.ai until every client runs v2.1.299 or later. For where to set the keys afterward, and which source’s value applies, see [Which managed source supplies login keys](</docs/en/managed-settings#which-managed-source-supplies-login-keys>). * **Gateway sign-in keys** : Claude Code never reads [`forceLoginGatewayUrl`](</docs/en/settings-reference#forcelogingatewayurl>), [`gatewayInternalNetworks`](</docs/en/settings-reference#gatewayinternalnetworks>), or the `"gateway"` value of [`forceLoginMethod`](</docs/en/settings-reference#forceloginmethod>) from server-managed settings, so a value there neither applies nor hides one set in an MDM policy or managed settings file. The [`managedSourcesBehavior` entry](</docs/en/settings-reference#managedsourcesbehavior>) says which admin source on the machine supplies them. -#### - -​ - -When a machine’s `apiKeyHelper` isn’t in effect +#### When a machine’s `apiKeyHelper` isn’t in effect When your server-managed settings are the selected source, an `apiKeyHelper` in a machine’s managed settings file or MDM policy isn’t in effect. Claude Code then [refuses prompts](</docs/en/errors#claude-code-didnt-send-your-claude-ai-login>) in a session that would use a saved claude.ai login, provided both of these hold: @@ -219,11 +171,7 @@ To clear the refusal, keep the helper and its API address in effect, name Anthropic’s API address in the server-managed settings, or remove the helper from the machine’s policy. The refusal requires Claude Code v2.1.314 or later. -### - -​ - -Fetch and caching behavior +### Fetch and caching behavior Claude Code fetches settings from Anthropic’s servers at startup and polls for updates hourly during active sessions. A client signed in through a Claude apps gateway fetches its settings from the gateway and waits for that fetch before the session starts, so the fetch in the lists below doesn’t apply to it. Enforce fail-closed startup covers what happens when that fetch fails. @@ -262,11 +210,7 @@ Claude Code reads the Workload Identity Federation variables and the `ANTHROPIC_PROFILE` and `ANTHROPIC_CONFIG_DIR` selectors only at startup, so a server-delivered value for them doesn’t switch the session’s credential source even after the fetch succeeds. To deliver those selectors on Claude Code v2.1.223 or later, use [endpoint-managed settings](</docs/en/managed-settings#delivery-mechanisms>) such as MDM or `managed-settings.json`. For `CLAUDE_CONFIG_DIR` and the operating-system directory variables, the withholding itself is the protection: the cached value stays out of the environment until the server confirms the payload. Every other key in the cached `env` block applies at startup. Once the server confirms the payload, and you approve it if it needs security approval, the withheld variables apply for the rest of the session. If your organization needs a proxy to reach `api.anthropic.com`, the withholding only affects the server-delivered `env` block itself: a proxy set in an [endpoint-managed](</docs/en/managed-settings#delivery-mechanisms>) `env` block through MDM or `managed-settings.json`, in the shell environment, or in [user settings](</docs/en/settings#where-settings-live>) reaches the settings fetch. The endpoint-managed source requires Claude Code v2.1.223 or later: the cached server-managed proxy value is withheld until the fetch confirms it, so the endpoint-managed value fills in per key and reaches the fetch itself. Before v2.1.223, use the shell environment or user settings so the proxy applies alongside a cached server payload. The first launch has no cache, so an endpoint-managed source, the shell environment, or user settings is still required for the initial fetch. Claude Code applies most settings updates to running sessions without a restart. Some updates apply only at the next launch, including OpenTelemetry exporter configuration, the `model` key, and the removal of a variable from the `env` block. -### - -​ - -Invalid entries in delivered settings +### Invalid entries in delivered settings When part of a payload fails schema validation, Claude Code surfaces a validation error and applies every remaining valid setting; [Invalid entries in managed settings](</docs/en/managed-settings#invalid-entries-in-managed-settings>) says what it drops and which keys fall back to a stricter value. Requires Claude Code v2.1.169 or later. Server-managed delivery adds these behaviors: @@ -283,11 +227,7 @@ To debug delivery issues, run `claude --debug-file <path>` and search the log for `Remote settings`. Validate a payload change with `claude doctor` on a test machine before rolling it out to the organization. -### - -​ - -Enforce fail-closed startup +### Enforce fail-closed startup By default, if the remote settings fetch fails at startup, the CLI continues with the settings cached from the last successful fetch. The values Claude Code withholds stay withheld until a fetch succeeds. On a machine that has never fetched them, the CLI continues without server-managed settings and still applies any [endpoint-managed settings](</docs/en/managed-settings#delivery-mechanisms>) on the device. Anthropic can require the settings instead. To stop clients from starting on cached or absent server-managed settings, set `forceRemoteSettingsRefresh: true` in your managed settings. Clients signed in through a Claude apps gateway wait for the startup fetch whether or not you set this, and handle a failed fetch as follows: @@ -302,11 +242,7 @@ You can also set this key in an [endpoint-managed](</docs/en/managed-settings#delivery-mechanisms>) MDM profile or system `managed-settings.json` file to enforce fail-closed behavior on first launch, before any server payload has arrived. This flag is an exception to the precedence rule above: Claude Code honors it when any admin-controlled managed source sets it, even if a cached server-managed payload is also present, so it doesn’t ignore an MDM-delivered value when server-managed settings exist. On later startups, Claude Code reads a server-delivered value from the cached settings, so the setting is active before the new session’s first fetch. To keep the setting active without relying on the cached copy, also set the key in an endpoint-managed source. When a [`policyHelper`](</docs/en/settings-reference#policyhelper>) supplies managed settings, its output replaces every other managed source for the keys Claude Code reads after startup. For the sources Claude Code reads this key from, see [its settings entry](</docs/en/settings-reference#forceremotesettingsrefresh>). The `policyHelper` entry says which sources Claude Code reads the helper from and when it runs. The settings fetch also sends a `Cache-Control: no-cache` header so intermediate HTTP proxies don’t serve a stale response. Before enabling this setting, ensure your network policies allow connectivity to `api.anthropic.com`. If that endpoint is unreachable, the CLI exits at startup and users cannot start Claude Code. The `claude auth` subcommands such as `claude auth login` are exempt from this check and from the gateway startup exit, so users can re-authenticate when expired credentials are the reason the settings fetch fails. -### - -​ - -Security approval dialogs +### Security approval dialogs Certain settings that could pose security risks require explicit user approval before Claude Code applies them in an interactive session: @@ -318,11 +254,7 @@ When these settings are present, users see a security dialog explaining what is being configured. Users must approve to proceed. If a user rejects the settings, Claude Code exits. A managed CLAUDE.md delivered through the [`claudeMd`](</docs/en/settings-reference#claudemd>) key doesn’t require approval, because it’s instruction text for Claude rather than a command Claude Code runs. Claude Code still checks [permissions](</docs/en/permissions>) for the tools Claude uses while following those instructions. Before v2.1.260, a `claudeMd` value required approval too. -#### - -​ - -Approval memory +#### Approval memory Claude Code records your approval in your configuration directory, `~/.claude` unless you set [`CLAUDE_CONFIG_DIR`](</docs/en/env-vars>). What it records depends on the credential the settings fetch uses: @@ -343,11 +275,7 @@ * **An error closes the dialog before you answer** : Claude Code doesn’t apply the delivered settings and keeps the last-approved settings. It shows the dialog again in the next session that can show it. * **A non-interactive run** , such as `claude -p`, an Agent SDK session, or a session in the VS Code extension’s chat panel or the desktop app’s Code tab: Claude Code can’t show the dialog. When the delivered settings would require approval, they apply for that run only. Claude Code doesn’t record the settings as approved or write them to the local cache, and the next interactive session shows the dialog. Until a user approves in an interactive session, each non-interactive run fetches the settings again at startup. -#### - -​ - -Environment variables and the approval dialog +#### Environment variables and the approval dialog Claude Code applies some delivered `env` variables without showing the user the approval dialog, including: @@ -365,11 +293,7 @@ When a delivered variable needs approval, the dialog names it, so the user sees exactly what the policy is asking to set. Claude Code decides whether four privacy toggles need approval by the delivered value rather than by the variable name: `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`, `DISABLE_ERROR_REPORTING`, `DISABLE_TELEMETRY`, and `DO_NOT_TRACK`. A truthy value such as `1` or `true` only turns tracking, reporting, or other nonessential traffic off, so Claude Code applies it without asking the user. For any other non-empty value, Claude Code shows the dialog. Claude Code also decides whether [`API_FORCE_IDLE_TIMEOUT`](</docs/en/env-vars>) needs approval by the delivered value: a truthy value only turns the [body idle timeout](</docs/en/network-config#streaming-idle-watchdogs>) on, so Claude Code applies it without asking the user. For any other non-empty value, Claude Code shows the dialog. Before v2.1.248, any non-empty value triggered the dialog. Whether [`ANTHROPIC_CUSTOM_HEADERS`](</docs/en/env-vars#variables>) needs approval also depends on the delivered value. Headers that only tag requests, such as `Accept-Language`, apply without the dialog. A line that names a credential, an org or tenant selector, a routing or host override, or an API-behavior header, such as `Authorization`, `X-Api-Key`, `Host`, `anthropic-beta`, or the `X-Amzn-Bedrock-*` headers, requires approval. A line also requires approval when its name isn’t a valid HTTP header token or its value contains a character an HTTP header can’t carry. The check matches words inside the header name, so `X-Client-Version`, which contains `client` and `version`, requires approval too. Before v2.1.251, any `ANTHROPIC_CUSTOM_HEADERS` value applied without it. A falsy value such as `0` or `false` for [`ENABLE_BETA_TRACING_DETAILED`](</docs/en/env-vars#variables>) or [`OTEL_LOG_RAW_API_BODIES`](</docs/en/env-vars#variables>) applies without the dialog, because it only turns detailed tracing or raw API body capture off. Any other non-empty value for either variable requires approval. -## - -​ - -Platform availability +## Platform availability Server-managed settings require a direct connection to `api.anthropic.com`. Delivery also requires the session to authenticate with one of these credentials: @@ -385,19 +309,11 @@ In a [Cowork](<https://claude.com/docs/cowork/overview>) session in the Claude Desktop app, Claude Code doesn’t fetch server-managed settings from the claude.ai admin console, even when the user signs in with a Team or Enterprise account. [Where and when a policy applies](</docs/en/managed-settings#where-and-when-a-policy-applies>) covers which policy reaches Cowork sessions on the user’s machine and remote Cowork sessions. claude.ai still applies your [`strictKnownMarketplaces`](</docs/en/settings-reference#strictknownmarketplaces>) and [`blockedMarketplaces`](</docs/en/settings-reference#blockedmarketplaces>) lists itself when a Cowork user adds a marketplace from a git repository on claude.ai or from **Customize** in Cowork. [How restrictions work](</docs/en/plugins/org#restrict-what-users-can-install>) describes that check. If you export a `CLAUDE_CODE_USE_*` provider variable or a non-default `ANTHROPIC_BASE_URL` in your shell, Claude Code skips the settings fetch for your sessions. `claude doctor` and `/status` report the skipped fetch and its cause. You can’t clear the export with a server-managed `env` block, because the block arrives through the fetch that the export prevents. An [endpoint-managed settings](</docs/en/managed-settings#delivery-mechanisms>) `env` block doesn’t restore the fetch either: Claude Code checks eligibility before it applies managed `env` blocks, so the endpoint-managed value changes the session’s provider selection but the fetch stays skipped. To restore server-managed delivery, remove the export from your shell, or set the variable to `""` in your user settings `env` block, which applies before the eligibility check. To enforce policy without relying on users to change their shells, deliver the settings through the endpoint-managed channel instead. For Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, and [Claude Platform on AWS](</docs/en/claude-platform-on-aws>) deployments, a self-hosted [Claude apps gateway](</docs/en/claude-apps-gateway>) provides the equivalent remote managed-settings delivery: gateway-signed-in clients fetch managed settings from the gateway instead of `api.anthropic.com`. The failure semantics differ at startup: a gateway client that can’t reach the gateway exits with an error instead of falling back to cached settings, while the hourly background refresh is fail-open on both channels. -## - -​ - -Audit logging +## Audit logging Audit log events for settings changes are available through the compliance API or audit log export. Contact your Anthropic account team for access. Audit events include the type of action performed, the account and device that performed the action, and references to the previous and new values. -## - -​ - -Security considerations +## Security considerations Server-managed settings provide centralized policy enforcement, but they operate as a client-side control, not a security boundary. On unmanaged devices, a user doesn’t need admin or sudo access to bypass them. @@ -414,11 +330,7 @@ To log edits to local settings files, including `managed-settings.json`, use [`ConfigChange` hooks](</docs/en/hooks#configchange>). Claude Code doesn’t run them when server-managed settings arrive or refresh, or when an MDM profile or registry policy changes, and a hook can’t block a `policy_settings` change. To restrict which organizations your users can access with credentials the client supplies, see [Enforce network-level access control with Tenant Restrictions](<https://support.claude.com/en/articles/13198485-enforce-network-level-access-control-with-tenant-restrictions>) in the Claude Help Center. For stronger enforcement guarantees, use [endpoint-managed settings](</docs/en/managed-settings#delivery-mechanisms>) on devices enrolled in an MDM solution. -## - -​ - -See also +## See also Related pages for managing Claude Code configuration:
modified Persist sessions to external storage View current →
Show diff (171 lines)
--- a/session-storage.md +++ b/session-storage.md @@ -4,11 +4,7 @@ * **Durability.** Local containers are ephemeral. An external store survives restarts and redeploys. * **Compliance and audit.** Keep transcripts in storage you already govern, with your own retention rules, encryption, and access controls. -## - -​ - -The `SessionStore` interface +## The `SessionStore` interface A `SessionStore` is an object with two required methods, `append` and `load`, and four optional methods. The SDK calls `append` to write transcript entries during a query and `load` to read them back for resume. @@ -91,11 +87,7 @@ In a `SessionSummaryEntry`, `mtime` is the sidecar’s storage write time and must share a clock source with the `mtime` values `listSessions` returns. `data` is opaque SDK-owned state; persist it verbatim without interpreting it. Build the entries by calling the exported `foldSessionSummary` helper, `fold_session_summary` in Python, on each batch inside `append`. Skip batches whose key has a `subpath`; subagent transcripts must not contribute to the main session’s summary. The fold never sets `mtime`: stamp it at persist time, through the `options.mtime` argument in TypeScript or by overwriting the field on the returned entry in Python. Concurrent `append` calls for the same session can race on the sidecar, so serialize the read-fold-write with a transaction, a compare-and-swap, or a per-session lock; the fold itself is pure. For what the SDK does with the transcript `load` returns, see Resume from the store. -## - -​ - -Quick start +## Quick start The SDK ships an `InMemorySessionStore` for development and testing. The example below runs a query with the store attached, captures the session ID from the result message, then resumes from the store in a second `query()` call. The second call passes the same store instance plus `resume`, so the SDK loads the transcript from the store instead of the local filesystem: @@ -171,19 +163,11 @@ The second query prints a summary of the files from the first query, which shows the agent resumed with full context from the store. -## - -​ - -Write your own adapter +## Write your own adapter Implement `append` and `load` against your backend. Add `listSessions`, `listSessionSummaries`, `delete`, and `listSubkeys` if you want `listSessions()`, one-call metadata reads, `deleteSession()`, and subagent resume to work against the store. Entries passed to `append` are typed as `SessionStoreEntry` (a `{ type: string; ... }` object). Treat them as opaque JSON-safe values: persist them in order and return them from `load` in the same order. `load` must return entries that are deep-equal to what was appended; byte-equal serialization is not required, so a backend that reorders object keys, such as a binary JSON column type, is fine. -## - -​ - -Reference implementations +## Reference implementations Both SDK repositories include runnable reference adapters under [`examples/session-stores/`](<https://github.com/anthropics/claude-agent-sdk-typescript/tree/main/examples/session-stores>) in TypeScript and [`examples/session_stores/`](<https://github.com/anthropics/claude-agent-sdk-python/tree/main/examples/session_stores>) in Python. There is one adapter per storage type, and each shows how `append` and `load` map onto that kind of backend. They are not published as packages; copy the adapter for the type closest to your backend into your project, install your backend’s client, and adapt it. @@ -224,11 +208,7 @@ // ... } -### - -​ - -Validate your adapter +### Validate your adapter Both SDKs ship a conformance suite that asserts the behavioral contract `append`, `load`, and the optional methods must satisfy. Tests for optional methods skip automatically when those methods are not implemented. In TypeScript, copy [`shared/conformance.ts`](<https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/shared/conformance.ts>) from the example directory into your test suite. In Python, the suite ships in the package. To run it with pytest, which isn’t an SDK dependency, install pytest first: @@ -247,17 +227,9 @@ Passing the `MyRedisStore` class itself, as this example does, works when the constructor takes no arguments. For an adapter that takes a pre-configured client, pass a lambda that constructs the store instead. Because the contracts reuse the same session keys, each store the factory returns must start with empty storage, so have the lambda provision isolated backing storage per call, such as a fresh in-memory fake, a unique key prefix, or a new test database. -## - -​ - -Behavior notes - -### - -​ - -Dual-write architecture +## Behavior notes + +### Dual-write architecture The Claude Code subprocess always writes each batch of transcript entries to local disk first, and the SDK then forwards the same batch to your store’s `append()`, so the store is a mirror of the local transcript rather than a replacement for it. Which copy outlives the run depends on how the run started: @@ -275,11 +247,7 @@ * **`persistSession: false`** in TypeScript: turns off the local writes the mirror is built from. The Python SDK has no equivalent option. * **File checkpointing** , `enableFileCheckpointing` in TypeScript or `enable_file_checkpointing` in Python: writes its file backups straight to local disk, and the SDK doesn’t mirror them to the store. -### - -​ - -Resume from the store +### Resume from the store When you pass `resume`, or `continue: true` in TypeScript or `continue_conversation=True` in Python, together with a store, the SDK asks the store for a transcript before it spawns the subprocess: @@ -297,51 +265,27 @@ * **`continue: true`** in TypeScript: the SDK starts a fresh session. * **`continue_conversation=True`** in Python: the SDK continues from the newest local session. -### - -​ - -Mirror writes are best-effort - -If `append()` rejects, the SDK retries the batch up to two more times with a short backoff, for at most three attempts in total. A call that times out isn’t retried, since the original call may still land. If the batch still fails, the SDK logs the error, emits a `{ type: "system", subtype: "mirror_error" }` message into the iterator, drops the batch, and continues the query. Because a retried batch can re-deliver entries that already landed, deduplicate by `entry.uuid` in your `append()` implementation. A store outage doesn’t interrupt the agent, since the subprocess writes locally first. Monitor for `mirror_error` if you need to detect store data loss. On a run resumed from the store, a dropped batch has no surviving copy once the run ends. - -### - -​ - -`getSessionMessages` returns the post-compaction chain +### Mirror writes are best-effort + +If `append()` rejects, the SDK retries the batch up to two more times with a short backoff, for at most three attempts in total. A call that times out isn’t retried, since the original call may still land. Because a retried batch can re-deliver entries that already landed, deduplicate by `entry.uuid` in your `append()` implementation, and keep every entry that has no `uuid`. If the batch still fails, the SDK logs the error, emits a `{ type: "system", subtype: "mirror_error" }` message into the iterator, drops the batch, and continues the query. A store outage doesn’t interrupt the agent, since the subprocess writes locally first. Monitor for `mirror_error` to detect store data loss. On a run resumed from the store, a dropped batch has no surviving copy once the run ends. + +### `getSessionMessages` returns the post-compaction chain `getSessionMessages({ sessionStore })` returns the linked message chain the agent would see on resume. After auto-compaction, earlier turns are replaced by a summary, so a session whose store holds 503 raw entries may return 18 messages from `getSessionMessages`. For the full raw history, including pre-compaction turns and metadata entries, call `store.load(key)` directly. -### - -​ - -`forkSession` is not a byte copy +### `forkSession` is not a byte copy `forkSession({ sessionStore })` reads the source entries, rewrites every `sessionId` field and remaps message UUIDs, then appends the transformed entries under a new key. An adapter-level copy or `CopyObject` shortcut would produce a transcript that still references the old session ID, so the SDK does not use one. -### - -​ - -Subagent transcripts +### Subagent transcripts Subagent transcripts are mirrored under `subpath: "subagents/agent-<id>"`. `listSubagents({ sessionStore })` requires the adapter to implement `listSubkeys`; `getSubagentMessages({ sessionStore })` uses it when available but falls back to the direct subpath when it is undefined. Resume also calls `listSubkeys` to restore subagent files; without it, only the main transcript is materialized. -### - -​ - -Retention +### Retention The SDK never deletes from your store on its own. Retention is the adapter’s responsibility: use your backend’s expiry or lifecycle mechanism, or run scheduled cleanup, according to your compliance requirements. Local transcripts under `CLAUDE_CONFIG_DIR` are swept independently by the `cleanupPeriodDays` setting, following the [retention sweep rules](</docs/en/claude-directory#cleaned-up-automatically>). A run resumed from the store leaves no local transcript, so for those runs your store’s retention is the only retention there is. -## - -​ - -Supported on +## Supported on The following TypeScript SDK functions accept a `sessionStore` option and operate against the store instead of the local filesystem when it is provided: @@ -359,11 +303,7 @@ In the Python SDK, set `session_store` in [`ClaudeAgentOptions`](</docs/en/agent-sdk/python#claudeagentoptions>) to run `query()` against a store. The remaining operations each have a store-backed Python function that takes the store as an argument: `list_sessions_from_store()`, `get_session_info_from_store()`, `get_session_messages_from_store()`, `list_subagents_from_store()`, `get_subagent_messages_from_store()`, `rename_session_via_store()`, `tag_session_via_store()`, `delete_session_via_store()`, and `fork_session_via_store()`. `startup()` has no Python equivalent. The standalone functions documented in the [Python SDK reference](</docs/en/agent-sdk/python#functions>), such as `list_sessions()`, read local session files. -## - -​ - -Related resources +## Related resources * [Work with sessions](</docs/en/agent-sdk/sessions>): Continue, resume, and fork without a custom store * [Host the SDK](</docs/en/agent-sdk/hosting>): Deployment patterns for multi-host environments
modified Work with sessions View current →
Show diff (145 lines)
--- a/sessions.md +++ b/sessions.md @@ -4,11 +4,7 @@ This guide covers how to pick the right approach for your app, the SDK interfaces that track sessions automatically, how to capture session IDs and use `resume` and `fork` manually, and what to know about resuming sessions across hosts. -## - -​ - -Choose an approach +## Choose an approach How much session handling you need depends on your application’s shape. Session management comes into play when you send multiple prompts that should share context. Within a single `query()` call, the agent already takes as many turns as it needs, and permission prompts and `AskUserQuestion` are [handled in-loop](</docs/en/agent-sdk/user-input>) (they don’t end the call). @@ -21,11 +17,7 @@ Try an alternative approach without losing the original| Fork the session. Stateless task, don’t want anything written to disk| Set [`persistSession: false`](</docs/en/agent-sdk/typescript#options>) (TypeScript only). The session exists only in memory for the duration of the call. In Python, set [`CLAUDE_CODE_SKIP_PROMPT_HISTORY`](</docs/en/env-vars>) in the `env` option to suppress transcript writes instead. -### - -​ - -Continue, resume, and fork +### Continue, resume, and fork Continue, resume, and fork are option fields you set on `query()` ([`ClaudeAgentOptions`](</docs/en/agent-sdk/python#claudeagentoptions>) in Python, [`Options`](</docs/en/agent-sdk/typescript#options>) in TypeScript). **Continue** and **resume** both pick up an existing session and add to it. The difference is how they find that session: @@ -34,19 +26,11 @@ **Fork** is different: it creates a new session that starts with a copy of the original’s history. The original stays unchanged. Use fork to try a different direction while keeping the option to go back. -## - -​ - -Automatic session management +## Automatic session management Both SDKs offer an interface that tracks session state for you across calls, so you don’t pass IDs around manually. Use these for multi-turn conversations within a single process. -### - -​ - -Python: `ClaudeSDKClient` +### Python: `ClaudeSDKClient` [`ClaudeSDKClient`](</docs/en/agent-sdk/python#claudesdkclient>) handles session IDs internally. Each call to `client.query()` automatically continues the same session. Call [`client.receive_response()`](</docs/en/agent-sdk/python#claudesdkclient>) to iterate over the messages for the current query. Use the client as an async context manager so connection setup and teardown are handled for you, or call `connect()` and `disconnect()` manually. This example runs two queries against the same `client`. The first asks the agent to analyze a module; the second asks it to refactor that module. Because both calls go through the same client instance, the second query has full context from the first without any explicit `resume` or session ID: @@ -95,11 +79,7 @@ Each query prints the agent’s text response followed by a status line from the result message, such as `[done: success, cost: $0.0042]`. See the [Python SDK reference](</docs/en/agent-sdk/python#choosing-between-query-and-claudesdkclient>) for details on when to use `ClaudeSDKClient` vs the standalone `query()` function. -### - -​ - -TypeScript: `continue: true` +### TypeScript: `continue: true` The TypeScript SDK doesn’t have a session-holding client object like Python’s `ClaudeSDKClient`. Instead, pass `continue: true` on each subsequent `query()` call and the SDK picks up the most recent session in the current directory. No ID tracking required. This example makes two separate `query()` calls. The first creates a fresh session; the second sets `continue: true`, which tells the SDK to find and resume the most recent session on disk. The agent has full context from the first call: @@ -138,17 +118,9 @@ The experimental [V2 session API](</docs/en/agent-sdk/typescript-v2-preview>), which provided `createSession()` with a `send` / `stream` pattern, was removed in TypeScript Agent SDK 0.3.142. Use the `query()` function and the session options described on this page instead. -## - -​ - -Use session options with `query()` - -### - -​ - -Capture the session ID +## Use session options with `query()` + +### Capture the session ID Resume and fork require a session ID. Read it from the `session_id` field on the result message ([`ResultMessage`](</docs/en/agent-sdk/python#resultmessage>) in Python, [`SDKResultMessage`](</docs/en/agent-sdk/typescript#sdkresultmessage>) in TypeScript), which is present on every result regardless of success or error. In TypeScript the ID is also available earlier as a direct field on the init `SystemMessage`; in Python it’s nested inside `SystemMessage.data`. @@ -211,11 +183,7 @@ When the query completes, the script prints the agent’s response followed by a line such as `Session ID: 5b3f2c1a-8d4e-4f6b-9a7c-2e1d0f9b8a6c`. In the next sections, you pass this ID to `resume`. -### - -​ - -Resume by ID +### Resume by ID Pass a session ID to `resume` to return to that specific session. The agent picks up with full context from wherever the session left off. Common reasons to resume: @@ -267,7 +235,7 @@ You should see a response that builds on the earlier analysis instead of starting fresh. That confirms the agent resumed the session with its prior context intact. -Claude Code stores sessions under `~/.claude/projects/<encoded-cwd>/*.jsonl`. If you set the `CLAUDE_CONFIG_DIR` environment variable, look under `$CLAUDE_CONFIG_DIR/projects/` instead.To find your session’s directory, replace every non-alphanumeric character in the absolute working directory with `-`: `/Users/me/proj` becomes `-Users-me-proj`. For a working directory whose converted name exceeds 200 characters, Claude Code [truncates the name and appends a hash](</docs/en/sessions#where-transcripts-are-stored>), so match the first 200 characters of the converted name when you list `projects/`.If you set [`CLAUDE_CODE_PROJECT_DIR_NAME`](</docs/en/sessions#name-the-project-directory-yourself>) beside `CLAUDE_CONFIG_DIR`, look under that name in `projects/` instead. Requires TypeScript Agent SDK v0.3.234 or later, or Python Agent SDK v0.2.140 or later.You can resume from any working directory: +Claude Code stores sessions under `~/.claude/projects/<encoded-cwd>/*.jsonl`. If you set the `CLAUDE_CONFIG_DIR` environment variable, look under `$CLAUDE_CONFIG_DIR/projects/` instead.To find your session’s directory, replace every non-alphanumeric character in the absolute working directory with `-`: `/Users/me/proj` becomes `-Users-me-proj`. For a working directory whose converted name exceeds 200 characters, Claude Code [truncates the name and appends a hash](</docs/en/sessions#where-transcripts-are-stored>), so match the first 200 characters of the converted name when you list `projects/`. If you set [`CLAUDE_CODE_PROJECT_DIR_NAME`](</docs/en/sessions#name-the-project-directory-yourself>) beside `CLAUDE_CONFIG_DIR`, look under that name in `projects/` instead. Requires TypeScript Agent SDK v0.3.234 or later, or Python Agent SDK v0.2.140 or later.You can resume from any working directory: * **Cross-directory lookup** : Claude Code searches beyond the current project directory to find the ID; see [Resume a session](</docs/en/sessions#where-the-session-picker-looks>) for the exact lookup order and how duplicate copies are handled. * **Same machine only** : the session file still needs to exist on the current machine. @@ -276,11 +244,7 @@ To resume sessions across machines or in serverless environments, mirror transcripts to shared storage with a [`SessionStore` adapter](</docs/en/agent-sdk/session-storage>). -### - -​ - -Fork to explore alternatives +### Fork to explore alternatives Forking creates a new session that starts with a copy of the original’s history but diverges from that point. The fork gets its own session ID; the original’s ID and history stay unchanged. You end up with two independent sessions you can resume separately. @@ -384,11 +348,7 @@ You should see that `forkedId` differs from the original session ID. Resuming the original session still continues the JWT thread, which confirms the fork did not modify the original history. -## - -​ - -Resume across hosts +## Resume across hosts Session files are local to the machine that created them. To resume a session on a different host (CI workers, ephemeral containers, serverless), pick the approach that fits: @@ -398,11 +358,7 @@ Both SDKs expose functions for enumerating sessions on disk and reading their messages: [`listSessions()`](</docs/en/agent-sdk/typescript#listsessions>) and [`getSessionMessages()`](</docs/en/agent-sdk/typescript#getsessionmessages>) in TypeScript, [`list_sessions()`](</docs/en/agent-sdk/python#list_sessions>) and [`get_session_messages()`](</docs/en/agent-sdk/python#get_session_messages>) in Python. Use them to build custom session pickers, cleanup logic, or transcript viewers. Both SDKs also expose functions for looking up and mutating individual sessions: [`get_session_info()`](</docs/en/agent-sdk/python#get_session_info>), [`rename_session()`](</docs/en/agent-sdk/python#rename_session>), and [`tag_session()`](</docs/en/agent-sdk/python#tag_session>) in Python, and [`getSessionInfo()`](</docs/en/agent-sdk/typescript#getsessioninfo>), [`renameSession()`](</docs/en/agent-sdk/typescript#renamesession>), and [`tagSession()`](</docs/en/agent-sdk/typescript#tagsession>) in TypeScript. Use them to organize sessions by tag or give them human-readable titles. -## - -​ - -Related resources +## Related resources * [How the agent loop works](</docs/en/agent-sdk/agent-loop>): Understand turns, messages, and context accumulation within a session * [File checkpointing](</docs/en/agent-sdk/file-checkpointing>): Snapshot and revert file changes the agent made within a session
modified Settings files and precedence View current →
Show diff (347 lines)
--- a/settings.md +++ b/settings.md @@ -6,11 +6,7 @@ This page covers Claude Code running on your machine: the terminal, the [VS Code](</docs/en/vs-code>) and [JetBrains](</docs/en/jetbrains>) extensions, and the [desktop app](</docs/en/desktop>), which all read the same settings files. A [cloud session](</docs/en/claude-code-on-the-web>) runs on a different machine and reads only some of them; see Settings in cloud sessions. -## - -​ - -Settings files and who they affect +## Settings files and who they affect Claude Code reads settings from four files, and an organization can also deliver managed settings from the claude.ai console. Each source has a scope: the set of people and projects a setting saved in it applies to, whether that’s only you, everyone in a project, or everyone in your organization. @@ -23,11 +19,7 @@ In the File column, `~/.claude` is the `.claude` folder in your home directory, and a bare `.claude` is the `.claude` folder inside your project. -### - -​ - -Compare the scope of each settings file +### Compare the scope of each settings file Suppose you have three projects on your machine, `website/`, `api/`, and `acme-app/`, a teammate has their own clone of `acme-app/`, and you start a cloud session on `acme-app/`. The graphic below shows which of those folders a setting applies in when you start Claude Code from them. Click a settings file to see the folders it reaches. @@ -36,11 +28,7 @@ * **`acme-app/.claude/settings.local.json`** : your `acme-app/` only. Claude Code adds it to your global git excludes the first time it writes the file, so it stays out of your commits; if you create the file by hand, add it to `.gitignore` yourself * **Managed settings** , whether a `managed-settings.json` file, an MDM policy, or [server-managed settings](</docs/en/server-managed-settings>) from the claude.ai console: every project on every machine your organization deploys it to, or that you sign in to with your organization account. Only server-managed settings reach the cloud session -### - -​ - -Find or create your settings files +### Find or create your settings files Installing Claude Code doesn’t create any settings file. If your machine or project already has one, it came from one of these sources: @@ -52,19 +40,11 @@ Claude Code also keeps a fifth file, [`~/.claude.json`](</docs/en/claude-directory#ce-claude-json>), that it writes for itself; you don’t need to edit it. It holds your account details, [MCP server](</docs/en/mcp>) configurations, per-project state such as trust decisions, and the [global config keys](</docs/en/settings-reference#global-config-settings>) that `/config` writes for you. -### - -​ - -Share settings with your team +### Share settings with your team Commit `.claude/settings.json` so everyone who clones the repository gets the same permissions, hooks, and plugin settings. Each teammate can still override it for themselves in their own `.claude/settings.local.json`, so personal exceptions don’t need a commit. For a complete team file, see [a team’s shared settings](</docs/en/settings-example#a-teams-shared-settings>). Some of what you commit waits until each teammate [trusts the folder](</docs/en/permissions#project-allow-rules-and-workspace-trust>), and a few keys never take effect from a repository file; Troubleshoot a setting that doesn’t apply covers both. -### - -​ - -Keep personal settings out of a repository +### Keep personal settings out of a repository To change a setting for yourself in one project without changing it for your teammates, save it in `.claude/settings.local.json` inside the project. Claude Code applies that file over the committed `.claude/settings.json`, so if your team’s file sets `"model": "claude-sonnet-5"` and you want Opus, put `"model": "claude-opus-5-5"` in your local file and only your sessions change. Claude Code also writes to this file, keeps it out of your commits, and applies its allow rules without the trust step: @@ -72,11 +52,7 @@ * **You don’t need to gitignore it yourself, unless you created it by hand.** The first time Claude Code writes the file in a git repository that doesn’t already ignore it, it adds `**/.claude/settings.local.json` to your global git excludes file, so the file stays out of your commits in every repository. That file is `core.excludesFile` when your global git config sets it to an absolute or `~`-prefixed path; otherwise it’s `$XDG_CONFIG_HOME/git/ignore`, or `~/.config/git/ignore` when `XDG_CONFIG_HOME` is unset. If you created the file by hand and Claude Code hasn’t written to it yet, add it to `.gitignore` yourself. * **Its allow rules don’t wait for trust while the file stays untracked.** Because the file is yours and not the repository’s, Claude Code applies its `allow` rules without the [workspace trust](</docs/en/permissions#project-allow-rules-and-workspace-trust>) step it requires for the committed file. If the file is tracked by git, the trust step applies to it too; see [When your local settings file needs trust](</docs/en/permissions#when-your-local-settings-file-needs-trust>). -#### - -​ - -Where Claude Code keeps the local file in a git repository +#### Where Claude Code keeps the local file in a git repository When Claude asks permission to run a Bash command and you choose “Yes, and don’t ask again”, Claude Code saves that approval as an `allow` rule in `.claude/settings.local.json`. If you start Claude Code in a subdirectory of a git repository, it reads and writes that file at the repository root and applies the approval across the whole repository. In a [worktree](</docs/en/worktrees>), it uses the file at the main checkout’s root. Two rules qualify the root location: @@ -85,11 +61,7 @@ Before v2.1.211, Claude Code kept the file in the starting directory. It still reads a file an earlier version left there alongside the root file; where both set the same key, the root’s value applies, and permission rules from both files apply. The Agent SDK’s [`resolveSettings()`](</docs/en/agent-sdk/typescript#resolvesettings>) helper always reads the file from the starting directory. Claude Code reads the shared `.claude/settings.json` from the session’s [primary working directory](</docs/en/permissions#working-directories>), so to use a file committed at the repository root, start Claude Code there. After you [move the session with `/cd`](</docs/en/permissions#move-the-session-to-another-directory>), Claude Code reads both project files from the new directory instead, placing the local file by the same rules. Reading them from the directory you moved to requires Claude Code v2.1.246 or later. For a worktree session that you start from the desktop app, see [What worktrees share with the main checkout](</docs/en/worktrees#what-worktrees-share-with-the-main-checkout>). -### - -​ - -Check what your organization enforces +### Check what your organization enforces If your organization manages Claude Code, some settings are decided for you and nothing you put in your own files changes them. To see which, run `/status`: the `Setting sources` line names the managed source that applies to you. Managed settings apply wherever Claude Code runs on this machine; [What a developer can change](</docs/en/managed-settings#what-a-developer-can-change>) covers local admin rights and tools other than Claude Code. Managed settings reach you through the [delivery mechanisms](</docs/en/managed-settings#delivery-mechanisms>) on the managed settings page, most commonly: @@ -99,19 +71,11 @@ In a [Cowork](<https://claude.com/docs/cowork/overview>) session that runs on your machine in the Claude Desktop app, Claude Code doesn’t fetch server-managed settings from the claude.ai admin console, and it reads policy deployed to your device unless your organization’s Claude Desktop configuration sets `requireCoworkFullVmSandbox`. [Where and when a policy applies](</docs/en/managed-settings#where-and-when-a-policy-applies>) covers Cowork and cloud sessions. If you’re the administrator, [Set up Claude Code for your organization](</docs/en/admin-setup>) walks through choosing what to enforce, and [Deploy managed settings](</docs/en/managed-settings>) covers delivery and how to confirm a policy is in force. For the warning the managed settings editor in the claude.ai admin console can show, see [Configure server-managed settings](</docs/en/server-managed-settings#configure-server-managed-settings>). -## - -​ - -Change a setting +## Change a setting You can change a setting from the `/config` menu, by editing a settings file, or for one session from the command line. Claude Code’s system prompt isn’t published. To give Claude standing instructions, use [`CLAUDE.md` files](</docs/en/memory>) or the `--append-system-prompt` flag. -### - -​ - -Use the /config menu +### Use the /config menu Run `/config` inside Claude Code and open the **Config** tab. It lists a short set of personal options such as theme, editor mode, and verbose output, not every settings key. Select an option to change it; Claude Code saves it for you: @@ -123,11 +87,7 @@ `/config` is part of the terminal interface. The [VS Code](</docs/en/vs-code>) chat panel and the [desktop app](</docs/en/desktop>) don’t open it; change settings there by editing a settings file or through those apps’ own settings. -### - -​ - -Edit a settings file +### Edit a settings file Open the settings file for the scope you want in your editor and add or change a key. Settings files are strict JSON: a `//` comment or a trailing comma is a syntax error, and Claude Code reports the file as a Settings Error at the next start. For example, to let Claude Code run your lint and test commands without asking and stop it reading `.env` files, add this to `~/.claude/settings.json`: @@ -149,11 +109,7 @@ Each entry under `permissions` is a rule that names a tool and what it may do; [Configure permissions](</docs/en/permissions>) explains the syntax. The `$schema` line points to the [published JSON schema](<https://json.schemastore.org/claude-code-settings.json>) for Claude Code settings, which gives you autocomplete and inline validation in VS Code, Cursor, and any other editor that supports JSON schema. The schema can lag behind the newest CLI releases, so a validation warning on a recently documented key doesn’t mean your configuration is invalid. After you save, run `/status` inside Claude Code to confirm the file loaded; Confirm what loaded says what the `Setting sources` line shows and how a broken file is reported. For a complete personal file, team file, and organization file, each shown with a comment on every key it sets, see the [example settings files](</docs/en/settings-example>). -### - -​ - -Change a setting for one session +### Change a setting for one session To try a value without saving it, set it when you start Claude Code. The value applies to that session and your settings files stay as they were. You have three ways to do it: @@ -165,32 +121,20 @@ claude --settings '{"model": "claude-opus-5-5"}' -### - -​ - -When edits take effect - -Claude Code watches your settings files and reloads them when they change, so it applies most edits to the running session without a restart, including edits to `permissions`, `hooks`, and credential helpers such as `apiKeyHelper`. Claude Code also loads a settings file you create mid-session if its folder existed when the session started. For the project’s `.claude/` folder, it loads the file even when you create the folder in the same session. The reload covers user, project, local, and managed settings, and Claude Code runs the [`ConfigChange` hook](</docs/en/hooks#configchange>) for each settings-file change it detects, not for managed settings that arrive from MDM or the claude.ai console. Managed settings that arrive through MDM or from the claude.ai console reach a running session on a schedule rather than on save; the [delivery table](</docs/en/managed-settings#choose-a-delivery-mechanism>) gives it per source. Claude Code reads some keys only once, at session start, so an edit to one of them doesn’t reach the running session. Admin-side keys that also wait for a restart, such as `requiredMinimumVersion`, are listed under [where and when a policy applies](</docs/en/managed-settings#where-and-when-a-policy-applies>). The ones you’re most likely to edit mid-session: +### When edits take effect + +Claude Code watches your settings files and reloads them when they change, so it applies most edits to the running session without a restart, including edits to `permissions`, `hooks`, and credential helpers such as `apiKeyHelper`. Claude Code also loads a settings file you create mid-session if its folder existed when the session started. For the project’s `.claude/` folder, it loads the file even when you create the folder in the same session. The reload covers user, project, local, and managed settings. Claude Code runs the [`ConfigChange` hook](</docs/en/hooks#configchange>) for direct edits to settings files, not for managed settings that arrive from MDM or the claude.ai console. Managed settings that arrive through MDM or from the claude.ai console reach a running session on a schedule rather than on save; the [delivery table](</docs/en/managed-settings#choose-a-delivery-mechanism>) gives it per source. Claude Code reads some keys only once, at session start, so an edit to one of them doesn’t reach the running session. Admin-side keys that also wait for a restart, such as `requiredMinimumVersion`, are listed under [where and when a policy applies](</docs/en/managed-settings#where-and-when-a-policy-applies>). The ones you’re most likely to edit mid-session: * [`model`](</docs/en/settings-reference#model>): use [`/model`](</docs/en/model-config#setting-your-model>) to switch mid-session. Each model has its own prompt cache, so the first request after a switch re-reads the whole conversation uncached; see [Switching models](</docs/en/prompt-caching#switching-models>) * [`effortLevel`](</docs/en/settings-reference#effortlevel>) and [`modelSettings`](</docs/en/settings-reference#modelsettings>): use [`/effort`](</docs/en/model-config#adjust-effort-level>) to change effort mid-session If you remove [`permissions.blockReadsOutsideWorkingDirectories`](</docs/en/settings-reference#permissions-blockreadsoutsideworkingdirectories>) mid-session, the file tools keep the block in the running session. To lift it, remove the key from every settings file that sets it, then restart each running session. -### - -​ - -Confirm what loaded +### Confirm what loaded Run `/status` inside Claude Code to see which settings sources are active. The **Status** tab includes a `Setting sources` line that lists each settings file Claude Code loaded for the current session, such as `User settings` or `Project local settings`. When [managed settings](</docs/en/admin-setup#decide-how-settings-reach-devices>) are in effect, the managed settings entry shows in parentheses how they reached your machine. The line confirms which files Claude Code read; it doesn’t show which file supplied each key. To list entries Claude Code rejected, run [`claude doctor`](</docs/en/debug-your-config>); for a model that project or managed settings set, the startup header names the file that set it. `/status` and `/config` open the same dialog on different tabs, and the **Config** tab isn’t a view of your `settings.json` contents. -### - -​ - -Fix a broken settings file +### Fix a broken settings file If you mistype JSON or set a key to a value Claude Code doesn’t accept, Claude Code tells you at the start of an interactive session. What it shows depends on how much of the file is affected: @@ -201,11 +145,7 @@ After you continue, run `/status` to see the affected files and `claude doctor` for the details of each error. A `-p` run shows no dialog. Unless [a managed settings document can’t be parsed](</docs/en/errors#managed-settings-document-could-not-be-parsed>), Claude Code skips a broken user, project, or local file or its broken values and continues with the rest. After a `-p` run that ignores a setting, run `claude doctor` from your terminal to see what it dropped. -## - -​ - -Settings precedence +## Settings precedence When the same key appears in more than one place, Claude Code uses the value from the highest level that sets it. The stack below shows the levels, highest on top; a key at a higher level overrides the same key anywhere below it. In order, highest precedence first: @@ -217,11 +157,7 @@ Environment variables aren’t a level in this stack. When a behavior has both a shell variable and a settings key, which one applies is decided per pair, not by level: `ANTHROPIC_MODEL` exported in your shell applies over the `model` key from any file, while `ANTHROPIC_DEFAULT_MODEL` applies only when no file sets `model`. The [environment variables reference](</docs/en/env-vars#precedence>) says which keys have a pair and which one Claude Code reads first. An `env` block inside a settings file is an ordinary key and follows the levels above. For a few security-sensitive keys, Claude Code honors a stricter value from a lower level over a managed value; Exceptions to managed settings precedence lists them. -### - -​ - -Lists merge instead of overriding +### Lists merge instead of overriding When you set the same list key, such as `permissions.allow`, in more than one file, Claude Code combines the lists instead of picking one, so each file can add entries without removing another file’s. Four keys that hold model lists or per-model entries follow their own rules: @@ -230,59 +166,31 @@ * [`availableModels`](</docs/en/settings-reference#availablemodels>): when the managed settings Claude Code applies define it, Claude Code applies that list as-is and ignores entries you add in user, project, or local settings, unless an app that embeds Claude Code supplies its own model list; see Exceptions to managed settings precedence. Across managed sources the list never merges either; [how Claude Code combines managed sources](</docs/en/managed-settings#how-claude-code-combines-managed-sources>) says which source’s list applies. Across non-managed scopes Claude Code merges the arrays as usual. * [`modelSettings`](</docs/en/settings-reference#modelsettings>): Claude Code resolves it one model at a time, together with [`effortLevel`](</docs/en/settings-reference#effortlevel>). The `modelSettings` entry states which file’s value applies to a model. -### - -​ - -Precedence examples +### Precedence examples While Claude works, Claude Code shows a one-line tip under the spinner, such as “Use /config to change your default permission mode (including Plan Mode)”. Suppose you want those tips off, so you set [`spinnerTipsEnabled`](</docs/en/settings-reference#spinnertipsenabled>) to `false` in `~/.claude/settings.json`. Each scenario below is something that can turn them back on, and what you can do about it. -#### - -​ - -Team settings override personal settings +#### Team settings override personal settings Your team’s `.claude/settings.json` sets it to `true`. Claude Code uses the project value because shared project sits above user, so you see tips in that project and nowhere else. You can get your value back: add `"spinnerTipsEnabled": false` to `.claude/settings.local.json` in that project. Project local sits above shared project, so your sessions there stop showing tips and your teammates’ sessions don’t change. -#### - -​ - -Organization settings override everything +#### Organization settings override everything Your organization’s managed settings set it to `true`. Nothing you put in user, project, or local settings turns tips off, and neither does `--settings`. Managed is the top level. You can’t get your value back. Run `/status` to see which managed source applies, and ask your administrator if the policy should change. -#### - -​ - -The command line overrides your files for one session +#### The command line overrides your files for one session You started the session with `claude --settings '{"spinnerTipsEnabled": true}'`. Command line sits above every file except managed, so that session shows tips even though your files say `false`. You get your value back on the next session; `--settings` lasts one session and doesn’t write to any file. -#### - -​ - -A flag or environment variable sets the same thing +#### A flag or environment variable sets the same thing Some keys have a command line flag or an environment variable that overrides the settings value regardless of which file set it: `ANTHROPIC_MODEL` overrides the [`model`](</docs/en/settings-reference#model>) setting, and `--model` overrides both for a session. Whether you can get your value back depends on the key: unset the variable or drop the flag, and check the key’s entry on the [settings reference](</docs/en/settings-reference>) and the variable’s row on the [environment variables reference](</docs/en/env-vars>) for which one Claude Code uses. -### - -​ - -Troubleshoot a setting that doesn’t apply +### Troubleshoot a setting that doesn’t apply When you set a key and Claude Code doesn’t behave as if you had, start with `/status` to see which files it loaded, then find your symptom below. [Debug your configuration](</docs/en/debug-your-config>) covers the wider checks, including a clean-configuration test. -#### - -​ - -A value you set is ignored +#### A value you set is ignored Something else is setting the same key, the file can’t set that value, or the file didn’t load: @@ -291,47 +199,27 @@ * **The file can’t set that value.** [`permissions.defaultMode`](</docs/en/settings-reference#permissions-defaultmode>) values `auto` and `bypassPermissions` don’t take effect from project or local settings; set them in user or managed settings instead, or pass `--permission-mode` for one session. Before v2.1.257, `bypassPermissions` took effect from any file. A telemetry export variable in an [`env`](</docs/en/settings-reference#env>) block doesn’t take effect from project or local settings either, apart from a few off values. [Variables Claude Code ignores in `env`](</docs/en/settings-reference#variables-claude-code-ignores-in-env>) lists the variables and those values. * **The file is broken.** Invalid JSON or a rejected value makes Claude Code skip the file or the entry; see Fix a broken settings file. -#### - -​ - -A change you made in Claude Code is lost in new sessions +#### A change you made in Claude Code is lost in new sessions When you save a choice for new sessions from inside Claude Code, such as a default model with `/model`, Claude Code writes it to your user settings file, `~/.claude/settings.json`. If you can’t write to that file, for example because another tool generates it or links it to a read-only copy, the change applies to the current session and is gone in the next one. Set the key in the tool that generates the file, or replace the file with one you can write to. If you can write to the file and the change still doesn’t last, check whether the change was for one session only or a higher level sets the same key. For the `model` key, [A new session starts on a different model than you picked](</docs/en/model-config#a-new-session-starts-on-a-different-model-than-you-picked>) lists more causes. -#### - -​ - -A managed change hasn’t reached you +#### A managed change hasn’t reached you Managed sources reach a running session on the schedule in the [delivery table](</docs/en/managed-settings#choose-a-delivery-mechanism>), so restart the session first. If `/status` then names a different source than the one your administrator changed, a higher-priority source applies; [How Claude Code combines managed sources](</docs/en/managed-settings#how-claude-code-combines-managed-sources>) gives the order. -#### - -​ - -A committed key doesn’t reach teammates +#### A committed key doesn’t reach teammates Two things keep a key in `.claude/settings.json` from applying for everyone who clones it: * **Claude Code ignores the key in a repository file.** Look for `User, local, or managed`, `User or managed`, `User`, `Managed`, or `Global config` in the Scope column of the [settings index](</docs/en/settings-reference#settings-index>). Those keys never apply from the shared file, apart from a few that a repository file can still switch off. Each of those entries says so on its Scope line. `Global config` keys apply only from `~/.claude.json`. Inside the `env` key, the telemetry export variables never apply from the shared file either, apart from a few off values; see [Variables Claude Code ignores in `env`](</docs/en/settings-reference#variables-claude-code-ignores-in-env>). * **The key waits for trust.** `permissions.allow` rules, `permissions.additionalDirectories`, `extraKnownMarketplaces`, and most [`env`](</docs/en/settings-reference#env>) values apply only after each teammate [trusts the folder](</docs/en/permissions#project-allow-rules-and-workspace-trust>). Until then they still see prompts and don’t get plugins from a marketplace the file declares. `deny` and `ask` rules apply right away. -#### - -​ - -Permission rules combine differently than you expected +#### Permission rules combine differently than you expected * **You chose “Yes, and don’t ask again” on a permission prompt but still get prompted for the same tool.** That choice saved an `allow` rule to your local file, and an `allow` rule there doesn’t outrank an `ask` rule from a project or managed file; [how permission rules combine](</docs/en/permissions#settings-precedence>) explains the order. In the VS Code extension the approval card lets you pick the destination file, including the project’s shared file, which changes the rule for everyone; in the CLI, Claude Code writes only to your local file. * **Your organization’s allow rules still apply alongside yours.** That’s expected: Claude Code merges [`permissions.allow`](</docs/en/settings-reference#permissions-allow>) across scopes, unless your organization sets [`allowManagedPermissionRulesOnly`](</docs/en/settings-reference#allowmanagedpermissionrulesonly>). -### - -​ - -Exceptions to managed settings precedence +### Exceptions to managed settings precedence For a few keys whose values restrict a session, Claude Code honors a restrictive value from a scope that otherwise couldn’t override managed settings. Find the key in this table to see which value it honors and from where. @@ -353,11 +241,7 @@ An app that runs Claude Code inside itself and sets [`CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST`](</docs/en/env-vars>) is also an exception. Claude Code takes that app’s model configuration over the `model`, `fallbackModel`, `modelPicker`, and `modelOverrides` keys from every managed source, and over the model-selection variables in a managed `env` block, such as `ANTHROPIC_MODEL` and the `ANTHROPIC_DEFAULT_*_MODEL` family. Claude Code keeps a managed [`availableModels`](</docs/en/settings-reference#availablemodels>) allowlist in force unless the app supplies its own. -## - -​ - -Settings in cloud sessions +## Settings in cloud sessions A [cloud session](</docs/en/claude-code-on-the-web>) runs in a [cloud environment](</docs/en/cloud-environments>) on a fresh clone of your repository, not on your machine. That changes which settings reach it: @@ -370,11 +254,7 @@ [What carries over from your setup](</docs/en/cloud-environments#what-carries-over-from-your-setup>) lists the rest: `CLAUDE.md`, skills, MCP servers, plugins, and credentials. -## - -​ - -What’s next +## What’s next * [All settings](</docs/en/settings-reference>): every key, with where you set it and an example * [Example settings files](</docs/en/settings-example>): a personal file, a team file, and an organization’s managed file
modified Example settings files View current →
--- a/settings-example.md +++ b/settings-example.md @@ -6,11 +6,7 @@ Each one is a plausible file for that reader, so you can see the shape and copy the parts you want. None of them is a recommended baseline. Every value comes from the key’s entry on the [settings reference](</docs/en/settings-reference>), which has its type, default, and where it can be set. Each example has two tabs. **Copyable settings file** is the file as you’d save it. **What each key does** is the same file with a comment above each key; Claude Code doesn’t accept comments in a settings file, so copy from the first tab. -## - -​ - -Your own settings +## Your own settings One developer’s personal settings. It picks a model and effort, adjusts the terminal, and pre-approves a read-only command and one file read. Everything not listed keeps its default. A file like this goes in `~/.claude/settings.json`, where it applies to every project you open. @@ -84,11 +80,7 @@ "cleanupPeriodDays": 20 } -## - -​ - -A team’s shared settings +## A team’s shared settings One team’s shared settings, committed to the repository so everyone who clones it gets the same permissions, hooks, and plugin marketplace. Save a file like this at `.claude/settings.json` at the top of the repository. What to know before you commit one: @@ -228,11 +220,7 @@ "plansDirectory": "./plans" } -## - -​ - -An organization’s managed settings +## An organization’s managed settings A `managed-settings.json` file that shows the shape of the managed keys, with one plausible value for each. It isn’t a recommended policy: pick the keys that match your own requirements and set your own values. The example sets these keys:
modified All settings View current →
Show diff (3878 lines)
--- a/settings-reference.md +++ b/settings-reference.md @@ -1,10 +1,6 @@ This reference page lists each key Claude Code reads from a settings file, plus the short group of keys it keeps in `~/.claude.json` instead. To pick a file, or check precedence, start with [Settings files and precedence](</docs/en/settings>). -## - -​ - -Settings index +## Settings index Every key below links to its entry. Scope lists the [files](</docs/en/settings#settings-files-and-who-they-affect>) it can go in: `User` is `~/.claude/settings.json`, `Project` is `.claude/settings.json`, `Local` is `.claude/settings.local.json`, and `Managed` is [what your organization deploys](</docs/en/managed-settings>). `Any file` means all four, and `Global config` means `~/.claude.json`. @@ -229,7 +225,6 @@ `strictPluginOnlyCustomization.mcp`| Block [MCP servers](</docs/en/mcp>) from user and project sources| Plugins and skills| Managed `strictPluginOnlyCustomization.skills`| Block [skills](</docs/en/skills>) from user and project sources| Plugins and skills| Managed `subagentPromptCacheTtl`| Choose the [prompt cache lifetime](</docs/en/prompt-caching#cache-lifetime>) for subagents and other requests outside the main conversation| Model and responses| Any file -`subagentStatusLine`| Rewrite rows in the [subagent](</docs/en/sub-agents>) task display with your own command| Interface and terminal| Any file `switchModelsOnFlag`| Switch models automatically or pause when a [safety classifier](</docs/en/model-config#ask-before-switching>) flags a request| Model and responses| Any file `syncClaudeAiPlugins`| Stop loading the [plugins enabled on your claude.ai account](</docs/en/plugins/loading#synced-plugins>) and stop downloading new ones| Plugins and skills| User, local, or managed `syncClaudeAiSkills`| Stop loading the [skills enabled on your claude.ai account](</docs/en/skills#how-synced-skills-behave>) and stop downloading new ones| Plugins and skills| User, local, or managed @@ -261,19 +256,11 @@ `worktree.symlinkDirectories`| Symlink large directories into each [worktree](</docs/en/worktrees>) instead of duplicating them| Agents, sessions, and worktrees| Any file `wslInheritsWindowsSettings`| Have WSL read [managed settings](</docs/en/managed-settings>) from the Windows policy chain| Enterprise and managed settings| Managed -## - -​ - -Model and responses +## Model and responses Choose which models Claude Code uses and how it responds. For how these settings interact with the `/model` command and environment variables, see [Model configuration](</docs/en/model-config>). -### - -​ - -`advisorModel` +### `advisorModel` Pick which model answers when Claude calls the server-side [advisor tool](</docs/en/advisor>). Unset it to turn the advisor off. The advisor must be at least as capable as your main model. See [Choose an advisor model](</docs/en/advisor#choose-an-advisor-model>) for the accepted pairings and what happens when you pick one that isn’t accepted. You don’t usually edit this key by hand. Run `/advisor` to open a picker that shows the current choice, the models that can advise, and **No advisor**. Claude Code saves your pick to this key in `~/.claude/settings.json`. If you pick from a [Remote Control](</docs/en/remote-control>) client or in a session attached to a remote worker, the pick applies to that session only and doesn’t change this key. If your account requires the [usage-credits consent](</docs/en/advisor#fable-advisor-and-usage-credits>), accept it first by running `/model fable`. Until you do, picking Fable in `/advisor` saves nothing and Claude Code tells you to run `/model fable` first. @@ -290,11 +277,7 @@ The key has no effect on providers where the advisor [isn’t available](</docs/en/advisor#requirements>), such as Amazon Bedrock. On Claude Platform on AWS, the key requires Claude Code v2.1.300 or later. `"fable"` requires [Fable access](</docs/en/advisor#choose-an-advisor-model>). -### - -​ - -`alwaysThinkingEnabled` +### `alwaysThinkingEnabled` Turn [extended thinking](</docs/en/model-config#extended-thinking>) off for every session by setting this to `false`. Thinking is on by default, so `true` changes nothing. Most people set this through `/config` rather than by editing the file. On models that always think, such as Opus 5.5, Sonnet 5.5, Haiku 5.5, and the Fable models, `false` has no effect. On [third-party providers](</docs/en/third-party-integrations>) Claude Code omits the `thinking` parameter instead of turning thinking off, so adaptive-reasoning models may still think. With thinking turned off on the Anthropic API, Claude Code sends effort `high` instead of a higher level to models it knows [don’t accept that combination](</docs/en/errors#effort-isnt-available-with-thinking-turned-off>), such as Opus 5. @@ -311,11 +294,7 @@ "alwaysThinkingEnabled": false } -### - -​ - -`availableModels` +### `availableModels` Restrict which models people can select for the main session, [subagents](</docs/en/sub-agents>), [skills](</docs/en/skills>), and the [advisor](</docs/en/advisor>). A managed list constrains `/model`, `--model`, and the `model` key in a developer’s own files; a model outside it can’t be selected. With the default prefix matching, this doesn’t touch the Default option on its own; pair it with `enforceAvailableModels` for that. @@ -333,11 +312,7 @@ A model ID entry such as `"claude-opus-5"` also permits later versions that extend it, such as Opus 5.5. To block one of those versions, use `deniedModels`. To make each model ID entry permit only the version it names, use `availableModelsMatch`. See [Restrict model selection](</docs/en/model-config#restrict-model-selection>). For third-party provider IDs, see [Pin models for third-party deployments](</docs/en/model-config#pin-models-for-third-party-deployments>). -### - -​ - -`availableModelsMatch` +### `availableModelsMatch` Choose how `availableModels` entries match model IDs. By default a model ID entry also permits later versions that extend it, so `"claude-opus-5"` permits Opus 5.5. With `"exact"`, each model ID entry permits only the version it names, so a newer version of that model stays blocked until you list it. Requires Claude Code v2.1.283 or later. @@ -358,11 +333,7 @@ With `"exact"`, the Default option is also limited to the listed models whenever the list names at least one model or family. See [Block specific models or versions](</docs/en/model-config#block-specific-models-or-versions>). -### - -​ - -`deniedModels` +### `deniedModels` Block specific models, with or without an `availableModels` allowlist and even when that list permits them. Claude Code hides a blocked model from the `/model` picker, and the model can’t be selected anywhere `availableModels` is enforced. A session on the Default option doesn’t run a blocked model either, as [Block specific models or versions](</docs/en/model-config#block-specific-models-or-versions>) describes. Requires Claude Code v2.1.283 or later. @@ -385,11 +356,7 @@ See [Block specific models or versions](</docs/en/model-config#block-specific-models-or-versions>). -### - -​ - -`effortLevel` +### `effortLevel` Set a default [effort level](</docs/en/model-config#adjust-effort-level>) for models you haven’t saved a level for. Lower levels are faster and cheaper on straightforward tasks, and higher levels reason more deeply on complex problems. When you run `/effort low`, `medium`, `high`, or `xhigh` in an interactive session on your machine, Claude Code saves the level for the active model under `modelSettings` rather than writing this key. Before v2.1.251, `/effort` wrote this key. Within the same settings file, Claude Code uses a model’s saved level rather than this key. `modelSettings` states the cross-file precedence. In a session attached to a remote worker, in a `-p` run, and in the Agent SDK, `/effort` applies to that session only. [Adjust effort level](</docs/en/model-config#adjust-effort-level>) lists the interactive picks that also apply to that session only. The message that `/effort` prints says which happened. @@ -410,11 +377,7 @@ In your user settings file, `~/.claude/settings.json`, this key is the older form `/effort` wrote before it saved levels per model, and it keeps applying where it applied before, on Opus 5, Fable 5.1, and earlier models. Opus 5.5 and models released after it ignore it and start at their own default until you save a level for them, which `/effort` writes under `modelSettings`. In project, local, and managed settings, and with `--settings`, this key applies to every model. -### - -​ - -`enforceAvailableModels` +### `enforceAvailableModels` The `/model` picker has a **Default** option, and [`default` model setting](</docs/en/model-config#default-model-setting>) describes the model it resolves to. An `availableModels` allowlist limits the models you can name, but with the default prefix matching it doesn’t remap your account type’s default, so **Default** can still resolve to a model outside the list. This key closes that gap. Requires Claude Code v2.1.175 or later. When your organization deploys any managed settings, Claude Code reads this key from the managed source alone and ignores it in your other files. For how this key applies to the startup model checks, see [Amazon Bedrock](</docs/en/amazon-bedrock#when-your-organization-enforces-a-model-allowlist>) and [Google Cloud’s Agent Platform](</docs/en/google-vertex-ai#when-your-organization-enforces-a-model-allowlist>). @@ -435,11 +398,7 @@ This key has no effect when `availableModels` is unset or empty. See [Enforce the allowlist for the Default model](</docs/en/model-config#enforce-the-allowlist-for-the-default-model>). Requires Claude Code v2.1.175 or later. -### - -​ - -`fallbackModel` +### `fallbackModel` Name backup models for Claude Code to try, in order, when your primary model is overloaded or unavailable. Claude Code switches to the next available model in the chain for the rest of the turn and shows a notice. Without a chain, Claude Code retries the same model and then surfaces the server’s error, and you retry or switch models yourself. A switch means one turn with a cold [prompt cache](</docs/en/prompt-caching#switching-models>) on the fallback model; your next message tries the primary model first again. @@ -458,11 +417,7 @@ Unlike most array settings, this key doesn’t merge across settings files: the highest-precedence file that defines it supplies the whole chain. If your project file sets `["claude-sonnet-5"]` and your user file sets `["claude-haiku-4-5"]`, the chain is `["claude-sonnet-5"]` only. Claude Code keeps at most three distinct allowed models from the list and ignores the rest. See [Fallback model chains](</docs/en/model-config#fallback-model-chains>). -### - -​ - -`fastMode` +### `fastMode` Turn [fast mode](</docs/en/fast-mode>) on for sessions where it’s available, for interactive work such as rapid iteration or live debugging where you want speed at a higher cost per token. You don’t usually edit this key yourself. Running `/fast` writes `fastMode: true` to `~/.claude/settings.json`, and running it again to turn fast mode off removes the key. On the Anthropic API, only Fable 5.2, Opus 5.5, Opus 5, and Opus 4.8 support fast mode. Running `/fast` from another model switches you to Opus, and switching to an unsupported model turns fast mode off. See [Switch models while fast mode is on](</docs/en/fast-mode#switch-models-while-fast-mode-is-on>). On Google Cloud’s Agent Platform, [`/fast` switches you to Fable 5.2](</docs/en/fast-mode#use-fast-mode-on-agent-platform>) instead and doesn’t write this key, and Claude Code ignores a saved `true`. @@ -479,11 +434,7 @@ "fastMode": true } -### - -​ - -`fastModePerSessionOptIn` +### `fastModePerSessionOptIn` Normally, running `/fast` saves `fastMode` to a person’s user settings, so new sessions on a supported model start with fast mode on. On Fable 5.2, that happens only if they [turned it on while using Fable 5.2](</docs/en/fast-mode#switch-models-while-fast-mode-is-on>). To make each person run `/fast` in each session they want it, set this key to `true`. Claude Code leaves `fastMode` in their file, so turning this key off restores the old behavior. Owners on Team or Enterprise plans can deploy it organization-wide through [server-managed settings](</docs/en/server-managed-settings>). When managed settings set the key, `/fast on` is refused outside interactive terminal sessions and reports that your organization has disabled fast mode. That covers [non-interactive mode](</docs/en/headless>), the [VS Code extension](</docs/en/vs-code>), and [cloud sessions](</docs/en/claude-code-on-the-web>). @@ -501,11 +452,7 @@ See [Require per-session opt-in](</docs/en/fast-mode#require-per-session-opt-in>). -### - -​ - -`language` +### `language` Have Claude respond in a language other than English by default. There is no fixed list for responses: Claude Code passes the value verbatim to Claude as an instruction to always respond in that language, so any language name Claude can read works. Claude Code doesn’t check the value, so a misspelled name reaches Claude as written rather than producing an error. The same value sets the language for [voice dictation](</docs/en/voice-dictation#change-the-dictation-language>), which does have a fixed list of [supported dictation languages](</docs/en/voice-dictation#change-the-dictation-language>), and for auto-generated session titles. @@ -519,11 +466,7 @@ "language": "japanese" } -### - -​ - -`maxEffortLevel` +### `maxEffortLevel` Cap the [effort level](</docs/en/model-config#adjust-effort-level>) a session can use, leaving lower levels available. Any higher level runs at the cap instead, including one from `/effort`, the `/model` picker, `--effort`, [`CLAUDE_CODE_EFFORT_LEVEL`](</docs/en/env-vars>), a skill’s or subagent’s `effort` frontmatter, or the model’s own default. Claude Code applies the cap itself before each request, so it holds on every provider, including Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry. Requires Claude Code v2.1.267 or later. @@ -547,11 +490,7 @@ When your organization also sets an [effort limit](</docs/en/model-config#organization-effort-limits>) for a model, the lower of the two caps applies. -### - -​ - -`model` +### `model` Set the model every new session uses, so you don’t have to pick one with `/model` each time. Setting it here doesn’t stop you from switching mid-session. If your admin set an [organization default model](</docs/en/model-config#organization-default-model>) to override user selection, you get that model even when you set this key in user, project, or local settings. @@ -568,11 +507,7 @@ A value here outranks [`ANTHROPIC_DEFAULT_MODEL`](</docs/en/model-config#set-a-default-model-for-new-sessions>), which Claude Code uses only when nothing else selects a model. -### - -​ - -`modelOverrides` +### `modelOverrides` Map Anthropic model IDs to provider-specific model IDs, such as Amazon Bedrock inference profile ARNs. Each model picker entry then uses its mapped value when calling the provider API. Administrators use this on [Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry](</docs/en/model-config#override-model-ids-per-version>) to route each model version to a specific inference profile, version name, or deployment for governance, cost allocation, or regional routing. @@ -592,11 +527,7 @@ See [Override model IDs per version](</docs/en/model-config#override-model-ids-per-version>). -### - -​ - -`modelPicker` +### `modelPicker` List the models the `/model` picker offers, in the order you write them and under labels you choose, so the picker lists the models your organization runs, after the built-in lineup or instead of it. Each row’s `model` is taken verbatim, so it accepts anything `--model` accepts: an alias such as `opus`, an Anthropic model ID, or a provider-format ID for Amazon Bedrock, Google Cloud’s Agent Platform, Microsoft Foundry, or an LLM gateway. Requires Claude Code v2.1.242 or later. @@ -621,11 +552,7 @@ } } -#### - -​ - -Fields for `modelPicker` +#### Fields for `modelPicker` The key takes two fields, one for the rows themselves and one for whether they replace the built-in lineup or add to it. @@ -642,11 +569,7 @@ Claude Code drops a row it can’t parse and keeps the rest. See [Fix a broken settings file](</docs/en/settings#fix-a-broken-settings-file>). -### - -​ - -`modelPricing` +### `modelPricing` Report spend at the rates your organization pays instead of list price. Set it when your organization has contracted rates, so the dollar figures developers see match your bill. Claude Code applies the rates in `/usage`, the [status line](</docs/en/statusline>), the Agent SDK’s `total_cost_usd`, the [`--max-budget-usd`](</docs/en/cli-reference>) limit, and the [OpenTelemetry](</docs/en/monitoring-usage>) cost metric and events. You supply the rates: Claude Code doesn’t read them from your contract or the Claude Console. Requires Claude Code v2.1.242 or later. @@ -674,11 +597,7 @@ Set `multiplier` above 1, up to 10, to mark every figure up. A markup requires Claude Code v2.1.271 or later. Earlier versions ignore a `multiplier` above 1 with a warning and keep the rest of the setting. For the steps, including how to confirm the rates are in effect, see [Report spend at your contracted rates](</docs/en/costs#report-spend-at-your-contracted-rates>). -#### - -​ - -Fields for `modelPricing` +#### Fields for `modelPricing` Field| Type| What it does ---|---|--- @@ -687,11 +606,7 @@ Claude Code uses a row’s rates exactly as you wrote them, without adding the fast-mode surcharge or the [US-only-inference rate](<https://platform.claude.com/docs/en/about-claude/pricing>). If you also set `multiplier`, Claude Code applies it on top of the row’s rates. Claude Code drops a row with a rate it can’t parse, or a `multiplier` it can’t parse, and keeps the rest; see [Fix a broken settings file](</docs/en/settings#fix-a-broken-settings-file>). -#### - -​ - -Which models a `modelPricing` row applies to +#### Which models a `modelPricing` row applies to Claude Code decides which models a row applies to from the row’s key: @@ -699,11 +614,7 @@ * **Any other key** : a key that isn’t a built-in model’s ID, such as a gateway model alias. Claude Code applies the row to that one ID only. When a model ID matches one of your keys exactly and also falls under a row keyed by a built-in model’s ID, Claude Code uses the exact match. * **A Bedrock application inference profile** : once Claude Code has resolved the profile to the model it routes to, through your `modelOverrides` map or the [`bedrock:GetInferenceProfile` lookup](</docs/en/amazon-bedrock#iam-configuration>), Claude Code applies that model’s row to the profile. -### - -​ - -`modelSettings` +### `modelSettings` Save an [effort level](</docs/en/model-config#adjust-effort-level>) for each model you use. Requires Claude Code v2.1.251 or later. In an interactive session on your machine, when you save `low`, `medium`, `high`, or `xhigh` as your default with `/effort` or the `/model` picker’s effort slider, Claude Code writes that level here under the model you’re using, so you rarely edit this key yourself. When you pick one of those levels in the [VS Code extension’s model picker](</docs/en/vs-code#use-the-prompt-box>), Claude Code saves it here the same way. The `effortLevel` entry lists the sessions where `/effort` applies to that session only. Edit the key by hand to change or remove a level you saved. A model’s `effortLevel` here takes precedence over the top-level `effortLevel` in the same settings file. Across files, Claude Code resolves each model separately: the highest-precedence [settings file](</docs/en/settings#settings-precedence>) that sets either an `effortLevel` for that model or a top-level `effortLevel` that applies to that model decides, so an `effortLevel` in managed settings outranks a level you saved in user settings. [Adjust effort level](</docs/en/model-config#adjust-effort-level>) lists what else can override a saved level, such as `--effort` at launch. To cap one model’s effort rather than set its level, add a `maxEffortLevel` field to that model’s entry. The field requires Claude Code v2.1.267 or later. @@ -728,11 +639,7 @@ Run `/effort auto` to clear your saved level for the model you’re using. Claude Code leaves the other entries and any top-level `effortLevel` in place. -### - -​ - -`outputStyle` +### `outputStyle` Select an [output style](</docs/en/output-styles>) by name. An output style is a saved set of instructions that changes Claude’s role, tone, and output format, such as the built-in Explanatory and Learning styles or one you wrote yourself. If you change this key during a session, Claude uses the new style starting with your next message. For what that message costs in prompt caching, see [Changing output style](</docs/en/prompt-caching#changing-output-style>). Before v2.1.251, the edit applied only after you ran `/clear` or started a new session. @@ -748,11 +655,7 @@ "outputStyle": "Explanatory" } -### - -​ - -`promptCacheTtl` +### `promptCacheTtl` Choose how long the [prompt cache](</docs/en/prompt-caching>) holds the main conversation. This key applies to your interactive, `-p`, and Agent SDK turns, together with the helpers Claude Code runs inline with them. The one-hour lifetime keeps the cache warm across longer breaks, and the API [bills each cache write at a higher rate](<https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pricing>) than at the five-minute lifetime. Requires Claude Code v2.1.242 or later. @@ -774,11 +677,7 @@ For what each lifetime costs, see [Cache lifetime](</docs/en/prompt-caching#cache-lifetime>). -### - -​ - -`showThinkingSummaries` +### `showThinkingSummaries` See summaries of Claude’s [extended thinking](</docs/en/model-config#extended-thinking>) in interactive sessions. Set it if you want the full summaries when you expand thinking with `Ctrl+O`. When unset or `false`, the Anthropic API redacts thinking blocks and Claude Code shows a collapsed stub. @@ -796,11 +695,7 @@ Redaction changes only what you see, not what the model generates. To reduce thinking spend, [lower the budget or disable thinking](</docs/en/model-config#extended-thinking>) instead. -### - -​ - -`subagentPromptCacheTtl` +### `subagentPromptCacheTtl` Choose how long the [prompt cache](</docs/en/prompt-caching>) holds the requests Claude Code makes outside the main conversation. This key applies to [subagents](</docs/en/sub-agents>), [workflows](</docs/en/workflows>), and Claude Code’s own background and helper requests, such as compaction and session titles. The one-hour lifetime keeps the cache warm across longer breaks, and the API [bills each cache write at a higher rate](<https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pricing>) than at the five-minute lifetime. Requires Claude Code v2.1.242 or later. @@ -821,11 +716,7 @@ This key covers the requests `promptCacheTtl` doesn’t, so set both to choose a lifetime for every request Claude Code makes. For how a subagent’s cache differs from the main conversation’s, see [Subagents and the cache](</docs/en/prompt-caching#subagents-and-the-cache>). -### - -​ - -`switchModelsOnFlag` +### `switchModelsOnFlag` Choose what happens when a [safety classifier flags a request](</docs/en/model-config#automatic-model-fallback>): switch to the fallback model and continue, or pause so you can choose between switching and editing the prompt. @@ -843,11 +734,7 @@ See [Ask before switching](</docs/en/model-config#ask-before-switching>). -### - -​ - -`ultracode` +### `ultracode` Start sessions with [ultracode](</docs/en/workflows#let-claude-decide-with-ultracode>) on. With it on, Claude plans a workflow for each substantive task instead of waiting for you to ask. Claude plans workflows only when [dynamic workflows](</docs/en/workflows>) are enabled for you and your model supports `xhigh` effort. The key doesn’t change the session’s effort level: ultracode runs at whichever level the session uses. Claude Code reads this key but never writes it: `/effort ultracode` turns ultracode on for the current session only. @@ -866,19 +753,11 @@ The session’s effort level comes from `effortLevel`, `modelSettings`, and the other [effort sources](</docs/en/model-config#adjust-effort-level>), and an [effort cap](</docs/en/model-config#organization-effort-limits>) such as `maxEffortLevel` lowers that level without turning ultracode off. This and the `/effort ultracode off` form require Claude Code v2.1.284 or later. Before v2.1.284, `ultracode: true` ran the session at `xhigh` effort, and an effort cap below `xhigh` kept ultracode off. An Agent SDK `apply_flag_settings` control request also accepts the key. -## - -​ - -Permission settings +## Permission settings Decide what Claude can do without asking, the default permission mode for new sessions, and what auto mode’s classifier allows. For rule syntax and the permission model, see [Configure permissions](</docs/en/permissions>). -### - -​ - -`allowManagedPermissionRulesOnly` +### `allowManagedPermissionRulesOnly` Make managed settings the only settings source of permission rules. Claude Code then ignores `allow`, `ask`, and `deny` rules in user, project, local, and `--settings` files, ignores `--allowedTools`, hides the always-allow choices in permission prompts, and stops saving new rules. When [parent settings from an embedding host](</docs/en/managed-settings#let-an-embedding-host-add-policy>) apply, Claude Code treats them as part of the managed tier. It drops their `allow` rules and `additionalDirectories`, and keeps their `deny` and `ask` rules except `Read` and `Edit` rules whose pattern starts with `!`. A host can’t carve paths out of the managed rules with a `!` rule, whether or not you set this key. `--disallowedTools` rules and the current session’s `deny` and `ask` rules still apply, including after Claude Code reloads settings mid-session. They only restrict, so they can’t widen what the managed rules grant. Before v2.1.257, Claude Code dropped those command-line and session rules at the first settings reload. For what a `!` pattern in a `--disallowedTools` or session rule can carve out, see [Read and Edit rules](</docs/en/permissions#read-and-edit>). When you set this key, Claude Code v2.1.282 or later also ignores the [`allowed-tools`](</docs/en/skills#pre-approve-tools-for-a-skill>) frontmatter in skills and `.claude/commands/` files from these sources: @@ -907,11 +786,7 @@ This key doesn’t lock down the MCP server allowlist; for that, set `allowManagedMcpServersOnly`. See [Managed-only settings](</docs/en/managed-settings#managed-only-settings>). -### - -​ - -`autoMode` +### `autoMode` Add your own rules to what the [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) classifier blocks and allows. Use it to tell the classifier which repos, buckets, and domains your organization trusts, so it stops blocking routine internal operations. The classifier ships with [built-in allow and deny rules](</docs/en/auto-mode-config#inspect-the-defaults-and-your-effective-config>). Include the literal string `"$defaults"` in an array to keep those built-in rules at that position and add yours around them; leave it out to replace them with yours. @@ -931,11 +806,7 @@ When more than one of those files sets the same array, Claude Code concatenates the entries. For the rule format and how each array is applied, see [Configure auto mode](</docs/en/auto-mode-config>). -### - -​ - -`autoMode.classifyAllShell` +### `autoMode.classifyAllShell` Send every Bash and PowerShell command through the auto mode classifier while auto mode is active. By default, auto mode suspends only allow rules that could run arbitrary code: tool-wide and wildcard rules such as `Bash(*)`, and interpreter or shell-wrapper prefixes such as `Bash(python *)`. A command that any other allow rule matches, such as `Bash(npm test)`, skips the classifier unless it carries [per-command allowed domains](</docs/en/sandboxing#per-command-allowed-domains-in-auto-mode>). When it skips, a destructive argument the rule’s prefix didn’t anticipate can get through unseen. Setting this key suspends every shell allow rule for the session so the classifier sees every command. Requires Claude Code v2.1.193 or later. @@ -955,11 +826,7 @@ See [Route all shell commands through the classifier](</docs/en/auto-mode-config#route-all-shell-commands-through-the-classifier>). -### - -​ - -`disableAutoMode` +### `disableAutoMode` Remove [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) from the `Shift+Tab` cycle. Any session that would otherwise [start in auto mode](</docs/en/permission-modes#which-mode-a-session-starts-in>), whether from `--permission-mode auto`, a settings file, or the built-in default, starts in `default` instead. Administrators set it in managed settings to prevent developers in their organization from using auto mode. @@ -973,11 +840,7 @@ "disableAutoMode": "disable" } -### - -​ - -`permissions` +### `permissions` Control which tools Claude can use without asking, which ones prompt, and which ones are blocked. Also set the default [permission mode](</docs/en/permission-modes>) for new sessions. Every `permissions.*` key below nests under this object. @@ -1000,11 +863,7 @@ The three rule arrays share one syntax; see Permission rule syntax under `permissions.allow`. For how permission rules from different files combine, see [how permission rules merge across scopes](</docs/en/permissions#settings-precedence>); for how settings keys in general combine, see [Settings precedence](</docs/en/settings#settings-precedence>) on the settings guide. -### - -​ - -`useAutoModeDuringPlan` +### `useAutoModeDuringPlan` Choose whether Claude Code uses the auto mode classifier to review shell commands in plan mode. With the default `true`, the classifier reviews each command during planning when auto mode is available and you see no prompt, except for [critical-path removals](</docs/en/permission-modes#critical-paths>). Set `false` to get a permission prompt for every command outside the built-in read-only set. Appears in `/config` as **Use auto mode during plan**. @@ -1021,11 +880,7 @@ "useAutoModeDuringPlan": false } -### - -​ - -`permissions.allow` +### `permissions.allow` List the tool uses Claude Code approves without asking you. In an MCP rule, `*` can appear only in the tool name after the `mcp__<server>__` prefix, such as `mcp__github__get_*`; it can’t appear in the server name. @@ -1046,11 +901,7 @@ Claude Code applies `allow` rules from a project’s `.claude/settings.json` only after you accept the [workspace trust dialog](</docs/en/permissions#project-allow-rules-and-workspace-trust>) for that folder. -#### - -​ - -Permission rule syntax +#### Permission rule syntax Permission rules follow the format `Tool` or `Tool(specifier)`. Claude Code evaluates `deny` rules first, then `ask`, then `allow`, and the first match decides regardless of how specific each rule is; see the [permission rule evaluation order](</docs/en/permissions#manage-permissions>). Each row shows one rule shape and what it matches. @@ -1063,11 +914,7 @@ For the complete rule syntax, including wildcard behavior, tool-specific patterns for Read, Edit, WebFetch, MCP, and Agent rules, and the security limitations of Bash patterns, see [Permission rule syntax](</docs/en/permissions#permission-rule-syntax>). -### - -​ - -`permissions.ask` +### `permissions.ask` List the tool uses that prompt you for confirmation even in a permission mode that would otherwise approve them, such as `acceptEdits` or `bypassPermissions`. In `dontAsk` mode Claude Code denies a matching tool use instead of prompting. @@ -1083,11 +930,7 @@ } } -### - -​ - -`permissions.deny` +### `permissions.deny` List the tool uses Claude Code blocks. Use it for files that hold API keys, secrets, or environment values: Claude Code excludes matching files from file discovery and search results, denies reads of them, and blocks the [Edit and Write tools](</docs/en/permissions#read-and-edit>) on the matching paths. Read and Edit deny rules apply to Claude’s built-in file tools, to file commands Claude Code recognizes in Bash, such as `cat`, `head`, `tail`, `sed`, and `tee`, and to the targets of Bash [redirections](</docs/en/permissions#redirections>) such as `> file` and `< file`; they don’t apply to a command that reads files without naming them, such as `grep -r pattern .`, or to arbitrary subprocesses, so for OS-level enforcement [enable the sandbox](</docs/en/sandboxing>). @@ -1114,11 +957,7 @@ Tool names accept glob patterns, so `"*"` denies every tool and `"mcp__*"` denies every MCP tool. Claude Code ignores a deny rule for the [`EndConversation`](</docs/en/tools-reference#endconversation-tool-behavior>) tool as long as any other tool is still available to Claude. A `Bash` deny rule matches the command as Claude writes it, so `Bash(curl *)` doesn’t stop `/usr/bin/curl` or `sh -c 'curl …'`; see [what a Bash rule doesn’t match](</docs/en/permissions#bash-rule-limits>). This key replaces the deprecated `ignorePatterns` configuration. -### - -​ - -`permissions.additionalDirectories` +### `permissions.additionalDirectories` Give Claude file access to directories outside the one you started in, as additional [working directories](</docs/en/permissions#working-directories>). Most `.claude/` configuration is [not discovered](</docs/en/permissions#additional-directories-grant-file-access-not-configuration>) from these directories. @@ -1137,11 +976,7 @@ Like `allow` rules, entries in a project’s `.claude/settings.json` take effect only after you accept the [workspace trust dialog](</docs/en/permissions#project-allow-rules-and-workspace-trust>) for that folder. -### - -​ - -`permissions.blockReadsOutsideWorkingDirectories` +### `permissions.blockReadsOutsideWorkingDirectories` Make Claude’s file tools refuse reads outside your [working directories](</docs/en/permissions#working-directories>) in every permission mode, including `bypassPermissions`. Claude Code denies `Read`, `Grep`, `Glob`, and `LSP` calls on those paths and tells Claude to ask you to add the directory with `/add-dir`. Files Claude Code itself needs stay readable, such as your skills, plugins, rules, agents, commands, and the `CLAUDE.md` memory file under `~/.claude/`. Requires Claude Code v2.1.257 or later. Claude Code doesn’t refuse shell commands the same way: @@ -1166,11 +1001,7 @@ To lift the block, remove the key from every settings file that sets it, then restart each running session. Directories you add with `--add-dir`, `/add-dir`, or `additionalDirectories` in your user or managed settings count as working directories for the block. Directories added only in repository settings don’t count: those in `.claude/settings.json`, and those in `.claude/settings.local.json` unless git reports that file as untracked. In a directory that isn’t a git repository, or when git tracks the file, Claude Code treats `.claude/settings.local.json` as repository settings, so put directories you want to keep readable in your user settings instead. When `autoMemoryDirectory` comes from the project’s `.claude/settings.json`, or from a `.claude/settings.local.json` [treated as repository-supplied](</docs/en/permissions#when-your-local-settings-file-needs-trust>), Claude Code loads no [auto memory](</docs/en/memory#storage-location>) from that directory and saves none to it. -#### - -​ - -Sandboxed commands under the block +#### Sandboxed commands under the block When [sandboxing](</docs/en/sandboxing>) is on, the block also covers sandboxed commands. Claude Code denies them read access to your home directory and to the other roots that hold user files: `/Users`, `/home`, `/root`, `/Volumes`, `/mnt`, `/media`, `/run/media`, and `/srv`. It then re-opens the working directories, [worktrees](</docs/en/worktrees>) Claude Code creates in the session, the session temp directory, and the parts of `~/.claude` that commands need, such as skills and plugins. While the block is in force, `allowRead` and `allowWrite` entries from repository settings don’t count. When the session’s working directory is a linked [git worktree](</docs/en/worktrees>), including one Claude Code entered mid-session, the repository’s common `.git` directory stays readable and writable to sandboxed commands, so git keeps working there. In these cases the block doesn’t reach sandboxed commands, while Claude’s file tools keep enforcing it: @@ -1186,11 +1017,7 @@ Claude Code judges each file separately. When a file lies where a sandboxed command can write, directly or through a symlink, Claude Code doesn’t re-open the files it names. On Linux and WSL2, a configuration file that is a symlink can stay unreadable at its own path, and `git` then runs without it. `~/.git-credentials` and `$XDG_CONFIG_HOME/git/credentials` stay blocked. If a re-opened file holds a secret, such as an `http.extraHeader` token, add its path to `sandbox.filesystem.denyRead`. A `denyRead` entry that covers a file always takes precedence over this re-open. -### - -​ - -`permissions.blockWritesOutsideWorkingDirectories` +### `permissions.blockWritesOutsideWorkingDirectories` Make the `Write`, `Edit`, and `NotebookEdit` tools refuse paths outside your [working directories](</docs/en/permissions#working-directories>) in every permission mode, including `bypassPermissions`, apart from some of Claude Code’s own files. The key doesn’t limit shell commands, MCP tools, or the programs hooks run. To limit where shell commands write, turn on [sandboxing](</docs/en/sandboxing>). Requires Claude Code v2.1.314 or later. Once the key is on, Claude Code also removes the `EnterWorktree` and `ExitWorktree` tools or refuses calls to them. To keep working in worktrees, follow [Claude has no `EnterWorktree` tool](</docs/en/worktrees#claude-has-no-enterworktree-tool>). @@ -1210,11 +1037,7 @@ To test the block, ask Claude to use the Write tool to create a file outside your working directories, such as `~/block-test.txt` if your home directory isn’t one of them. Claude Code refuses the call, and the refusal says the [setting blocks writes outside the working directories](</docs/en/errors#setting-blocks-writes-outside-the-working-directories>). To lift the block, remove the key from every settings file that sets it, then restart Claude Code. -#### - -​ - -What the write block refuses and what stays writable +#### What the write block refuses and what stays writable Some of Claude Code’s own files stay writable, such as plan files, the [scratchpad](</docs/en/claude-directory#session-scratchpad-directory>), a [background session](</docs/en/agent-view>)’s `tmp` directory, and `.md` files in this project’s [auto memory](</docs/en/memory#storage-location>). Along with your own files outside the working directories, the block refuses writes to: @@ -1225,19 +1048,11 @@ Settings files stay refused whatever you add. To let a write through in any of the other cases, add a working directory. `/add-dir` needs a directory that exists, so name the `.claude/worktrees` directory at the repository root for subagent worktrees. -#### - -​ - -Let one directory through the read or write block +#### Let one directory through the read or write block To let Claude reach one directory outside the project while `blockReadsOutsideWorkingDirectories` or `blockWritesOutsideWorkingDirectories` is `true`, add it as a working directory. Run `/add-dir <directory>` in the session, pass `--add-dir <directory>` when you start Claude Code, or list it under `additionalDirectories` in your user or managed settings. No [allow rule](</docs/en/permissions#read-and-edit>) lets Claude’s file tools through either block. -### - -​ - -`permissions.defaultMode` +### `permissions.defaultMode` Set the default [permission mode](</docs/en/permission-modes>) for new sessions. When you leave it unset, the [built-in default](</docs/en/permission-modes#which-mode-a-session-starts-in>) for your surface applies. @@ -1263,11 +1078,7 @@ Permission rules layer on top of every mode: `deny` rules block in every mode, including `bypassPermissions`. See [Permission modes](</docs/en/permission-modes>). In cloud sessions, Claude Code honors only `acceptEdits`, `plan`, `default`, and `auto` from this key. For conversations the VS Code extension starts, see [which setting the extension reads for the starting permission mode](</docs/en/permission-modes#switch-permission-modes>). -### - -​ - -`permissions.denyInsteadOfPrompting` +### `permissions.denyInsteadOfPrompting` Set this to `true` to keep a session running when nobody is there to answer a permission prompt. Claude Code denies a tool call that would otherwise wait on a prompt, and the turn continues. Requires Claude Code v2.1.319 or later. A call goes ahead if an allow rule, your [permission mode](</docs/en/permission-modes>), or auto mode’s classifier approves it. To allow most calls that would otherwise prompt, answer from a [`PermissionRequest` hook](</docs/en/hooks#permissionrequest>). @@ -1290,11 +1101,7 @@ The key applies in `-p` runs, interactive terminal sessions, the [VS Code extension](</docs/en/vs-code>), local sessions in the [Desktop app](</docs/en/desktop>), [subagents](</docs/en/sub-agents>), and [agent teams](</docs/en/agent-teams>). To deny what would prompt in a single [non-interactive](</docs/en/headless>) run instead, pass [`--permission-prompts none`](</docs/en/headless#turn-off-permission-prompts-in-unattended-runs>) with `-p`. -#### - -​ - -What else `denyInsteadOfPrompting` stops +#### What else `denyInsteadOfPrompting` stops With the setting on, Claude Code also stops these requests for an answer: @@ -1305,11 +1112,7 @@ A session can still wait on the [workspace trust dialog](</docs/en/permissions#project-allow-rules-and-workspace-trust>) and on [project MCP server approval](</docs/en/mcp#project-server-approvals-and-workspace-trust>). Answer both before you leave the session running. -#### - -​ - -Messages from `denyInsteadOfPrompting` +#### Messages from `denyInsteadOfPrompting` These messages report refused calls. They aren’t prompts, so nothing waits for your answer. The denial Claude reads can open with this text: @@ -1325,11 +1128,7 @@ A `-p` run reports that turn as `error_during_execution`. -### - -​ - -`permissions.disableBypassPermissionsMode` +### `permissions.disableBypassPermissionsMode` Prevent anyone from entering `bypassPermissions` mode. Claude Code then rejects the `--dangerously-skip-permissions` flag, and ignores an [agent definition’s](</docs/en/sub-agents#permission-modes>) `permissionMode: bypassPermissions`, so the subagent runs with the parent session’s permission mode. @@ -1348,11 +1147,7 @@ Before v2.1.223, Claude Code applied the frontmatter permission mode even with bypass disabled. -### - -​ - -`skipAutoPermissionPrompt` +### `skipAutoPermissionPrompt` Skip the one-time notice describing [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) that Claude Code shows when you first enter auto mode yourself, for example through your own settings or the mode selector, rather than when the built-in default starts a session in it. Claude Code shows that notice once and then records that it was shown, so this key only matters where the notice hasn’t appeared yet. @@ -1368,11 +1163,7 @@ "skipAutoPermissionPrompt": true } -### - -​ - -`skipDangerousModePermissionPrompt` +### `skipDangerousModePermissionPrompt` Skip the confirmation dialog Claude Code shows before a session enters `bypassPermissions` mode, whether from `--dangerously-skip-permissions` or from `defaultMode: "bypassPermissions"`. Claude Code writes `true` here in your user settings when you accept that dialog once. @@ -1388,19 +1179,11 @@ "skipDangerousModePermissionPrompt": true } -## - -​ - -Sandbox settings +## Sandbox settings Isolate the commands Claude runs from your filesystem, your network, and your credentials. For how sandboxing works and platform requirements, see [Sandboxing](</docs/en/sandboxing>). -### - -​ - -`sandbox` +### `sandbox` Isolate the Bash commands Claude runs from your filesystem and network with [sandboxing](</docs/en/sandboxing>). Turn the sandbox on with `enabled`, then narrow or widen what sandboxed commands can touch with the `filesystem`, `network`, and `credentials` sub-objects. The sandbox runs on macOS, Linux, and WSL2. @@ -1429,11 +1212,7 @@ When managed settings set a Boolean key such as `enabled` or `failIfUnavailable`, that value overrides anything a developer sets. Claude Code merges array keys across the settings scopes the session loads, so a developer can append entries; see [Keep developers from widening the policy](</docs/en/sandboxing#keep-developers-from-widening-the-policy>) for the managed-only locks. To require the sandbox for an organization, see [Enforce sandboxing with managed settings](</docs/en/sandboxing#enforce-sandboxing-with-managed-settings>). -### - -​ - -`sandbox.enabled` +### `sandbox.enabled` Turn on [sandboxing](</docs/en/sandboxing>) for Bash commands. When you pick a mode in the `/sandbox` panel, Claude Code writes this key to `.claude/settings.local.json` for the current project; set it in `~/.claude/settings.json` to sandbox every project. @@ -1453,11 +1232,7 @@ On Linux and WSL2 the sandbox needs `bubblewrap` and `socat`; see [Set up Linux and WSL2](</docs/en/sandboxing#set-up-linux-and-wsl2>). When the sandbox can’t start, Claude Code runs commands unsandboxed unless you also set `failIfUnavailable`. -### - -​ - -`sandbox.failIfUnavailable` +### `sandbox.failIfUnavailable` Make Claude Code exit with an error at startup when `sandbox.enabled` is `true` but the sandbox can’t start because the platform doesn’t support it or the dependency check fails. Without this key, Claude Code runs commands unsandboxed. Managed deployments that require sandboxing as a security gate can use this setting. On a platform the sandbox doesn’t support, Claude Code doesn’t start with this key on. See [Enforce sandboxing with managed settings](</docs/en/sandboxing#enforce-sandboxing-with-managed-settings>). @@ -1480,11 +1255,7 @@ See [Enforce sandboxing with managed settings](</docs/en/sandboxing#enforce-sandboxing-with-managed-settings>). -### - -​ - -`sandbox.autoAllowBashIfSandboxed` +### `sandbox.autoAllowBashIfSandboxed` Let Claude Code run sandboxed Bash commands without a permission prompt. Commands that can’t run in the sandbox still go through the regular permission flow, and `deny` rules and content-scoped `ask` rules such as `Bash(git push *)` still apply; a bare `Bash` ask rule is skipped for sandboxed commands. Set it to `false` to send sandboxed commands through the regular permission flow too, which the `/sandbox` **Mode** tab calls regular permissions mode. @@ -1507,11 +1278,7 @@ See [Auto-allow mode](</docs/en/sandboxing#auto-allow-mode>) for what auto-allow mode still prompts on and how it behaves in plan mode. -### - -​ - -`sandbox.excludedCommands` +### `sandbox.excludedCommands` Name commands that Claude Code runs outside the sandbox, such as tools that don’t work under it. Each entry uses the same syntax as the content of a `Bash(...)` [permission rule](</docs/en/permissions#permission-rule-syntax>): an exact command, a prefix such as `docker *`, or a wildcard pattern. A pattern with no wildcard is an exact match, so `docker` matches only `docker` with no arguments. Your entries take a Bash call out of the sandbox only when they cover every command in it, and some call shapes stay sandboxed even then. A `docker *` entry alone doesn’t take `npm ci && docker build .` out of the sandbox. @@ -1538,11 +1305,7 @@ For example, `cd build && docker compose up` stays sandboxed under a `docker *` entry, and adding a `cd` entry doesn’t change that. Under a `git *` entry, `git clone <url> vendor/lib` runs outside the sandbox, but `git clone <url> ~/tools` stays sandboxed. A clone writes a whole tree of files, possibly executable ones, wherever its destination path points. Excluded commands still go through the regular permission flow. Exclusion is a convenience, not a security boundary: when a tool only needs to write somewhere specific, `filesystem.allowWrite` keeps it sandboxed. Entries from the settings scopes the session loads combine into one list unless the sandbox is [admin-required](</docs/en/sandboxing#repository-settings-under-an-admin-required-sandbox>). While it is, Claude Code ignores entries in `.claude/settings.json` and `.claude/settings.local.json`, so a cloned repository can’t take commands out of the sandbox. Entries in managed settings, `--settings`, and your `~/.claude/settings.json` still apply, and no managed-only lock covers this list. -### - -​ - -`sandbox.allowUnsandboxedCommands` +### `sandbox.allowUnsandboxedCommands` Let Claude retry a command outside the sandbox with the `dangerouslyDisableSandbox` parameter after the sandbox blocks it. When it’s `false`, Claude Code ignores that parameter. While the sandbox is running, commands Claude runs are then sandboxed unless they match an `excludedCommands` entry. The `/sandbox` **Overrides** tab shows that state as **Strict sandbox mode**. A `false` in managed settings turns on strict sandbox mode for the developers it covers. @@ -1565,11 +1328,7 @@ A `false` from managed settings or `--settings` also makes the sandbox [admin-required](</docs/en/sandboxing#repository-settings-under-an-admin-required-sandbox>). A `false` in your user settings holds against a project’s `true` but doesn’t make the sandbox admin-required. Holding against a project’s value requires Claude Code v2.1.285 or later. Who approves an unsandboxed retry depends on your permission mode and allow rules. See [The unsandboxed retry escape hatch](</docs/en/sandboxing#the-unsandboxed-retry-escape-hatch>). To see when commands you type yourself at the [`!` shell-mode prompt](</docs/en/interactive-mode#shell-mode-with-prefix>) run sandboxed, see [strict sandbox mode](</docs/en/sandboxing#turn-off-the-retry-with-strict-sandbox-mode>). -### - -​ - -`sandbox.filesystem` +### `sandbox.filesystem` Control which paths sandboxed commands can read and write. By default they can write to the working directory, the per-user temp directory, and directories you add with `--add-dir`, `/add-dir`, or `permissions.additionalDirectories`, and can read the rest of the filesystem, including credential files. Widen or narrow that with the four path lists, or switch the filesystem layer off with `disabled`. See [Filesystem isolation](</docs/en/sandboxing#filesystem-isolation>) for the default boundaries. @@ -1592,11 +1351,7 @@ Claude Code enforces these lists at the OS sandbox boundary, so they apply to every subprocess a sandboxed command starts, such as `kubectl`, `terraform`, or `npm`. Claude Code adds your [permission rules](</docs/en/sandboxing#permission-rules>) to the same lists: `Edit` allow and deny rules to `allowWrite` and `denyWrite`, `Read` deny rules to `denyRead`, and `WebFetch(domain:...)` allow and deny rules to the `network` domain lists. Unless a lock applies, Claude Code merges these lists across the settings files the session loads. `allowManagedReadPathsOnly` limits `allowRead` to entries from managed settings, and `allowManagedDomainsOnly` does the same for allowed domains. [Repository locks](</docs/en/sandboxing#repository-settings-under-an-admin-required-sandbox>) leave out entries from a repository’s settings files. [Configure sandboxing](</docs/en/sandboxing#configure-sandboxing>) covers sources you exclude with `--setting-sources`. When you edit a list during a session, Claude Code [applies the change to the running session](</docs/en/settings#when-edits-take-effect>). -#### - -​ - -Sandbox path prefixes +#### Sandbox path prefixes Paths in `allowWrite`, `denyWrite`, `denyRead`, `allowRead`, and `credentials.files` resolve by their prefix: @@ -1639,11 +1394,7 @@ * **Brackets such as`[user-id]` or `[post-id]`, where the hyphen’s left character sorts after its right**: `./app/[user-id]` covers only the directory with exactly that name, in every list on every platform. Before v2.1.304, sandboxed commands on Linux and WSL2 failed to start while `denyRead` or `allowRead` held such an entry. * **Braces and parentheses** : these are ordinary characters, so `~/data/{keys,tokens}` covers one directory named `{keys,tokens}`, not two alternatives. To cover `~/data/keys` and `~/data/tokens`, add each as its own entry. -### - -​ - -`sandbox.filesystem.allowWrite` +### `sandbox.filesystem.allowWrite` Add paths where sandboxed commands can write, beyond the working directory, the per-user temp directory, and the directories you’ve added with `--add-dir`, `/add-dir`, or `permissions.additionalDirectories`. Use it when a subprocess such as `kubectl` or a build tool needs to write outside the project. @@ -1663,13 +1414,9 @@ } } -Claude Code merges `allowWrite` entries and the paths from your `Edit(...)` allow permission rules across the settings scopes the session loads, leaving out the ones from repository settings while `permissions.blockReadsOutsideWorkingDirectories` is on. [Repository locks](</docs/en/sandboxing#repository-settings-under-an-admin-required-sandbox>) can leave out a repository’s entries too. An `allowWrite` entry can’t lift a [protected path](</docs/en/sandboxing#protected-paths>). - -### - -​ - -`sandbox.filesystem.denyWrite` +On Linux and WSL2, an entry for a path that doesn’t exist yet has no effect, so create the path first. Claude Code merges `allowWrite` entries and the paths from your `Edit(...)` allow permission rules across the settings scopes the session loads, leaving out the ones from repository settings while `permissions.blockReadsOutsideWorkingDirectories` is on. [Repository locks](</docs/en/sandboxing#repository-settings-under-an-admin-required-sandbox>) can leave out a repository’s entries too. An `allowWrite` entry can’t lift a [protected path](</docs/en/sandboxing#protected-paths>). + +### `sandbox.filesystem.denyWrite` Block sandboxed commands from writing to specific paths, including paths inside a directory that is otherwise writable. @@ -1691,11 +1438,7 @@ Claude Code merges entries across every settings scope the session loads, and adds the paths from your `Edit(...)` deny permission rules. -### - -​ - -`sandbox.filesystem.denyRead` +### `sandbox.filesystem.denyRead` Block sandboxed commands from reading specific paths, such as credential files that the default read policy would otherwise expose. To protect a credential file and keep it usable through the sandbox proxy, see `sandbox.credentials` instead. @@ -1715,11 +1458,7 @@ Claude Code merges entries across every settings scope the session loads, and adds the paths from your `Read(...)` deny permission rules. When `filesystem.disabled` is `true`, Claude Code doesn’t enforce these entries. -### - -​ - -`sandbox.filesystem.allowRead` +### `sandbox.filesystem.allowRead` Re-open reading for specific paths inside a region that `denyRead` blocks, to build workspace-only read access. An exact or wildcard `denyRead` entry stays blocked inside a broader `allowRead`, as the [overlap table](</docs/en/sandboxing#configure-sandboxing>) shows. When a wildcard `denyRead` entry such as `~/**/.env` matches a directory, Claude Code blocks reads of its contents as well. Before v2.1.236 on macOS, Claude Code re-opened the paths a wildcard `denyRead` entry matched wherever a broader `allowRead` entry covered them, and left a matched directory’s contents readable. @@ -1742,11 +1481,7 @@ Claude Code resolves a `.` entry to the project root in project settings and to `~/.claude` in user settings. Claude Code merges entries across the settings files the session loads unless `allowManagedReadPathsOnly` is set, and leaves out entries from repository settings while `permissions.blockReadsOutsideWorkingDirectories` is on. [Repository locks](</docs/en/sandboxing#repository-settings-under-an-admin-required-sandbox>) can leave out a repository’s entries too. -### - -​ - -`sandbox.filesystem.allowManagedReadPathsOnly` +### `sandbox.filesystem.allowManagedReadPathsOnly` Honor only the `allowRead` entries that come from managed settings, so developers can’t re-open read access to paths your organization blocked. Claude Code still merges `denyRead` entries from every settings scope the session loads. @@ -1772,11 +1507,7 @@ See [Keep developers from widening the policy](</docs/en/sandboxing#keep-developers-from-widening-the-policy>). -### - -​ - -`sandbox.filesystem.disabled` +### `sandbox.filesystem.disabled` Skip filesystem isolation while keeping network isolation. Sandboxed commands get unrestricted read and write access to the host filesystem, and their network egress stays confined to `network.allowedDomains`. Use it when you sandbox to control where commands connect rather than what they write. @@ -1804,11 +1535,7 @@ With the layer off, Claude Code doesn’t enforce `denyRead` or `credentials.files` `deny` entries, while `credentials.envVars` entries and applied `mask` entries keep working. `autoAllowBashIfSandboxed` still defaults to `true`, so set it to `false` to keep prompting. See [Disable filesystem isolation](</docs/en/sandboxing#disable-filesystem-isolation>) for the full list of sources that can set it and what changes when isolation is off. -### - -​ - -`sandbox.ignoreViolations` +### `sandbox.ignoreViolations` Silence sandbox violation reports for paths you expect a command to probe and be refused, such as a tool that checks `/etc/hosts` on startup, so those denials don’t show up as violations or in what Claude sees. The sandbox still blocks the access; only the report is suppressed. Keys are substrings to match against the command, with `*` matching every command, and values are substrings of the violation to ignore for that command, such as a filesystem path. @@ -1826,11 +1553,7 @@ } } -### - -​ - -`sandbox.enableWeakerNestedSandbox` +### `sandbox.enableWeakerNestedSandbox` Run the Linux sandbox inside an unprivileged Docker container, where bubblewrap can’t mount a fresh `/proc`. Instead the inner sandbox bind-mounts the container’s existing `/proc`, which exposes process information that a fresh mount would hide. This reduces security; use it only when the outer container already provides the isolation you need. @@ -1851,11 +1574,7 @@ Linux and WSL2 only. See [Bubblewrap fails to start inside a container](</docs/en/sandboxing#bubblewrap-fails-to-start-inside-a-container>). -### - -​ - -`sandbox.enableWeakerNetworkIsolation` +### `sandbox.enableWeakerNetworkIsolation` Let sandboxed commands on macOS reach the system TLS trust service, `com.apple.trustd.agent`. Go-based tools such as `gh`, `gcloud`, and `terraform` need it to verify TLS certificates when you use `network.httpProxyPort` with a MITM proxy and a custom CA. This reduces security by opening a potential data exfiltration path through the trust service. @@ -1876,11 +1595,7 @@ If you don’t use a MITM proxy, list the failing tools in `excludedCommands` instead; see [Go-based CLIs fail TLS verification on macOS](</docs/en/sandboxing#go-based-clis-fail-tls-verification-on-macos>). -### - -​ - -`sandbox.allowAppleEvents` +### `sandbox.allowAppleEvents` Let sandboxed commands on macOS send Apple Events, which `open`, `osascript`, and tools that open URLs in a browser need; without it they fail with error `-600`. This removes code-execution isolation: sandboxed commands can launch other applications unsandboxed with no user prompt, and can send AppleScript commands to running applications such as Terminal, subject to the per-app macOS automation-consent prompt (TCC). @@ -1901,11 +1616,7 @@ To keep isolation and still run one such tool, add it to `excludedCommands` instead. See [Apple Events on macOS](</docs/en/sandboxing#security-limitations>). -### - -​ - -`sandbox.allowNestedUserNamespaces` +### `sandbox.allowNestedUserNamespaces` Let sandboxed commands on Linux and WSL2 create user namespaces, which Chromium’s and Electron’s own sandbox, a nested bubblewrap, and `unshare` need. If you set this key to `true`, you turn off a security boundary: code from a sandboxed command can end up running outside the sandbox. For rootless Podman or Buildah, use `excludedCommands` instead, because the sandbox stops them in other ways too. Requires Claude Code v2.1.305 or later. @@ -1926,11 +1637,7 @@ With this key on, don’t rely on any of the sandbox’s restrictions, including [protected paths](</docs/en/sandboxing#protected-paths>) and `credentials.files` entries, to stop a malicious command. In [auto-allow mode](</docs/en/sandboxing#auto-allow-mode>), that command can run without a permission prompt. If your organization has a security team, check with them before you turn the key on. To find the fix for your tool, see [Chromium or rootless Podman fails inside the sandbox on Linux](</docs/en/sandboxing#chromium-or-rootless-podman-fails-inside-the-sandbox-on-linux>). -### - -​ - -`sandbox.ripgrep` +### `sandbox.ripgrep` Point the sandbox at a ripgrep binary of your own instead of the one Claude Code uses, for example when your platform needs a differently built `rg`. @@ -1948,11 +1655,7 @@ } } -### - -​ - -`sandbox.bwrapPath` +### `sandbox.bwrapPath` Point the sandbox at a bubblewrap binary installed outside `PATH`, such as a vendored copy on an air-gapped host. Claude Code uses the path both for the startup dependency check and when it wraps each sandboxed command. @@ -1971,11 +1674,7 @@ Linux and WSL2 only. -### - -​ - -`sandbox.socatPath` +### `sandbox.socatPath` Point the sandbox network proxy at a `socat` binary installed outside `PATH`. @@ -1994,11 +1693,7 @@ Linux and WSL2 only. -### - -​ - -`sandbox.credentials` +### `sandbox.credentials` Declare the credential files and environment variables to [protect from sandboxed commands](</docs/en/sandboxing#protect-credentials>). Each entry names a file `path` or a variable `name` and a `mode`: `deny` hides the credential inside the sandbox, and `mask` shows sandboxed commands a placeholder while the [sandbox proxy](</docs/en/sandboxing#mask-credentials>) substitutes the real value on outbound requests. Claude Code protects only the entries you list; there is no built-in credential deny list. @@ -2021,11 +1716,7 @@ The `deny` file protection is part of the filesystem layer, so it doesn’t apply when you [disable filesystem isolation](</docs/en/sandboxing#disable-filesystem-isolation>); the environment variable protection still does. -#### - -​ - -Invalid credential entries in managed settings +#### Invalid credential entries in managed settings When a managed `sandbox.credentials` entry fails validation, Claude Code keeps protecting the credential where it can: @@ -2035,11 +1726,7 @@ Applies in v2.1.191 and later; before v2.1.221, every invalid entry was stripped. For the other managed keys with per-field handling, see [Invalid entries in managed settings](</docs/en/managed-settings#invalid-entries-in-managed-settings>). -### - -​ - -`sandbox.credentials.files` +### `sandbox.credentials.files` Protect credential files or directories from sandboxed commands. With `"mode": "deny"`, Claude Code blocks reads of the path inside the sandbox, the same read block as `sandbox.filesystem.denyRead`. With `"mode": "mask"`, sandboxed commands on Linux and WSL2 read a sentinel copy of the file, and the sandbox proxy substitutes the real value on outbound requests to that entry’s `injectHosts`; on macOS the file is unreadable inside the sandbox instead. `"mode": "mask"` requires Claude Code v2.1.221 or later. @@ -2064,11 +1751,7 @@ Paths use the same prefixes as the `sandbox.filesystem.*` settings, and Claude Code merges the arrays from every settings scope the session loads. [Protect credentials](</docs/en/sandboxing#protect-credentials>) covers what still applies from sources you exclude with `--setting-sources`. `mask` entries require Claude Code v2.1.221 or later. `mask` substitution runs only through the sandbox proxy, so set `sandbox.network.tlsTerminate`, or `allowPlaintextInject` for plain-HTTP test networks. `mask` applies to a single file, so list each credential file individually. Claude Code accepts but ignores the `mask` fields on a `deny` entry. [Mask credentials](</docs/en/sandboxing#mask-credentials>) covers which settings sources are honored, and [Mask credential files](</docs/en/sandboxing#mask-credential-files>) covers when an entry falls back to `deny`. -#### - -​ - -Mask fields for files +#### Mask fields for files A `mask` entry accepts these optional fields. Without `extract` or `decode`, Claude Code replaces the entire file content with one sentinel. On macOS with filesystem isolation on, Claude Code applies a `mask` entry as `deny` before `extract` or `decode` runs; see [Mask credential files](</docs/en/sandboxing#mask-credential-files>). @@ -2102,11 +1785,7 @@ } } -### - -​ - -`sandbox.credentials.envVars` +### `sandbox.credentials.envVars` Protect environment variables from sandboxed commands. With `"mode": "deny"`, Claude Code removes the variable from the environment of sandboxed commands. With `"mode": "mask"`, sandboxed commands see a per-session sentinel value, and the sandbox proxy substitutes the real value on outbound requests to that entry’s `injectHosts`, so tools such as `gh` and `npm` keep authenticating without ever holding the real credential. @@ -2131,11 +1810,7 @@ The `name` must start with a letter or underscore and contain only letters, digits, and underscores. Claude Code merges the arrays from every settings scope the session loads, and applies `deny` when the same variable appears with both modes. [Protect credentials](</docs/en/sandboxing#protect-credentials>) covers what still applies from sources you exclude with `--setting-sources`. `mask` substitution runs only through the sandbox proxy, so set `sandbox.network.tlsTerminate`, or `allowPlaintextInject` for plain-HTTP test networks; see [Mask credentials](</docs/en/sandboxing#mask-credentials>). Claude Code accepts but ignores the `mask` fields on a `deny` entry. -#### - -​ - -Mask fields for environment variables +#### Mask fields for environment variables A `mask` entry accepts these optional fields. Without `extract` or `decode`, Claude Code replaces the entire value with one sentinel. `extract` and `decode` can’t be combined on the same entry. @@ -2172,11 +1847,7 @@ } } -### - -​ - -`sandbox.credentials.allowPlaintextInject` +### `sandbox.credentials.allowPlaintextInject` Allow `mask` substitution on plain HTTP requests as well as TLS-terminated HTTPS. On plain HTTP the upstream identity is unverified and the credential travels in cleartext, so leave this off outside trusted test networks. @@ -2196,11 +1867,7 @@ } } -### - -​ - -`sandbox.credentials.awsPairs` +### `sandbox.credentials.awsPairs` Group masked environment variables that form one AWS credential for [SigV4 re-signing](</docs/en/sandboxing#re-sign-aws-requests>) when your credential lives in variables with non-standard names. Claude Code links the conventional `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_SESSION_TOKEN` trio automatically when you mask their whole values, so you need this key only for other names. Requires Claude Code v2.1.224 or later. @@ -2232,11 +1899,7 @@ * When `sessionTokenVar` is set, the proxy sends the real token as `x-amz-security-token` on re-signed requests * Naming any of the conventional variables in a pair replaces the automatic pairing -### - -​ - -`sandbox.credentials.sigv4` +### `sandbox.credentials.sigv4` Choose what the sandbox proxy does with AWS request forms it [can’t re-sign](</docs/en/sandboxing#re-sign-aws-requests>): `streaming` for aws-chunked streaming uploads, `presigned` for presigned URLs, and `sigv4a` for SigV4A asymmetric signatures. This applies only to requests signed with a masked pair’s placeholder access key ID. Requires Claude Code v2.1.224 or later. @@ -2262,11 +1925,7 @@ With `deny`, the proxy fails the request. With `passthrough`, the proxy forwards the request with its signature computed from the masked placeholder, so AWS rejects it and the calling tool receives AWS’s own response instead of a proxy error. -### - -​ - -`sandbox.network` +### `sandbox.network` Control which hosts, ports, and sockets sandboxed commands can reach. The sandbox routes outbound traffic through a proxy that enforces these lists; see [Network isolation](</docs/en/sandboxing#network-isolation>) for how the proxy decides and when it prompts. @@ -2290,11 +1949,7 @@ Claude Code merges the array sub-keys across settings scopes, so a project can add domains to your user list unless a [repository lock](</docs/en/sandboxing#repository-settings-under-an-admin-required-sandbox>) applies. `WebFetch(domain:...)` allow and deny [permission rules](</docs/en/sandboxing#permission-rules>) feed the same allow and deny lists. -### - -​ - -`sandbox.network.allowUnixSockets` +### `sandbox.network.allowUnixSockets` List the Unix socket paths sandboxed commands can connect to on macOS. Claude Code ignores this list on Linux and WSL2, where the seccomp filter can’t inspect socket paths; use `allowAllUnixSockets` there instead. @@ -2314,11 +1969,7 @@ A socket path can grant broad access: allowing `/var/run/docker.sock`, for example, lets a sandboxed command control the Docker daemon. See [Security limitations](</docs/en/sandboxing#security-limitations>). -### - -​ - -`sandbox.network.allowAllUnixSockets` +### `sandbox.network.allowAllUnixSockets` Let sandboxed commands connect to every Unix socket. On Linux and WSL2, the sandbox’s [seccomp filter](</docs/en/sandboxing#set-up-linux-and-wsl2>) blocks `socket(AF_UNIX, ...)` calls, so this is the only way to permit Unix sockets there. When the filter is missing, which `/sandbox` reports on its Dependencies tab, the sandbox doesn’t block Unix-socket calls. See [Set up Linux and WSL2](</docs/en/sandboxing#set-up-linux-and-wsl2>) for where the filter comes from. @@ -2340,11 +1991,7 @@ On WSL2, `true` also reopens the interop socket that launches Windows binaries such as `cmd.exe` and `powershell.exe`. -### - -​ - -`sandbox.network.allowLocalBinding` +### `sandbox.network.allowLocalBinding` Let sandboxed commands on macOS listen on network ports, for example to start a dev server, and connect to any port on localhost. A command that listens on a non-loopback address accepts connections from other machines. The key has no effect on Linux and WSL2, where each sandboxed command has its own loopback interface. To reach a server on the host from Linux or WSL2, see [A command fails to reach a server on localhost](</docs/en/sandboxing#a-command-fails-to-reach-a-server-on-localhost>). @@ -2364,11 +2011,7 @@ } } -### - -​ - -`sandbox.network.allowMachLookup` +### `sandbox.network.allowMachLookup` List additional XPC and Mach service names the macOS sandbox may look up. Tools that communicate over XPC, such as the iOS Simulator or Playwright, need their services listed here. Sandboxed commands can reach outside the sandbox to each service that you list, and the sandbox [doesn’t confine what those services do for those commands](</docs/en/sandboxing#security-limitations>). @@ -2388,11 +2031,7 @@ } } -### - -​ - -`sandbox.network.allowedDomains` +### `sandbox.network.allowedDomains` Pre-allow domains for outbound traffic from sandboxed commands, so the sandbox doesn’t prompt for them. Wildcards such as `*.example.com` match subdomains, and an optional `:port` suffix limits an entry to one port; an entry without a port matches every port. @@ -2414,11 +2053,7 @@ Write IPv6 literals bracketed, with an optional port: `"[::1]"` allows every port and `"[::1]:443"` one port. The bracketed form requires Claude Code v2.1.229 or later. See [IPv6 addresses in domain lists](</docs/en/sandboxing#ipv6-addresses-in-domain-lists>). -### - -​ - -`sandbox.network.deniedDomains` +### `sandbox.network.deniedDomains` Block domains for outbound traffic from sandboxed commands, using the same wildcard, port, and IPv6 syntax as `allowedDomains`. A denied domain stays blocked even when an `allowedDomains` entry matches it too. @@ -2438,11 +2073,7 @@ Claude Code merges this list from every settings source the session loads even when `allowManagedDomainsOnly` is set, so a developer can always tighten the deny list. For IPv6 literals, see [IPv6 addresses in domain lists](</docs/en/sandboxing#ipv6-addresses-in-domain-lists>). An entry written with the trailing dot that marks a fully qualified domain name, such as `example.com.`, blocks the same connections as `example.com`. -### - -​ - -`sandbox.network.strictAllowlist` +### `sandbox.network.strictAllowlist` Deny sandboxed commands access to hosts outside the allowlist instead of prompting for approval. The allowlist is `allowedDomains` plus domains from `WebFetch(domain:...)` allow rules, or only the managed settings entries when `allowManagedDomainsOnly` is set. [Locks that apply without an admin-required sandbox](</docs/en/sandboxing#locks-that-apply-without-an-admin-required-sandbox>) covers a repository’s entries. Requires Claude Code v2.1.219 or later. @@ -2464,11 +2095,7 @@ Claude Code enforces this for sandboxed commands only; in-process tools such as `WebFetch` still follow their [permission rules](</docs/en/sandboxing#permission-rules>). When any of the honored sources sets it to `true`, it stays on. See [Network isolation](</docs/en/sandboxing#network-isolation>). Requires Claude Code v2.1.219 or later. -### - -​ - -`sandbox.network.allowManagedDomainsOnly` +### `sandbox.network.allowManagedDomainsOnly` Lock the network allowlist to what managed settings define. Claude Code then honors only `allowedDomains` and `WebFetch(domain:...)` allow rules from managed settings, ignores domains from user, project, local, and `--settings` settings, and blocks a non-allowed domain automatically instead of prompting. @@ -2493,11 +2120,7 @@ While the key is `true`, the sandbox is [admin-required](</docs/en/sandboxing#repository-settings-under-an-admin-required-sandbox>), and only managed settings can set a proxy port. Denied domains still merge from every source the session loads. See [Keep developers from widening the policy](</docs/en/sandboxing#keep-developers-from-widening-the-policy>). -### - -​ - -`sandbox.network.httpProxyPort` +### `sandbox.network.httpProxyPort` Point the sandbox at your own HTTP proxy instead of the one Claude Code runs. Organizations do this to inspect HTTPS traffic, apply their own filtering rules, or log requests. Your proxy takes over filtering, and Claude Code stops applying its domain lists and network prompts to traffic sent there. When unset, Claude Code starts its own proxy for HTTP traffic. @@ -2517,11 +2140,7 @@ Set `socksProxyPort` too if your proxy should carry SOCKS traffic as well; with only one of the two set, Claude Code still runs its own proxy for the other protocol. See [Custom proxy configuration](</docs/en/sandboxing#custom-proxy-configuration>). -### - -​ - -`sandbox.network.socksProxyPort` +### `sandbox.network.socksProxyPort` Point the sandbox at your own SOCKS5 proxy instead of the one Claude Code runs. Your proxy takes over filtering, and Claude Code stops applying its domain lists and network prompts to traffic sent there. When unset, Claude Code starts its own proxy for SOCKS traffic. @@ -2541,11 +2160,7 @@ See [Custom proxy configuration](</docs/en/sandboxing#custom-proxy-configuration>). -### - -​ - -`sandbox.network.tlsTerminate` +### `sandbox.network.tlsTerminate` Make the sandbox proxy terminate TLS so it can read the contents of HTTPS requests. This is experimental, and `mask` [credential substitution](</docs/en/sandboxing#mask-credentials>) requires it. Set `{}` to generate an ephemeral certificate authority for the session, or set `caCertPath` and `caKeyPath` to use your own. @@ -2565,19 +2180,11 @@ When more than one honored source sets it, Claude Code uses the value from the highest-precedence source: managed settings, then the `--settings` flag, then user settings. -## - -​ - -Memory and context +## Memory and context Control what Claude Code loads into context, how it compacts, and where it keeps memory and plans. See [Manage context](</docs/en/context-window>) and [Memory](</docs/en/memory>). -### - -​ - -`autoCompactEnabled` +### `autoCompactEnabled` Have Claude Code [compact the conversation automatically](</docs/en/context-window#when-your-context-fills-up>) when context approaches the limit. Appears in `/config` as **Auto-compact** , and toggling it there writes this key to your user settings. @@ -2596,11 +2203,7 @@ The manual `/compact` command keeps working while auto-compact is off. If you turn auto-compact off, idle compaction turns off too. -### - -​ - -`autoCompactWindow` +### `autoCompactWindow` Set how full the context window gets before Claude Code [compacts automatically](</docs/en/context-window#when-your-context-fills-up>). @@ -2617,11 +2220,7 @@ The [`/autocompact`](</docs/en/commands#all-commands>) command saves a window for the current model under `modelSettings`, which takes precedence over this key in the same file for that model. [Set the auto-compact window](</docs/en/model-config#set-the-auto-compact-window>) covers how the command, flag, variable, and setting interact. -### - -​ - -`autoMemoryDirectory` +### `autoMemoryDirectory` Store [auto memory](</docs/en/memory#storage-location>) in a directory of your choice instead of the per-project default. @@ -2637,11 +2236,7 @@ From project or local settings, Claude Code honors this key under the same [workspace trust rule as hooks](</docs/en/permissions#what-runs-before-you-trust-a-folder>), since a cloned repository can supply those files. -### - -​ - -`autoMemoryEnabled` +### `autoMemoryEnabled` Turn [auto memory](</docs/en/memory#enable-or-disable-auto-memory>) on or off. When `false`, Claude doesn’t read from or write to the auto memory directory. You can also toggle it with `/memory` during a session, which writes this key to your user settings. @@ -2658,11 +2253,7 @@ "autoMemoryEnabled": false } -### - -​ - -`bashOutputMaxChars` +### `bashOutputMaxChars` Set how many characters of a successful Bash or PowerShell command’s [output Claude receives inline](</docs/en/tools-reference#output-limits>). When output passes the limit, Claude Code saves it to a file and Claude receives a short preview plus the file’s path. Raise the limit when command output, such as a verbose build or a full test-suite log, routinely overflows the default and you want Claude to read it without opening the file. Requires Claude Code v2.1.261 or later. @@ -2678,11 +2269,7 @@ When you set this key, Claude Code ignores the [`BASH_MAX_OUTPUT_LENGTH`](</docs/en/env-vars>) environment variable. -### - -​ - -`claudeMd` +### `claudeMd` Inject CLAUDE.md-style instructions as organization-managed memory without deploying a separate file. Claude Code loads the text as a managed memory entry ahead of user and project CLAUDE.md files. @@ -2700,11 +2287,7 @@ See [Deploy organization-wide CLAUDE.md](</docs/en/memory#deploy-organization-wide-claude-md>). -### - -​ - -`claudeMdExcludes` +### `claudeMdExcludes` Skip specific `CLAUDE.md` files when Claude Code loads [memory](</docs/en/memory#exclude-specific-claude-md-files>). In a large monorepo, use it to skip CLAUDE.md files from other teams that aren’t relevant to your work; [Exclude irrelevant CLAUDE.md files](</docs/en/large-codebases#exclude-irrelevant-claude-md-files>) in the large-codebases guide walks through that case. Patterns match against absolute file paths. @@ -2720,11 +2303,7 @@ Exclusions apply only to user, project, and local memory files; managed policy CLAUDE.md files can’t be excluded. -### - -​ - -`env` +### `env` Set environment variables for every session and for the subprocesses Claude Code starts from it. Most variables in the [environment variables reference](</docs/en/env-vars>) can go here, which is how you apply one to every session or roll it out to your team. Project and local settings can’t set some of them. @@ -2743,11 +2322,7 @@ } } -#### - -​ - -How `env` values interact with your shell +#### How `env` values interact with your shell * A value here overwrites the same variable exported in your shell, and when more than one settings file sets a variable, the [highest-precedence](</docs/en/settings#settings-precedence>) one applies. Variables Claude Code ignores in `env` lists the exceptions for project and local settings. * When the Claude Desktop app or a [self-hosted environment](</docs/en/self-hosted-environments>) runner starts the session, the launch environment it builds takes precedence instead: Claude Code ignores an `env` value from any settings file for a variable the launch environment already sets. The [debug log](</docs/en/debug-your-config>) names each ignored variable. @@ -2755,22 +2330,14 @@ * `NO_COLOR` and `FORCE_COLOR` set here reach only subprocesses. To change Claude Code’s own interface colors, set them in your shell before launching `claude`. * Values here are plain text in the settings file and reach every subprocess Claude Code starts. For an OTLP bearer token that rotates, use `otelHeadersHelper`; for API credentials, use `apiKeyHelper`. -#### - -​ - -When Claude Code applies `env` values +#### When Claude Code applies `env` values * From user settings, `--settings`, and managed settings: at startup, and again in the running session when a saved change alters the merged `env`. * From project and local settings: after you trust the workspace, or at startup in `-p` mode, which never shows the trust dialog, and again when a saved change alters the merged `env`. * Variables Claude Code classifies as safe, such as model selection, timeouts and limits, and feature toggles: at startup from every settings file, apart from the variables project and local settings can’t set. * After you [move the session with `/cd`](</docs/en/permissions#move-the-session-to-another-directory>) on v2.1.246 or later: the new directory’s project and local `env` values, on top of the previous directory’s. -#### - -​ - -Variables Claude Code ignores in `env` +#### Variables Claude Code ignores in `env` * Project and local settings can’t set variables that a checked-out repository shouldn’t control; set those in your shell, user settings, or managed settings instead. Claude Code drops each one, apart from a few values that turn telemetry off, and logs a warning you can see with `claude --debug`. They include: * Variables that choose where Claude Code stores or writes its own files: `CLAUDE_CONFIG_DIR`, `CLAUDE_CODE_TMPDIR`, and the operating-system directory variables such as `HOME`, `TMPDIR`, `TMP`, `TEMP`, and the `XDG_*` family. @@ -2799,11 +2366,7 @@ * [`CLAUDE_CODE_EVEN_MORE_DANGEROUSLY_SKIP_PERMISSIONS`](</docs/en/env-vars#variables>), which Claude Code reads from the launch environment only, is ignored from every file. * [`CLAUDE_CODE_WARN_DISK_FREE_GIB` and `CLAUDE_CODE_WARN_MEMORY_FREE_GIB`](</docs/en/env-vars#variables>), which Claude Code reads from the launch environment only, are ignored from every file. The variables require Claude Code v2.1.304 or later. -### - -​ - -`fileCheckpointingEnabled` +### `fileCheckpointingEnabled` Have Claude Code snapshot files before each edit so [`/rewind`](</docs/en/checkpointing>) can restore them. Appears in `/config` as **Rewind code (checkpoints)** , and toggling it there writes this key to your user settings. @@ -2822,11 +2385,7 @@ In a `-p` run or an Agent SDK session, Claude Code ignores this key. The SDK turns checkpointing on with its `enableFileCheckpointing` option, and a bare `-p` run needs `CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING=true`. See [File checkpointing in the Agent SDK](</docs/en/agent-sdk/file-checkpointing>). -### - -​ - -`idleCompaction` +### `idleCompaction` Idle compaction [compacts](</docs/en/context-window#what-survives-compaction>) a long conversation that you’ve stepped away from. Your next message then sends a summary instead of the whole conversation. Once compacted, the conversation shows a notice: @@ -2864,11 +2423,7 @@ The key requires Claude Code v2.1.290 or later. On an earlier version, which ignores this key, turn off `autoCompactEnabled` to stop idle compaction. -#### - -​ - -Change the idle compaction threshold +#### Change the idle compaction threshold Set [`CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS`](</docs/en/env-vars>) to the number of tokens a conversation’s context must reach before idle compaction applies to it. Use a positive whole number. Values below `100000` are raised to `100000`, the lowest threshold. At the default, a conversation on a 200K context window auto-compacts before it reaches 200,000 tokens. This example lowers the threshold to 150,000 so that those conversations qualify: @@ -2880,11 +2435,7 @@ } } -#### - -​ - -Idle compaction in VS Code and the desktop app +#### Idle compaction in VS Code and the desktop app A notice like this one means Claude Code [replaced your earlier conversation with a summary](</docs/en/context-window#what-survives-compaction>) that Claude now works from: @@ -2892,11 +2443,7 @@ You don’t need to do anything. To turn idle compaction off, set `idleCompaction` to `false` in `~/.claude/settings.json` on the machine or WSL distribution where the session runs, or in another [settings file](</docs/en/settings#settings-files-and-who-they-affect>). -### - -​ - -`plansDirectory` +### `plansDirectory` Choose where Claude Code stores the plan files it writes in [plan mode](</docs/en/permission-modes#analyze-before-you-edit-with-plan-mode>). Claude Code resolves the path relative to the project root. @@ -2915,11 +2462,7 @@ * **Outside the project root** : the path resolves outside the project root, as `"../plans"` does. * **Backslash on macOS, Linux, and WSL** : the resolved path contains a backslash, as the Windows-style `"docs\\plans"` does. Write `"docs/plans"`, which works on Windows too. -### - -​ - -`skillListingBudgetFraction` +### `skillListingBudgetFraction` Each turn, Claude sees a [listing of your skills](</docs/en/skills#skill-descriptions-are-cut-short>) with their descriptions, and Claude Code caps that listing at a share of the context window. When the listing is over the cap, Claude Code keeps every skill’s name but drops the descriptions of the least-used skills, so Claude can still invoke those skills but is less likely to choose one on its own. Raise this key to keep more descriptions visible at the cost of more context per turn. @@ -2935,11 +2478,7 @@ To see how much context the listing uses and which skills contribute most, run `/doctor`. -### - -​ - -`skillListingMaxDescChars` +### `skillListingMaxDescChars` Each turn, Claude sees a [listing of your skills](</docs/en/skills#skill-descriptions-are-cut-short>) that shows each skill’s `description` and `when_to_use` text. This key caps how many characters of that text Claude Code shows per skill; longer text is cut at the cap. @@ -2955,29 +2494,17 @@ Raise it to keep long descriptions intact at the cost of more context per turn; lower it to fit more skills under `skillListingBudgetFraction`. -### - -​ - -`taskOutputMaxChars` +### `taskOutputMaxChars` Removed in v2.1.277, together with the `TaskOutput` tool it sized. Setting it has no effect on current versions. Claude reads a background task’s [output file](</docs/en/tools-reference#background-commands>) with `Read` instead. Through v2.1.276, you set this key to the number of characters of a [background task’s](</docs/en/tools-reference#background-commands>) output that Claude received inline when it read the task with the `TaskOutput` tool. -## - -​ - -Interface and terminal +## Interface and terminal Change how Claude Code looks and behaves in your terminal: theme, editor mode, status line, spinner, notifications inside the session, and accessibility. See [Terminal configuration](</docs/en/terminal-config>). -### - -​ - -`askUserQuestionTimeout` +### `askUserQuestionTimeout` Let an unanswered [`AskUserQuestion`](</docs/en/tools-reference>) dialog auto-continue after a period of idle time, submitting whatever options you had already selected. Set it when you step away and want Claude to continue without you. With the default, questions wait until you answer them. For when the timer pauses or never starts, see [Question auto-continue timeout](</docs/en/tools-reference#question-auto-continue-timeout>). @@ -2993,11 +2520,7 @@ Appears in `/config` as **Question auto-continue timeout** , which writes this key to user settings; Claude Code hides the row while managed settings or the `--settings` flag set the key. -### - -​ - -`autoContinueAtUsageLimit` +### `autoContinueAtUsageLimit` After a claude.ai usage limit stops your session, wait in the open session and continue the task automatically after the reset. See [Turn automatic continue off](</docs/en/interactive-mode#turn-automatic-continue-off>). Requires Claude Code v2.1.234 or later. @@ -3015,11 +2538,7 @@ Appears in `/config` as **Continue automatically at usage limit** , which writes this key to user settings; Claude Code hides the row while managed settings or the `--settings` flag set the key. -### - -​ - -`autoScrollEnabled` +### `autoScrollEnabled` Follow new output to the bottom of the conversation in [fullscreen rendering](</docs/en/fullscreen>). Turn it off to stay where you scrolled while Claude keeps working; permission prompts still scroll into view. @@ -3037,11 +2556,7 @@ Appears in `/config` as **Auto-scroll** when fullscreen rendering is on, which writes this key to user settings. -### - -​ - -`axScreenReader` +### `axScreenReader` Render screen-reader friendly output: flat text without decorative borders or animations. Screen-reader mode uses the classic renderer, so the `tui` setting has no effect while it is active; attached [background sessions](</docs/en/agent-view>) still render fullscreen. @@ -3058,11 +2573,7 @@ "axScreenReader": true } -### - -​ - -`bashEditDiffEnabled` +### `bashEditDiffEnabled` Choose whether Claude Code records which files changed in a Git repository while a Bash command runs. When it records them, you see their diff in the terminal after the command, and your [PostToolUse Bash hooks](</docs/en/hooks#bash>) receive the changed-file list. A listed file isn’t always one the command changed. A change that another program or another Bash call made while the command ran can appear there too. Set the key to `true` to record them in every permission mode. Requires Claude Code v2.1.269 or later. @@ -3077,11 +2588,7 @@ "bashEditDiffEnabled": true } -### - -​ - -`companyAnnouncements` +### `companyAnnouncements` Show your organization’s announcements to users at startup. When you list more than one, Claude Code picks one at random for each session; on a person’s very first launch it shows the first entry. @@ -3097,11 +2604,7 @@ ] } -### - -​ - -`defaultShell` +### `defaultShell` Choose whether Bash or PowerShell runs the shell commands you type with the [`!` prefix](</docs/en/interactive-mode#shell-mode-with-prefix>) in the input box, the ones Claude Code runs directly and adds to the session. `"powershell"` works only while the [PowerShell tool](</docs/en/tools-reference#powershell-tool>) is on. The tool is on by default on Windows without Git Bash, and on Windows with Git Bash for claude.ai and Console accounts. In Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry sessions, and on macOS, Linux, and WSL, set `CLAUDE_CODE_USE_POWERSHELL_TOOL=1` to turn the tool on. Set that variable to `0` to turn the tool off. @@ -3119,11 +2622,7 @@ If the shell you name isn’t available, Claude Code uses the other one: `"powershell"` falls back to Bash when the PowerShell tool is off, and `"bash"` falls back to PowerShell when Bash isn’t installed. -### - -​ - -`dialogExpiry` +### `dialogExpiry` Set the deadline for dialogs Claude Code [forwards to a remote client](</docs/en/remote-control#limitations>), such as a Remote Control or SDK host, and for the approval dialog for a [held cross-session message](</docs/en/cross-session-messaging#control-inbound-messages>). On Claude Code v2.1.236 or later, the same deadline bounds the mid-session [Fable usage-credits consent prompt](</docs/en/model-config#fable-and-usage-credits>) in a session that may have nobody at the terminal. When no answer arrives before the deadline, Claude Code cancels the dialog and continues with its no-action default. Requires Claude Code v2.1.224 or later. @@ -3140,11 +2639,7 @@ Permission prompts and [`AskUserQuestion`](</docs/en/tools-reference#askuserquestion-tool-behavior>) questions use their own flows and aren’t governed by this deadline. Appears in `/config` as **Dialog expiry** , which writes this key to user settings; the row requires Claude Code v2.1.232 or later, and Claude Code hides it while managed settings or the `--settings` flag set the key. -### - -​ - -`editorMode` +### `editorMode` Choose the key binding mode for the input prompt. @@ -3162,11 +2657,7 @@ Appears in `/config` as **Editor mode** , which writes this key to user settings. -### - -​ - -`emojiCompletionEnabled` +### `emojiCompletionEnabled` Show emoji suggestions when you type `:` plus a shortcode in the prompt input, and replace a completed shortcode such as `:heart:` with its emoji. Set it to `false` to turn off both. @@ -3184,11 +2675,7 @@ See [Emoji shortcodes](</docs/en/interactive-mode#emoji-shortcodes>). -### - -​ - -`fileSuggestion` +### `fileSuggestion` Run your own command to supply `@` file path autocomplete instead of the built-in file suggestion. The built-in suggestion uses fast filesystem traversal; a large monorepo may do better with project-specific indexing such as a pre-built file index. @@ -3207,11 +2694,7 @@ After you save this, type `@` followed by part of a path in the prompt: the suggestions come from your command’s output. -#### - -​ - -Command input and output +#### Command input and output Claude Code runs the command with the same environment variables as [hooks](</docs/en/hooks>), including `CLAUDE_PROJECT_DIR`, and stops waiting after five seconds. The command receives JSON on stdin with a `query` field holding what you’ve typed so far: @@ -3230,11 +2713,7 @@ # Replace your-repo-file-index with your own file search command your-repo-file-index --query "$query" | head -20 -### - -​ - -`footerLinksRegexes` +### `footerLinksRegexes` Render extra clickable badges in the footer below the input box when a regex matches turn output: tool results, including file contents and fetched pages, and Claude’s own responses. Use it to turn IDs printed by project CLIs, such as review tools and issue trackers, into session links. @@ -3259,11 +2738,7 @@ With this configured, when `PROJ-1234` appears in a tool result or in Claude’s reply, a `PROJ-1234` badge appears in the footer linking to `https://issues.example.com/browse/PROJ-1234`. -#### - -​ - -Badge constraints +#### Badge constraints Each entry’s URL, label, and badge count are bounded as follows: @@ -3277,11 +2752,7 @@ When a turn completes, Claude Code matches each entry’s `pattern` regex against the turn output on the main thread, so a slow regex blocks the UI until it finishes. Nested quantifiers such as `(a+)+$` can take exponentially long against certain inputs and freeze the session, so keep each `pattern` linear and avoid nesting `+` or `*`. Footer badges render alongside a [custom status line](</docs/en/statusline>) when one is configured; neither replaces the other. Use a status line for a script-driven row that computes its own content from session data, and footer badges to turn IDs from the conversation into links without a script. -### - -​ - -`keybindingFlavor` +### `keybindingFlavor` Deprecated since v2.1.261 and has no effect. The prompt’s word-editing keys always [follow readline conventions](</docs/en/interactive-mode#make-ctrl-w-delete-back-to-whitespace>), as in Bash. Claude Code still accepts `keybindingFlavor`, so a settings file that sets it stays valid. @@ -3291,11 +2762,7 @@ * **Type** : string, `"classic"` or `"readline"` * **Default** : unset -### - -​ - -`maxProseWidth` +### `maxProseWidth` Cap the width of the prose in Claude’s responses so lines stay readable in a wide terminal. Paragraphs, headings, lists, and blockquotes wrap within this many columns, while tables and code blocks keep the full terminal width. Requires Claude Code v2.1.282 or later. @@ -3309,11 +2776,7 @@ "maxProseWidth": 80 } -### - -​ - -`prefersReducedMotion` +### `prefersReducedMotion` Reduce or turn off interface animations such as the spinner, shimmer, and flash effects. Appears in `/config` as **Reduce motion**. @@ -3329,11 +2792,7 @@ "prefersReducedMotion": true } -### - -​ - -`promptSuggestionEnabled` +### `promptSuggestionEnabled` Show or hide [prompt suggestions](</docs/en/interactive-mode#prompt-suggestions>), the grayed-out predictions that appear in your prompt input. Set it to `false`, or turn off **Prompt suggestions** in `/config`, to hide them. @@ -3352,11 +2811,7 @@ Prompt suggestions need a claude.ai or Console account with telemetry on. On Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry, or with telemetry turned off, such as by [`DISABLE_TELEMETRY`](</docs/en/env-vars>), this key has no effect and only `CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION=1` turns them on. -### - -​ - -`respectGitignore` +### `respectGitignore` Control whether the `@` file picker leaves out files that match `.gitignore` patterns. Appears in `/config` as **Respect .gitignore in file picker**. @@ -3372,11 +2827,7 @@ "respectGitignore": false } -### - -​ - -`respondToBashCommands` +### `respondToBashCommands` Choose whether Claude responds after you run a shell command with the [`!` prefix](</docs/en/interactive-mode#shell-mode-with-prefix>) in the input box. By default, Claude Code adds the command’s output to the conversation and Claude replies to it. Set this key to `false` to add the output to context without a reply, so you can run several commands and ask about them together. @@ -3394,11 +2845,7 @@ See [Shell mode with `!` prefix](</docs/en/interactive-mode#shell-mode-with-prefix>). -### - -​ - -`showClearContextOnPlanAccept` +### `showClearContextOnPlanAccept` When Claude finishes a plan in [plan mode](</docs/en/permission-modes#review-and-approve-a-plan>), it shows an approval menu. Planning can use a lot of context, so this key adds a first option to that menu, **Yes, clear context and …** , that approves the plan, clears the conversation context, and starts implementing from the plan alone. The rest of the label names the permission mode the session continues in, and shows how much of your context the planning used. @@ -3414,11 +2861,7 @@ "showClearContextOnPlanAccept": true } -### - -​ - -`showTurnDuration` +### `showTurnDuration` Show or hide the turn duration message after each response, such as “Cooked for 1m 6s · done 6:05 PM”. The clock after “done” shows when the turn finished; `timeFormat` and `timeZone` control its format and zone. Appears in `/config` as **Show turn duration**. @@ -3434,11 +2877,7 @@ "showTurnDuration": false } -### - -​ - -`spellcheck` +### `spellcheck` Underline misspelled words in the prompt input as you type, using a spell checker you install. Claude Code checks only the text in the input box. [Check spelling as you type](</docs/en/interactive-mode#check-spelling-as-you-type>) covers installing aspell, hunspell, or ispell and what the checker covers. Requires Claude Code v2.1.235 or later. @@ -3452,11 +2891,7 @@ "spellcheck": { "enabled": true, "language": "en_GB" } } -### - -​ - -`spinnerTipsEnabled` +### `spinnerTipsEnabled` While Claude works, the spinner line rotates through short tips about Claude Code features, such as “Use Plan Mode to prepare for a complex request before making changes. Press Shift+Tab twice to enable.” Set this key to `false` to hide them. Appears in `/config` as **Show tips**. @@ -3472,11 +2907,7 @@ "spinnerTipsEnabled": false } -### - -​ - -`spinnerTipsOverride` +### `spinnerTipsOverride` Add your own tips to the spinner tips that Claude Code shows while Claude works, or replace the built-in tips with yours. Claude Code puts your tips in the same rotation as the built-in ones. If you set `spinnerTipsEnabled` to `false`, Claude Code hides all tips, yours included. @@ -3528,11 +2959,7 @@ While Claude works, Claude Code shows your tips in the spinner with your prefix, such as `Acme tip: Run /review before opening a PR`. -### - -​ - -`spinnerVerbs` +### `spinnerVerbs` While a turn is in progress, the spinner shows a rotating verb such as “Accomplishing”, “Architecting”, or “Baking”. Use this key to add your own verbs to that rotation or replace the built-in list with yours. @@ -3555,11 +2982,7 @@ In `"replace"` mode with an empty `verbs` array, Claude Code keeps the built-in verbs. -### - -​ - -`statusLine` +### `statusLine` Run your own command to render a [status line](</docs/en/statusline>) below the prompt with context such as the model, cost, or git branch. Optional fields adjust spacing, add periodic re-runs, and hide the built-in vim mode indicator when your script renders `vim.mode` itself. @@ -3581,34 +3004,7 @@ The example needs [`jq`](<https://jqlang.org/>) installed and runs in a shell. For PowerShell and Git Bash equivalents, see [Windows configuration](</docs/en/statusline#windows-configuration>); for the full setup, see [Manually configure a status line](</docs/en/statusline#manually-configure-a-status-line>). -### - -​ - -`subagentStatusLine` - -When Claude runs [subagents](</docs/en/sub-agents>), Claude Code lists them in a task display below the prompt, one row per subagent showing `name · description · token count`. This key lets you run your own command to rewrite those rows, for example to show each subagent’s context usage as a percentage. On each refresh, Claude Code sends the visible rows as one JSON object on stdin, with a `tasks` array carrying each subagent’s `id`, `name`, `status`, `model`, `tokenCount`, and more, and replaces the row for each `id` you write back as a `{"id", "content"}` line. Rows you don’t write back keep the default rendering. - - * **Scope** : `Any file`. When `allowManagedHooksOnly` is on, or `disableAllHooks` is set outside managed settings, only the managed settings value runs. - * **Type** : object with `type` set to `"command"` and a `command` string - * **Default** : unset, so Claude Code renders the default rows - -settings.json - - { - "subagentStatusLine": { - "type": "command", - "command": "jq -c '.tasks[] | {id, content: \"\\(.name): \\(.tokenCount) tokens\"}'" - } - } - -See [Subagent status lines](</docs/en/statusline#subagent-status-lines>). - -### - -​ - -`syntaxHighlightingDisabled` +### `syntaxHighlightingDisabled` Claude Code colors code by language in the diffs, code blocks, and file previews it shows in the terminal, with its built-in highlighter. Set this key to `true` to show them as plain text instead, for example if the colors clash with your terminal theme or slow a screen reader. @@ -3624,11 +3020,7 @@ "syntaxHighlightingDisabled": true } -### - -​ - -`terminalProgressBarEnabled` +### `terminalProgressBarEnabled` Some terminals can show a progress indicator on the tab or in the taskbar for the program running in them. While Claude is working, Claude Code reports an in-progress state to the terminal, so you can see from another tab or window whether the session is still busy. The indicator stays visible after the turn ends while [background subagents](</docs/en/sub-agents#run-subagents-in-foreground-or-background>) or [dynamic workflows](</docs/en/workflows>) are still running, and clears once the session is idle. Claude Code reports it only in terminals that support the indicator: ConEmu, Ghostty 1.2.0 or later, and iTerm2 3.6.6 or later. Set this key to `false` to stop Claude Code from reporting it. Appears in `/config` as **Terminal progress bar**. @@ -3644,11 +3036,7 @@ "terminalProgressBarEnabled": false } -### - -​ - -`terminalTitleFromRename` +### `terminalTitleFromRename` Claude Code sets your terminal tab’s title. By default it uses a title it generates from the conversation, and once you give the session a [name](</docs/en/sessions#name-your-sessions>) with `/rename` or `--name`, the tab shows that name instead. Set this key to `false` to keep the generated title on the tab even after you name the session. The name itself still applies, so `/resume <name>` and the session picker find it. @@ -3666,11 +3054,7 @@ To stop Claude Code from updating the terminal title at all, set [`CLAUDE_CODE_DISABLE_TERMINAL_TITLE`](</docs/en/env-vars>) to `1` instead. -### - -​ - -`theme` +### `theme` Pick the color theme for the interface. Appears in `/config` as **Theme**. @@ -3694,11 +3078,7 @@ See [Create a custom theme](</docs/en/terminal-config#create-a-custom-theme>). -### - -​ - -`timeFormat` +### `timeFormat` Choose how Claude Code writes the times it shows in the interface, such as the `done 6:05 PM` at the end of each turn duration message and the timestamps in the [transcript viewer](</docs/en/interactive-mode#transcript-viewer>). To pick a preset, run `/config` and set **Time format**. Requires Claude Code v2.1.257 or later. @@ -3735,11 +3115,7 @@ The same surfaces then show times such as `2026-09-01 18:05`. -### - -​ - -`timeZone` +### `timeZone` Show the times in the interface in a time zone other than your system’s. Set it to an [IANA time zone name](<https://www.iana.org/time-zones>), such as `"UTC"` or `"Europe/Dublin"`. The times that `timeFormat` controls then show in this zone. If `timeFormat` is `"24-hour-utc"`, times stay in UTC and Claude Code ignores this key. `/config` has no row for this key, so set it in a settings file. Requires Claude Code v2.1.257 or later. @@ -3753,11 +3129,7 @@ "timeZone": "Europe/Dublin" } -### - -​ - -`tui` +### `tui` Choose the terminal UI renderer. Use `"fullscreen"` for the flicker-free [alt-screen renderer](</docs/en/fullscreen>) with virtualized scrollback, or `"default"` for the classic main-screen renderer. Running `/tui fullscreen` or `/tui default` writes this key for you. @@ -3776,11 +3148,7 @@ Under tmux `-CC` or over SSH to Windows, Claude Code keeps the classic renderer unless you set `CLAUDE_CODE_NO_FLICKER=1`. Background sessions opened from [agent view](</docs/en/agent-view>) always use the fullscreen renderer regardless of this setting. -### - -​ - -`verbose` +### `verbose` By default, the transcript collapses each tool call to a short summary, such as the command Claude ran and a line count of its output, and you press `Ctrl+O` to switch the whole transcript to the expanded view when you want the details. Set this key to `true` to show every tool call’s full input and output inline as it happens, which is useful when you’re debugging a hook, an MCP server, or a long shell command. Appears in `/config` as **Verbose output**. @@ -3799,11 +3167,7 @@ A `viewMode` value or a sticky `/focus` selection overrides this key every session. -### - -​ - -`viewMode` +### `viewMode` Set the transcript view Claude Code starts in: `"default"`, `"verbose"`, or `"focus"`. When set, it overrides both the sticky `/focus` selection and the `verbose` setting. @@ -3821,11 +3185,7 @@ "viewMode": "focus" } -### - -​ - -`vimInsertModeRemaps` +### `vimInsertModeRemaps` Map two-key INSERT-mode sequences to Escape in [vim editor mode](</docs/en/interactive-mode#vim-editor-mode>). Each key is exactly two printable characters typed in sequence, and `"<Esc>"` is the only supported target; Claude Code ignores other entries. @@ -3843,11 +3203,7 @@ Has no effect unless `editorMode` is `"vim"`. See [Remap INSERT-mode key sequences](</docs/en/interactive-mode#remap-insert-mode-key-sequences>). -### - -​ - -`voice` +### `voice` Turn on [voice dictation](</docs/en/voice-dictation>) and choose how the dictation key behaves. Claude Code writes this object for you when you run `/voice`. @@ -3870,11 +3226,7 @@ `autoSubmit` sends the prompt when you release the key in hold mode. Voice dictation requires a claude.ai account. -### - -​ - -`voiceEnabled` +### `voiceEnabled` Deprecated since v2.1.92, when the `voice` object replaced it. Claude Code still reads it so older settings files keep working, but new configurations should set `voice.enabled`. @@ -3892,11 +3244,7 @@ "voiceEnabled": true } -### - -​ - -`wheelScrollAccelerationEnabled` +### `wheelScrollAccelerationEnabled` Accelerate mouse-wheel scroll speed during fast scrolls in [fullscreen rendering](</docs/en/fullscreen#mouse-wheel-scrolling>). Set it to `false` for a constant scroll rate per wheel notch. @@ -3912,19 +3260,11 @@ "wheelScrollAccelerationEnabled": false } -## - -​ - -Git and attribution +## Git and attribution Control the attribution Claude Code adds to commits and pull requests and how it works with git. -### - -​ - -`attribution` +### `attribution` Customize the attribution Claude Code adds to git commits and pull requests. Commits get a [git trailer](<https://git-scm.com/docs/git-interpret-trailers>) such as `Co-Authored-By` by default; pull request descriptions get plain text. Set each part separately with the sub-keys below. @@ -3946,11 +3286,7 @@ Once you set `commit` or `pr`, Claude Code ignores the deprecated `includeCoAuthoredBy` setting and uses its default text for whichever of the two you left unset. Claude Code tells Claude that your own instructions about attribution, such as a CLAUDE.md or [memory](</docs/en/memory>) rule, take precedence over these commit and PR lines, unless the line is set in [managed settings](</docs/en/managed-settings>). -### - -​ - -`includeCoAuthoredBy` +### `includeCoAuthoredBy` Deprecated since v2.0.62, when `attribution` replaced it. Claude Code still reads it, but new configurations should set `attribution`. @@ -3970,11 +3306,7 @@ To hide all attribution, see `attribution`. -### - -​ - -`includeGitInstructions` +### `includeGitInstructions` Claude Code gives Claude two git-related pieces of context: its built-in instructions for how to write commits and pull requests, in the Bash tool’s description, and a git status snapshot of your repository. The snapshot holds the current branch, the main branch, `git status` output, and recent commits. Claude Code reads it when a conversation starts. Set this key to `false` to leave both out, for example when you use your own git workflow skills. @@ -3996,11 +3328,7 @@ * **`-p` runs**: you replace the prompt when you pass [`--system-prompt`](</docs/en/cli-reference#system-prompt-flags>) or `--system-prompt-file`. You also replace it when you run a custom agent with its own prompt, selected with [`--agent`](</docs/en/sub-agents#invoke-subagents-explicitly>) or the `agent` setting. Outside [bare mode](</docs/en/headless#start-faster-with-bare-mode>), to keep the snapshot, run without a custom agent and add your instructions with [`--append-system-prompt`](</docs/en/cli-reference#system-prompt-flags>) instead of replacing the prompt. * **[Agent SDK](</docs/en/agent-sdk/modifying-system-prompts>)** : you replace the prompt with a custom system prompt or a custom main-thread agent. If you set no system prompt, the SDK uses its minimal default and the session starts without the snapshot too. Outside [bare mode](</docs/en/headless#start-faster-with-bare-mode>), to keep the snapshot, use the `claude_code` preset without a custom `agent`. -### - -​ - -`prUrlTemplate` +### `prUrlTemplate` Point the PR links Claude Code renders, in the footer badge and in tool-result summaries, at an internal code-review tool instead of `github.com`. Claude Code substitutes `{host}`, `{owner}`, `{repo}`, `{number}`, and `{url}` from the PR URL. [GitLab merge request](</docs/en/interactive-mode#gitlab-merge-requests>) links on both surfaces keep their GitLab URL. @@ -4016,11 +3344,7 @@ Claude Code applies the template only to the links it renders itself; a PR number Claude writes in a message, such as `#123`, stays as Claude wrote it. A URL that doesn’t have the `/pull/<number>` shape is left unchanged. -### - -​ - -`attribution.commit` +### `attribution.commit` Set the attribution text Claude Code adds to git commits, including any trailers. Set it to an empty string to hide commit attribution. @@ -4040,11 +3364,7 @@ } } -### - -​ - -`attribution.pr` +### `attribution.pr` Set the attribution text Claude Code adds to pull request descriptions. Set it to an empty string to hide pull request attribution. @@ -4060,11 +3380,7 @@ } } -### - -​ - -`attribution.sessionUrl` +### `attribution.sessionUrl` Choose whether Claude Code appends the claude.ai session link when it commits or opens a pull request from a [cloud](</docs/en/claude-code-on-the-web>) or [Remote Control](</docs/en/remote-control>) session. Claude Code adds the link as a `Claude-Session` trailer on commits and as a link in pull request descriptions. Set it to `false` to omit the link. @@ -4082,19 +3398,11 @@ } } -## - -​ - -Hooks and automation +## Hooks and automation Register hooks, restrict which hooks run, and control workflows. For hook events and payloads, see the [hooks reference](</docs/en/hooks>). -### - -​ - -`allowedHttpHookUrls` +### `allowedHttpHookUrls` Limit which URLs [HTTP hooks](</docs/en/hooks#http-hook-fields>) can target. When you define this key, Claude Code runs an HTTP hook only if its URL matches one of the patterns and blocks the rest without running them; an empty array blocks every HTTP hook. @@ -4112,11 +3420,7 @@ Hostname matching is case-insensitive and treats `hooks.example.com.`, with the trailing dot that marks a fully qualified domain name, the same as `hooks.example.com`, which is how DNS treats them. The allowlist applies to hooks from every source, including managed settings. In the Agent SDK’s `managedSettings` option, Claude Code ignores a list with entries, so pass it in the SDK’s [`settings` option](</docs/en/agent-sdk/typescript#options>) instead. See [what an empty list does in parent settings](</docs/en/claude-apps-gateway#how-hook-and-skill-keys-in-parent-settings-take-effect>). -### - -​ - -`allowManagedHooksOnly` +### `allowManagedHooksOnly` Restrict hook execution to hooks your organization deploys. @@ -4132,11 +3436,7 @@ "allowManagedHooksOnly": true } -#### - -​ - -What runs under `allowManagedHooksOnly` +#### What runs under `allowManagedHooksOnly` When you set it to `true`, Claude Code changes which hooks and hook-like commands load: @@ -4146,15 +3446,11 @@ * **Everything else is blocked** : user, project, and local hooks, hooks and mods from other installed plugins, and hooks declared in agent frontmatter. [Mods built into Claude Code](</docs/en/plugins/mods/overview#mods-built-into-claude-code>) keep running. To block only users’ mods, set [`allowManagedModsOnly`](</docs/en/plugins/mods/admin#set-options-on-the-built-in-guard>) instead. * **Command-sourced plugins are disabled** : Claude Code also disables plugins with a [`command` source](</docs/en/plugins/marketplace-reference#command-plugin-source>), including plugins force-enabled in managed `enabledPlugins`, unless you set `disableCommandPluginSources` to `false` explicitly * **Marketplace`headersHelper` commands are blocked**: Claude Code also blocks marketplace [`headersHelper` commands](</docs/en/plugins/host-marketplace#authenticate-archive-downloads>) unless `disableCommandPluginSources` is explicitly set to `false`, except for a marketplace that managed settings themselves declare. Requires Claude Code v2.1.238 or later - * **Status line and file suggestion narrow to managed settings** : Claude Code reads [`statusLine`](</docs/en/statusline>), `fileSuggestion`, and [`subagentStatusLine`](</docs/en/statusline#subagent-status-lines>) from managed settings only, following the status line and file suggestion gates + * **Status line and file suggestion narrow to managed settings** : Claude Code reads [`statusLine`](</docs/en/statusline>) and `fileSuggestion` from managed settings only, following the status line and file suggestion gates The [`/goal`](</docs/en/goal>) command can’t run while this key is set, because it depends on hooks. -### - -​ - -`disableAllHooks` +### `disableAllHooks` Turn off [hooks](</docs/en/hooks#disable-or-remove-hooks>), any custom [status line](</docs/en/statusline>), and any custom file suggestion command. Use it to turn all of these off temporarily without deleting them from your settings. @@ -4183,24 +3479,16 @@ Mods built into Claude Code keep running in both cases. Each has [its own switch](</docs/en/plugins/mods/overview#mods-built-into-claude-code>). Keeping Agent SDK hooks running when managed settings set this key requires Claude Code v2.1.242 or later. The [`/goal`](</docs/en/goal>) command can’t run while hooks are disabled, and the `/hooks` menu shows a notice instead of your hooks. -#### - -​ - -Status line and file suggestion gates - -Claude Code makes two decisions for `statusLine`, `fileSuggestion`, and `subagentStatusLine`, in this order: +#### Status line and file suggestion gates + +Claude Code makes two decisions for `statusLine` and `fileSuggestion`, in this order: * **Off entirely** : when managed settings set `disableAllHooks`, or when the folder isn’t trusted under the same [workspace trust rule as hooks in settings files](</docs/en/permissions#what-runs-before-you-trust-a-folder>) * **Narrowed to managed settings** : when `allowManagedHooksOnly` is set, when `disableAllHooks` is `true` outside managed settings after [settings precedence](</docs/en/hooks#disable-or-remove-hooks>) applies, or when you start Claude Code with `--safe-mode` Under narrowing, Claude Code runs a managed value if one is deployed. Otherwise it skips your value without warning: the status line is disabled, and `@` autocomplete falls back to the built-in file suggestion. -### - -​ - -`disableWorkflows` +### `disableWorkflows` Turn off [dynamic workflows](</docs/en/workflows#turn-workflows-off>) and the bundled workflow commands for everyone your settings reach, such as an organization through managed settings. To turn workflows on or off just for yourself, use `enableWorkflows` instead, which the **Dynamic workflows** toggle in `/config` writes to your user settings. @@ -4217,11 +3505,7 @@ "disableWorkflows": true } -### - -​ - -`enableWorkflows` +### `enableWorkflows` Turn [dynamic workflows](</docs/en/workflows>) on or off for yourself when your plan’s default isn’t what you want. Appears in `/config` as **Dynamic workflows** , which writes this key to your user settings and removes it again when you toggle back to your plan’s default. To turn workflows off for everyone from managed settings, use `disableWorkflows` instead. @@ -4240,11 +3524,7 @@ `disableWorkflows` and your organization’s workflows policy also take precedence: `enableWorkflows: true` can’t turn workflows back on while any source turns workflows off. Claude Code hides the `/config` row while a source other than your user settings sets `enableWorkflows`, or sets `disableWorkflows` to `true`. -### - -​ - -`hooks` +### `hooks` Run your own commands, prompts, agents, HTTP requests, or MCP tools as [hooks](</docs/en/hooks>) at points in Claude Code’s lifecycle, such as before a tool call or when a session starts; the [hooks reference](</docs/en/hooks#hook-events>) lists every event, its payload, and its exit codes. Each event maps to a list of matcher groups, and each group lists the handlers to run when the matcher applies. @@ -4271,11 +3551,7 @@ For every event, matcher pattern, and handler field, see the [hooks reference](</docs/en/hooks#configuration>). To turn hooks off, see `disableAllHooks`; to limit hooks to the ones your organization deploys, see `allowManagedHooksOnly`. -### - -​ - -`httpHookAllowedEnvVars` +### `httpHookAllowedEnvVars` An [HTTP hook](</docs/en/hooks#http-hook-fields>) can put the value of an environment variable into a request header, for example an `Authorization: Bearer $HOOK_TOKEN` header, but only for variables the hook lists in its own `allowedEnvVars`. This key sets an outer limit on that list for every HTTP hook: a hook can use a variable only if both its own `allowedEnvVars` and this key name it. Use it to stop a hook from reading a secret it shouldn’t, even when the hook’s definition asks for it. @@ -4293,11 +3569,7 @@ The allowlist applies to hooks from every source, including managed settings. In the Agent SDK’s `managedSettings` option, Claude Code ignores a list with entries, so pass it in the SDK’s [`settings` option](</docs/en/agent-sdk/typescript#options>) instead. See [what an empty list does in parent settings](</docs/en/claude-apps-gateway#how-hook-and-skill-keys-in-parent-settings-take-effect>). -### - -​ - -`workflowKeywordTriggerEnabled` +### `workflowKeywordTriggerEnabled` Choose whether typing the keyword `ultracode` in a prompt triggers a [dynamic workflow](</docs/en/workflows#ask-for-a-workflow-in-your-prompt>). Set it to `false` to type the word without triggering one. @@ -4315,11 +3587,7 @@ The `ultracode` effort setting, `/workflows`, and saved workflow commands are unaffected. -### - -​ - -`workflowSizeGuideline` +### `workflowSizeGuideline` Set the [agent count Claude aims for](</docs/en/workflows#set-a-size-guideline>) in the dynamic workflows it writes. Claude Code sends the value to Claude as advice, not an enforced cap: `"small"` asks for fewer than 5 agents, `"medium"` fewer than 10, and `"large"` fewer than 50. Choose `"small"` when you want to bound what a workflow spends. @@ -4337,19 +3605,11 @@ "workflowSizeGuideline": "small" } -## - -​ - -Plugins and skills +## Plugins and skills Enable plugins, register marketplaces, restrict which plugin sources an organization allows, and control which skills load. For installing and building plugins, see [Plugins](</docs/en/plugins/overview>). -### - -​ - -`disableBundledSkills` +### `disableBundledSkills` Turn off the [skills](</docs/en/skills>) and workflows included with Claude Code. Claude Code removes bundled skills and workflows entirely, while built-in commands such as `/init` stay typable but are hidden from the model. @@ -4368,11 +3628,7 @@ Skills from plugins, `.claude/skills/`, and `.claude/commands/` are unaffected. `/doctor` stays typable like the built-in commands; to hide it, set [`DISABLE_DOCTOR_COMMAND`](</docs/en/env-vars>) instead. -### - -​ - -`disableSkillShellExecution` +### `disableSkillShellExecution` Turn off inline shell execution for `!`...`` and ````!` blocks in [skills](</docs/en/skills>) and custom commands from user, project, plugin, or additional-directory sources. Claude Code replaces each command with `[shell command execution disabled by policy]` instead of running it. @@ -4390,11 +3646,7 @@ Bundled skills and skills deployed through managed settings are unaffected. -### - -​ - -`skillOverrides` +### `skillOverrides` Hide or collapse a [skill](</docs/en/skills#override-skill-visibility-from-settings>) without editing its `SKILL.md`. Claude Code applies the value under each skill’s name to the skill list Claude sees and to your `/` autocomplete. @@ -4419,11 +3671,7 @@ Overrides don’t apply to plugin skills, which you manage through `/plugin`. In managed settings and files passed with `--settings`, a key on a bundled skill’s alias, such as `checkup` for `/doctor`, also applies to the skill; see [how alias keys combine with keys on the skill’s own name](</docs/en/skills#override-skill-visibility-from-settings>). -### - -​ - -`syncClaudeAiSkills` +### `syncClaudeAiSkills` Turn off the download of the [skills enabled for your claude.ai account](</docs/en/skills#how-synced-skills-behave>). Claude Code downloads them into `~/.claude/skills/synced/` in [terminal sessions where you sign in with your claude.ai account](</docs/en/skills#where-synced-skills-load>), interactive or non-interactive, and in Cowork and cloud sessions. Set `false` to stop that download and stop loading the skills it already synced. Claude Code honors only `false`: `true` is the same as unset and doesn’t turn syncing on where it’s otherwise off. @@ -4441,11 +3689,7 @@ "syncClaudeAiSkills": false } -### - -​ - -`syncClaudeAiPlugins` +### `syncClaudeAiPlugins` Turn off the download of the [plugins enabled for your claude.ai account](</docs/en/plugins/loading#synced-plugins>). Claude Code downloads them into `~/.claude/plugins/synced/` at the start of terminal sessions where you sign in with your claude.ai account and in Cowork sessions, and loads each one as `<name>@synced`. Set `false` to stop that download and stop loading the plugins it already synced. Claude Code honors only `false`: `true` is the same as unset and doesn’t turn syncing on where it’s otherwise off. Requires Claude Code v2.1.273 or later. @@ -4463,11 +3707,7 @@ "syncClaudeAiPlugins": false } -### - -​ - -`allowedChannelPlugins` +### `allowedChannelPlugins` Choose which [channel](</docs/en/channels>) plugins can push messages into sessions in your organization. When you set it, Claude Code uses your list in place of the default Anthropic allowlist; each entry names a plugin and the marketplace it comes from. @@ -4488,11 +3728,7 @@ An empty array blocks every channel plugin. This key takes effect once channels pass the `channelsEnabled` gate for the account: on Team and Enterprise plans, and on Console accounts with managed settings, that means `channelsEnabled: true`. See [Restrict which channel plugins can run](</docs/en/channels#restrict-which-channel-plugins-can-run>). -### - -​ - -`blockedMarketplaces` +### `blockedMarketplaces` Block plugin marketplace sources for your organization. Claude Code checks the blocklist on marketplace add and on plugin install, update, refresh, and auto-update, so a marketplace someone added before you set the policy can’t be used to fetch plugins either. Blocked sources are checked before download, so they never touch the filesystem. If you set this key in the [claude.ai admin console](</docs/en/server-managed-settings>), claude.ai also applies it when anyone in your organization adds a marketplace from a git repository on claude.ai, as [How restrictions work](</docs/en/plugins/org#restrict-what-users-can-install>) describes. @@ -4512,11 +3748,7 @@ A `github` entry may use the owner-wildcard form `"owner/*"` to block every repository under that GitHub owner, which requires Claude Code v2.1.223 or later. Add `{ "source": "skills-dir" }` to stop Claude Code loading [`@skills-dir` plugins](</docs/en/plugins/loading#plugins-shared-through-a-repository>) from both `~/.claude/skills/` and a project’s `.claude/skills/`, without restricting any marketplace. See [Managed marketplace restrictions](</docs/en/plugins/org#restrict-what-users-can-install>). -### - -​ - -`channelsEnabled` +### `channelsEnabled` Allow [channels](</docs/en/channels>) for your organization. On claude.ai Team and Enterprise plans, Claude Code blocks channels until you set this to `true`. For [Anthropic Console](</docs/en/authentication#claude-console-authentication>) accounts that authenticate with an API key, channels are allowed by default. If your organization deploys managed settings, Claude Code blocks channels on those accounts too until you set this key to `true`. @@ -4534,11 +3766,7 @@ To restrict which plugins can register as channels once they’re enabled, set `allowedChannelPlugins`. See [Enterprise controls](</docs/en/channels#enterprise-controls>). -### - -​ - -`disableCommandPluginSources` +### `disableCommandPluginSources` Block the [`command` plugin source](</docs/en/plugins/marketplace-reference#command-plugin-source>), which installs a plugin by running a marketplace-declared command on the user’s machine. When you set it to `true`, Claude Code never runs the command, doesn’t install or update command-sourced plugins, and stops loading the ones already installed. Set it to `false` to allow them explicitly. Whenever it blocks command sources, whether you set it to `true` or leave it unset under `allowManagedHooksOnly`, it also blocks marketplace [`headersHelper` commands](</docs/en/plugins/host-marketplace#authenticate-archive-downloads>), except for a marketplace that managed settings themselves declare. Requires Claude Code v2.1.229 or later, and the `headersHelper` block requires v2.1.238 or later. @@ -4556,11 +3784,7 @@ Requires Claude Code v2.1.229 or later. -### - -​ - -`pluginSuggestionMarketplaces` +### `pluginSuggestionMarketplaces` Name the marketplaces whose plugins can appear as contextual install suggestions, in spinner tips and pinned at the top of the `/plugin` **Discover** tab. The built-in first-party frontend-design tip is unaffected. Suggestions come from each plugin’s `relevance` declaration in its marketplace entry. @@ -4576,11 +3800,7 @@ A name takes effect only when the marketplace is registered on the machine and its registered source is also declared in the same managed settings, either as the `extraKnownMarketplaces` entry for that name or as an entry of `strictKnownMarketplaces`. Claude Code ignores a marketplace registered from a different source under an allowlisted name. The official marketplace is exempt from the source requirement: allowlisting its name alone suffices, since that name can only register from the official Anthropic source. See [Suggest plugins by context](</docs/en/plugins/relevance>). -### - -​ - -`pluginTrustMessage` +### `pluginTrustMessage` Add your organization’s own text to the plugin trust warning Claude Code shows before installation, for example to confirm that plugins from your internal marketplace are vetted. @@ -4594,11 +3814,7 @@ "pluginTrustMessage": "All plugins from our marketplace are approved by IT" } -### - -​ - -`strictKnownMarketplaces` +### `strictKnownMarketplaces` Restrict which plugin marketplace sources people in your organization can add and install plugins from. Claude Code enforces the allowlist on marketplace add and on plugin install, update, refresh, and auto-update, before any network or filesystem operation, so a marketplace someone added before you set the policy can’t be used to fetch plugins once its source no longer matches. Blocked users see an error naming the managed policy. If you set this key in the [claude.ai admin console](</docs/en/server-managed-settings>), claude.ai also applies it when anyone in your organization adds a marketplace from a git repository on claude.ai, as [How restrictions work](</docs/en/plugins/org#restrict-what-users-can-install>) describes. @@ -4620,11 +3836,7 @@ You can also write this key as `allowedMarketplaces`; Marketplace key aliases describes how Claude Code treats the alias and which version accepts it. This key is a policy gate: it controls what users may add but registers nothing. To restrict and pre-register in one file, see Combine with `extraKnownMarketplaces`. For the user-facing view, see [Managed marketplace restrictions](</docs/en/plugins/org#restrict-what-users-can-install>). -#### - -​ - -Allowed source types +#### Allowed source types Each entry below shows one allowlist entry per source type and the fields it accepts. Most types match exactly; `hostPattern` and `pathPattern` match by regex, and `github` entries can use an owner wildcard. @@ -4650,11 +3862,7 @@ * **`pathPattern`** : use it to allow filesystem marketplaces alongside `hostPattern` entries for network sources. `".*"` allows every local path; a narrower pattern such as `"^/opt/approved/"` restricts to a directory. * **`skills-dir`** : any allowlist, even an empty one, stops Claude Code loading [`@skills-dir` plugins](</docs/en/plugins/loading#plugins-shared-through-a-repository>) from both `~/.claude/skills/` and a project’s `.claude/skills/`. To keep loading them, add the `{ "source": "skills-dir" }` entry and leave `strictPluginOnlyCustomization` unset. The entry has no meaning outside this key and `blockedMarketplaces`. -#### - -​ - -Owner wildcards +#### Owner wildcards A `github` entry whose `repo` value is `"<owner>/*"` matches every repository under that GitHub owner. Owner wildcards require Claude Code v2.1.223 or later and work only in `strictKnownMarketplaces` and `blockedMarketplaces`. Everywhere else a `github` source appears, such as `extraKnownMarketplaces` or `/plugin marketplace add`, the `repo` value must name a single repository. Before v2.1.223, Claude Code compared the entry literally, so an allowlist entry matched no repository and a blocklist entry blocked nothing; single-repository entries are enforced on every version. This entry allows any marketplace repository in the `acme-corp` organization: @@ -4675,11 +3883,7 @@ `ref`| Follows the exact-entry rules: an entry with a `ref` matches only sources with that exact ref, and an entry without one matches only sources that don’t specify a ref| An entry without a `ref` blocks all refs of the repositories it matches `path`| Looser than the exact-entry rules: an entry with a `path` requires that exact value, while an entry without one matches any path inside the repository| An entry without a `path` blocks all paths of the repositories it matches -#### - -​ - -Exact matching +#### Exact matching For every source type except owner-wildcard `github` entries and the regex-matched `hostPattern` and `pathPattern` entries, Claude Code allows a user’s addition only when the marketplace source matches an entry exactly. For the git-based sources `github` and `git`, exact matching includes the optional fields: @@ -4692,11 +3896,7 @@ * `{ "source": "github", "repo": "acme-corp/plugins" }` and `{ "source": "github", "repo": "acme-corp/plugins", "ref": "main" }` * `{ "source": "github", "repo": "acme-corp/plugins", "path": "marketplace" }` and `{ "source": "github", "repo": "acme-corp/plugins" }` -#### - -​ - -Allow only the official marketplace +#### Allow only the official marketplace To allow the official Anthropic marketplace and nothing else, list its repository: @@ -4716,11 +3916,7 @@ On these machines, add the marketplace to `extraKnownMarketplaces` in the same `managed-settings.json` so Claude Code registers it automatically, or run `claude plugin marketplace add anthropics/claude-plugins-official`. -#### - -​ - -Combine with `extraKnownMarketplaces` +#### Combine with `extraKnownMarketplaces` The two keys do different jobs. This table compares them: @@ -4750,11 +3946,7 @@ With only `strictKnownMarketplaces` set, users can still add an allowed marketplace themselves with `/plugin marketplace add`. The official Anthropic marketplace is the only one Claude Code registers automatically, and only when the allowlist allows it. Allow only the official marketplace lists the machines it misses. -### - -​ - -`strictPluginOnlyCustomization` +### `strictPluginOnlyCustomization` Block skills, agents, hooks, and MCP servers from user and project sources. Combine it with `strictKnownMarketplaces` to choose which marketplaces users can install plugins from. Add `disableSideloadFlags` to reject the CLI flags that sideload plugins, agents, and MCP servers for a single run. @@ -4772,11 +3964,7 @@ If you lock any surface, Claude Code also stops loading [skills-directory plugins](</docs/en/plugins/loading#skills-directory-plugins-blocked-by-managed-settings>), the plugin folders that users keep under `~/.claude/skills/` or `.claude/skills/`. Users place those folders themselves rather than installing them from a marketplace, so Claude Code treats them as user customization under this setting. The four sub-key entries below list what else each surface blocks and what still loads. Claude Code ignores surface names it doesn’t recognize rather than failing the settings file, so you can add new surface names before every client has updated. -### - -​ - -`strictPluginOnlyCustomization.skills` +### `strictPluginOnlyCustomization.skills` Lock the `skills` surface. Claude Code stops loading skills from `~/.claude/skills/` and `.claude/skills/`, custom commands from `~/.claude/commands/` and `.claude/commands/`, skills and commands under `--add-dir` directories, and skills synced from your claude.ai account. It keeps loading bundled skills, skills in the managed policy directory, and skills from plugins other than [skills-directory plugins](</docs/en/plugins/loading#skills-directory-plugins-blocked-by-managed-settings>). @@ -4790,11 +3978,7 @@ "strictPluginOnlyCustomization": ["skills"] } -### - -​ - -`strictPluginOnlyCustomization.agents` +### `strictPluginOnlyCustomization.agents` Lock the `agents` surface. Claude Code stops loading agents from `~/.claude/agents/`, `.claude/agents/`, and `--add-dir` directories. It keeps loading built-in agents, agents in the managed policy directory, and agents from plugins other than [skills-directory plugins](</docs/en/plugins/loading#skills-directory-plugins-blocked-by-managed-settings>). @@ -4808,11 +3992,7 @@ "strictPluginOnlyCustomization": ["agents"] } -### - -​ - -`strictPluginOnlyCustomization.hooks` +### `strictPluginOnlyCustomization.hooks` Lock the `hooks` surface: @@ -4833,11 +4013,7 @@ "strictPluginOnlyCustomization": ["hooks"] } -### - -​ - -`strictPluginOnlyCustomization.mcp` +### `strictPluginOnlyCustomization.mcp` Lock the `mcp` surface. Claude Code stops loading MCP servers from `~/.claude.json` and `.mcp.json`. It keeps loading [`managed-mcp.json`](</docs/en/managed-mcp>) servers, servers from `managedMcpServers`, and MCP servers from plugins other than [skills-directory plugins](</docs/en/plugins/loading#skills-directory-plugins-blocked-by-managed-settings>). @@ -4851,11 +4027,7 @@ "strictPluginOnlyCustomization": ["mcp"] } -### - -​ - -`enabledPlugins` +### `enabledPlugins` Turn individual [plugins](</docs/en/plugins/overview>) on or off, keyed by `plugin-name@marketplace-name`. A plugin with no entry at any scope falls back to its [`defaultEnabled`](</docs/en/plugins/manifest-reference#fields>) value. When you enable or disable a plugin with `/plugin` or `claude plugin enable`, Claude Code writes this key for you. @@ -4884,11 +4056,7 @@ Project settings take precedence over user settings, so setting a plugin to `false` in `~/.claude/settings.json` doesn’t disable a plugin that the project’s `.claude/settings.json` enables. To opt out of a project-enabled plugin on your machine, set it to `false` in `.claude/settings.local.json` instead. Plugins force-enabled by managed settings can’t be disabled this way, since managed settings override local settings. -### - -​ - -`extraKnownMarketplaces` +### `extraKnownMarketplaces` Register additional plugin marketplaces by name, so that people who open the repository, or everyone your managed settings reach, get the marketplace without adding it themselves. Claude Code registers each marketplace it doesn’t already know. Whether a plugin that `enabledPlugins` names from it installs depends on the plugin’s source and which file enables it; [Enabled in project settings but not installed](</docs/en/plugins/loading#enabled-in-project-settings-but-not-installed>) has the rules. @@ -4919,11 +4087,7 @@ [What runs before you trust a folder](</docs/en/permissions#what-runs-before-you-trust-a-folder>) compares the trust gate with the other content a repository can supply. You can also write this key as `additionalMarketplaces`; see Marketplace key aliases. Set `"autoUpdate": true` alongside `source` to make Claude Code refresh that marketplace and update its installed plugins in the background after startup. When omitted, `claude-plugins-official` and most other official Anthropic marketplaces default to `true`, and third-party marketplaces default to `false`. See [Configure auto-updates](</docs/en/plugins/install#keep-plugins-updated>). When more than one settings file defines a marketplace entry under the same name, Claude Code uses the entry from the [highest-precedence file](</docs/en/settings#settings-precedence>) whole. That entry replaces the lower-precedence entry and inherits none of its fields, so a redefinition can’t combine one file’s `source.headers` credential with a URL another file controls. Before v2.1.228, Claude Code merged same-name entries field by field, so an entry in a higher-precedence file could inherit fields it didn’t set, including another file’s `headers`. -#### - -​ - -Marketplace source types +#### Marketplace source types The `source` object takes one of these forms: @@ -4969,11 +4133,7 @@ * **Folder trust** : for an entry in a project’s `.claude/settings.json` or `.claude/settings.local.json`, Claude Code runs the command only after the user has also [trusted that folder](</docs/en/permissions#what-runs-before-you-trust-a-folder>). * **Header filter** : Claude Code drops [request-routing and client-identity header names](</docs/en/plugins/host-marketplace#when-claude-code-skips-a-headershelper-command-or-drops-its-output>) from an entry in a project’s `.claude/settings.json` or `.claude/settings.local.json`, because a repository can supply those files. Claude Code applies the same filter to a catalog entry and to an entry in an `--add-dir` directory’s settings, and no filter to an entry in your user settings, a `--settings` file, or managed settings. -#### - -​ - -Marketplace key aliases +#### Marketplace key aliases On Claude Code v2.1.232 or later, you can write `extraKnownMarketplaces` as `additionalMarketplaces` and `strictKnownMarketplaces` as `allowedMarketplaces`. Claude Code treats each alias as follows: @@ -4982,11 +4142,7 @@ * Claude Code may rewrite `additionalMarketplaces` to `extraKnownMarketplaces` when it updates the file. * If you set both spellings in one file, Claude Code uses the canonical value and ignores the alias. -### - -​ - -`pluginConfigs` +### `pluginConfigs` Store the non-sensitive answers you give a plugin’s [`userConfig`](</docs/en/plugins/manifest-reference#user-configuration>) configuration dialog, keyed by plugin ID. Claude Code writes this key to your user settings when you fill in the dialog, so you don’t need to edit it by hand. Claude Code stores sensitive options in the macOS Keychain instead, falling back to `~/.claude/.credentials.json` when the Keychain rejects the write; on platforms without a supported keychain, it stores them in `~/.claude/.credentials.json`. @@ -5010,11 +4166,7 @@ Built-in plugins store their options under the same key with an `@builtin` suffix. For example, the [**Project instructions**](</docs/en/memory#choose-which-instruction-files-load>) setting that controls whether Claude Code reads `AGENTS.md` files is `pluginConfigs["cc-plugin-agents-md@builtin"].options.instructionFiles`. Before v2.1.285, the plugin’s ID was `agents-md@builtin`. Later versions read an entry under either ID. Claude Code ignores project and local entries because it substitutes these values into plugin hook, MCP, and LSP configurations, and a cloned repository must not be able to supply them. -### - -​ - -`prependPlugins` +### `prependPlugins` List the managed plugins whose [mods](</docs/en/plugins/mods/overview>) run before every mod a user installs, in the listed order. When you set this key in managed settings, name `sec-default@builtin` in the list to keep the built-in guard. In managed settings, Claude Code skips an id whose plugin doesn’t count as your organization’s. See [Install your organization’s mods and set the order](</docs/en/plugins/mods/admin#install-your-organizations-mods>) for those conditions and for how the two ordering keys work together. @@ -5034,11 +4186,7 @@ "prependPlugins": ["acme-guard@acme-tools", "sec-default@builtin"] } -### - -​ - -`appendPlugins` +### `appendPlugins` List the managed plugins whose [mods](</docs/en/plugins/mods/overview>) run after every mod a user installs, in the listed order. An id listed in both `prependPlugins` and `appendPlugins` is prepended. In managed settings, Claude Code skips an id whose plugin doesn’t [count as your organization’s](</docs/en/plugins/mods/admin#install-your-organizations-mods>). @@ -5058,19 +4206,11 @@ "appendPlugins": ["acme-audit@acme-tools"] } -## - -​ - -MCP +## MCP Control which MCP servers Claude Code connects to and which an organization allows. See [Connect to external tools with MCP](</docs/en/mcp>) and [Managed MCP configuration](</docs/en/managed-mcp>). -### - -​ - -`allowAllClaudeAiMcps` +### `allowAllClaudeAiMcps` Load the [claude.ai connectors](</docs/en/mcp#use-mcp-servers-from-claude-ai>) Claude Code fetches itself alongside a deployed `managed-mcp.json`. Without this key, `managed-mcp.json` takes exclusive control of MCP servers and suppresses those connectors. @@ -5088,11 +4228,7 @@ `allowedMcpServers` and `deniedMcpServers` still apply to the connectors this key loads. Connectors delivered to a [cloud session](</docs/en/claude-code-on-the-web>) whose host carries a `managed-mcp.json`, such as a self-hosted runner, stay suppressed. See [Allow claude.ai connectors alongside the managed set](</docs/en/managed-mcp#allow-claude-ai-connectors-alongside-the-managed-set>). -### - -​ - -`allowClaudeInChromeWithManagedMcp` +### `allowClaudeInChromeWithManagedMcp` Let the built-in [Claude in Chrome](</docs/en/chrome>) server run alongside a deployed `managed-mcp.json`. Without this key, a deployed `managed-mcp.json` blocks Claude in Chrome in terminal sessions. Requires Claude Code v2.1.282 or later. @@ -5110,11 +4246,7 @@ A `deniedMcpServers` entry for `claude-in-chrome` still blocks the server with this key on. See [Allow Claude in Chrome alongside the managed set](</docs/en/managed-mcp#allow-claude-in-chrome-alongside-the-managed-set>). -### - -​ - -`allowedMcpServers` +### `allowedMcpServers` Allowlist the MCP servers people can add. Claude Code blocks any server that doesn’t match an entry wherever it’s defined, including plugin servers, servers a user passes with `--mcp-config`, and servers from claude.ai. Built-in servers such as Claude in Chrome, the `ide` server Claude Code connects to in a running [VS Code](</docs/en/vs-code#the-built-in-ide-mcp-server>) or [JetBrains](</docs/en/jetbrains#the-built-in-ide-mcp-server>) IDE, and servers the CLI itself configures are exempt from the allowlist, and the denylist still applies to them. On Claude Code v2.1.268 or later, a [Claude Tag](</docs/en/claude-tag>) session’s Slack tools are also exempt from the allowlist, and the denylist still applies to them. In-process `type: "sdk"` servers are exempt from both lists; the [app that started the session](</docs/en/mcp#how-connectors-reach-claude-code>) registers them. Servers your organization delivers are also exempt from the allowlist, and the denylist still applies to them. The exemption covers every `managedMcpServers` entry, and any [`managed-mcp.json`](</docs/en/managed-mcp#exclusive-control-with-managed-mcp-json>) entry whose values use [no `${VAR}` expansion outside `env`](</docs/en/managed-mcp#how-allowlists-and-denylists-apply-to-the-managed-set>). See [How a server is evaluated](</docs/en/managed-mcp#how-a-server-is-evaluated>) for the full check order. Before v2.1.259, servers from `managed-mcp.json` had to match too. @@ -5134,11 +4266,7 @@ A `deniedMcpServers` entry takes precedence, so a server on both lists is blocked. Once the list contains any `serverCommand` entry, a stdio server must match a `serverCommand` entry, and once it contains any `serverUrl` entry, a remote server must match a `serverUrl` entry: a `serverName` match no longer admits that kind of server. See [Policy-based control with allowlists and denylists](</docs/en/managed-mcp#policy-based-control-with-allowlists-and-denylists>). -### - -​ - -`allowManagedMcpServersOnly` +### `allowManagedMcpServersOnly` Make the managed allowlist the only one that applies. Claude Code then reads `allowedMcpServers` from managed settings alone and ignores allowlists in user, project, and local settings; `deniedMcpServers` still merges from every settings scope, so users can still block servers for themselves. Administrators set it so a user’s own settings can’t broaden what the managed allowlist permits. @@ -5161,11 +4289,7 @@ Users can still add MCP servers of their own; only servers that match the managed allowlist load. See [Restrict the allowlist to managed settings only](</docs/en/managed-mcp#restrict-the-allowlist-to-managed-settings-only>). -### - -​ - -`deniedMcpServers` +### `deniedMcpServers` Block specific MCP servers. Claude Code refuses to load a matching server wherever it’s defined, including plugin servers, servers passed with `--mcp-config`, servers from `managed-mcp.json`, servers from `managedMcpServers`, and the claude.ai connectors [it fetches itself](</docs/en/mcp#how-connectors-reach-claude-code>). In-process `type: "sdk"` servers are exempt; the app that started the session registers them. @@ -5183,11 +4307,7 @@ The denylist takes precedence over `allowedMcpServers`, so a server on both lists is blocked. See [Policy-based control with allowlists and denylists](</docs/en/managed-mcp#policy-based-control-with-allowlists-and-denylists>). -### - -​ - -`disableClaudeAiConnectors` +### `disableClaudeAiConnectors` Turn off the [claude.ai MCP connectors](</docs/en/mcp#use-mcp-servers-from-claude-ai>) [Claude Code fetches itself](</docs/en/mcp#how-connectors-reach-claude-code>), so it neither fetches nor connects them. A `true` in any settings file applies: a checked-in project `.claude/settings.json` can opt a repository out of those connectors, but a project-level `false` can’t override a user- or managed-level `true`. @@ -5206,11 +4326,7 @@ Servers you pass explicitly with `--mcp-config` are unaffected. To block individual connectors instead of all of them, use `deniedMcpServers`. See [Disable claude.ai connectors](</docs/en/mcp#disable-claude-ai-connectors>). -### - -​ - -`disabledMcpjsonServers` +### `disabledMcpjsonServers` Reject specific servers defined in a project’s `.mcp.json` file so Claude Code never connects them or asks you to approve them. A rejection in any settings file applies, including a project `.claude/settings.json` checked into the repository. @@ -5226,11 +4342,7 @@ Claude Code writes this key to `.claude/settings.local.json` when you reject a server in the approval dialog. `claude mcp get <name>` shows a rejected server as `✘ Rejected (see disabledMcpjsonServers in settings)`. Rejection takes precedence over `enabledMcpjsonServers` and `enableAllProjectMcpServers`. -### - -​ - -`enableAllProjectMcpServers` +### `enableAllProjectMcpServers` Approve every MCP server defined in project `.mcp.json` files without a prompt. Claude Code writes this key to `.claude/settings.local.json` when you choose to approve all servers in the approval dialog. @@ -5248,11 +4360,7 @@ A `disabledMcpjsonServers` entry still rejects a server. -### - -​ - -`enabledMcpjsonServers` +### `enabledMcpjsonServers` Approve specific servers defined in project `.mcp.json` files so Claude Code connects them without asking. Claude Code writes this key to `.claude/settings.local.json` when you approve a server in the approval dialog. @@ -5270,11 +4378,7 @@ A `disabledMcpjsonServers` entry still rejects a server. -### - -​ - -`managedMcpServers` +### `managedMcpServers` Provide remote MCP servers to every user from managed settings. Users keep the servers they add themselves and can’t edit or remove the ones you provide. Requires Claude Code v2.1.259 or later. @@ -5297,25 +4401,17 @@ For precedence, how provided servers combine with `managed-mcp.json` and the allow and deny lists, and what users see, see [Provide servers through managed settings](</docs/en/managed-mcp#provide-servers-through-managed-settings>). -## - -​ - -Agents, sessions, and worktrees +## Agents, sessions, and worktrees Set the default agent, control teammates and cross-session messaging, and configure worktrees. See [Subagents](</docs/en/sub-agents>) and [Worktrees](</docs/en/worktrees>). -### - -​ - -`agent` +### `agent` Run the main thread as a named [subagent](</docs/en/sub-agents#invoke-subagents-explicitly>), so Claude Code applies that subagent’s system prompt, tool restrictions, and model to your session. The same key sets the default agent for sessions you dispatch from `claude agents`. * **Scope** : `Any file` * **Type** : string, the name of a built-in or custom agent - * **Default** : unset, so the main thread runs as Claude Code’s default agent + * **Default** : unset * **Per-session overrides** : `--agent` takes precedence over this key for one session settings.json @@ -5324,13 +4420,7 @@ "agent": "code-reviewer" } -A plugin’s own `settings.json` can also supply this key; see [Ship default settings with your plugin](</docs/en/plugins/components#default-settings>). - -### - -​ - -`crossSessionInbound` +### `crossSessionInbound` Choose what this session does with [messages arriving from your other Claude Code sessions](</docs/en/cross-session-messaging#control-inbound-messages>). When no value applies, Claude Code decides per message from the two sessions’ permission-mode classes. @@ -5349,11 +4439,7 @@ Claude Code reads managed settings first, then the `--settings` flag, then user settings, and applies the first value found. `refuse` is stricter than `hold`, and `hold` is stricter than `accept`. When none of the trusted sources sets a value, a project or local `hold` or `refuse` still applies, replacing the per-message default. In sessions with cross-session messaging, this key appears in `/config` as **Messages from your other sessions** , which writes it to user settings; the row requires Claude Code v2.1.232 or later, and Claude Code hides it while the `--settings` flag or managed settings set the key. Claude Code [warns](</docs/en/errors#crosssessioninbound-must-be-one-of-accept-hold-refuse>) when you set a value it doesn’t recognize. While that value is present in a user, project, local, or `--settings` file, Claude Code holds inbound messages, even when a source that takes precedence sets `accept`. A `refuse` that another source sets still applies. Fix or remove the value to clear the hold. When the unrecognized value is in [managed settings](</docs/en/managed-settings>), Claude Code instead treats it as `refuse` until an administrator fixes it. Before v2.1.248, Claude Code ignored an unrecognized value without warning. -### - -​ - -`disableAgentView` +### `disableAgentView` Turn off [background agents and agent view](</docs/en/agent-view>): `claude agents`, `--bg`, `/background`, and the on-demand supervisor. Set it in [managed settings](</docs/en/managed-settings>) to enforce it for an organization. @@ -5370,11 +4456,7 @@ "disableAgentView": true } -### - -​ - -`isolatePeerMachines` +### `isolatePeerMachines` Require your explicit approval before Claude’s `SendMessage` reaches one of your sessions beyond this machine; see [Require approval for cross-machine messages](</docs/en/cross-session-messaging#require-approval-for-cross-machine-messages>). The approval prompt appears even in [`bypassPermissions` mode](</docs/en/permission-modes#skip-all-checks-with-bypasspermissions-mode>). @@ -5392,11 +4474,7 @@ The cross-machine `SendMessage` approval requires Claude Code v2.1.224 or later. -### - -​ - -`processWrapper` +### `processWrapper` On macOS and Linux, place a corporate launcher command in front of the [background processes Claude Code starts](</docs/en/corporate-launcher#what-the-launcher-covers>). Claude Code runs the launcher with its own command line appended, so the launcher must exec into Claude Code; see [Run Claude Code behind a corporate launcher](</docs/en/corporate-launcher>) for the launcher contract. Requires Claude Code v2.1.210 or later. @@ -5413,11 +4491,7 @@ Claude Code ignores the launcher on Windows and starts every process unwrapped. Requires Claude Code v2.1.210 or later. -### - -​ - -`teammateMode` +### `teammateMode` Choose where Claude Code shows [agent team](</docs/en/agent-teams>) teammates: inside your main terminal pane, or in split panes when your terminal supports them. See [Choose a display mode](</docs/en/agent-teams#choose-a-display-mode>). @@ -5436,11 +4510,7 @@ "teammateMode": "auto" } -### - -​ - -`worktree` +### `worktree` Configure how Claude Code creates and manages [git worktrees](</docs/en/worktrees>) for `--worktree`, the `EnterWorktree` tool, and isolated subagents and background sessions. @@ -5461,11 +4531,7 @@ To copy gitignored files like `.env` into new worktrees, add a [`.worktreeinclude` file](</docs/en/worktrees#copy-gitignored-files-into-worktrees>) to your project root instead of a setting. -### - -​ - -`worktree.baseRef` +### `worktree.baseRef` Choose which ref new worktrees branch from. `"fresh"` branches from `origin/<default-branch>` for a clean tree matching the remote; `"head"` branches from your current local `HEAD`, so unpushed commits and feature-branch state are present in the worktree. @@ -5485,11 +4551,7 @@ Inside a linked worktree, `"head"` resolves to that worktree’s `HEAD`, not the main checkout’s. -### - -​ - -`worktree.symlinkDirectories` +### `worktree.symlinkDirectories` Symlink directories from the main repository into each worktree so you don’t duplicate large directories on disk. @@ -5507,11 +4569,7 @@ } } -### - -​ - -`worktree.sparsePaths` +### `worktree.sparsePaths` Check out only the listed directories in each worktree through git sparse-checkout. Claude Code writes only those directories plus root-level files to disk, which is faster in large monorepos; see [Check out only the directories you need](</docs/en/large-codebases#check-out-only-the-directories-you-need>). @@ -5531,11 +4589,7 @@ While a sparse worktree exists, git enables `extensions.worktreeConfig` in the repository’s shared `.git/config`. -### - -​ - -`worktree.bgIsolation` +### `worktree.bgIsolation` Choose how [background sessions](</docs/en/agent-view#how-file-edits-are-isolated>) isolate their file edits. If you moved a session to the background with `←` or `/background`, that session edits files in place whatever this key says. With `"worktree"`, Claude Code blocks `Edit` and `Write` in the main checkout until the session calls `EnterWorktree`; with `"none"`, background jobs edit the working copy directly. Set `"none"` for a repository where git worktrees are impractical. @@ -5555,11 +4609,7 @@ Outside a git repository, a [`WorktreeCreate` hook](</docs/en/worktrees#non-git-version-control>) that fails releases the block so the session can edit the working directory in place. -### - -​ - -`worktree.location` +### `worktree.location` Choose the folder on a remote machine where [Desktop SSH sessions](</docs/en/desktop#choose-where-ssh-session-worktrees-go>) create their worktrees, instead of `<project-root>/.claude/worktrees/`. Only the desktop app reads this key: `--worktree`, the `EnterWorktree` tool, isolated subagents, and background sessions ignore it. Requires Claude Desktop v1.44121.0 or later. @@ -5579,19 +4629,11 @@ A **Worktree folder** set on the SSH connection in Desktop takes precedence. If your organization restricts which folders sessions may use, Desktop keeps worktrees inside the project. -## - -​ - -Remote, desktop, and notifications +## Remote, desktop, and notifications Configure Remote Control, cloud environments, the desktop app, and the notifications Claude Code sends when it needs you. See [Remote Control](</docs/en/remote-control>). -### - -​ - -`agentPushNotifEnabled` +### `agentPushNotifEnabled` Allow Claude to send a push notification to your phone when it decides one is worth sending, for example when a long task finishes. In a local session, Claude can send one while [Remote Control](</docs/en/remote-control>) is connected. Appears in `/config` as **Push when Claude decides**. When you change it there, Claude Code also saves the value to your account. @@ -5609,11 +4651,7 @@ If you run sessions under a [`claude remote-control`](</docs/en/remote-control#start-a-remote-control-session>) server, they follow the value saved to your account rather than this key. To change that value, run `/config` in a Claude Code session in your terminal and turn **Push when Claude decides** on or off. If the toggle already shows the value you want, change it and change it back so that Claude Code saves that value to your account. See [Mobile push notifications](</docs/en/remote-control#mobile-push-notifications>). -### - -​ - -`awaySummaryEnabled` +### `awaySummaryEnabled` Show a one-line session recap when you return to the terminal after a few minutes away. Set it to `false`, or turn off **Session recap** in `/config`, to stop the recap. @@ -5632,11 +4670,7 @@ Claude Code never shows the recap in non-interactive mode. -### - -​ - -`disableArtifact` +### `disableArtifact` Deprecated, and replaced by `enableArtifact`. Claude Code still honors `disableArtifact: true` as equivalent to `enableArtifact: false`, and ignores `disableArtifact: false`. @@ -5657,11 +4691,7 @@ [Disable artifacts](</docs/en/artifacts#disable-artifacts>) lists every way to turn the tool off. -### - -​ - -`disableDeepLinkRegistration` +### `disableDeepLinkRegistration` Stop Claude Code from registering the `claude-cli://` protocol handler with the operating system. [Deep links](</docs/en/deep-links>) let external tools open a Claude Code session with a pre-filled prompt. Set this in environments where protocol handler registration is restricted or managed separately. @@ -5675,11 +4705,7 @@ "disableDeepLinkRegistration": "disable" } -### - -​ - -`disableDesktopLocalSessions` +### `disableDesktopLocalSessions` Turn off Code sessions that run on the device in the [desktop app](</docs/en/desktop#local-sessions-on-managed-devices>), for deployments where developers should work on remote machines over SSH. With the key set to `true`, users see this in the Code tab: @@ -5704,11 +4730,7 @@ The desktop app ignores any other value, and a value that isn’t a Boolean, such as the string `"true"` or `1`, also logs a warning. Pair it with `sshConfigs` so users land on a working connection, and with `sshHostAllowlist` to limit which hosts they can reach. See [Local sessions on managed devices](</docs/en/desktop#local-sessions-on-managed-devices>). Claude Desktop supplies Code sessions with policy derived from your desktop configuration, for example the egress allowlist, filesystem sandbox, and MCP restrictions in third-party deployments. Claude Code ignores those parent settings whenever an [admin source](</docs/en/managed-settings#how-claude-code-combines-managed-sources>) is present: server-managed settings, an MDM or OS-level policy, or a managed settings file. Deploying this key through one of those on a device that had none before, as in third-party deployments, therefore stops the desktop-derived policies from applying. [Let an embedding host add policy](</docs/en/managed-settings#let-an-embedding-host-add-policy>) covers when parent settings can still merge; this holds for any key you deploy that way, not only this one. -### - -​ - -`disableRemoteControl` +### `disableRemoteControl` Turn off [Remote Control](</docs/en/remote-control>): Claude Code then refuses `claude remote-control`, the `--remote-control` flag, auto-start, and the in-session toggle, and reports that your organization’s policy disabled it. Place it in [managed settings](</docs/en/managed-settings>) for per-device MDM enforcement. @@ -5724,11 +4746,7 @@ "disableRemoteControl": true } -### - -​ - -`disableRemotePreviewScripts` +### `disableRemotePreviewScripts` Keep scripts from running when people [preview an HTML file](</docs/en/desktop#preview-html-files-in-ssh-and-wsl-sessions>) from an SSH or WSL session in the desktop app. External browsing in the Browser pane is unaffected. The desktop app reads this key; the terminal CLI ignores it. Requires Claude Desktop v5.1231.0 or later. Earlier versions ignore the key: to stop the scripts there, also set `disableBrowserExternalNavigation`, which turns off external browsing too. @@ -5748,11 +4766,7 @@ The desktop app ignores any other value, and a value that isn’t a Boolean, such as the string `"true"` or `1`, also logs a warning. -### - -​ - -`enableArtifact` +### `enableArtifact` Turn off the [Artifact](</docs/en/artifacts>) tool, which publishes session output as a private web page on claude.ai. When you turn the **Artifacts** row off in `/config`, Claude Code writes this key to your user settings, so you don’t usually edit it by hand. @@ -5770,11 +4784,7 @@ While a source other than your own user settings keeps the tool turned off, Claude Code hides the **Artifacts** row in `/config`, because turning it on there wouldn’t change anything. [Disable artifacts](</docs/en/artifacts#disable-artifacts>) lists every way to turn the tool off. -### - -​ - -`inputNeededNotifEnabled` +### `inputNeededNotifEnabled` Get a push notification on your phone when a permission prompt or question is waiting for your input. In a local session, Claude Code sends these only while [Remote Control](</docs/en/remote-control>) is connected. Appears in `/config` as **Push when actions required**. @@ -5790,11 +4800,7 @@ See [Mobile push notifications](</docs/en/remote-control#mobile-push-notifications>). -### - -​ - -`preferredNotifChannel` +### `preferredNotifChannel` Choose how Claude Code notifies you when a task completes or a permission prompt is waiting. A [mod’s notifications](</docs/en/plugins/mods/api#show-something-without-starting-a-turn>) use the same setting. Appears in `/config` as **Local notifications**. @@ -5817,11 +4823,7 @@ With `"auto"`, Claude Code sends a desktop notification when it detects iTerm2, Ghostty, or Kitty. In Terminal.app it rings the bell character only when you have turned Terminal’s audible bell off, and in other terminals it does nothing. Set `"terminal_bell"` to ring the bell character in any terminal. See [Get a terminal bell or notification](</docs/en/terminal-config#get-a-terminal-bell-or-notification>). -### - -​ - -`remote.defaultEnvironmentId` +### `remote.defaultEnvironmentId` Pick the default [cloud environment](</docs/en/cloud-environments>) for cloud sessions you create from the CLI, such as with `claude --cloud`. Claude Code writes this key to your user settings when you pick an environment with [`/remote-env`](</docs/en/cloud-environments#select-an-environment-from-the-cli>). @@ -5840,11 +4842,7 @@ An Anthropic-hosted environment ID, which starts with `env_`, follows the standard settings precedence, so a value in a repository’s project settings overrides your user-level pick. A [self-hosted environment](</docs/en/self-hosted-environments>) ID, which starts with `ccpool_`, is honored only from user settings, managed settings, and the `--settings` flag; Claude Code ignores one in a repository’s project or local settings, and `/remote-env` shows which value it ignored, so a checked-in file can’t steer sessions onto a self-hosted environment you didn’t choose. -### - -​ - -`remoteControlAtStartup` +### `remoteControlAtStartup` Connect [Remote Control](</docs/en/remote-control>) automatically when each interactive session starts, instead of waiting for `/remote-control`. Set it to `true` to turn auto-connect on, `false` to turn it off. Appears in `/config` as **Enable Remote Control for all sessions**. @@ -5863,11 +4861,7 @@ Claude Code ignores a `true` from project or local settings, so a repository can turn auto-connect off for its checkout but can’t turn it on. For the full per-scope behavior, see [Enable Remote Control for all sessions](</docs/en/remote-control#enable-remote-control-for-all-sessions>) and the [security keys where the stricter value applies](</docs/en/settings#security-keys-where-the-stricter-value-applies>). -### - -​ - -`sshConfigs` +### `sshConfigs` Add SSH connections to the [Desktop](</docs/en/desktop#pre-configure-ssh-connections-for-your-team>) environment selector. Administrators use `sshConfigs` to distribute shared connections to a team. Users can select a managed connection and [set their own **Worktree folder**](</docs/en/desktop#set-the-worktree-folder-on-an-existing-connection>) for it. They can’t edit its other fields or delete it in the app. @@ -5889,11 +4883,7 @@ ] } -### - -​ - -`sshHostAllowlist` +### `sshHostAllowlist` Limit the hosts a [Desktop SSH session](</docs/en/desktop#restrict-which-ssh-hosts-users-can-connect-to>) can connect to. Only the Desktop app reads this key; the CLI doesn’t. Patterns are case-insensitive: `*` matches any host, `*.example.com` matches `example.com` and every subdomain, and anything else is an exact match against the hostname after `~/.ssh/config` resolution. An empty array turns SSH sessions off. With Claude Desktop v3.1623.0 or later, a session’s [jump hosts](</docs/en/desktop#allow-jump-hosts>) have to match a pattern too. @@ -5911,11 +4901,7 @@ A value that Desktop can’t read as a list of hosts, such as `true` or an object, counts as an empty array until you correct it, except `null`, which counts as unset. Requires Claude Desktop v2.26454.0 or later. If you set `managedSourcesBehavior` to `"merge"` in your highest-ranked source, Desktop combines the lists from every [admin source](</docs/en/managed-settings#how-claude-code-combines-managed-sources>) and allows a host that matches any of them. If you set an empty array in one source, SSH sessions stay on for the hosts another source lists. -### - -​ - -`sshHostCommands` +### `sshHostCommands` Add SSH connections whose host comes from a command to the [Desktop](</docs/en/desktop#create-an-ssh-connection-from-a-command>) environment selector. When you create a connection or create another machine for it, Desktop runs the entry’s command on your computer and connects to the host that the command prints. Requires Claude Desktop v3.6556.0 or later on macOS or Linux, or v4.16336.0 or later on Windows, signed in with a Claude account. On Windows, Desktop also has to [connect through the OpenSSH client](</docs/en/desktop#use-your-ssh-configuration>). @@ -5939,19 +4925,11 @@ On Windows, a bare name such as `acme-dev` doesn’t work, so [start the command with the program’s full path](</docs/en/desktop#write-the-command-on-windows>). Before Claude Code v2.1.307, the Edit tool refused a change that added this key to a valid settings file, with the error `Unrecognized field: sshHostCommands`. On those versions, add the key in a text editor instead; Claude Code loads a file that holds the key. In Desktop, the version that counts is the [Code tab’s Claude Code version](</docs/en/desktop#claude-code-version-in-the-code-tab>), not your terminal’s. -## - -​ - -Authentication and providers +## Authentication and providers Supply credentials through helper scripts and, for organizations, force a login method or organization. See [Authentication](</docs/en/authentication>). -### - -​ - -`allowedProviders` +### `allowedProviders` List the services a machine may reach Claude through, such as the Anthropic API, Amazon Bedrock, or an LLM gateway. A session on a provider that isn’t listed is refused at startup, at login, and when it next contacts the API, so switching to an unlisted provider mid-session is refused too. The [refusal message](</docs/en/errors#managed-settings-dont-allow-this-api-provider>) names what selected the provider and the steps to continue. Requires Claude Code v2.1.285 or later. @@ -5975,11 +4953,7 @@ Each cloud provider’s entry means that provider’s own service, including its regional, FIPS, and private endpoints. An entry Claude Code doesn’t recognize as a provider name is dropped and reported, and the rest of the list stays enforced. With an empty list, or one whose every entry is unrecognized, Claude Code refuses every provider and doesn’t start on the machine. -#### - -​ - -Endpoints that need a pin in managed `env` +#### Endpoints that need a pin in managed `env` A pin is an endpoint variable’s value set in a managed `env` block. When a session sends a provider’s traffic somewhere other than that provider’s own service, Claude Code admits it only if the session’s value is the same as the pin. These endpoints need one: @@ -5994,11 +4968,7 @@ The list doesn’t judge a cloud provider’s credential and tenancy variables or the network path, such as `HTTPS_PROXY` and certificate settings. Set those for the fleet in the managed `env` block. -### - -​ - -`apiKeyHelper` +### `apiKeyHelper` Run your own command to produce the credential Claude Code sends with model requests. Claude Code runs the command through the system shell, `/bin/sh` on macOS and Linux and `cmd` on Windows, and sends its output as both the `X-Api-Key` and `Authorization: Bearer` headers. Use it for dynamic or rotating credentials, such as short-lived tokens fetched from a vault. @@ -6021,11 +4991,7 @@ The last three cases apply only when the helper’s output is the credential Claude Code sends and `ANTHROPIC_AUTH_TOKEN` isn’t set. In interactive sessions, when the command comes from project or local settings, Claude Code doesn’t run it until you accept the workspace trust prompt. See [Credential management](</docs/en/authentication#credential-management>). -### - -​ - -`awsAuthRefresh` +### `awsAuthRefresh` Run your own command, such as `aws sso login`, to refresh the credentials in your `.aws` directory when the ones Claude Code has for [Amazon Bedrock](</docs/en/amazon-bedrock>) stop working. Claude Code checks the current credentials against STS first and runs the command only when that check fails, then reads the refreshed `.aws` directory. When the check fails at the same time in several Claude Code processes that use the same command and credentials, such as separate terminals or IDE windows, one process runs the command and the rest wait for that run instead of starting their own. A process that has waited 60 seconds with a request pending runs the command itself. To turn this off, set [`CLAUDE_CODE_DISABLE_AUTH_REFRESH_LOCK`](</docs/en/env-vars>) to `1`. @@ -6041,11 +5007,7 @@ Use this key when your refresh flow writes to `.aws`; use `awsCredentialExport` when it prints credentials instead. See [advanced credential configuration](</docs/en/amazon-bedrock#advanced-credential-configuration>). -### - -​ - -`awsCredentialExport` +### `awsCredentialExport` Run your own command that prints AWS credentials as JSON, so Claude Code can call [Amazon Bedrock](</docs/en/amazon-bedrock>) with credentials that don’t live in your `.aws` directory. Claude Code accepts the `aws sts` output shape and the flat `aws configure export-credentials` shape, and scopes the credentials to its own Bedrock client, so the shell commands Claude runs still see your ambient credentials. @@ -6061,11 +5023,7 @@ Unlike `awsAuthRefresh`, Claude Code always runs this command when it’s set, without checking the ambient credentials first. See [advanced credential configuration](</docs/en/amazon-bedrock#advanced-credential-configuration>). -### - -​ - -`forceLoginMethod` +### `forceLoginMethod` Restrict which kind of account people can log in with: `"claudeai"` for claude.ai sign-in or `"console"` for Claude Console sign-in. Set `"gateway"` to send people to a [cloud gateway](</docs/en/claude-apps-gateway>) instead of a first-party login. Administrators set it in managed settings and pair it with `forceLoginOrgUUID` to keep developers’ claude.ai logins inside one organization. If you set it to `"claudeai"` in any settings file, Claude Code also stops offering the [keyless Console sign-in](</docs/en/authentication#sign-in-without-an-api-key>) in the sessions that file applies to. With `"console"` alone, people can still reach the keyless sign-in after a failed login. To stop Claude Code offering it, see [Stop offering the keyless sign-in on managed machines](</docs/en/authentication#stop-offering-the-keyless-sign-in-on-managed-machines>), which also lists what else `forceLoginOrgUUID` changes. @@ -6084,11 +5042,7 @@ Every first-party login path applies the restriction, including the [VS Code extension](</docs/en/vs-code>), the Agent SDK, `claude setup-token`, and `/install-github-app`, except the terminal’s interactive login screen, reached by `/login` or first-run onboarding, which pre-selects the method without enforcing it. Before v2.1.212, only terminal logins applied it. See [Restrict login to your organization](</docs/en/authentication#restrict-login-to-your-organization>) for how each login path, environment credentials, and third-party providers are handled. When a managed source on the machine sets `"gateway"`, Claude Code doesn’t use a leftover login, API key, or `apiKeyHelper` credential. See [Administrator policy requires a Cloud gateway sign-in](</docs/en/errors#administrator-policy-requires-a-cloud-gateway-sign-in>) for the message each one produces. If you select a cloud provider through `CLAUDE_CODE_USE_BEDROCK` or a similar environment variable, the session doesn’t need the gateway sign-in. Before v2.1.261, Claude Code used a leftover login on these machines. -### - -​ - -`forceLoginGatewayUrl` +### `forceLoginGatewayUrl` Set the gateway URL the `/login` Cloud gateway screen connects to, so people reach your [cloud gateway](</docs/en/claude-apps-gateway>) without typing its address. The screen has no URL field: with this key set, it shows your gateway URL and connects when the person presses Enter; without it, it tells them to contact their IT administrator. In managed settings, either this key or `forceLoginMethod: "gateway"` makes the machine gateway-only, except for sessions that select a cloud provider with `CLAUDE_CODE_USE_*`. `/login` then opens on the Cloud gateway screen with no login-method picker. See [Administrator policy requires a Cloud gateway sign-in](</docs/en/errors#administrator-policy-requires-a-cloud-gateway-sign-in>) for what happens to a leftover first-party login or API key. Set both keys so the screen connects instead of showing an error. @@ -6104,11 +5058,7 @@ If the value isn’t a valid URL, the sign-in screen reports it, and the rest of the managed settings file still applies. See [Set the gateway URL](</docs/en/claude-apps-gateway#set-the-gateway-url>). -### - -​ - -`forceLoginOrgUUID` +### `forceLoginOrgUUID` From a managed source, require claude.ai account logins to belong to one Anthropic organization, given as a single UUID, or to any of several organizations, given as an array. From any settings file, Claude Code also uses a single UUID to pre-select that organization during a claude.ai or Claude Console login, and pre-selects nothing for an array. If you set the key in any settings file, Claude Code also stops offering the [keyless Console sign-in](</docs/en/authentication#sign-in-without-an-api-key>) in the sessions that file applies to and creates an API key instead. @@ -6126,11 +5076,7 @@ If a managed source sets an empty array, or a value that isn’t a string or an array of strings, users who sign in with an Anthropic account can’t start Claude Code or complete a login. They see a message that names `forceLoginOrgUUID` and tells them to contact their administrator. A `policyHelper` that emits a value of the wrong type fails its run instead. See [Restrict login to your organization](</docs/en/authentication#restrict-login-to-your-organization>) for how Claude Code treats Claude Console logins, the other login paths, and environment credentials. -### - -​ - -`gatewayInternalNetworks` +### `gatewayInternalNetworks` Declare the public IPv4 blocks that your organization numbers its internal network from, so `/login` accepts a [cloud gateway](</docs/en/claude-apps-gateway>) there. Requires Claude Code v2.1.268 or later. Without this key, `/login` connects to any gateway on a private address and nothing else. With it, `/login` also accepts a gateway inside a listed block, over a direct connection only. The machine’s own address on that connection must also be inside the same block. @@ -6146,11 +5092,7 @@ Replace the documentation range in the example with your own block. Claude Code refuses the documentation ranges, the ranges that VPN and NAT64 clients use locally, and reserved space that no network is numbered from, such as multicast. If an entry is invalid, or the value isn’t a list of strings, `/login` names the problem and refuses every new gateway sign-in on the machine until you fix the value. Existing sign-ins keep working. See [Allow a gateway on public address space you own](</docs/en/claude-apps-gateway#allow-a-gateway-on-public-address-space-you-own>) for the full rules and what developers see. -### - -​ - -`gcpAuthRefresh` +### `gcpAuthRefresh` Run your own command to refresh Google Cloud Application Default Credentials when Claude Code finds they’ve expired or can’t be loaded, so [Google Cloud’s Agent Platform](</docs/en/google-vertex-ai>) requests keep working without you re-authenticating by hand. When several Claude Code processes that use the same command and credentials, such as separate terminals or IDE windows, find them expired at the same time, one process runs the command and the rest wait for that run instead of starting their own. A process that has waited 60 seconds with a request pending runs the command itself. To turn this off, set [`CLAUDE_CODE_DISABLE_AUTH_REFRESH_LOCK`](</docs/en/env-vars>) to `1`. @@ -6166,11 +5108,7 @@ See [advanced credential configuration](</docs/en/google-vertex-ai#advanced-credential-configuration>). -### - -​ - -`otelHeadersHelper` +### `otelHeadersHelper` Run your own command to generate the headers Claude Code sends with OpenTelemetry exports, for backends whose tokens rotate. Claude Code runs it at startup and periodically after that, and expects a JSON object of string header values on stdout. @@ -6186,19 +5124,11 @@ Set the refresh interval with [`CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS`](</docs/en/env-vars>). See [Dynamic headers](</docs/en/monitoring-usage#dynamic-headers>) for the script requirements and what happens when the helper fails. -## - -​ - -Updates and versioning +## Updates and versioning Choose an update channel and, for organizations, pin the versions people can run. See [Update Claude Code](</docs/en/setup#update-claude-code>). -### - -​ - -`autoUpdatesChannel` +### `autoUpdatesChannel` Choose which [release channel](</docs/en/setup#configure-release-channel>) background auto-updates and `claude update` follow. Set `"stable"` for a version that is typically about one week old and skips releases with major regressions, or `"latest"` for the most recent release. @@ -6216,11 +5146,7 @@ Claude Code writes `"stable"` to your user settings when you pick it under **Auto-update channel** in `/config`, and removes the key when you switch back to latest there. `claude install stable` and `claude install latest` also save the channel you name. Switching from `"latest"` to `"stable"` in `/config` asks whether to allow a downgrade or stay on your current version; staying sets `minimumVersion`. Homebrew installs ignore this key: the `claude-code` cask tracks stable and `claude-code@latest` tracks latest, and `claude update` defers to `brew upgrade`. To turn auto-updates off entirely, set [`DISABLE_AUTOUPDATER`](</docs/en/setup#disable-auto-updates>) in `env`. -### - -​ - -`minimumVersion` +### `minimumVersion` Keep background auto-updates and `claude update` from installing any version below this one, so moving to the `"stable"` channel doesn’t downgrade you from a newer `"latest"` build. Claude Code writes this key for you when you choose to stay on your current version while switching channels in `/config`, and clears it when you switch back to `"latest"`. @@ -6239,11 +5165,7 @@ This key only constrains updates. To make Claude Code refuse to start below a version, use `requiredMinimumVersion` instead. See [Pin a minimum version](</docs/en/setup#pin-a-minimum-version>). -### - -​ - -`requiredMaximumVersion` +### `requiredMaximumVersion` Set the newest Claude Code version your organization allows to start. When the running version is newer, Claude Code exits at startup and tells the user to install an approved version through your organization’s approved method; `claude install <version>` may also work. Requires Claude Code v2.1.163 or later. @@ -6259,11 +5181,7 @@ Background auto-updates and `claude update` skip versions above the ceiling, so an installation inside the range stays inside it. `claude update`, `claude install`, and `claude doctor` keep working above the ceiling so users can recover. Pair it with `requiredMinimumVersion` to enforce a range. -### - -​ - -`requiredMinimumVersion` +### `requiredMinimumVersion` Set the oldest Claude Code version your organization allows to start. When the running version is older, Claude Code exits at startup and tells the user to update through your organization’s approved method. The check runs at startup only, so a session that’s already running continues. Requires Claude Code v2.1.163 or later. @@ -6279,19 +5197,11 @@ `claude update`, `claude install`, and `claude doctor` keep working below the floor so users can recover. Unlike `minimumVersion`, which only prevents downgrades, this key blocks startup. Pair it with `requiredMaximumVersion` to enforce a range. -## - -​ - -Tools +## Tools Turn off specific tools in the [Claude Code desktop app](</docs/en/desktop>). The terminal CLI ignores these keys. For the tools themselves, see [Tools available to Claude](</docs/en/tools-reference>). -### - -​ - -`browserExternalPageTools` +### `browserExternalPageTools` Stop Claude from using its tools to read or act on external pages in the desktop app’s [Browser pane](</docs/en/desktop#browse-external-sites>). People in your organization can still open external sites themselves, and local dev server previews keep working with Claude’s tools. The desktop app reads this key; the terminal CLI ignores it. @@ -6307,11 +5217,7 @@ Any other value leaves Claude’s tools on, and a non-empty string that isn’t one of the two accepted values logs a warning. To block external sites for people and Claude alike, set `disableBrowserExternalNavigation` instead. See [Restrict external browsing for your organization](</docs/en/desktop#restrict-external-browsing-for-your-organization>). -### - -​ - -`disableBrowserExternalNavigation` +### `disableBrowserExternalNavigation` Turn off external browsing in the desktop app’s [Browser pane](</docs/en/desktop#browse-external-sites>) for people and Claude alike. Localhost dev server previews keep working. HTML previews in SSH and WSL sessions still open, but they [don’t run scripts](</docs/en/desktop#turn-off-scripts-in-ssh-and-wsl-previews-for-your-organization>). The desktop app reads this key; the terminal CLI ignores it. @@ -6329,11 +5235,7 @@ The desktop app ignores any other value, and a value that isn’t a Boolean, such as the string `"true"` or `1`, also logs a warning. To leave external browsing on but keep Claude’s tools off external pages, set `browserExternalPageTools` instead. See [Restrict external browsing for your organization](</docs/en/desktop#restrict-external-browsing-for-your-organization>). If the computer that runs the desktop app receives no other Claude Code managed settings, also set `parentSettingsBehavior` to `"merge"` in the managed settings that you create. On Windows, if you create a managed settings file, users also lose WSL sessions until you [allow them](</docs/en/admin-setup#wsl-sessions-in-claude-code-desktop>). See [Turn off scripts in SSH and WSL previews for your organization](</docs/en/desktop#turn-off-scripts-in-ssh-and-wsl-previews-for-your-organization>) for the reasons. -### - -​ - -`disableMobileSimulatorTools` +### `disableMobileSimulatorTools` Block Claude’s tools for the desktop app’s [iOS Simulator pane](</docs/en/desktop-ios-simulator#turn-off-simulator-access>). People keep manual use of the pane; only Claude’s access is removed, and nobody can turn it back on from inside the app. The desktop app reads this key; the terminal CLI ignores it. @@ -6351,19 +5253,11 @@ The desktop app ignores any other value, and a value that isn’t a Boolean, such as the string `"true"` or `1`, also logs a warning. -## - -​ - -Privacy and telemetry +## Privacy and telemetry Control how long Claude Code keeps session data and what it sends. The switches that turn off usage metrics and error reports are environment variables, not settings keys: set `DISABLE_TELEMETRY`, `DISABLE_ERROR_REPORTING`, or `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` in the `env` key or in the shell. [Telemetry services](</docs/en/data-usage#telemetry-services>) says what each one stops. Two exceptions turn off from a settings file: `feedbackDrafts` below for Claude-drafted feedback, and `feedbackSurveyRate` below for the session survey. -### - -​ - -`cleanupPeriodDays` +### `cleanupPeriodDays` Set how many days Claude Code keeps [session transcripts and other application data](</docs/en/claude-directory#cleaned-up-automatically>) before deleting them. Claude Code runs the deletion as a background sweep after a session starts, as long as it can safely determine the retention period. The sweep deletes transcripts without showing a message, so a session you haven’t used for longer than the retention period no longer appears in the [`/resume`](</docs/en/sessions#resume-a-session>) picker. By default, Claude Code keeps transcripts of sessions you started or most recently continued in Claude Desktop or Cowork past this period, even if you set this key yourself. This period [still applies to them in some cases](</docs/en/claude-directory#cleaned-up-automatically>), such as under the HIPAA configuration. Before v2.1.248, Claude Code deleted them after this period. @@ -6379,11 +5273,7 @@ Setting `0` fails validation, so pick a large value such as `3650` for long retention. To stop Claude Code from writing transcripts at all, see [Plaintext storage](</docs/en/claude-directory#plaintext-storage>). -### - -​ - -`desktopSessionCleanupPeriodDays` +### `desktopSessionCleanupPeriodDays` Set an age limit in days for the transcripts of sessions you started or most recently continued in Claude Desktop or Cowork. Without this key, Claude Code [keeps those transcripts at any age](</docs/en/claude-directory#cleaned-up-automatically>), except in cases such as a session you deleted in Claude Desktop. Requires Claude Code v2.1.248 or later. Claude Code deletes each transcript once it’s older than both this limit and `cleanupPeriodDays`, so with `cleanupPeriodDays` at its default of 30, a value of `7` still keeps them 30 days. [Cleaned up automatically](</docs/en/claude-directory#cleaned-up-automatically>) lists cases where `cleanupPeriodDays` applies instead and Claude Code ignores this key. @@ -6397,11 +5287,7 @@ "desktopSessionCleanupPeriodDays": 90 } -### - -​ - -`feedbackDrafts` +### `feedbackDrafts` Control [Claude-drafted feedback](</docs/en/tools-reference#sendfeedback-tool-behavior>): whether Claude can queue feedback drafts for you to review, and whether Claude Code shows a card when Claude queues one. @@ -6421,11 +5307,7 @@ Appears in `/config` as **Claude-drafted feedback** , which writes this key to your user settings. You see the `/config` row only in sessions [where Claude can draft feedback](</docs/en/tools-reference#sessions-without-claude-drafted-feedback>); setting `"off"` doesn’t hide it, so you can turn the feature back on from the same row. A value in managed settings takes precedence over your user setting, so when an administrator sets this key, the row shows the managed value and changing it has no effect. Claude Code ignores this key in project and local settings. -### - -​ - -`feedbackSurveyRate` +### `feedbackSurveyRate` Set the probability that the [session quality survey](</docs/en/data-usage#session-quality-surveys>) appears when a session is eligible for it. Set `0` to keep the survey from appearing. @@ -6442,11 +5324,7 @@ The same rate applies to the survey in the VS Code extension. -### - -​ - -`skipWebFetchPreflight` +### `skipWebFetchPreflight` Skip the [WebFetch domain safety check](</docs/en/data-usage#webfetch-domain-safety-check>), which sends each requested hostname to `api.anthropic.com` before fetching. Set `true` in environments that block traffic to Anthropic, such as Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry deployments with restrictive egress. @@ -6464,19 +5342,11 @@ With the check skipped, WebFetch attempts any URL without consulting the blocklist, so pair it with [`WebFetch` permission rules](</docs/en/permissions#webfetch>) if you need to restrict which domains Claude can reach. -## - -​ - -Enterprise and managed settings +## Enterprise and managed settings Keys an organization uses to compute, refresh, and combine managed settings. See [Set up managed settings](</docs/en/admin-setup>). -### - -​ - -`disableSideloadFlags` +### `disableSideloadFlags` Reject the `--plugin-dir`, `--plugin-url`, `--agents`, and `--mcp-config` CLI flags at startup, which users could otherwise pass to bypass `strictKnownMarketplaces` for a single run. Claude Code exits with an error naming the rejected flags. In [cloud sessions](</docs/en/claude-code-on-the-web>), Claude Code instead starts the session and drops every server-delivered `--mcp-config` entry except in-process `type: "sdk"` entries and a [Claude Tag](</docs/en/claude-tag>) session’s Slack tools. Requires Claude Code v2.1.193 or later. @@ -6502,11 +5372,7 @@ * **[Code sessions on the user’s machine](</docs/en/desktop#environment-configuration>)** : they also start without the skills enabled for the user’s claude.ai account. Plugins that Claude Code installs from marketplaces in your managed settings still load. In [Claude Desktop on 3P](<https://claude.com/docs/third-party/claude-desktop/overview>), MCP servers from plugins you deploy to the device’s `org-plugins` directory stay available too, because the desktop app connects to them itself. Before Claude Desktop v1.37937.0, these sessions failed at startup instead. * **[Cowork sessions on the user’s machine](</docs/en/managed-settings#where-and-when-a-policy-applies>)** : the skills inside those plugins and the skills enabled for the user’s claude.ai account stay available. In [Claude Desktop on 3P](<https://claude.com/docs/third-party/claude-desktop/overview>), MCP servers from plugins you deploy to the device’s `org-plugins` directory stay available too, because the desktop app connects to them itself. Before Claude Desktop v1.44121.0, these sessions failed at startup instead. -### - -​ - -`forceRemoteSettingsRefresh` +### `forceRemoteSettingsRefresh` Block CLI startup until Claude Code has freshly fetched [server-managed settings](</docs/en/server-managed-settings>). If the fetch fails, Claude Code exits instead of continuing with cached or no settings. Set it when your environment can’t accept even a brief window in which a session runs without its managed policy. When the key is unset, Claude Code doesn’t block startup on the fetch, though when the developer signs in at startup it waits up to five seconds for the fetch. [Anthropic can require the settings](</docs/en/server-managed-settings#fetch-and-caching-behavior>), which does block a start without them. A Cloud gateway session waits, and exits if the gateway can’t be reached. @@ -6524,11 +5390,7 @@ Set it in an MDM profile or the managed settings file to enforce fail-closed startup before the first server payload arrives. Claude Code applies the check only in sessions that fetch server-managed settings, so a session that [doesn’t fetch them](</docs/en/server-managed-settings#platform-availability>) starts without waiting. The `claude auth` subcommands are exempt, so users can re-authenticate when expired credentials are why the fetch fails. See [Enforce fail-closed startup](</docs/en/server-managed-settings#enforce-fail-closed-startup>). -### - -​ - -`managedSourcesBehavior` +### `managedSourcesBehavior` Choose whether Claude Code applies only the highest-priority [managed source](</docs/en/managed-settings#how-claude-code-combines-managed-sources>) your organization delivers, or combines every admin source it delivers. By default Claude Code takes the highest-priority source that carries a [policy key](</docs/en/managed-settings#how-claude-code-combines-managed-sources>) and ignores the rest. A policy key is any settings key other than this one and `wslInheritsWindowsSettings`. Under that default, once server-managed settings or an MDM policy deliver a policy key, a `managed-settings.json` file contributes only the [keys Claude Code reads from every admin source](</docs/en/managed-settings#keys-read-from-every-admin-source>). With `"merge"`, every admin source you deliver contributes its keys to one combined policy. Requires Claude Code v2.1.242 or later. Set `"merge"` only where every source [ranked](</docs/en/managed-settings#how-claude-code-combines-managed-sources>) below your highest one is under an administrator’s control, because Claude Code then adds entries from a lower source, such as `permissions.allow` rules, to the policy. @@ -6567,11 +5429,7 @@ To confirm which sources combined on a machine, run `/status` and [read the `Setting sources` line](</docs/en/managed-settings#read-the-source-in-/status>). -### - -​ - -`parentSettingsBehavior` +### `parentSettingsBehavior` Choose whether Claude Code applies managed settings supplied by an embedding host process, such as the Agent SDK or an IDE extension, when an admin-deployed managed tier is also present. With `"first-wins"`, Claude Code drops the host-supplied settings; with `"merge"`, it applies them under the admin tier through a restrictive-only filter. Set `"merge"` when a host needs to pass its own restrictions to the sessions it launches, for example Claude Desktop delivering a gateway’s egress allowlist. @@ -6589,11 +5447,7 @@ This key has no effect when no admin-deployed managed tier exists: the host’s settings then apply as the only managed tier, still filtered to restrictive values. For the filter’s limits and how the managed sources interact, see [Parent settings from embedding hosts](</docs/en/managed-settings#parent-settings-from-embedding-hosts>) and [Restrict parent settings](</docs/en/claude-apps-gateway#restrict-parent-settings>). -### - -​ - -`policyHelper` +### `policyHelper` Run an executable you deploy that computes managed settings at startup, so you can derive policy from device posture, identity, or a remote service instead of a static file. Claude Code runs the helper before it accepts the first prompt and treats the settings it emits as the managed settings for the session. @@ -6613,11 +5467,7 @@ } } -#### - -​ - -Write the helper output +#### Write the helper output Claude Code runs the helper with no arguments, sets `CLAUDE_CODE_VERSION` in its environment, and reads a JSON envelope from stdout, capped at 1 MiB. Put the settings under a `managedSettings` key. A bare settings object with no `managedSettings` key parses with `managedSettings` undefined and applies nothing, and Claude Code reports no error: @@ -6629,11 +5479,7 @@ When the helper emits `managedSettings`, that object becomes the only managed settings source for the run: Claude Code ignores the MDM, file, and HKCU sources, reads the [cross-source keys](</docs/en/managed-settings#keys-read-from-every-admin-source>) from the helper’s output alone, and never merges [parent settings](</docs/en/managed-settings#parent-settings-from-embedding-hosts>). The startup `forceRemoteSettingsRefresh` check runs before the helper and reads any admin source. A helper that exits `0` with an envelope that omits `managedSettings` contributes no managed settings, and the other sources apply as usual. -#### - -​ - -Helper failures +#### Helper failures A helper run fails when: @@ -6645,11 +5491,7 @@ When the startup run fails, Claude Code prints the reason and refuses to start. After a non-zero exit, the reason includes the helper’s stderr, or its stdout when stderr is empty. After a timeout, the reason names the `timeoutMs` limit and includes none of the helper’s output. The refusal covers interactive sessions, `claude -p`, Agent SDK sessions, [background sessions](</docs/en/agent-view>), and most subcommands. The refusal is deliberate, so a helper that needs outage resilience should serve from its own cache and exit `0`. When a background refresh fails, Claude Code keeps the last successful policy in effect, and `/status` shows the failing refresh with its reason until a refresh succeeds. Each refresh runs under the same `timeoutMs` and failure rules as the startup run. With `--debug`, Claude Code writes the helper’s stderr from every run to the [debug log](</docs/en/debug-your-config>). Claude Code reports an invalid `policyHelper` value as a [dropped entry](</docs/en/managed-settings#find-entries-claude-code-dropped>) and starts the session on the remaining managed settings without running a helper. Invalid values include a bare path string and a `timeoutMs` below its minimum. To turn a helper off, remove the key from the source that sets it. -### - -​ - -`policyHelper.path` +### `policyHelper.path` Name the helper executable Claude Code runs. For what happens when the path breaks the rules below, see Helper failures. @@ -6665,11 +5507,7 @@ } } -### - -​ - -`policyHelper.timeoutMs` +### `policyHelper.timeoutMs` Set how long Claude Code waits for the helper before treating the run as failed. A timed-out run fails the same way as a non-zero exit, so at startup Claude Code refuses to start. @@ -6686,11 +5524,7 @@ } } -### - -​ - -`policyHelper.refreshIntervalMs` +### `policyHelper.refreshIntervalMs` Have Claude Code re-run the helper in the background on an interval so policy changes reach a running session. When a refresh succeeds, its output replaces the previous managed settings without a restart; when a refresh fails, Claude Code keeps the policy it already has. @@ -6709,11 +5543,7 @@ } } -### - -​ - -`wslInheritsWindowsSettings` +### `wslInheritsWindowsSettings` Have Claude Code on WSL read managed settings from the Windows policy chain, with HKLM and the Windows managed settings file taking priority over `/etc/claude-code` and HKCU below it. While the chain is on, Claude Code reads `/etc/claude-code` only when [no Windows admin document is present](</docs/en/managed-settings#present-admin-documents>) in the HKLM registry value or the `C:\Program Files\ClaudeCode\` folder. Set it to extend the policy you already deploy on Windows to WSL sessions on the same machine, so they follow the same rules as host sessions. Claude Code honors it only when set in the HKLM registry key or in a managed settings file or drop-in under `C:\Program Files\ClaudeCode\`, both of which require Windows admin to write. @@ -6731,19 +5561,11 @@ Once an admin source turns the chain on, HKCU policy joins it on WSL only when HKCU also sets the key to `true`. That copy doesn’t turn the chain on by itself. A Windows source that contains only this key, set to `true` or `false`, doesn’t count as a policy source, so a lower-priority source still supplies the policy. This key has no effect on native Windows. Claude Code reads `true` and `false` with or without quotes and reads `null` as removing the key. An admin-controlled Windows source that holds any other value counts as a [present admin document](</docs/en/managed-settings#present-admin-documents>) with the chain turned on: neither `/etc/claude-code` nor HKCU applies, and a startup warning names the key. An HKLM value or Windows-folder file that exists but can’t be read also keeps `/etc/claude-code` from applying whether or not the chain is on. Requires Claude Code v2.1.282 or later. -## - -​ - -Global config settings +## Global config settings Save these keys in `~/.claude.json`, not in a settings file. Claude Code ignores them anywhere else. Claude Code and `/config` write most of them for you, and you can also edit them by hand. -### - -​ - -`autoConnectIde` +### `autoConnectIde` Connect to a running IDE automatically when you start Claude Code from an external terminal. Appears in `/config` as **Auto-connect to IDE (external terminal)** when you run Claude Code outside a VS Code or JetBrains terminal. @@ -6762,11 +5584,7 @@ Claude Code ignores this key in `settings.json`. -### - -​ - -`autoInstallIdeExtension` +### `autoInstallIdeExtension` Let [`/ide`](</docs/en/commands>) install the Claude Code IDE extension in a running VS Code, Cursor, or Devin Desktop when you run the command from an external terminal. Claude Code doesn’t install or update the extension when you start `claude`. Before v2.1.318, Claude Code installs or updates the extension when you start `claude` in one of those editors’ terminals, unless this key is `false`. Appears in `/config` as **Auto-install IDE extension** when you run Claude Code inside a VS Code or JetBrains terminal. @@ -6785,11 +5603,7 @@ Claude Code ignores this key in `settings.json`. -### - -​ - -`claudeInChromeDefaultEnabled` +### `claudeInChromeDefaultEnabled` Start every interactive CLI session with [Chrome integration](</docs/en/chrome>) on, without passing `--chrome` each time. If you run [`claude remote-control`](</docs/en/remote-control>), a session it starts for one of your [project](</docs/en/claude-projects>) threads follows this key too, except in `bypassPermissions` mode. With Claude Code v2.1.287 or later, this key also applies to sessions in the [VS Code extension](</docs/en/vs-code#automate-browser-tasks-with-chrome>): see [Enable Chrome by default](</docs/en/chrome#enable-chrome-by-default>). Running `/chrome` and selecting **Enabled by default** sets this key for you, as does answering the [“Claude in Chrome extension detected” dialog](</docs/en/chrome#answer-the-startup-dialog>). Appears in `/config` as **Claude in Chrome enabled by default**. @@ -6808,11 +5622,7 @@ Claude Code ignores this key in `settings.json`. -### - -​ - -`copyFullResponse` +### `copyFullResponse` Make [`/copy`](</docs/en/commands>) copy the full response every time, without showing the picker. Selecting **Always copy full response** in that picker sets this key to `true`. Appears in `/config` as **Skip the /copy picker**. @@ -6830,11 +5640,7 @@ Claude Code ignores this key in `settings.json`. -### - -​ - -`copyOnSelect` +### `copyOnSelect` Copy text to your clipboard automatically when you finish selecting it with the mouse in [fullscreen rendering](</docs/en/fullscreen#use-the-mouse>) or [agent view](</docs/en/agent-view>). Appears in `/config` as **Copy on select** while fullscreen rendering is on. @@ -6852,11 +5658,7 @@ Claude Code ignores this key in `settings.json`. -### - -​ - -`defaultToAgentsView` +### `defaultToAgentsView` Open [agent view](</docs/en/agent-view>) instead of a new conversation when you run `claude` with no arguments. Appears in `/config` as **Open agents view by default** unless agent view is turned off. @@ -6874,11 +5676,7 @@ Claude Code ignores this key in `settings.json`. -### - -​ - -`diffTool` +### `diffTool` Choose where Claude Code shows the diff of an `Edit` or `Write` change it proposes when a [VS Code](</docs/en/vs-code>) or [JetBrains](</docs/en/jetbrains#features>) IDE is connected: `"auto"` opens it in the IDE’s diff viewer, `"terminal"` keeps it in the terminal. Appears in `/config` as **Diff tool** only while Claude Code is connected to a VS Code or JetBrains IDE. @@ -6896,11 +5694,7 @@ Claude Code ignores this key in `settings.json`. -### - -​ - -`externalEditorContext` +### `externalEditorContext` When you press `Ctrl+G`, Claude Code opens the prompt you’re typing in your [external editor](</docs/en/interactive-mode#general-controls>). With this key on, the editor buffer starts with Claude’s previous response as `#` comment lines, so you can read it while you write, and Claude Code strips those lines when you save. Appears in `/config` as **Show last response in external editor**. @@ -6928,11 +5722,7 @@ Claude Code keeps the last 50 lines of the response and marks the cut with `# … (earlier output truncated)`. Claude Code ignores this key in `settings.json`. -### - -​ - -`leftArrowOpensAgents` +### `leftArrowOpensAgents` Press `←` on an empty prompt to [background the session and open agent view](</docs/en/agent-view#switch-sessions-without-leaving-the-terminal>). Set this key to `false` to turn the shortcut off. Appears in `/config` as **← opens agents** when agent view is available. @@ -6950,11 +5740,7 @@ Claude Code ignores this key in `settings.json`. -### - -​ - -`permissionExplainerEnabled` +### `permissionExplainerEnabled` Removed in v2.1.257, together with the `Ctrl+E` command explanation on Bash and PowerShell permission prompts. Setting it has no effect on current versions. @@ -6964,11 +5750,7 @@ * **Type** : Boolean * **Default** : `true` -### - -​ - -`prStatusFooterEnabled` +### `prStatusFooterEnabled` Show a badge in the prompt footer for the current branch’s open pull request or merge request, with a colored underline that shows its [status](</docs/en/interactive-mode#pr-review-status>). Appears in `/config` as **Show PR status footer**. @@ -6986,11 +5768,7 @@ Claude Code ignores this key in `settings.json`. -### - -​ - -`teammateDefaultModel` +### `teammateDefaultModel` Removed in v2.1.234, together with its `/config` row **Default teammate model**. Setting it has no effect on current versions. @@ -7000,11 +5778,7 @@ * **Type** : string, a model alias or full model ID, or `null` * **Default** : unset -## - -​ - -See also +## See also * [Configure permissions](</docs/en/permissions>): rule syntax, permission modes, and workspace trust * [Environment variables](</docs/en/env-vars>): every `CLAUDE_*`, `ANTHROPIC_*`, and provider variable Claude Code reads
modified Advanced setup View current →
Show diff (382 lines)
--- a/setup.md +++ b/setup.md @@ -1,10 +1,6 @@ This page covers system requirements, platform-specific installation details, updates, and uninstallation. For a guided walkthrough of your first session, see the [quickstart](</docs/en/quickstart>). If you’ve never used a terminal before, see the [terminal guide](</docs/en/terminal-guide>). -## - -​ - -System requirements +## System requirements Claude Code runs on the following platforms and configurations: @@ -19,20 +15,12 @@ * **Shell** : Bash, Zsh, PowerShell, or CMD. * **Location** : [Anthropic supported countries](<https://www.anthropic.com/supported-countries>) -### - -​ - -Additional dependencies +### Additional dependencies * **ripgrep** : usually included with Claude Code. If search fails, see [search troubleshooting](</docs/en/troubleshooting#search-and-discovery-issues>). * **Git** : optional. If git is installed, [`claude plugin eval`](</docs/en/plugin-evals#requirements>) requires 2.31 or later. [Uploads of a local repository to a cloud session](</docs/en/claude-code-on-the-web#send-local-repositories-without-github>) from macOS, Linux, or WSL need git 2.31 or later. Run `git --version` to see your version. -## - -​ - -Install Claude Code +## Install Claude Code Prefer a graphical interface? The [Desktop app](</docs/en/desktop-quickstart>) lets you use Claude Code without the terminal. Download it for [macOS](<https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code&utm_medium=docs>), [Windows](<https://claude.com/download?utm_source=claude_code&utm_medium=docs>), or [Linux](</docs/en/desktop-linux>). @@ -76,11 +64,7 @@ Claude Code opens an interactive session in your terminal. If you encounter any issues during installation, see [Troubleshoot installation and login](</docs/en/troubleshoot-install>). -### - -​ - -Set up on Windows +### Set up on Windows You can run Claude Code natively on Windows or inside WSL. Pick based on where your projects are located and which features you need: @@ -90,11 +74,7 @@ WSL 2| WSL 2 enabled| Supported| Linux toolchains or sandboxed command execution WSL 1| WSL 1 enabled| Not supported| If WSL 2 is unavailable -#### - -​ - -Install on native Windows +#### Install on native Windows Run the install command from PowerShell or CMD. You do not need to run as Administrator. Installing [Git for Windows](<https://git-scm.com/downloads/win>) is optional. It provides Git Bash, which the [Bash tool](</docs/en/tools-reference#bash-tool-behavior>) and the [Monitor tool](</docs/en/tools-reference#monitor-tool>) need. Whether you install from PowerShell or CMD only affects which install command you run. Your prompt shows `PS C:\Users\YourName>` in PowerShell and `C:\Users\YourName>` without the `PS` in CMD. If you’re new to the terminal, the [terminal guide](</docs/en/terminal-guide#windows>) walks through each step. After installation, launch `claude` from any terminal. @@ -109,41 +89,17 @@ When Git for Windows is installed, the PowerShell tool is available alongside Bash: on by default for claude.ai and Console accounts, and enabled with `CLAUDE_CODE_USE_POWERSHELL_TOOL=1` in Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry sessions. Set it to `0` to turn the tool off. See [PowerShell tool](</docs/en/tools-reference#powershell-tool>) for setup and limitations. -#### - -​ - -Install in WSL +#### Install in WSL Open your WSL distribution and run the Linux installer from the install instructions. You install and launch `claude` inside the WSL terminal, not from PowerShell or CMD. -### - -​ - -Alpine Linux and musl-based distributions - -Installing Claude Code on Alpine and other musl/uClibc-based distributions requires `bash` and `curl` for the install command, and `libgcc`, `libstdc++`, and `ripgrep` at runtime. Alpine doesn’t include `bash` or `curl` by default, so the documented install command fails with a `not found` error until you install them. Install these packages using your distribution’s package manager, then set `USE_BUILTIN_RIPGREP=0`. This example installs the required packages on Alpine: - - apk add bash curl libgcc libstdc++ ripgrep - -On Alpine, `ripgrep` is in the community repository. If `apk` reports that the package is missing, add the community repository to `/etc/apk/repositories`, using your Alpine version: - - echo "https://dl-cdn.alpinelinux.org/alpine/v3.22/community" >> /etc/apk/repositories - -Run `apk update` to refresh the package index, and retry the `apk add` command. Then set `USE_BUILTIN_RIPGREP` to `0` in your [`settings.json`](</docs/en/settings-reference#all-settings>) file: - - { - "env": { - "USE_BUILTIN_RIPGREP": "0" - } - } - -## - -​ - -Verify your installation +### Alpine Linux and musl-based distributions + +On Alpine and other musl-based distributions, the install command requires `bash` and `curl`, and Claude Code itself requires `bash` or `zsh`. Alpine doesn’t include `bash` or `curl` by default, so the documented install command fails with a `not found` error until you install them. This example installs the required packages on Alpine: + + apk add bash curl + +## Verify your installation After installing, confirm Claude Code is working: @@ -155,37 +111,21 @@ `claude doctor` prints read-only installation and settings diagnostics without starting a session, including install health, settings-file validation errors, and any warnings with suggested fixes. -## - -​ - -Authenticate +## Authenticate Claude Code requires a Pro, Max, Ultra, Team, Enterprise, or Console account. The free claude.ai plan does not include Claude Code access. You can also use Claude Code with a third-party API provider like [Amazon Bedrock](</docs/en/amazon-bedrock>), [Google Cloud’s Agent Platform](</docs/en/google-vertex-ai>), or [Microsoft Foundry](</docs/en/microsoft-foundry>). After installing, log in by running `claude` and following the browser prompts. If you’ve set the `ANTHROPIC_API_KEY` environment variable and you approve the key when Claude Code asks whether to use it, Claude Code skips the login prompt. See [Authentication](</docs/en/authentication>) for all account types and team setup options. -## - -​ - -Update Claude Code +## Update Claude Code Native installations automatically update in the background. You can configure the release channel to control whether you receive updates immediately or on a delayed stable schedule, or disable auto-updates entirely. Homebrew, WinGet, and Linux package manager installations require manual updates by default. -### - -​ - -Auto-updates +### Auto-updates Claude Code checks for updates on startup and periodically while running. Updates download and install in the background, then take effect the next time you start Claude Code. Run `claude doctor` in your shell to see the result of the last update attempt Claude Code recorded. On a native installation, if it reports a failed attempt, see [`Auto-update failed` in the session footer](</docs/en/troubleshoot-install#auto-update-failed>) for what to do next. On macOS and Linux, the native installer manages the launcher at `~/.local/bin/claude` as a symlink into `~/.local/share/claude/versions/`. If you replace that launcher with your own script or symlink, auto-update and `claude update` leave it in place: new versions still install under the `versions/` directory, and your launcher decides which version runs. With a custom launcher, Claude Code also keeps every installed version on disk because it can’t tell which version the launcher needs. `claude doctor` reports a launcher that the native installer didn’t create. To let Claude Code manage the launcher again, remove `~/.local/bin/claude` and run `claude update`. If an npm global install can’t auto-update because the npm global directory isn’t writable, Claude Code shows a one-time notice at startup, and `claude doctor` lists the available fixes. See [permission errors during installation](</docs/en/troubleshoot-install#permission-errors-during-installation>) for details. Homebrew, WinGet, apt, dnf, and apk installations do not auto-update by default; see below to opt in for Homebrew and WinGet. To upgrade Homebrew manually, run `brew upgrade claude-code` or `brew upgrade claude-code@latest`, depending on which cask you installed. For WinGet, run `winget upgrade Anthropic.ClaudeCode`. For Linux package managers, see the upgrade commands in Install with Linux package managers.To have Claude Code run the upgrade command for you on Homebrew or WinGet, set [`CLAUDE_CODE_PACKAGE_MANAGER_AUTO_UPDATE`](</docs/en/env-vars>) to `1`. Claude Code then runs the upgrade in the background when a new version is available and shows a restart prompt on success. The upgrade targets only the Claude Code package and does not affect other software you have installed.On WinGet the upgrade may fail while Claude Code is running because Windows locks the executable. In that case Claude Code shows the manual command instead. apt, dnf, and apk continue to require a manual upgrade because those commands need elevated privileges.**Known issue:** Claude Code may notify you of updates before the new version is available in these package managers. If an upgrade fails, wait and try again later.Homebrew keeps old versions on disk after upgrades. Run `brew cleanup` periodically to reclaim disk space. -### - -​ - -Configure release channel +### Configure release channel Control which release channel Claude Code follows for auto-updates and `claude update` with the `autoUpdatesChannel` setting: @@ -200,11 +140,7 @@ A newly launched model can require a Claude Code version newer than the stable channel serves. To run the model now, move to the latest channel. For enterprise deployments, you can enforce a consistent release channel across your organization using [managed settings](</docs/en/managed-settings>). Homebrew installations choose a channel by cask name instead of this setting: `claude-code` tracks stable and `claude-code@latest` tracks latest. Installations from the apt, dnf, and apk repositories choose a channel by repository instead of this setting. To switch one, follow Install with Linux package managers. -### - -​ - -Pin a minimum version +### Pin a minimum version The `minimumVersion` setting establishes a floor. Background auto-updates and `claude update` refuse to install any version below this value, so moving to the `"stable"` channel does not downgrade you if you are already on a newer `"latest"` build. Switching from `"latest"` to `"stable"` via `/config` prompts you to either stay on the current version or allow the downgrade. Choosing to stay sets `minimumVersion` to that version. Switching back to `"latest"` clears it. Add it to your [settings.json file](</docs/en/settings>) to pin a floor explicitly: @@ -215,11 +151,7 @@ In [managed settings](</docs/en/managed-settings>), this enforces an organization-wide minimum that user and project settings cannot override. The `minimumVersion` pin only constrains updates. To make Claude Code refuse to start outside a version range, use the managed settings `requiredMinimumVersion` and `requiredMaximumVersion` instead. Updates also respect the `requiredMaximumVersion` ceiling. See [`requiredMinimumVersion`](</docs/en/settings-reference#requiredminimumversion>) and [`requiredMaximumVersion`](</docs/en/settings-reference#requiredmaximumversion>). -### - -​ - -Disable auto-updates +### Disable auto-updates Set `DISABLE_AUTOUPDATER` to `"1"` in the `env` key of your [`settings.json`](</docs/en/settings-reference#all-settings>) file: @@ -231,11 +163,7 @@ On a native or npm installation, confirm the change took effect by running `claude doctor` and checking that the `Auto-updates` line shows `disabled (set by env: DISABLE_AUTOUPDATER)` instead of `enabled`. `DISABLE_AUTOUPDATER` only stops the background check; `claude update` and `claude install` still work. To block all update paths, including manual updates, set [`DISABLE_UPDATES`](</docs/en/env-vars>) instead. Use this when you distribute Claude Code through your own channels and need users to stay on the version you provide. -### - -​ - -Update manually +### Update manually To apply an update immediately without waiting for the next background check, run: @@ -243,19 +171,11 @@ When an update installs, the command reports `Successfully updated from <old version> to version <new version>`. If you’re already on the newest version, it reports `Claude Code is up to date (<version>)`. Installs managed by Homebrew, WinGet, or apk report `Claude is up to date!` instead. -## - -​ - -Advanced installation options +## Advanced installation options These options are for version pinning, Linux package managers, npm, network storage, and verifying binary integrity. -### - -​ - -Install a specific version +### Install a specific version The native installer accepts either a specific version number or a release channel (`latest` or `stable`). The channel you choose at install time becomes your default for auto-updates. See configure release channel for more information. To install the latest version (default): @@ -301,11 +221,7 @@ To confirm which version installed, run `claude --version`: the command prints the exact version you passed, such as `2.1.89 (Claude Code)`. -### - -​ - -Install with Linux package managers +### Install with Linux package managers Claude Code publishes signed apt, dnf, and apk repositories. Each repository offers two channels: `stable` serves a version that is typically about one week old, skipping releases with major regressions, and `latest` serves every release as soon as it ships. The commands below configure the `stable` channel, which fits most users; each tab also shows the `latest` repository URL. Package manager installations do not auto-update through Claude Code; updates arrive through your normal system upgrade workflow. All repositories are signed with the Claude Code release signing key. Before trusting the key, verify it as described in each tab. @@ -366,7 +282,7 @@ wget -O /etc/apk/keys/claude-code.rsa.pub \ https://downloads.claude.ai/keys/claude-code.rsa.pub echo "https://downloads.claude.ai/claude-code/apk/stable" >> /etc/apk/repositories - apk add claude-code + apk add bash claude-code To switch to the `latest` channel, remove the `stable` repository line and add the `latest` repository: @@ -375,11 +291,7 @@ Verify the downloaded key with `sha256sum /etc/apk/keys/claude-code.rsa.pub`, which should report `395759c1f7449ef4cdef305a42e820f3c766d6090d142634ebdb049f113168b6`.To upgrade later, run `apk update && apk upgrade claude-code`. -### - -​ - -Install with npm +### Install with npm If `npm --version` prints a version starting with `12` in your shell, follow [Fix an npm 12 install](</docs/en/troubleshoot-install#fix-an-npm-12-install>) instead. Don’t install with `sudo`. Claude Code runs npm without `sudo` when it updates itself, so an install that needs `sudo` can’t update automatically. @@ -391,11 +303,7 @@ Do NOT use `sudo npm install -g` as this can lead to permission issues and security risks. If you encounter permission errors, see [troubleshooting permission errors](</docs/en/troubleshoot-install#permission-errors-during-installation>). -### - -​ - -Install on network storage +### Install on network storage A running session reads parts of the Claude Code executable from disk as it works, not only at startup. If the file becomes unreadable mid-session, for example because it was truncated or deleted on network storage, the session crashes. On Linux, your shell reports this as a `Bus error`. When home directories live on network storage, such as an NFS home mounted on several machines, lay out installs so that each session’s executable stays readable until the session ends: @@ -406,19 +314,11 @@ The native installer deletes old versions from `~/.local/share/claude/versions/` on its own, which matters when that directory is on shared storage. Besides the version the launcher points to and any version a session on the same machine is running, it keeps the two newest versions and deletes the rest. A session on another machine that is running a deleted version loses its binary. With a custom launcher, Claude Code keeps every installed version and leaves cleanup to you. -### - -​ - -Binary integrity and code signing +### Binary integrity and code signing Each release publishes a `manifest.json` containing SHA256 checksums for every platform binary. The manifest is signed with an Anthropic GPG key, so verifying the signature on the manifest transitively verifies every binary it lists. -#### - -​ - -Verify the manifest signature +#### Verify the manifest signature Steps 1-3 require a POSIX shell with `gpg` and `curl`. On Windows, run them in Git Bash or WSL. Step 4 includes a PowerShell option. @@ -479,11 +379,7 @@ Manifest signatures are available for releases from `2.1.89` onward. Earlier releases publish checksums in `manifest.json` without a detached signature. -#### - -​ - -Platform code signatures +#### Platform code signatures In addition to the signed manifest, individual binaries carry platform-native code signatures where supported. @@ -491,19 +387,11 @@ * **Windows** : signed by “Anthropic, PBC”. Verify with `Get-AuthenticodeSignature .\claude.exe`. * **Linux** : binaries are not individually code-signed. If you download directly from the `claude-code-releases` bucket or use the native installer, verify integrity with the manifest signature above. If you install with apt, dnf, or apk, your package manager verifies signatures automatically using the repository signing key. -## - -​ - -Uninstall Claude Code +## Uninstall Claude Code To remove Claude Code, follow the instructions for your installation method. If `claude` still runs afterward, you likely have a second installation or a leftover shell alias from an older installer. See [Check for conflicting installations](</docs/en/troubleshoot-install#check-for-conflicting-installations>) to find and remove it. -### - -​ - -Uninstall a native installation +### Uninstall a native installation Remove the Claude Code binary and version files: @@ -517,11 +405,7 @@ Remove-Item -Path "$env:USERPROFILE\.local\bin\claude.exe" -Force Remove-Item -Path "$env:USERPROFILE\.local\share\claude" -Recurse -Force -### - -​ - -Uninstall with Homebrew +### Uninstall with Homebrew Remove the Homebrew cask you installed. If you installed the stable cask: @@ -531,21 +415,13 @@ brew uninstall --cask claude-code@latest -### - -​ - -Uninstall with WinGet +### Uninstall with WinGet Remove the WinGet package: winget uninstall Anthropic.ClaudeCode -### - -​ - -Uninstall with apt, dnf, or apk +### Uninstall with apt, dnf, or apk Remove the package and the repository configuration: @@ -565,21 +441,13 @@ sed -i '\|downloads.claude.ai/claude-code/apk|d' /etc/apk/repositories rm /etc/apk/keys/claude-code.rsa.pub -### - -​ - -Uninstall with npm +### Uninstall with npm Remove the global npm package: npm uninstall -g @anthropic-ai/claude-code -### - -​ - -Remove configuration files +### Remove configuration files Removing configuration files will delete all your settings, allowed tools, MCP server configurations, and session history.
modified Extend agents with skills View current →
Show diff (250 lines)
--- a/skills.md +++ b/skills.md @@ -1,10 +1,6 @@ Agent Skills extend Claude with specialized capabilities that Claude invokes when relevant. Skills are packaged as `SKILL.md` files containing instructions, descriptions, and optional supporting resources. This page also covers commands in Agent SDK sessions. For more information about skills, including benefits, architecture, and authoring guidelines, see the [Agent Skills overview](<https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview>). -## - -​ - -How skills work with the Agent SDK +## How skills work with the Agent SDK When using the Claude Agent SDK, skills are: @@ -19,11 +15,7 @@ Skills are discovered through the filesystem setting sources. With default `query()` options, the SDK loads user and project sources, so skills in `~/.claude/skills/`, `<cwd>/.claude/skills/`, and `.claude/skills/` in any parent directory of `<cwd>` up to the repository root are available. The project source also covers `<dir>/.claude/skills/` in each directory you pass through `additionalDirectories` (TypeScript) or `add_dirs` (Python), because the SDK passes those directories to Claude Code as [`--add-dir`](</docs/en/skills#skills-from-additional-directories>). If you set `settingSources` explicitly, include `'project'` to keep project and added-directory skills and `'user'` to keep your personal skills, or use the [`plugins` option](</docs/en/agent-sdk/plugins>) to load skills from a specific path. -## - -​ - -Use skills with the Agent SDK +## Use skills with the Agent SDK Set the `skills` option on `query()` to control which skills Claude can invoke in the session. When omitted, discovered skills are enabled and the Skill tool is available, matching CLI behavior. Pass `"all"` to let Claude invoke every discovered skill, a list of skill names to allow only those, or `[]` to let Claude invoke none. For example, to let Claude invoke only two named skills: @@ -35,11 +27,7 @@ const options = { skills: ["pdf", "docx"] }; -### - -​ - -Set up skills in a session +### Set up skills in a session When you set `skills`, the SDK adds the Skill tool to `allowedTools` automatically. If you also pass an explicit `tools` list, include `"Skill"` in that list so Claude can invoke skills. Once configured, Claude automatically discovers skills from the filesystem and invokes them when relevant to the user’s request. The following example enables every discovered skill in a session and pre-approves the tools that skills commonly need. The example sets `cwd` to the process’s current working directory, so run it from inside a project that has a `.claude/skills/` directory in the current directory or any parent up to the repository root: @@ -81,19 +69,11 @@ console.log(message); } -### - -​ - -Confirm skills loaded +### Confirm skills loaded Near the start of the stream, the SDK yields a system message with subtype `init`. Check its `skills` array to confirm your skills loaded before Claude starts working. The array includes the user-invocable skills that you have defined with a `description` or `when_to_use` frontmatter field, along with [bundled skills included with Claude Code](</docs/en/skills#bundled-skills>). The array lists user-invocable skills only. A skill with [`user-invocable: false`](</docs/en/skills#control-who-invokes-a-skill>) in its frontmatter loads and remains available to Claude, but doesn’t appear in the array. The array lists the same skills whether or not they’re in your `skills` list. -### - -​ - -Allow only specific skills +### Allow only specific skills To let Claude invoke only specific skills, pass their names in the `skills` list: @@ -103,11 +83,7 @@ The list takes exact skill names only. If an entry can’t work as an exact name, `query()` rejects the list before the session starts. See Invalid skill name error for the name rules and the error each SDK raises. The model doesn’t see unlisted skills and the Skill tool rejects them, while their files remain on disk and stay reachable through Read and Bash. Restricting the list doesn’t restrict dispatch by name. To let Claude invoke every discovered skill, pass `skills: "all"` rather than a wildcard. -## - -​ - -Commands in Agent SDK sessions +## Commands in Agent SDK sessions This section is the SDK’s command documentation. A command is anything you run by sending `/<name>` in a prompt. Entries on the command surface differ in what backs them: @@ -118,11 +94,7 @@ By default, both you and Claude can invoke any skill. You can restrict either path through the skill’s [frontmatter](</docs/en/skills#control-who-invokes-a-skill>). For definitions of command and skill, see the glossary’s [Command](</docs/en/glossary#command>) and [Skill](</docs/en/glossary#skill>) entries. See [Commands in Claude Code](</docs/en/commands>) for every built-in and [Extend Claude with skills](</docs/en/skills>) for the complete guide to both artifact forms. -### - -​ - -Discover available commands +### Discover available commands You can dispatch commands that work without an interactive terminal through the SDK. The `system/init` message lists the ones available in your session in its `slash_commands` field. Commands that need an interactive terminal, such as `/theme` and `/terminal-setup`, don’t appear in the list. Access the field when your session starts: @@ -157,21 +129,13 @@ A skill with [`user-invocable: false`](</docs/en/skills#control-who-invokes-a-skill>) in its frontmatter doesn’t appear in this list or in the `skills` array from Confirm skills loaded. Sessions that configure [MCP servers](</docs/en/agent-sdk/mcp>) can also expose [MCP prompts as commands](</docs/en/mcp#use-mcp-prompts-as-commands>). -### - -​ - -Dispatch commands by name +### Dispatch commands by name Send a command by including it in your prompt string, the same way you send regular text. Dispatch doesn’t depend on the `skills` option. Sending `/<name>` runs a user-invocable skill even when your `skills` list omits it. Commands that act on conversation history, such as `/compact`, need prior messages to work with. A `/<name>` that matches neither a command in the session nor a built-in Claude Code command doesn’t fail the query. Claude Code sends the prompt to Claude as an ordinary message, with a note that the command didn’t run, so the query spends a model turn and returns Claude’s reply. Before v2.1.274, a `/<name>` that matched nothing returned `Unknown command: /<name>` as the result without a model turn. A `/<name>` that matches a built-in Claude Code command that isn’t available in the session, such as `/theme`, returns `/theme isn't available in this environment.` as the result without a model turn. A command can hit the `maxTurns` / `max_turns` limit like any other prompt, ending the query with an error result instead of `success`. For the error-result contract, see [Handle the result](</docs/en/agent-sdk/agent-loop#handle-the-result>). If your command might hit the limit, wrap the loop in a `try`/`catch` in TypeScript or `try`/`except` in Python, as shown in [Single Message Input](</docs/en/agent-sdk/streaming-vs-single-mode#single-message-input>), or set `maxTurns` high enough for the work to complete. -### - -​ - -Compact history with `/compact` +### Compact history with `/compact` The `/compact` command reduces the size of your conversation history by summarizing older messages while preserving important context. Compaction needs an existing conversation with enough prior messages to summarize. This example has a conversation first, then compacts it and reads the `compact_boundary` system message that reports the result: @@ -248,30 +212,18 @@ A `compact_boundary` message only arrives when compaction ran. When a continued session has messages but nothing `/compact` can summarize, the run still ends with a `success` result rather than an error, and no `compact_boundary` message arrives. The result text then carries the reason, for example `Not enough messages to compact.` when the session holds a prompt but no reply from Claude yet. A fresh one-shot `query()` call starts with empty context, so use this pattern in a session with prior turns, for example in [streaming input mode](</docs/en/agent-sdk/streaming-vs-single-mode>) or when resuming a session. -### - -​ - -Reset context with `/clear` +### Reset context with `/clear` The `/clear` command resets the conversation to an empty context, so subsequent prompts start with no prior conversation history. The previous conversation remains on disk. You can return to that conversation by passing its session ID to the [`resume` option](</docs/en/agent-sdk/sessions#resume-by-id>). `/clear` is useful in [streaming input mode](</docs/en/agent-sdk/streaming-vs-single-mode>), where you send multiple prompts over a single connection. For one-shot `query()` calls, each call already starts with empty context, so sending `/clear` has no practical effect. Start a new `query()` instead. -## - -​ - -Create skills +## Create skills Create each skill as a directory containing a `SKILL.md` file with YAML frontmatter and Markdown content. The `description` field determines when Claude invokes your skill. **Example directory structure** : .claude/skills/security-check/ └── SKILL.md -### - -​ - -Choose a discovery level +### Choose a discovery level Save skills at either of the two most common [discovery levels](</docs/en/skills#where-skills-live>): @@ -280,11 +232,7 @@ If you have existing custom command files in `.claude/commands/`, they keep working. A command file at `.claude/commands/deploy.md` creates `/deploy` and works the same way as a skill at `.claude/skills/deploy/SKILL.md` would. If a command file and a skill share a name, see [Resolve skills that share a name](</docs/en/skills#resolve-skills-that-share-a-name>) for which one runs. The SDK loads `.claude/commands/` and `~/.claude/commands/` files from the same two scopes as skills. See [Extend Claude with skills](</docs/en/skills>) for the complete guide to both artifact forms. -### - -​ - -Create and dispatch your first skill +### Create and dispatch your first skill To see the full flow, create `.claude/skills/security-check/SKILL.md`: @@ -339,11 +287,7 @@ Claude Code includes bundled `code-review` and `verify` skills. If you name a `.claude/commands/` file after one of them, for example `.claude/commands/code-review.md`, the file’s command shadows the bundled skill and `slash_commands` lists the name once. -## - -​ - -Pre-approve tools for skills +## Pre-approve tools for skills In SDK sessions, you can pre-approve tools for a project or personal skill with the skill’s [`allowed-tools`](</docs/en/skills#pre-approve-tools-for-a-skill>) frontmatter or with the `allowedTools` option (`allowed_tools` in Python) in your query configuration. If your organization sets [`allowManagedPermissionRulesOnly`](</docs/en/settings-reference#allowmanagedpermissionrulesonly>) in managed settings, Claude Code ignores both. Skills [synced from claude.ai](</docs/en/skills#how-claude-code-handles-the-frontmatter-of-a-synced-skill>) follow their own frontmatter rules. @@ -384,17 +328,9 @@ In the stream, the skill invocation appears as a Skill tool use, followed by Read calls on the project files. The run ends with a `success` result whose text carries the findings. The list pre-approves the named tools rather than restricting the others. For the full permission flow, including permission modes and the `canUseTool` callback, see [Permissions](</docs/en/agent-sdk/permissions>). -## - -​ - -Troubleshooting - -### - -​ - -Skills not found +## Troubleshooting + +### Skills not found **Check settingSources configuration** : the SDK discovers skills through the `user` and `project` setting sources. If you set `settingSources`/`setting_sources` explicitly and omit those sources, the SDK doesn’t load skills: @@ -451,19 +387,11 @@ # Check personal skills ls ~/.claude/skills/*/SKILL.md -### - -​ - -Skill not being used +### Skill not being used **Check the`skills` option**: if you passed a `skills` list, confirm the skill’s name is included. When Claude tries to invoke an unlisted skill, the Skill tool returns `Skill <name> is not in this session's skills allowlist`. Add the name to your list, or dispatch the skill directly by sending `/<name>` in a prompt, which works without listing. **Check the description** : ensure it’s specific and includes relevant keywords. See [Agent Skills best practices](<https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices#writing-effective-descriptions>) for guidance on writing effective descriptions. -### - -​ - -Invalid skill name error +### Invalid skill name error When a name in your `skills` list can’t work as an exact skill name, `query()` rejects the list before starting the Claude Code process. Names that trigger the rejection include: @@ -490,19 +418,11 @@ An empty name reports `Skill names must be non-empty strings`.Before Python Agent SDK 0.2.129, the SDK didn’t run this check. -### - -​ - -Additional troubleshooting +### Additional troubleshooting For general skills troubleshooting, such as YAML syntax errors and debugging, see the [Claude Code skills troubleshooting section](</docs/en/skills#troubleshooting>). -## - -​ - -Next steps +## Next steps The [Claude Code skills guide](</docs/en/skills>) covers authoring in depth. Its guidance applies to SDK sessions. Start with these sections: @@ -511,11 +431,7 @@ * [Inject dynamic context](</docs/en/skills#inject-dynamic-context>): `!`command`` lines that run before Claude sees the skill content * [Choose where skills load](</docs/en/skills#where-skills-live>): every skill location, plugin namespacing, and which skill runs when two share a name -## - -​ - -Related resources +## Related resources * [Commands in Claude Code](</docs/en/commands>): the full command surface, including every built-in * [Agent Skills overview](<https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview>): conceptual overview, benefits, and architecture
modified Claude Code in Slack View current →
Show diff (309 lines)
--- a/slack.md +++ b/slack.md @@ -6,21 +6,13 @@ Claude Code in Slack brings the power of Claude Code directly into your Slack workspace. When you mention `@Claude` with a coding task, Claude automatically detects the intent and creates a Claude Code cloud session, allowing you to delegate development work without leaving your team conversations. This integration is built on the existing Claude for Slack app but adds intelligent routing to Claude Code cloud sessions for coding-related requests. Each session runs under your own Claude account, using your connected repositories and your plan limits. -## - -​ - -Use cases +## Use cases * **Bug investigation and fixes** : Describe a bug and ask Claude to investigate and fix it. * **Quick code reviews and modifications** : Have Claude implement small features or refactor code. * **Parallel task execution** : Kick off coding tasks in Slack while you continue other work, receiving notifications when complete. -## - -​ - -Prerequisites +## Prerequisites Before using Claude Code in Slack, ensure you have the following: @@ -32,11 +24,7 @@ GitHub Account| Connected at [claude.ai/code](<https://claude.ai/code>) with at least one repository authenticated Slack Authentication| Your Slack account linked to your Claude account via the Claude app -## - -​ - -Setting up Claude Code in Slack +## Setting up Claude Code in Slack 1 @@ -84,27 +72,15 @@ Claude is not automatically added to any channels after installation. To use Claude in a channel, invite it by typing `/invite @Claude` in that channel. Claude can only respond to @mentions in channels where it has been added. -## - -​ - -How it works - -### - -​ - -Automatic detection +## How it works + +### Automatic detection In Code + Chat routing mode, when you mention @Claude in a Slack channel or thread, Claude automatically detects whether your message is a coding task. Coding tasks go to a Claude Code cloud session. Anything else gets a regular chat reply. In Code only mode, every @mention goes to Claude Code. You can also explicitly tell Claude to handle a request as a coding task, even if it doesn’t automatically detect it. Claude Code in Slack only works in channels (public or private). It does not work in direct messages (DMs). -### - -​ - -Context gathering +### Context gathering * **From threads** : when you first @mention Claude in a thread, it gathers context from your messages and its own in that thread. * **From channels** : when you @mention Claude directly in a channel, it looks at your recent messages and its own in that channel, and at the channel’s name, topic, and description. @@ -113,11 +89,7 @@ When @Claude is invoked in Slack, Claude is given access to the conversation context to better understand your request. Claude may follow directions from other messages in the context, so users should make sure to only use Claude in trusted Slack conversations. -### - -​ - -Session flow +### Session flow 1. **Initiation** : You @mention Claude with a coding request 2. **Detection** : Claude analyzes your message and detects coding intent @@ -126,41 +98,21 @@ 5. **Completion** : When finished, Claude updates its message in the thread with its final response and action buttons, and sends you a direct message linking to it 6. **Review** : Click **View session** to see the full transcript, or **Create PR** to open a pull request -## - -​ - -User interface elements - -### - -​ - -Message actions +## User interface elements + +### Message actions * **View session** : Opens the full Claude Code session in your browser where you can see all work performed, continue the session, or make additional requests. * **Create PR** : Opens GitHub’s compare page for the session’s branch, where you create the pull request. It appears on the status message Claude posted when the session started, once the session finishes. * **Switch to code repo…** : If Claude responds in Chat but you wanted a coding session, click this button and select a repository, and Claude starts a Claude Code session with your original request. -### - -​ - -Repository selection +### Repository selection Claude automatically selects a repository based on context from your Slack conversation. If Claude can’t tell which repository you mean, it asks you to choose: click **Select repository** and select one from the list. -## - -​ - -Access and permissions - -### - -​ - -User-level access +## Access and permissions + +### User-level access Access Type| Requirement ---|--- @@ -169,11 +121,7 @@ Repository Access| Users can only access repositories they’ve personally connected Session History| Sessions appear in your Claude Code history on claude.ai/code -### - -​ - -Workspace-level access +### Workspace-level access Slack workspace administrators control whether the Claude app is available in their workspace: @@ -183,57 +131,29 @@ Enterprise Grid distribution| For Enterprise Grid organizations, organization admins can control which workspaces have access to the Claude app App removal| Removing the app from a workspace immediately revokes access for all users in that workspace -### - -​ - -Channel-based access control +### Channel-based access control Installing the app doesn’t add Claude to any channels. Claude responds to @mentions only in channels where it has been added; invite it with `/invite @Claude`. It works in both public and private channels. Admins can control who uses Claude Code by managing which channels Claude is invited to and who has access to those channels. This adds a layer of access control beyond workspace-level permissions. -## - -​ - -What’s accessible where +## What’s accessible where **In Slack** : You’ll see status updates, completion summaries, and action buttons. The full transcript is preserved and always accessible. **At claude.ai/code** : The complete Claude Code session with full conversation history, all code changes, and file operations. Sessions stay in your Claude Code history at [claude.ai/code](<https://claude.ai/code>), where you can continue past sessions, reference them, or create pull requests. For Enterprise and Team accounts, sessions created from Claude in Slack are automatically visible to the organization. See [cloud session sharing](</docs/en/claude-code-on-the-web#share-sessions>) for more details. -## - -​ - -Best practices - -### - -​ - -Writing effective requests +## Best practices + +### Writing effective requests * **Be specific** : Include file names, function names, or error messages when relevant. * **Provide context** : Mention the repository or project. * **Define success** : Explain what “done” looks like. Should Claude write tests? Update documentation? Create a PR? -### - -​ - -When to use Slack vs. web +### When to use Slack vs. web **Use Slack when** : You want to start a task asynchronously, or you’re collaborating with teammates who need visibility. **Use the web directly when** : You need to upload files, want real-time interaction during development, or are working on longer, more complex tasks. -## - -​ - -Troubleshooting - -### - -​ - -“This workspace isn’t set up for Claude Tag yet” +## Troubleshooting + +### “This workspace isn’t set up for Claude Tag yet” @Claude replies in the thread with this notice instead of an answer when both of these are true: @@ -242,37 +162,21 @@ Claude Tag is available on Team and Enterprise plans. To connect the workspace, start with the `@Claude connect` command the notice names, then follow [Set up Claude Tag](<https://claude.com/docs/claude-tag/overview>). -### - -​ - -“The legacy Claude in Slack bot is retired” +### “The legacy Claude in Slack bot is retired” The notice opens with `The legacy Claude in Slack bot is retired effective October 5, 2026 and no longer responds in channels.` Your Slack workspace is connected to a Claude organization. The earlier version is still selected for the channel, the workspace, or the organization default in that organization’s Claude Tag settings. The notice doesn’t depend on your own plan, so Pro, Max, and Ultra accounts get it too. If you’re an Owner of that organization, open [Claude admin settings](<https://claude.ai/admin-settings/claude-tag>) and turn on Claude Tag for the channel. To fix every channel that inherits the setting, change it on the workspace or the organization default instead. For the full move, see [Migrate from the earlier Claude in Slack](<https://claude.com/docs/claude-tag/admins/migrate-from-earlier>). If you’re not an Owner, send this entry to one. -### - -​ - -”Claude Code is not enabled for your account” +### ”Claude Code is not enabled for your account” This error means your Claude account has no cloud environment yet. Sign in at [claude.ai/code](<https://claude.ai/code>) once with the same account you connected to Slack and finish [web onboarding](</docs/en/web-quickstart#connect-github>), which creates your default cloud environment or asks you to create it. The error clears on your next mention. Each user must do this individually. -### - -​ - -Sessions not starting +### Sessions not starting 1. Verify your Claude account is connected in the Claude App Home 2. Check that cloud sessions are enabled for your account 3. Ensure you have at least one GitHub repository connected to Claude Code -### - -​ - -Sessions from a Claude Tag channel fail to start +### Sessions from a Claude Tag channel fail to start This entry applies to workspaces using [Claude Tag](<https://claude.com/docs/claude-tag/overview>). If you created the channel’s cloud environment at [claude.ai/code](<https://claude.ai/code>), it belongs to your personal account, and Claude can’t start channel sessions in a personal environment. Claude Code fails the session immediately, and retrying doesn’t help. If you’re an Owner and the environment is your own, [share it with the organization](</docs/en/cloud-environments#organization-shared-environments>) from the environment selector. Otherwise, an Owner recreates it as an organization-shared environment from the **Cloud environments** page in [admin settings](<https://claude.ai/admin-settings>). You can apply it in two ways: @@ -281,48 +185,28 @@ If you’re not an Owner, send this entry to one. -### - -​ - -Repository not showing +### Repository not showing 1. Connect the repository at [claude.ai/code](<https://claude.ai/code>) 2. Verify your GitHub permissions for that repository 3. Try disconnecting and reconnecting your GitHub account -### - -​ - -Wrong repository selected +### Wrong repository selected Include the repository name in your request for more accurate selection. -### - -​ - -Authentication errors +### Authentication errors 1. Disconnect and reconnect your Claude account in the App Home 2. Ensure you’re signed into the correct Claude account in your browser -## - -​ - -Current limitations +## Current limitations * **GitHub only** : repositories must be on GitHub. * **One PR at a time** : each session can create one pull request. * **Cloud session access required** : users need access to [cloud sessions](</docs/en/claude-code-on-the-web>). -## - -​ - -Related resources +## Related resources ## Claude Code in the cloud
modified Customize your status line View current →
Show diff (438 lines)
--- a/statusline.md +++ b/statusline.md @@ -9,19 +9,11 @@ This page walks through setting up a basic status line, explains how the data flows from Claude Code to your script, lists all the fields you can display, and provides ready-to-use examples for common patterns like git status, cost tracking, and progress bars. -## - -​ - -Set up a status line +## Set up a status line Use the `/statusline` command to have Claude Code generate a script for you, or manually create a script and add it to your settings. -### - -​ - -Use the /statusline command +### Use the /statusline command The `/statusline` command accepts natural language instructions describing what you want displayed. Claude Code generates a script file in `~/.claude/` and updates your settings automatically: @@ -29,11 +21,7 @@ Approve the file edit prompts if Claude Code asks for permission during setup. -### - -​ - -Manually configure a status line +### Manually configure a status line Add a `statusLine` field to your user settings (`~/.claude/settings.json`, where `~` is your home directory) or [project settings](</docs/en/settings#where-settings-live>). Set `type` to `"command"` and point `command` to a script path or an inline shell command. For a full walkthrough of creating a script, see Build a status line step by step. @@ -56,19 +44,11 @@ The optional `padding` field adds extra horizontal spacing (in characters) to the status line content. Defaults to `0`. This padding is in addition to the interface’s built-in spacing, so it controls relative indentation rather than absolute distance from the terminal edge. The optional `refreshInterval` field re-runs your command every N seconds in addition to the event-driven updates. The minimum is `1`. Set this when your status line shows time-based data such as a clock, or when background subagents change git state while the main session is idle. Leave it unset to run only on events. The optional `hideVimModeIndicator` field suppresses the built-in `-- INSERT --` text below the prompt. Set this to `true` when your script renders `vim.mode` itself, so the mode is not shown twice. -### - -​ - -Disable the status line +### Disable the status line Run `/statusline` and ask it to remove or clear your status line (for example, `/statusline delete`, `/statusline clear`, `/statusline remove it`). You can also manually delete the `statusLine` field from your settings.json. -## - -​ - -Build a status line step by step +## Build a status line step by step This walkthrough shows what `/statusline` sets up for you by manually creating a status line that displays the current model, working directory, and context window usage percentage. @@ -118,21 +98,13 @@ Your status line appears at the bottom of the interface. Claude Code reloads settings automatically and runs your script as soon as you save the file. -## - -​ - -How status lines work +## How status lines work Claude Code runs your script with JSON session data on stdin and displays whatever the script prints to stdout. The status line runs locally and does not consume API tokens. It temporarily hides during certain UI interactions, including the help menu and permission prompts. -### - -​ - -When the status line updates +### When the status line updates Your script runs once when a session starts, including when you resume one. After that, it runs again when: @@ -147,11 +119,7 @@ Claude Code debounces updates at 300ms, so rapid changes batch together and your script runs once after the changes stop. A change to the `command` itself skips the debounce: Claude Code runs the new command right away. If a new update triggers while your script is still running, Claude Code cancels the in-flight script. If you edit your script, the changes appear the next time an update trigger re-runs it. The event-driven triggers can go quiet when the main session is idle, for example while a coordinator waits on background subagents. To keep time-based or externally-sourced segments current during idle periods, set `refreshInterval` to also re-run the command on a fixed timer. -### - -​ - -What your script can output +### What your script can output Your script can print more than a single line of plain text: @@ -159,19 +127,11 @@ * **Colors** : use [ANSI escape codes](<https://en.wikipedia.org/wiki/ANSI_escape_code#Colors>) like `\033[32m` for green (terminal must support them). See the git status example. * **Links** : use [OSC 8 escape sequences](<https://en.wikipedia.org/wiki/ANSI_escape_code#OSC>) to make text clickable (Cmd+click on macOS, Ctrl+click on Windows/Linux). Requires a terminal that supports hyperlinks like iTerm2, Kitty, or WezTerm. See the clickable links example. -### - -​ - -Size output to the terminal +### Size output to the terminal Claude Code captures your script’s output instead of connecting it directly to the terminal, so `tput cols` and language-level width detection cannot read the terminal size from inside the script. Read the `COLUMNS` and `LINES` environment variables instead. Claude Code sets these to the current terminal dimensions before running your script. -## - -​ - -Available data +## Available data Claude Code sends the following JSON fields to your script via stdin: @@ -355,11 +315,7 @@ Handle missing fields with conditional access and null values with fallback defaults in your scripts. -### - -​ - -Context window fields +### Context window fields The `context_window` object describes the live context window from the most recent API response. @@ -375,11 +331,7 @@ For what the cache fields mean and how they’re billed, see [check cache performance](</docs/en/prompt-caching#check-cache-performance>). The `used_percentage` field is calculated from input tokens only: `input_tokens + cache_creation_input_tokens + cache_read_input_tokens`. It does not include `output_tokens`. If you calculate context percentage manually from `current_usage`, use the same input-only formula to match `used_percentage`. The `current_usage` object is `null` before the first API call in a session, and again immediately after `/compact` until the next API call repopulates it. -### - -​ - -Spend limit fields +### Spend limit fields Behind a [Claude apps gateway with spend limits](</docs/en/claude-apps-gateway-spend-limits#usage-warnings-in-claude-code>), the `rate_limits.spend_limit` object describes the spend limit that applies to you. It appears after the session’s first API response and requires Claude Code v2.1.251 or later. Your script receives its fields on separate schedules: @@ -388,11 +340,7 @@ Treat `used_usd`, `limit_usd`, and `period` as optional even when `spend_limit` is present, because your script receives the percentage before them. Read each with a fallback in your script, such as `jq -r '.rate_limits.spend_limit.used_usd // empty'`. Before Claude Code v2.1.295, they stayed absent if you set `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`, which turned that request off. -### - -​ - -Prompt cache fields +### Prompt cache fields The `prompt_cache` object summarizes how the session’s main conversation is using the [prompt cache](</docs/en/prompt-caching>). Claude Code computes it from the cache token counts in the API’s responses, so it works on every provider. The object appears after the main conversation’s first API response. Claude Code doesn’t count subagent requests in these statistics. Requires Claude Code v2.1.251 or later. The table lists each field with its meaning. Timestamps are Unix epoch seconds, the same unit as `rate_limits.*.resets_at`. A short status line usually shows one or two of these; `warm` and `hit_ratio` summarize the cache state most directly. @@ -415,22 +363,14 @@ Claude Code shows the same statistics in the terminal, on the [`/usage` command’s `Prompt cache (main)` line](</docs/en/costs#prompt-cache-statistics>). -#### - -​ - -Last miss cause +#### Last miss cause The `last_miss_cause` object reports what Claude Code identified as the likely cause of the most recent miss. Its `causes` array holds one or more cause names, such as `tools_changed`, `system_prompt_changed`, `ttl_expired_5m`, or `likely_server_side`. The object is `null` until the session’s first miss, and again whenever Claude Code couldn’t identify a cause for the most recent miss. Requires Claude Code v2.1.260 or later. Two causes add counts to the object: * `tools_added` and `tools_removed`: with `tools_changed`, how many tools were added to or removed from the request * `system_char_delta`: with `system_prompt_changed`, the change in the system prompt’s length, in characters -## - -​ - -Examples +## Examples These examples show common status line patterns. To use any example: @@ -440,11 +380,7 @@ The Bash examples use [`jq`](<https://jqlang.org/>) to parse JSON. Python and Node.js have built-in JSON parsing. -### - -​ - -Context window usage +### Context window usage Display the current model and context window usage with a visual progress bar. Each script reads JSON from stdin, extracts the `used_percentage` field, and builds a 10-character bar where filled blocks (▓) represent usage: @@ -505,11 +441,7 @@ console.log(`[${model}] ${bar} ${pct}%`); }); -### - -​ - -Git status with colors +### Git status with colors Show git branch with color-coded indicators for staged and modified files. This script uses [ANSI escape codes](<https://en.wikipedia.org/wiki/ANSI_escape_code#Colors>) for terminal colors: `\033[32m` is green, `\033[33m` is yellow, and `\033[0m` resets to default. @@ -597,11 +529,7 @@ } }); -### - -​ - -Cost and duration tracking +### Cost and duration tracking Track your session’s API costs and elapsed time. The `cost.total_cost_usd` field accumulates the estimated cost of all API calls in the current session. The `cost.total_duration_ms` field measures the total time the session has been running, while `cost.total_api_duration_ms` tracks only the time spent waiting for API responses. Each script formats cost as currency and converts milliseconds to minutes and seconds: @@ -654,11 +582,7 @@ console.log(`[${model}] 💰 $${cost.toFixed(2)} | ⏱️ ${mins}m ${secs}s`); }); -### - -​ - -Display multiple lines +### Display multiple lines Your script can output multiple lines to create a richer display. @@ -759,11 +683,7 @@ console.log(`${barColor}${bar}${RESET} ${pct}% | ${YELLOW}$${cost.toFixed(2)}${RESET} | ⏱️ ${mins}m ${secs}s`); }); -### - -​ - -Clickable links +### Clickable links This example creates a clickable link to your GitHub repository. Hold Cmd (macOS) or Ctrl (Windows/Linux) and click to open the link in your browser. @@ -837,11 +757,7 @@ } }); -### - -​ - -Rate limit usage +### Rate limit usage Display claude.ai subscription rate limit usage, or your spend against a Claude apps gateway spend limit, in the status line. For subscribers, the `rate_limits` object can contain a rolling `five_hour` window and a weekly `seven_day` window. Each window provides `used_percentage`, from 0 to 100, and `resets_at`, the Unix epoch seconds when the window resets. Behind a gateway, read the `spend_limit` object, described under spend limit fields. The `rate_limits` object is only present for claude.ai Pro, Max, and Ultra subscribers, or behind a Claude apps gateway with spend limits, and only after the first API response. Each script handles the absent fields gracefully, and behind a gateway prints `spend: $314.12 / $500`, or `spend: 63%` while the dollar fields are absent: @@ -924,11 +840,7 @@ console.log(parts.length ? `[${model}] | ${parts.join(' ')}` : `[${model}]`); }); -### - -​ - -Cache expensive operations +### Cache expensive operations Your status line script runs frequently during active sessions. Commands like `git status` or `git diff` can be slow, especially in large repositories. This example caches git information to a temp file and only refreshes it every 5 seconds. The cache filename needs to be stable across status line invocations within a session, but unique across sessions so concurrent sessions in different repositories don’t read each other’s cached git state. Process-based identifiers like `$$`, `os.getpid()`, or `process.pid` change on every invocation and defeat the cache. Use the `session_id` from the JSON input instead: it’s stable for the lifetime of a session and unique per session. Each script checks if the cache file is missing or older than 5 seconds before running git commands: @@ -1056,11 +968,7 @@ } }); -### - -​ - -Windows configuration +### Windows configuration On Windows, Claude Code runs status line commands through Git Bash when Git Bash is installed, or through PowerShell when Git Bash is absent. Git Bash treats unquoted backslashes as escape characters, so a Windows-style path such as `C:\Users\username\script.mjs` reaches the script runner with its separators removed and the command fails without a visible error. Write file paths in the `command` string with forward slashes, as shown in the examples below. The `~` shorthand also works and expands to your Windows home directory. To run a PowerShell script as your status line, invoke it via `powershell`. This works whether Claude Code routes the command through Git Bash or PowerShell: @@ -1107,53 +1015,7 @@ dirname="${cwd##*[/\\]}" echo "$dirname [$model]" -## - -​ - -Subagent status lines - -The `subagentStatusLine` setting renders a custom row body for each [subagent](</docs/en/sub-agents>) shown in the agent panel below the prompt. Use it to replace the default `name · description · token count` row with your own formatting. - - { - "subagentStatusLine": { - "type": "command", - "command": "~/.claude/subagent-statusline.sh" - } - } - -The command runs once per refresh tick and receives all visible subagent rows as a single JSON object on stdin. The input includes the [base hook fields](</docs/en/hooks#common-input-fields>), a `columns` field with the usable row width, and a `tasks` array with one entry per row, described in Task fields. Write one JSON line to stdout per row you want to override, in the form `{"id": "<task id>", "content": "<row body>"}`. The `content` string is rendered as-is, including ANSI colors and OSC 8 hyperlinks. Omit a task’s `id` to keep the default rendering for that row; emit an empty `content` string to hide it. The same trust, `disableAllHooks`, and [`allowManagedHooksOnly`](</docs/en/settings-reference#allowmanagedhooksonly>) gates that apply to `statusLine` apply here. Plugins can ship a default `subagentStatusLine` in their [`settings.json`](</docs/en/plugins/manifest-reference#standard-layout>), but unlike hooks, plugin values don’t run under `allowManagedHooksOnly` even when the plugin is force-enabled in managed settings `enabledPlugins`. - -### - -​ - -Task fields - -Each entry in the `tasks` array describes one subagent row with the fields below. Fields marked optional are omitted when they have no value, so guard for their absence in your script. - -Field| Type| Description ----|---|--- -`id`| string| Identifier of the task. Echo it as `id` in the line you write back for this row -`name`| string, optional| Name the subagent is [addressed by](</docs/en/sub-agents#subagent-names>), when it has one -`type`| string| Kind of task: `local_agent` -`agentType`| string| Subagent type the task runs as, such as the built-in [`Explore`](</docs/en/sub-agents#built-in-subagents>) or a custom `code-reviewer`. Holds the same value that hooks receive as [`agent_type`](</docs/en/hooks#subagentstart>). Requires Claude Code v2.1.293 or later -`status`| string| State of the task, such as `running`, `completed`, `failed`, or `killed` -`description`| string| Short description of the task, such as the one Claude gave when it spawned the subagent -`label`| string| Short progress summary of the task when Claude Code has one, otherwise the same text as `description` -`startTime`| number| When the task started, in milliseconds since the Unix epoch -`model`| string, optional| ID of the resolved model the task runs on. Omitted until the model is resolved -`effort`| string or number, optional| Reasoning effort set for the subagent in its [definition frontmatter](</docs/en/sub-agents#supported-frontmatter-fields>) or on the individual invocation: `low`, `medium`, `high`, `xhigh`, `max`, or a numeric token budget. This is the configured value, and the effort Claude Code applies can differ when the model doesn’t support that level. Omitted when no effort is set -`contextWindowSize`| number, optional| Context window of `model` in tokens, computed the same way as the main status line’s `context_window.context_window_size`, so you can render a per-row percentage from `tokenCount`. Omitted when `model` is -`tokenCount`| number| Running token count of the subagent, the figure the default row shows -`tokenSamples`| array of numbers| Up to the last 16 `tokenCount` readings, one per refresh tick, oldest first and ending with the current one -`cwd`| string| Working directory of the subagent: its own directory when it runs in one, such as an isolated worktree, otherwise the session’s working directory - -## - -​ - -Tips +## Tips * **Test with mock input** : `echo '{"model":{"display_name":"Opus"},"workspace":{"current_dir":"/home/user/project"},"context_window":{"used_percentage":25},"session_id":"test-session-abc"}' | ./statusline.sh` * **Keep output short** : the status bar has limited width, so long output may get truncated or wrap awkwardly @@ -1161,19 +1023,11 @@ Community projects like [ccstatusline](<https://github.com/sirmalloc/ccstatusline>) and [starship-claude](<https://github.com/martinemde/starship-claude>) provide pre-built configurations with themes and additional features. -## - -​ - -Troubleshooting +## Troubleshooting If the status line is blank, start with Status line not appearing. A folder you haven’t trusted and a script that fails also leave it blank, as Workspace trust required and Script errors or hangs describe. -### - -​ - -Status line not appearing +### Status line not appearing If you configured a status line and nothing shows at the bottom of the interface, work through these checks: @@ -1186,27 +1040,15 @@ * Run `claude --debug` to log your script’s stderr on every status line invocation, and its exit code on the first invocation in a session * Ask Claude to read your settings file and execute the `statusLine` command directly to surface errors -### - -​ - -Status line shows `--` or empty values +### Status line shows `--` or empty values Fields may be `null` before the first API response completes, so handle null values in your script with fallbacks such as `// 0` in jq. Restart Claude Code if values remain empty after multiple messages. -### - -​ - -Context percentage shows unexpected values +### Context percentage shows unexpected values The status line reports the counts from the last API response, while `/context` adds an estimate for messages added since that response, so `/context` can read higher until the next response. Use `used_percentage` for the simplest accurate context state. For the formula behind `used_percentage`, see Context window fields. -### - -​ - -OSC 8 links not clickable +### OSC 8 links not clickable Whether a link is clickable depends on your terminal, on whether Claude Code detects hyperlink support in it, on whether SSH or tmux strips the escape sequence, and on how your script prints it: @@ -1223,27 +1065,15 @@ * SSH and tmux sessions may strip OSC sequences depending on configuration * If escape sequences appear as literal text like `\e]8;;`, use `printf '%b'` instead of `echo -e` for more reliable escape handling -### - -​ - -Display glitches with escape sequences +### Display glitches with escape sequences Complex escape sequences (ANSI colors, OSC 8 links) can occasionally cause garbled output if they overlap with other UI updates. Multi-line status lines with escape codes are more prone to rendering issues than single-line plain text. If you see corrupted text, try simplifying your script to plain text output. -### - -​ - -Workspace trust required +### Workspace trust required Until you accept the workspace trust dialog, the status line stays blank. Because `statusLine` executes a shell command, Claude Code runs it under the same [workspace trust rule as hooks in settings files](</docs/en/permissions#what-runs-before-you-trust-a-folder>). Accepting the dialog for the folder, or for a parent directory whose trust extends to it, is enough. Until then, `claude --debug` logs `Status line command skipped: workspace trust not accepted`. Restart Claude Code and accept the trust dialog to enable it. -### - -​ - -Script errors or hangs +### Script errors or hangs Claude Code displays your script’s output only after the script exits with code 0: @@ -1252,11 +1082,7 @@ * If a new update triggers while a slow script is running, the in-flight script is cancelled * Test your script independently with mock input before configuring it -### - -​ - -Notifications share the status line row +### Notifications share the status line row Outside [fullscreen rendering](</docs/en/fullscreen>), Claude Code shows notifications on the same row as your status line. In fullscreen rendering, Claude Code gives notifications a row of their own.
modified Stream responses in real-time View current →
Show diff (102 lines)
--- a/streaming-output.md +++ b/streaming-output.md @@ -2,11 +2,7 @@ This page covers output streaming (receiving tokens in real-time). For input modes (how you send messages), see [Send messages to agents](</docs/en/agent-sdk/streaming-vs-single-mode>). You can also [stream responses using the Agent SDK via the CLI](</docs/en/headless>). -## - -​ - -Enable streaming output +## Enable streaming output To enable streaming, set `include_partial_messages` (Python) or `includePartialMessages` (TypeScript) to `true` in your options. This causes the SDK to yield `StreamEvent` messages containing raw API events as they arrive, in addition to the usual `AssistantMessage` and `ResultMessage`. Your code then needs to: @@ -59,11 +55,7 @@ } } -## - -​ - -StreamEvent reference +## StreamEvent reference When partial messages are enabled, you receive raw Claude API streaming events wrapped in an object. The type has different names in each SDK: @@ -81,11 +73,7 @@ `message_delta`| Message-level updates (stop reason, usage) `message_stop`| End of the message -## - -​ - -Message flow +## Message flow Claude Code emits an `AssistantMessage` as each non-empty content block completes, so a response with a text block and a tool call yields two `AssistantMessage` objects. Each one carries only its own content block, and both share the same message ID, which you read as `message.message.id` in TypeScript and `message.message_id` in Python. With partial messages enabled, each `AssistantMessage` arrives before that block’s `content_block_stop` event, and you receive messages in this order: @@ -106,11 +94,7 @@ 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 +### Handle a stream that’s cut off If a stream is cut off mid-message, you still receive that message’s `message_stop` before the turn ends. Causes of a cut-off stream include an interrupted turn, a dropped connection, and a fallback to a non-streaming request. `content_block_stop` and `message_delta` can be missing before that `message_stop`: @@ -119,11 +103,7 @@ 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. -## - -​ - -Stream tool calls +## Stream tool calls Tool calls also stream incrementally. You can track when tools start, receive their input as it’s generated, and see when they complete. The example below tracks the current tool being called and accumulates the JSON input as it streams in. It uses three event types: @@ -218,11 +198,7 @@ } } -## - -​ - -Build a streaming UI +## Build a streaming UI This example combines text and tool streaming into a cohesive UI. It tracks whether the agent is currently executing a tool (using an `in_tool` flag) to show status indicators like `[Using Read...]` while tools run. Text streams normally when not in a tool, and tool completion triggers a “done” message. This pattern is useful for chat interfaces that need to show progress during multi-step agent tasks. @@ -317,19 +293,11 @@ } } -## - -​ - -Known limitations +## Known limitations * **Structured output** : with partial messages enabled, the JSON streams as a tool call’s unvalidated `input_json_delta` chunks, and only the validated result reaches the final `ResultMessage.structured_output`. [Recognize the StructuredOutput tool call](</docs/en/agent-sdk/structured-outputs#recognize-the-structuredoutput-tool-call>) covers how that call appears in your stream. -## - -​ - -Next steps +## Next steps Now that you can stream text and tool calls in real-time, explore these related topics:
modified Streaming Input View current →
--- a/streaming-vs-single-mode.md +++ b/streaming-vs-single-mode.md @@ -1,27 +1,15 @@ -## - -​ - -Overview +## Overview The Claude Agent SDK supports two distinct input modes for interacting with agents: * **Streaming Input Mode** : a persistent, interactive session * **Single Message Input** : one-shot queries that use session state and resuming -## - -​ - -Streaming Input Mode (Recommended) +## Streaming Input Mode (Recommended) Streaming input mode is the **preferred** way to use the Claude Agent SDK. It provides full access to the agent’s capabilities and enables rich, interactive experiences. It allows the agent to operate as a long lived process that takes in user input, handles interruptions, surfaces permission requests, and handles session management. -### - -​ - -Benefits +### Benefits In streaming input mode, you work in a persistent session with these capabilities: @@ -31,11 +19,7 @@ * **Real-time feedback** : see responses as they’re generated, not just final results * **Context persistence** : maintain conversation context across multiple turns naturally -### - -​ - -Implementation Example +### Implementation Example These examples read an image named `diagram.png` from the working directory. Create one there first, or change the filename to point at your own image. @@ -162,19 +146,11 @@ In the TypeScript SDK, if your message generator throws, for example when a file it reads is missing, the stream ends with an error that reads `Claude Code process aborted by user` instead of the original error, so check the code inside your generator first when you see that message. The error may also be preceded by a long minified line of bundled SDK source, so read to the end of the output for the error text.In the Python SDK, a generator exception is logged at debug level and the session stalls without raising, so if a streaming session hangs with no output, enable debug logging and check your generator. -## - -​ - -Single Message Input +## Single Message Input Single message input is simpler but more limited. -### - -​ - -When to Use Single Message Input +### When to Use Single Message Input Use single message input when: @@ -182,11 +158,7 @@ * You do not need image attachments or mid-session control methods * You need to operate in a stateless environment, such as a lambda function -### - -​ - -Limitations +### Limitations Single message input mode does **not** support: @@ -197,11 +169,7 @@ If a query ends with an error result, such as `error_max_turns`, a single message `query()` call raises an error that includes the failure text after yielding the final result message, so wrap the loop in a try block if your code needs to continue. See [Handle the result](</docs/en/agent-sdk/agent-loop#handle-the-result>) for the result subtypes. -### - -​ - -Implementation Example +### Implementation Example TypeScript
modified Get structured output from agents View current →
Show diff (105 lines)
--- a/structured-outputs.md +++ b/structured-outputs.md @@ -1,10 +1,6 @@ Structured outputs let you define the exact shape of data you want back from an agent. The agent can use any tools it needs to complete the task, and you still get validated JSON matching your schema at the end. Define a [JSON Schema](<https://json-schema.org/understanding-json-schema/about>) for the structure you need, and the SDK validates the output against it, re-prompting on mismatch. If validation does not succeed within the retry limit, the result is an error instead of structured data; see Error handling. For full type safety, use Zod (TypeScript) or Pydantic (Python) to define your schema and get strongly typed objects back. -## - -​ - -Why structured outputs? +## Why structured outputs? Agents return free-form text by default, which works for chat but not when you need to use the output programmatically. Structured outputs give you typed data you can pass directly to your application logic, database, or UI components. Consider a recipe app where an agent searches the web and brings back recipes. Without structured outputs, you get free-form text that you’d need to parse yourself. With structured outputs, you define the shape you want and get typed data you can use directly in your app. @@ -38,11 +34,7 @@ Typed data you can use directly in your UI. -## - -​ - -Quick start +## Quick start To use structured outputs, define a [JSON Schema](<https://json-schema.org/understanding-json-schema/about>) describing the shape of data you want, then pass it to `query()` via the `outputFormat` option (TypeScript) or `output_format` option (Python). When the agent finishes, the result message includes a `structured_output` field with validated data matching your schema. Before running the examples on this page, install the Claude Agent SDK by following the [quickstart](</docs/en/agent-sdk/quickstart#setup>). The example below asks the agent to research Anthropic and return the company name, year founded, and headquarters as structured output. @@ -122,11 +114,7 @@ asyncio.run(main()) -## - -​ - -Type-safe schemas with Zod and Pydantic +## Type-safe schemas with Zod and Pydantic Instead of writing JSON Schema by hand, you can use [Zod](<https://zod.dev/>) (TypeScript) or [Pydantic](<https://docs.pydantic.dev/latest/>) (Python) to define your schema. These libraries generate the JSON Schema for you and let you parse the response into a fully-typed object you can use throughout your codebase with autocomplete and type checking. The example below defines a schema for a feature implementation plan with a summary, list of steps (each with complexity level), and potential risks. The agent plans the feature and returns a typed `FeaturePlan` object. You can then access properties like `plan.summary` and iterate over `plan.steps` with full type safety. The SDK validates schemas with JSON Schema draft-07, so schemas that declare a newer version are rejected. Zod targets draft 2020-12 by default, so pass `target: "draft-7"` when converting your schema. @@ -233,11 +221,7 @@ asyncio.run(main()) -## - -​ - -Output format configuration +## Output format configuration The `outputFormat` (TypeScript) or `output_format` (Python) option accepts an object with: @@ -246,11 +230,7 @@ The SDK supports standard JSON Schema features including all basic types (object, array, string, number, boolean, null), `enum`, `const`, `required`, nested objects, and `$ref` definitions. For the full list of supported features and limitations, see [JSON Schema limitations](<https://platform.claude.com/docs/en/build-with-claude/structured-outputs#json-schema-limitations>). A schema that isn’t valid JSON Schema fails the run at startup with an error naming the problem. Before v2.1.205, an invalid schema was silently ignored and the agent returned unstructured text. The `format` keyword, such as `"format": "email"`, is accepted as an annotation and isn’t enforced by the SDK’s validator. Before v2.1.205, any schema containing `format` was treated as invalid. -## - -​ - -Example: TODO tracking agent +## Example: TODO tracking agent This example demonstrates how structured outputs work with multi-step tool use. The agent needs to find TODO comments in the codebase, then look up git blame information for each one. It autonomously decides which tools to use (Grep to search, Bash to run git commands) and combines the results into a single structured response. The schema includes optional fields (`author` and `date`) since git blame information might not be available for all files. The agent fills in what it can find and omits the rest. @@ -364,11 +344,7 @@ asyncio.run(main()) -## - -​ - -Recognize the StructuredOutput tool call +## Recognize the StructuredOutput tool call When you set `outputFormat` in TypeScript or `output_format` in Python, your message stream carries a tool call named `StructuredOutput` that you never defined. Claude Code adds this tool to the session, and the agent calls it to return its answer. The [system init message](</docs/en/agent-sdk/typescript#sdksystemmessage>) lists it in the `tools` array, and each call arrives as two blocks: @@ -377,11 +353,7 @@ When that object doesn’t match your schema, the `tool_result` carries `is_error: true` instead and the agent calls `StructuredOutput` again, so your stream can hold several calls for one query. Read the validated data from `structured_output` on the result message rather than from a `tool_use` block, and see Error handling for the result you get when no attempt succeeds. If your application shows or logs tool calls, skip the ones named `StructuredOutput` so the mechanism doesn’t appear as a step the agent chose. A `tool_result` block carries no tool name, only the `tool_use_id` of the call it answers, so match that against the `id` of each call you skipped. -## - -​ - -Error handling +## Error handling Structured output generation can fail when the agent cannot produce valid JSON matching your schema. This typically happens when the schema is too complex for the task, the task itself is ambiguous, or the agent hits its retry limit trying to fix validation errors. It can also happen without any validation failure: a [model fallback](</docs/en/model-config#automatic-model-fallback>) can retract an already-completed output mid-stream, and if no retry replaces it the run ends with the same error. Check the `errors` list on the error result message to tell the two causes apart before debugging your schema. Check the result message’s `subtype`: @@ -486,11 +458,7 @@ * **Match schema to task.** If the task might not have all the information your schema requires, make those fields optional. * **Use clear prompts.** Ambiguous prompts make it harder for the agent to know what output to produce. -## - -​ - -Related resources +## Related resources * [JSON Schema documentation](<https://json-schema.org/>): learn JSON Schema syntax for defining complex schemas with nested objects, arrays, enums, and validation constraints * [API Structured Outputs](<https://platform.claude.com/docs/en/build-with-claude/structured-outputs>): use structured outputs with the Claude API directly for single-turn requests without tool use
modified Create custom subagents View current →
Show diff (695 lines)
--- a/sub-agents.md +++ b/sub-agents.md @@ -12,11 +12,7 @@ Claude uses each subagent’s description to decide when to delegate tasks. When you create a subagent, write a clear description so Claude knows when to use it. Those descriptions take up context, so keep them short. When the combined descriptions of your subagents, except the built-in ones, exceed 15,000 tokens, Claude Code shows a [warning at startup with the total token count](</docs/en/errors#agent-descriptions-are-over-the-15000-token-limit>). Trim the `description` fields of your subagents, and move detail into each subagent’s system prompt, which only loads when that subagent runs. -## - -​ - -Built-in subagents +## Built-in subagents Claude Code includes built-in subagents that Claude automatically uses when appropriate. Each inherits the parent conversation’s permission rules; most run with a restricted tool set. Explore and Plan start without your CLAUDE.md files and the git status snapshot to keep research fast and inexpensive. Other built-in and custom subagents load both, unless you set `omitClaudeMd` in a custom subagent’s definition to start it without the user, project, and local CLAUDE.md files. For the full breakdown of what reaches a subagent, see what loads at startup. @@ -71,11 +67,7 @@ An Agent tool call that omits `subagent_type` fails with [`subagent_type is required`](</docs/en/errors#subagent-type-is-required>) when the session has no `general-purpose` subagent to fall back on. Beyond these built-in subagents, you can create your own with custom prompts, tool restrictions, permission modes, hooks, and skills. The following sections show how to get started and customize subagents. -## - -​ - -Quickstart: create your first subagent +## Quickstart: create your first subagent Subagents are Markdown files with YAML frontmatter. To create one, ask Claude to write it for you, or write the file yourself. This walkthrough creates a user-level subagent that reviews code and suggests improvements. @@ -124,19 +116,11 @@ Running `/agents` prints a reminder to ask Claude or edit `.claude/agents/` and `~/.claude/agents/` directly. On Claude Code v2.1.197 and earlier, `/agents` opens an interactive wizard with a **Running** tab that lists live subagents and a **Library** tab for creating, editing, and deleting them. -## - -​ - -Configure subagents +## Configure subagents A subagent’s file location determines who it’s available to, and its frontmatter determines what it can do. This section covers where subagent files live and every field they support. -### - -​ - -Choose the subagent scope +### Choose the subagent scope Store subagent files in different locations depending on scope. When multiple subagents share the same name, Claude Code uses the one from the higher-priority location. @@ -194,11 +178,7 @@ You can also reuse a subagent definition as an [agent team](</docs/en/agent-teams>) teammate: name the subagent type when you ask Claude to spawn the teammate, and Claude Code applies parts of that definition to it. [Use subagent definitions for teammates](</docs/en/agent-teams#use-subagent-definitions-for-teammates>) says which scopes and which parts apply in each display mode. -### - -​ - -Write subagent files +### Write subagent files Subagent files use YAML frontmatter for configuration, followed by the system prompt in Markdown: @@ -227,11 +207,7 @@ The redirect vectors and the shape rules are listed under [How Claude Code enforces isolation](</docs/en/worktrees#how-claude-code-enforces-isolation>). PowerShell commands get only the working-directory check. [Monitor](</docs/en/tools-reference#monitor-tool>) commands go through the same working-directory and command-content checks as Bash commands. When the main conversation itself runs isolated in a worktree, Claude Code applies the same checks to the session and to every subagent it spawns, including subagents without `isolation: worktree`; see [How Claude Code enforces isolation](</docs/en/worktrees#how-claude-code-enforces-isolation>). -### - -​ - -Frontmatter reference +### Frontmatter reference Configure a subagent with YAML [frontmatter](</docs/en/glossary#frontmatter>) between `---` markers at the top of its file, and write its system prompt as Markdown after the closing `---`. Only `name` and `description` are required. Multi-word field names use camelCase, such as `maxTurns` and `disallowedTools`, and must match the table exactly: Claude Code ignores a field it doesn’t recognize without reporting an error. @@ -269,11 +245,7 @@ cacheTtl: 1h --- -#### - -​ - -Subagent files Claude Code skips +#### Subagent files Claude Code skips Claude Code skips a file in a project, user, or managed `agents` directory, or in one under a directory you add with `--add-dir`, without reporting it in the session, when the frontmatter has any of these problems: @@ -289,11 +261,7 @@ To find files in an `agents` directory whose frontmatter doesn’t parse, run `claude plugin validate` against the directory, for example `.claude/agents` or `~/.claude/agents`. Claude Code checks only [the directory you name](</docs/en/plugins/cli-reference#validate-a-directory>), and doesn’t flag a file whose frontmatter parses but has no `name`. Requires Claude Code v2.1.233 or later. -### - -​ - -Choose a model +### Choose a model The `model` field controls which model the subagent uses: @@ -320,11 +288,7 @@ In interactive sessions, Claude Code shows a warning naming the requested model and the model the subagent runs on, for either substitution. To check which model a subagent is running on, run [`/tasks`](</docs/en/commands>). Claude Code names the model on the subagent’s row, and adds the [effort level](</docs/en/model-config#adjust-effort-level>) set for that subagent, if any. Requires Claude Code v2.1.242 or later. A per-invocation `model` parameter also applies when the subagent is resumed or sent a follow-up message, so the subagent stays on that model. As of v2.1.198, subagents also inherit the main conversation’s [extended thinking](</docs/en/model-config#extended-thinking>) configuration: if thinking is on in your session, it’s on for the subagent, and if it’s off, it stays off. There is no per-subagent thinking setting. Before v2.1.198, subagents ran with extended thinking disabled regardless of the main conversation’s setting. -#### - -​ - -Run every subagent on one model +#### Run every subagent on one model `CLAUDE_CODE_SUBAGENT_MODEL` is a default, so a subagent’s definition or a model Claude passes still takes precedence over it. To apply one model to every subagent, [teammate](</docs/en/agent-teams#specify-teammates-and-models>), and [workflow agent](</docs/en/workflows>), also set `CLAUDE_CODE_SUBAGENT_MODEL_FORCE` to `1`. Requires Claude Code v2.1.257 or later. @@ -345,35 +309,19 @@ * A fork * A [skill that runs in a subagent](</docs/en/skills#run-skills-in-a-subagent>) with `model: inherit` -### - -​ - -Choose an effort level +### Choose an effort level To run a subagent at its own [effort level](</docs/en/model-config#adjust-effort-level>), set the `effort` field in its definition. When you ask Claude to run a non-fork subagent at a specific effort level, it can also pass an `effort` parameter for that invocation. The parameter overrides the `effort` field and stays in effect when the subagent is resumed. The [`CLAUDE_CODE_EFFORT_LEVEL`](</docs/en/env-vars#variables>) environment variable takes precedence over both. The per-invocation parameter requires Claude Code v2.1.292 or later. -#### - -​ - -When a subagent has no `effort` field or parameter +#### When a subagent has no `effort` field or parameter On the main conversation’s model, the subagent runs at the level you pick in the session, such as with `/effort`, or set with `--effort`. On another model, [that level doesn’t apply](</docs/en/model-config#effort-level-of-subagents-and-teammates>). To choose its level, set the `effort` field. -### - -​ - -Control subagent capabilities +### Control subagent capabilities You can control what subagents can do through tool access, permission modes, and conditional rules. -#### - -​ - -Available tools +#### Available tools Subagents inherit the [built-in tools](</docs/en/tools-reference>) and MCP tools available in the main conversation, narrowed by two filters: the first removes a short list of tools from every subagent, and the second reduces the built-in tool set for subagents that run in the background, which is the default. On macOS, Linux, and WSL, a subagent can also receive the Glob and Grep tools when the main conversation doesn’t have them, as described under [Glob tool behavior](</docs/en/tools-reference#glob-tool-behavior>). Forks skip both filters and receive the main conversation’s exact tool pool. The first filter removes these tools, even when listed in the `tools` field: @@ -388,11 +336,7 @@ The second filter applies to subagents running in the background. Apart from `Agent` and `ExitPlanMode`, which follow the first filter’s conditions wherever the subagent runs, a background subagent keeps every MCP tool but only these built-in tools: `Read`, `Grep`, `Glob`, `LSP`, `Bash`, `PowerShell`, `Edit`, `Write`, `NotebookEdit`, `WebFetch`, `WebSearch`, `TodoWrite`, `Skill`, `ToolSearch`, `EnterWorktree`, `ExitWorktree`, `Monitor`, `TaskStop`, `SendMessage`, and `Artifact`, plus [`SubagentHandback`](</docs/en/tools-reference>) for a subagent that reports through it. Claude Code removes every other built-in tool from a background subagent, whether inherited or listed in the `tools` field, so the same definition can resolve to different tools in the foreground and the background. The removal reports no error unless it leaves the `tools` list [resolving to nothing](</docs/en/errors#agent-would-be-spawned-with-zero-tools>). Before v2.1.280, background subagents couldn’t use `LSP`. [`ListAgents`](</docs/en/cross-session-messaging>) follows these filters like any built-in tool: a foreground subagent inherits it in sessions where cross-session messaging is enabled, and a background subagent doesn’t keep it. Teammates in [agent teams](</docs/en/agent-teams>) additionally keep the task tools and cron tools: `TaskCreate`, `TaskGet`, `TaskList`, `TaskUpdate`, `CronCreate`, `CronDelete`, and `CronList`. In a [session without the Task tools](</docs/en/tools-reference#task-tool-availability>), Claude Code doesn’t provide the task tools to subagents either, even when the subagent runs a different model. An in-process teammate follows your session the same way. To find out whether a split-pane teammate has the task tools, see [Task tool availability](</docs/en/tools-reference#task-tool-availability>). -#### - -​ - -Restrict which tools a subagent can use +#### Restrict which tools a subagent can use To restrict tools, use the `tools` field as an allowlist or the `disallowedTools` field as a denylist. If both are set, `disallowedTools` is applied first, then `tools` is resolved against the remaining pool. A tool listed in both is removed. This example uses `tools` to allow only Read, Grep, Glob, and Bash. The subagent can’t edit files, write files, or use any MCP tools: @@ -435,11 +379,7 @@ * **In`tools`**: write `mcp__` followed by the [server’s whole name](</docs/en/permissions#mcp>) and `__*`, as in `mcp__reports__v2__*`. Without the trailing `__*`, `mcp__reports__v2` matches none of that server’s tools. * **In`disallowedTools`**: look for `mcp__reports` or `mcp__reports__*`, the entries that withhold a server named `reports`. With either entry, the subagent loses every `reports__v2` tool as well, because those tool names also begin with `mcp__reports__`. To withhold only the `reports` server’s tools, list them one by one instead, such as `mcp__reports__run_query`. -#### - -​ - -Restrict which subagents can be spawned +#### Restrict which subagents can be spawned When an agent runs as the main thread with `claude --agent`, it can spawn subagents using the Agent tool. To restrict which subagent types it can spawn, use `Agent(agent_type)` syntax in the `tools` field. @@ -457,11 +397,7 @@ If you omit `Agent` from the `tools` list entirely, the agent can’t spawn any subagents with the Agent tool. The `Agent(agent_type)` allowlist syntax applies only to an agent running as the main thread with `claude --agent`. In a subagent definition, listing `Agent` in `tools` lets that subagent spawn subagents of its own while the depth limit allows it, but any type list inside the parentheses is ignored. -#### - -​ - -Scope MCP servers to a subagent +#### Scope MCP servers to a subagent Use the `mcpServers` field to give a subagent access to [MCP](</docs/en/mcp>) servers that aren’t available in the main conversation. Inline servers defined here are connected when the subagent starts, subject to the trust rule for the agent file’s folder, and disconnected when it finishes. String references share the parent session’s connection. @@ -497,11 +433,7 @@ When one of these blocks a server, Claude Code skips it and shows a warning naming the blocked servers. Managed-settings restrictions apply to every subagent regardless of how it is defined. `--strict-mcp-config` doesn’t filter servers you pass inline via `--agents` or the SDK `agents` option, since those are explicit caller input. -#### - -​ - -Trust required for inline MCP servers +#### Trust required for inline MCP servers Claude Code loads an inline MCP server from an agent file in your project’s `.claude/agents/` directory, or in an `--add-dir` directory’s `.claude/agents/`, only after you [trust the folder the agent file came from](</docs/en/permissions#what-runs-before-you-trust-a-folder>). Before v2.1.238, Claude Code loaded these servers without checking trust. @@ -514,11 +446,7 @@ * A name that references a server you already configured * An inline server in an agent file from `~/.claude/agents/`, in one you pass with `--agents` or the SDK `agents` option, or in one that managed settings supplies -#### - -​ - -Permission modes +#### Permission modes Set `permissionMode` to choose the permission mode a subagent runs in. Use the modes’ config values, so Manual mode is `default`. If you leave it unset, the subagent inherits the main conversation’s [permission mode](</docs/en/permission-modes>). The main conversation’s permission mode decides whether Claude Code uses the value you set: @@ -539,11 +467,7 @@ `bypassPermissions`| [Skip permission prompts](</docs/en/permission-modes#skip-all-checks-with-bypasspermissions-mode>). A subagent runs in this mode only when the main conversation does `plan`| Plan mode (read-only exploration) -#### - -​ - -Preload skills into subagents +#### Preload skills into subagents Use the `skills` field to inject skill content into a subagent’s context at startup. This gives the subagent domain knowledge without requiring it to discover and load skills during execution. @@ -561,11 +485,7 @@ This is the inverse of [running a skill in a subagent](</docs/en/skills#run-skills-in-a-subagent>). With `skills` in a subagent, the subagent controls the system prompt and loads skill content. With `context: fork` in a skill, the skill content is injected into the agent you specify. In both cases the subagent starts without your conversation history. -#### - -​ - -Enable persistent memory +#### Enable persistent memory The `memory` field gives the subagent a persistent directory that survives across conversations. The subagent uses this directory to build up knowledge over time, such as codebase patterns, debugging insights, and architectural decisions. @@ -604,11 +524,7 @@ knowledge across conversations. Write concise notes about what you found and where. -#### - -​ - -Conditional rules with hooks +#### Conditional rules with hooks For more dynamic control over tool usage, use `PreToolUse` hooks to validate operations before they execute. This is useful when you need to allow some operations of a tool while blocking others. This example creates a subagent that only allows read-only database queries. The `PreToolUse` hook runs the script specified in `command` before each Bash command executes: @@ -646,11 +562,7 @@ To test the rule, ask the subagent to run an `UPDATE` statement: the script exits with code 2, Claude Code blocks the command, and the subagent sees the `Blocked: Only SELECT queries are allowed` message. See [Hook input](</docs/en/hooks#pretooluse-input>) for the complete input schema and [exit codes](</docs/en/hooks#exit-code-output>) for how exit codes affect behavior. On Windows, write hook scripts in PowerShell and add `shell: powershell` to the hook entry as shown in [running hooks in PowerShell](</docs/en/hooks#windows-powershell-tool>). -#### - -​ - -Disable specific subagents +#### Disable specific subagents You can prevent Claude from using specific subagents by adding them to the `deny` array in your [settings](</docs/en/settings-reference#permission-settings>). Use the format `Agent(subagent-name)` where `subagent-name` matches the subagent’s name field. @@ -666,11 +578,7 @@ See [Permissions documentation](</docs/en/permissions#tool-specific-permission-rules>) for more details on permission rules. -### - -​ - -Define hooks for subagents +### Define hooks for subagents Subagents can define [hooks](</docs/en/hooks>) that run during the subagent’s lifecycle. There are two ways to configure hooks: @@ -679,11 +587,7 @@ Hooks from [settings files, managed policy settings, and plugins](</docs/en/hooks#hook-locations>) all apply inside subagents, so a `PreToolUse` hook in `settings.json` also runs before every tool a subagent uses. -#### - -​ - -Hooks in subagent frontmatter +#### Hooks in subagent frontmatter Define hooks directly in the subagent’s markdown file. These hooks only run while that specific subagent is active and are cleaned up when it finishes. @@ -717,11 +621,7 @@ When the agent is invoked as a subagent, `Stop` hooks in frontmatter are automatically converted to `SubagentStop` events. -#### - -​ - -Project-level hooks for subagent events +#### Project-level hooks for subagent events Configure hooks in `settings.json` that respond to subagent lifecycle events in the main session. @@ -754,25 +654,13 @@ See [Hooks](</docs/en/hooks>) for the complete hook configuration format. -## - -​ - -Work with subagents - -### - -​ - -Understand automatic delegation +## Work with subagents + +### Understand automatic delegation Claude automatically delegates tasks based on the task description in your request, the `description` field in subagent configurations, and current context. To encourage proactive delegation, include phrases like “use proactively” in your subagent’s description field. Keep descriptions brief: Claude Code shows a startup warning when your subagents’ combined descriptions pass [the 15,000-token limit](</docs/en/errors#agent-descriptions-are-over-the-15000-token-limit>), and still loads every subagent. If the subagent ships in a [plugin](</docs/en/plugins/overview>), you can measure how reliably Claude delegates to it across realistic prompts instead of checking one at a time: [`claude plugin eval`](</docs/en/plugin-evals>) runs each prompt with and without the plugin and scores the results. -### - -​ - -Invoke subagents explicitly +### Invoke subagents explicitly When automatic delegation isn’t enough, you can request a subagent yourself. Three patterns escalate from a one-off suggestion to a session-wide default: @@ -809,22 +697,14 @@ The CLI flag overrides the setting if both are present. -### - -​ - -Run subagents in foreground or background +### Run subagents in foreground or background Subagents can run in the foreground or the background: * **Foreground subagents** block the main conversation until complete. Permission prompts are passed through to you as they come up. * **Background subagents** run concurrently while you continue working. When a background subagent reaches a tool call that needs permission, Claude Code surfaces the prompt in your main session and names the subagent that is asking. Approve to let the subagent continue, or press Esc to deny that one tool call without stopping the subagent. -#### - -​ - -Which subagents run in the background +#### Which subagents run in the background With nothing configured, a subagent that Claude spawns from your main conversation starts in the background. @@ -833,11 +713,7 @@ For a skill with `context: fork`, Claude Code follows the rules in [Run skills in a subagent](</docs/en/skills#run-skills-in-a-subagent>) instead, whether or not fork mode is on. -#### - -​ - -Let Claude wait for a subagent +#### Let Claude wait for a subagent 1. Turn fork mode off by setting `CLAUDE_CODE_FORK_SUBAGENT` to `0`, for example in [`settings.json`](</docs/en/settings>): @@ -852,19 +728,11 @@ To keep working while Claude waits, press **Ctrl+B** in the terminal or click [**Run in background**](</docs/en/vs-code#move-a-running-command-or-subagent-to-the-background>) in VS Code. If you set the [`CLAUDE_CODE_DISABLE_BACKGROUND_TASKS`](</docs/en/env-vars>) environment variable to `1` instead of turning fork mode off, Claude waits for subagents to finish before it continues. Background commands are off too, and **Ctrl+B** doesn’t move anything to the background. -#### - -​ - -Tools, permissions, and results of background subagents +#### Tools, permissions, and results of background subagents Background subagents run with a smaller built-in tool set than foreground subagents, except for conversation forks and resumed foreground subagents. Background subagents surface every permission prompt in your main session. When you answer one of those prompts with a choice that lasts beyond that one tool call, such as a grant that lasts for the rest of the session, Claude Code applies your answer to the whole session, including your main conversation. A background subagent can leave a background [Bash or PowerShell command](</docs/en/tools-reference#background-commands>) [running past the end of its turn](</docs/en/interactive-mode#how-backgrounding-works>). When that command ends, Claude Code sends the subagent a notification. A background subagent’s results reach Claude as a completion notification in a later turn. Claude waits for that notification before reporting the subagent’s results, and if you ask about progress first, it reports that the subagent is still running. -#### - -​ - -Finished subagents in the panel and task list +#### Finished subagents in the panel and task list Claude Code clears a background subagent’s row from the subagent panel below the prompt input in one of two ways, depending on how the subagent ended: @@ -873,19 +741,11 @@ A background subagent that completes stays listed in [`/tasks`](</docs/en/commands>), marked done and sorted below running work, for the same 30 seconds as the footer hint. Its detail view stays open when the subagent finishes. Subagents that fail or that you stop leave the list. Before v2.1.208, a completed subagent left the list the moment it finished and its detail view closed. -### - -​ - -Subagent names +### Subagent names If you start a session with [agent teams](</docs/en/agent-teams#enable-agent-teams>) enabled, Claude can give a subagent a name by passing a `name` parameter on the Agent tool call. It may do so on its own, without asking you first. The name makes the subagent addressable: Claude can message or resume it by name after it finishes. In an interactive session with [agent teams](</docs/en/agent-teams>) enabled, a subagent that Claude spawns from the main conversation with a `name` launches as a teammate instead, unless the call is a fork or passes `isolation` on the call itself. An `isolation` value in the subagent’s frontmatter doesn’t prevent it, and the teammate then runs in the main session’s working directory. See [How Claude starts agent teams](</docs/en/agent-teams#how-claude-starts-agent-teams>). -### - -​ - -API errors in subagents +### API errors in subagents When something [cuts off a subagent’s response mid-stream](</docs/en/errors#the-response-above-may-be-incomplete>), and the partial response contains text but no tool calls, Claude Code prompts the subagent to continue rather than ending the run. This happens in interactive sessions too. The run ends on the error only once those continuations are used up. A subagent whose run ends on an API error, such as a usage limit or a repeated server error, reports that failure back to Claude. What Claude receives depends on where the subagent ran: @@ -898,11 +758,7 @@ When you configure a [fallback model chain](</docs/en/model-config#fallback-model-chains>) and a subagent encounters a failure the chain covers, such as its model being unavailable, Claude Code switches the subagent to the first model in the chain that accepts the request. The subagent keeps working instead of ending on the error. Once the underlying API error clears, ask Claude to retry the task or resume the subagent. -### - -​ - -Subagent output scanning +### Subagent output scanning Claude Code scans each subagent’s final report before Claude reads it. A subagent may have read files, web pages, or command output you never reviewed, and text from those sources can carry instructions aimed at the main conversation. The scan never removes or rewords anything; it makes two kinds of change you may notice in a report: @@ -911,27 +767,15 @@ The scan doesn’t judge whether content is malicious, and it doesn’t change what an instruction in a report can do: a tool call the report leads Claude to make still goes through the session’s [permission checks](</docs/en/permissions>) and [sandboxing](</docs/en/sandboxing>). It isn’t a substitute for restricting what a subagent can reach. A report that returns to Claude as the subagent’s result also arrives under a header marking it as subagent output. The header states that instructions or approval claims inside the report are the subagent’s words and carry no authority from you. A background subagent’s report arrives inside a completion notification, which is marked as an automated event rather than a message from you. -### - -​ - -Common patterns - -#### - -​ - -Isolate high-volume operations +### Common patterns + +#### Isolate high-volume operations One of the most effective uses for subagents is isolating operations that produce large amounts of output. Running tests, fetching documentation, or processing log files can consume significant context. By delegating these to a subagent, the verbose output stays in the subagent’s context while only the relevant summary returns to your main conversation. Use a subagent to run the test suite and report only the failing tests with their error messages -#### - -​ - -Run parallel research +#### Run parallel research For independent investigations, spawn multiple subagents to work simultaneously: @@ -943,21 +787,13 @@ For work that needs to keep running in parallel or won’t fit in one context window, run it in [separate sessions](</docs/en/agents>) and let Claude [pass findings between them](</docs/en/cross-session-messaging>). -#### - -​ - -Chain subagents +#### Chain subagents For multi-step workflows, ask Claude to use subagents in sequence. Each subagent completes its task and returns results to Claude, which then passes relevant context to the next subagent. Use the code-reviewer subagent to find performance issues, then use the optimizer subagent to fix them -### - -​ - -Choose between subagents and main conversation +### Choose between subagents and main conversation Use the **main conversation** when: @@ -974,11 +810,7 @@ Consider [Skills](</docs/en/skills>) instead when you want reusable prompts or workflows that run in the main conversation context rather than isolated subagent context. For a question about something already in your conversation, use [`/btw`](</docs/en/interactive-mode#side-questions-with-%2Fbtw>) instead of a subagent. It has no tool access, and the answer isn’t added to history. -### - -​ - -Let subagents spawn their own subagents +### Let subagents spawn their own subagents By default, a subagent can spawn subagents of its own, up to three layers below the main conversation. At the depth limit, Claude Code withholds the `Agent` tool from every subagent except a fork, so a subagent at the limit does its delegated work itself and returns one summary. A fork at the limit keeps `Agent` in its inherited tool list, but the tool returns an error instead of spawning. Nested subagents suit a delegated task that itself splits into parallel subtasks, such as a reviewer subagent that dispatches a verifier per finding. By default the spawning subagent waits for each nested subagent’s report: @@ -995,11 +827,7 @@ With this value, your subagents can delegate to a second layer of their own, and that second layer can’t delegate further. Set `1` to turn nesting off. A nested subagent is configured the same way as a top-level one and resolves from the same scopes. To keep one subagent from spawning while nesting is on, such as a reviewer that should stay read-only, omit `Agent` from its `tools` list or add it to `disallowedTools`. In the terminal, Claude Code shows nested subagents as a tree in the subagent panel below the prompt input and marks each row that still has descendants in the panel with a `(+N)` count of them. Open a row to see that subagent’s siblings and direct children with a path back to `main`. -### - -​ - -Concurrent subagent limit +### Concurrent subagent limit Two limits control subagent use, each with its own variable: this one stops Claude from spawning more subagents while too many are running, and the depth limit caps how deeply subagents nest. There’s no limit on the total number of subagents Claude can spawn over a session. By default, when 20 subagents are running in a session, spawning another with the Agent tool fails with `Concurrent subagent limit reached`, and the error tells Claude not to retry. Spawning succeeds again when the running count drops below the limit. To change the limit, set [`CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS`](</docs/en/env-vars>) to any positive whole number. Sessions with [ultracode](</docs/en/model-config#adjust-effort-level>) active are exempt: the limit isn’t enforced there. Requires Claude Code v2.1.217 or later. The limit blocks only subagents Claude spawns with the Agent tool, but other runs occupy the same slots: @@ -1008,17 +836,9 @@ Agents that other features run, such as [workflow](</docs/en/workflows>) agents and [agent team](</docs/en/agent-teams>) teammates, follow their own limits instead. -### - -​ - -Manage subagent context - -#### - -​ - -What loads at startup +### Manage subagent context + +#### What loads at startup Each subagent starts with a fresh, isolated context window. It doesn’t see your conversation history, the skills you’ve already invoked, or the files Claude has already read. Claude composes a delegation message that summarizes the task, and the subagent works from there. The exception is a fork, which inherits the parent conversation instead of starting fresh. A non-fork subagent’s initial context contains: @@ -1035,11 +855,7 @@ * **Auto memory** : the main conversation’s [auto memory](</docs/en/memory#auto-memory>) isn’t loaded. To give a subagent persistent memory of its own, use the `memory` field. * **Context window size** : a subagent’s context window is sized by its own model, not the parent’s. Delegating to a model with a smaller window gives that subagent the smaller window. -#### - -​ - -Resume subagents +#### Resume subagents Each subagent invocation creates a new instance rather than continuing an earlier one. To continue an existing subagent’s work instead of starting over, ask Claude to resume it. Resumed subagents retain their full conversation history, including all previous tool calls, results, and reasoning. If the subagent spawned background subagents of its own, that history includes the results they delivered while it ran. Before v2.1.304, a subagent that Claude messaged or resumed right after it finished could forget its most recent work. @@ -1067,11 +883,7 @@ If Claude can’t message a subagent by name after you restart Claude Code and resume the session, give Claude the subagent’s agent ID instead. Names Claude gave from the main conversation since its last [compaction](</docs/en/context-window#what-survives-compaction>) survive the restart. A name from before that compaction doesn’t. To find the ID for a name, look for that name in the `agent-{agentId}.meta.json` files in `~/.claude/projects/{project}/{sessionId}/subagents/`. After one message by ID, the subagent’s name works again, unless a newer agent has taken that name. Before v2.1.299, no name survived a restart, and a send by name was refused even when the agent ID still worked. -#### - -​ - -Auto-compaction +#### Auto-compaction Subagents support automatic compaction. Compaction triggers as the subagent’s own context window fills, and `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` applies to subagents as well. See [environment variables](</docs/en/env-vars>) for when the override takes effect. Compaction events are logged in subagent transcript files: @@ -1101,11 +913,7 @@ * **The value isn’t below the[auto-compact window](</docs/en/model-config#context-window-and-auto-compaction>) the subagent would otherwise inherit**: to compact earlier, set a value below that window. * **You run the whole session as this subagent with`--agent` or the `agent` setting**: the field has no effect there. To set the session’s window, see [Set the auto-compact window](</docs/en/model-config#set-the-auto-compact-window>). -## - -​ - -Fork the current conversation +## Fork the current conversation When [agent view is turned off](</docs/en/agent-view#turn-off-agent-view>), `/subtask` isn’t available and `/fork` starts the forked subagent instead; otherwise `/fork` copies the whole session into a new [background session](</docs/en/agent-view#from-inside-a-session>). @@ -1115,11 +923,7 @@ The fork appears in a panel below your prompt and runs in the background while you keep working. When it finishes, its result arrives as a message in your main conversation. The next section covers the panel controls for watching and steering forks while they run. -### - -​ - -Observe and steer running forks +### Observe and steer running forks Running forks appear in a panel below the prompt input, with one row for the main session and one for each fork. When a fork finishes successfully, Claude Code removes its row. Claude Code keeps the row of a fork that failed or that you stopped for 30 seconds, the same as for any other background subagent. Before v2.1.232, Claude Code kept a finished fork’s row for 30 seconds as well. Use these keys to interact with the panel: @@ -1137,11 +941,7 @@ To have the viewed agent read your message before the work it’s waiting on finishes, send it with [`Ctrl+Enter` or `Ctrl+X Ctrl+S`](</docs/en/keybindings#chat-actions>). Any shell command or subagent the agent is waiting on that can move to the [background](</docs/en/tools-reference#background-commands>) moves there and keeps running. When the agent is writing a response, or waiting on work that can’t move to the background, it keeps going and reads your message once that finishes. Requires Claude Code v2.1.286 or later. -### - -​ - -How forks differ from other subagents +### How forks differ from other subagents A fork inherits everything the main session has at the moment it spawns. Any other subagent starts fresh from its definition. @@ -1154,11 +954,7 @@ Because a fork’s system prompt and tool definitions are identical to the parent, its first request reuses the parent’s [prompt cache](</docs/en/prompt-caching#subagents-and-the-cache>). Because of that reuse, a fork costs less than a fresh subagent for tasks that need the same context. When Claude spawns a fork through the Agent tool, it can pass `isolation: "worktree"` so the fork’s file edits are written to a separate git worktree instead of your checkout. A fork can’t spawn further forks. -### - -​ - -Turn fork mode off +### Turn fork mode off Fork mode lets Claude start a fork on its own. To stop Claude from starting forks: @@ -1167,11 +963,7 @@ While fork mode is on, Claude also can’t wait for a subagent in interactive terminal, VS Code, or desktop sessions on your machine. Fork mode is on by default from Claude Code v2.1.302, and in an interactive terminal session from v2.1.232. -## - -​ - -Example subagents +## Example subagents These examples demonstrate effective patterns for building subagents. Use them as starting points, or generate a customized version with Claude. @@ -1182,11 +974,7 @@ * **Limit tool access:** grant only necessary permissions for security and focus * **Check into version control:** share project subagents with your team -### - -​ - -Code reviewer +### Code reviewer A read-only subagent that reviews code without modifying it. This example shows how to design a focused subagent with limited tool access that excludes Edit and Write, and a detailed prompt that specifies exactly what to look for and how to format output. @@ -1221,11 +1009,7 @@ Include specific examples of how to fix issues. -### - -​ - -Debugger +### Debugger A subagent that can both analyze and fix issues. Unlike the code reviewer, this one includes Edit because fixing bugs requires modifying code. The prompt provides a clear workflow from diagnosis to verification. @@ -1260,11 +1044,7 @@ Focus on fixing the underlying issue, not the symptoms. -### - -​ - -Data scientist +### Data scientist A domain-specific subagent for data analysis work. This example shows how to create subagents for specialized workflows outside of typical coding tasks. It explicitly sets `model: sonnet` for more capable analysis. @@ -1299,11 +1079,7 @@ Always ensure queries are efficient and cost-effective. -### - -​ - -Database query validator +### Database query validator A subagent that allows Bash access but validates commands to permit only read-only SQL queries. This example shows how to use `PreToolUse` hooks for conditional validation when you need finer control than the `tools` field provides. @@ -1357,11 +1133,7 @@ On Windows, write the validation script in PowerShell and add `shell: powershell` to the hook entry. See [running hooks in PowerShell](</docs/en/hooks#windows-powershell-tool>). The hook receives JSON via stdin with the Bash command in `tool_input.command`. Exit code 2 blocks the operation and feeds the error message back to Claude. See [Hooks](</docs/en/hooks#exit-code-output>) for details on exit codes and [Hook input](</docs/en/hooks#pretooluse-input>) for the complete input schema. The system prompt tells the subagent to refuse write requests, so the hook is a backstop: if the subagent attempts a write anyway, Claude Code blocks the command and the subagent sees the `Blocked: Write operations not allowed. Use SELECT queries only.` message. -## - -​ - -Next steps +## Next steps Now that you understand subagents, explore these related features:
modified Subagents in the SDK View current →
Show diff (286 lines)
--- a/subagents.md +++ b/subagents.md @@ -1,10 +1,6 @@ Subagents are separate agent instances that your main agent can spawn to handle focused subtasks. Use them to isolate context, run multiple analyses in parallel, and apply specialized instructions without adding to the main agent’s prompt. -## - -​ - -Overview +## Overview You can create subagents in three ways: @@ -14,11 +10,7 @@ This guide focuses on the programmatic approach, which is recommended for SDK applications. -## - -​ - -Benefits of using subagents +## Benefits of using subagents Because subagents are separate agent instances, delegating work to them gives you four benefits: @@ -27,17 +19,9 @@ * **Specialized instructions and knowledge** : each subagent can have a tailored system prompt with specific expertise, best practices, and constraints. A `database-migration` subagent can have detailed knowledge about SQL best practices, rollback strategies, and data integrity checks that would be unnecessary noise in the main agent’s instructions. * **Tool restrictions** : subagents can be limited to specific tools, reducing the risk of unintended actions. A `doc-reviewer` subagent might only have access to Read and Grep tools, ensuring it can analyze but never accidentally modify your documentation files. -## - -​ - -Create subagents - -### - -​ - -Programmatic definition (recommended) +## Create subagents + +### Programmatic definition (recommended) Define subagents directly in your code using the `agents` parameter. Claude invokes subagents through the `Agent` tool. Most examples on this page print only the final result. To confirm that Claude delegated to a subagent rather than answering directly, see Detect subagent invocation. This example creates two subagents: a code reviewer with read-only access and a test runner that can execute commands. @@ -139,11 +123,7 @@ if ("result" in message) console.log(message.result); } -### - -​ - -AgentDefinition configuration +### AgentDefinition configuration Field| Type| Required| Description ---|---|---|--- @@ -165,32 +145,20 @@ In the Python SDK, multi-word field names such as `disallowedTools` and `mcpServers` keep their camelCase spelling to match the wire format rather than following Python’s snake_case convention. See the [`AgentDefinition` reference](</docs/en/agent-sdk/python#agentdefinition>) for details. -#### - -​ - -Choose whether Claude waits for subagents +#### Choose whether Claude waits for subagents By default, a subagent your main agent spawns [runs in the background](</docs/en/sub-agents#run-subagents-in-foreground-or-background>). The Agent tool result has `status: "async_launched"`, and the report arrives in a later turn. Claude waits when its next action needs the report: the call blocks and returns `status: "completed"`. To make that choice yourself: * **In your prompt** : ask Claude to wait, such as “run the test-runner agent and wait for it” * **In the definition** : set `background` to `true` to keep that agent in the background -### - -​ - -Filesystem-based definition (alternative) +### Filesystem-based definition (alternative) You can also define subagents as markdown files in `.claude/agents/` directories. See the [Claude Code subagents documentation](</docs/en/sub-agents>) for details on this approach. Programmatically defined agents take precedence over filesystem-based agents with the same name. When Claude calls the Agent tool without a `subagent_type`, it gets the built-in `general-purpose` subagent, which Claude can spawn even when you define no agents of your own. Setting [`CLAUDE_AGENT_SDK_DISABLE_BUILTIN_AGENTS=1`](</docs/en/env-vars>) removes that default, and such a call fails with [`subagent_type is required`](</docs/en/errors#subagent-type-is-required>). -## - -​ - -What subagents inherit +## What subagents inherit Unless the subagent is a [fork](</docs/en/sub-agents#fork-the-current-conversation>), its context window starts fresh, with no parent conversation, but isn’t empty. The only content you pass from parent to subagent is the Agent tool’s prompt string, so include any file paths, error messages, or decisions the subagent needs directly in that prompt. A subagent that has the [`SendMessage`](</docs/en/tools-reference>) tool starts with a list of the other named agents running in the session, so it knows which names it can send messages to. Claude Code adds the list to the subagent’s first turn automatically. A [fork](</docs/en/sub-agents#fork-the-current-conversation>) doesn’t get the list because it inherits the parent conversation instead. A subagent also inherits the main session’s extended thinking configuration. The table below lists what a non-fork subagent’s context contains and what it leaves out. @@ -210,25 +178,13 @@ An API error that ends the subagent early, such as a rate limit, is never delivered as its result. See [API errors in subagents](</docs/en/sub-agents#api-errors-in-subagents>) for the foreground and background behavior. -## - -​ - -Invoke subagents - -### - -​ - -Automatic invocation +## Invoke subagents + +### Automatic invocation Claude automatically decides when to invoke subagents based on the task and each subagent’s `description`. For example, if you define a `performance-optimizer` subagent with the description “Performance optimization specialist for query tuning”, Claude will invoke it when your prompt mentions optimizing queries. Write clear, specific descriptions so Claude can match tasks to the right subagent. -### - -​ - -Explicit invocation +### Explicit invocation To guarantee Claude uses a specific subagent, mention it by name in your prompt: @@ -236,11 +192,7 @@ This bypasses automatic matching and directly invokes the named subagent. -### - -​ - -Forked subagents +### Forked subagents A [fork](</docs/en/sub-agents#fork-the-current-conversation>) is a subagent that copies the conversation so far instead of starting fresh. From Claude Code v2.1.302, Claude can start forks in your application with nothing configured, by calling the Agent tool with `subagent_type: "fork"`. To stop Claude from starting forks, add an [`Agent(fork)` deny rule](</docs/en/agent-sdk/permissions#allow-and-deny-rules>): @@ -258,11 +210,7 @@ disallowedTools: ["Agent(fork)"] }; -### - -​ - -Dynamic agent configuration +### Dynamic agent configuration You can create agent definitions dynamically based on runtime conditions. This example creates a security reviewer with different strictness levels, using a more capable model for strict reviews. @@ -333,11 +281,7 @@ if ("result" in message) console.log(message.result); } -## - -​ - -Detect subagent invocation +## Detect subagent invocation Claude invokes subagents through the Agent tool. To detect when a subagent is invoked, check for `tool_use` blocks where `name` is `"Agent"`. Messages from within a subagent’s context include a `parent_tool_use_id` field. In TypeScript, each assistant and user message a subagent produces also carries [`agent_id`](</docs/en/agent-sdk/typescript#sdkassistantmessage>): the `task_id` of that subagent’s [task events](</docs/en/agent-sdk/typescript#sdktaskstartedmessage>). `agent_id` stays the same when you resume the subagent. `agent_id` requires TypeScript Agent SDK v0.3.292 or later. @@ -425,11 +369,7 @@ } } -## - -​ - -Resume subagents +## Resume subagents You can resume a subagent to continue where it left off rather than starting fresh. A resumed subagent retains its full conversation history, including all previous tool calls, results, and reasoning. When a subagent stops at its `maxTurns` limit, Claude Code marks the output in the Agent tool result as partial, so Claude knows the run is unfinished. When a subagent completes, the Agent tool result includes a text block containing `agentId: <id>`. The built-in [`Explore` and `Plan` agents](</docs/en/sub-agents#built-in-subagents>) are one-shot and don’t return an `agentId`, so use a custom agent or `general-purpose` when you need to resume. To resume a subagent programmatically: @@ -560,11 +500,7 @@ Subagent transcripts are stored in separate files and persist independently of the main conversation. See [resume subagents in Claude Code](</docs/en/sub-agents#resume-subagents>) for compaction behavior and the `cleanupPeriodDays` cleanup period. -## - -​ - -Tool restrictions +## Tool restrictions Use the `tools` field to limit what a subagent can do: @@ -621,11 +557,7 @@ if ("result" in message) console.log(message.result); } -### - -​ - -Common tool combinations +### Common tool combinations Use case| Tools| Description ---|---|--- @@ -634,11 +566,7 @@ Code modification| `Read`, `Edit`, `Write`, `Grep`, `Glob`| Full read/write access without command execution Full access| All tools| Inherits the tools available to subagents (omit the `tools` field) -## - -​ - -Cap subagent depth, concurrency, and spend +## Cap subagent depth, concurrency, and spend This section describes TypeScript SDK v0.3.219 and Python SDK v0.2.127 and later, the releases that bundle Claude Code v2.1.219 or later. On earlier releases, some of these limits are missing or default differently, so upgrade before you rely on them to bound a run. The [environment variable reference](</docs/en/env-vars>) and [turns and budget](</docs/en/agent-sdk/agent-loop#turns-and-budget>) record the Claude Code version that added each variable and the spend cap’s subagent enforcement. @@ -714,11 +642,7 @@ * **At the spend cap** : you see `error_max_budget_usd` with a cost at or above `5`, and then your error handler runs. * **At the concurrency limit** : you see a `tool_result` block in the message stream carrying `Concurrent subagent limit reached`. Claude receives the same block as the Agent tool’s result. -### - -​ - -Run Opus 5 with subagents +### Run Opus 5 with subagents Claude Opus 5 delegates to subagents more readily than earlier models, so the depth, concurrency, and spend limits matter most on queries that run Opus 5. The [Opus 5 prompting guide](<https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5#controlling-subagent-spawning>) has a delegation instruction you can add to any prompt. Whether Claude Code adds an instruction of its own depends on which [system prompt](</docs/en/agent-sdk/modifying-system-prompts#how-system-prompts-work>) you use: @@ -727,36 +651,20 @@ Either instruction only steers Claude, so set the limits as well. Claude Code enforces them however Claude decides to delegate. -## - -​ - -Scale up with dynamic workflows +## Scale up with dynamic workflows Subagents work well for a few delegated tasks per turn. For runs that coordinate dozens to hundreds of agents, use the `Workflow` tool, which moves the orchestration into a script the runtime executes outside the conversation context. See [dynamic workflows](</docs/en/workflows>) for how workflows differ from turn-by-turn subagent delegation. The `Workflow` tool is available in the TypeScript Agent SDK v0.3.149 and later. Include `Workflow` in `allowedTools` to auto-approve workflow runs. The tool input and output schemas are listed in the [TypeScript reference](</docs/en/agent-sdk/typescript#workflow>). -## - -​ - -Troubleshooting - -### - -​ - -Claude not delegating to subagents +## Troubleshooting + +### Claude not delegating to subagents If Claude completes tasks directly instead of delegating to your subagent: * **Use explicit prompting** : mention the subagent by name in your prompt, for example “Use the code-reviewer agent to check the authentication module” * **Write a clear description** : explain exactly when to use the subagent so Claude can match tasks appropriately -### - -​ - -Filesystem-based agents not loading +### Filesystem-based agents not loading Claude Code watches `~/.claude/agents/` and `.claude/agents/` and picks up a new or edited agent file within a few seconds, with no restart needed. If a definition never appears, work through these causes: @@ -768,11 +676,7 @@ For the file format, see [how to write subagent files](</docs/en/sub-agents#write-subagent-files>). -## - -​ - -Related documentation +## Related documentation * [Claude Code subagents](</docs/en/sub-agents>): subagent documentation including filesystem-based definitions * [Dynamic workflows](</docs/en/workflows>): orchestrate many subagents from a script for jobs too large for one conversation
modified Configure your terminal for Claude Code View current →
Show diff (292 lines)
--- a/terminal-config.md +++ b/terminal-config.md @@ -10,17 +10,13 @@ This page is about getting your terminal to send the right signals to Claude Code. To change which keys Claude Code itself responds to, see [keybindings](</docs/en/keybindings>) instead. -## - -​ - -Enter multiline prompts +## Enter multiline prompts Pressing Enter submits your message. To add a line break without submitting, press Ctrl+J, or type `\` and then press Enter. Both work in every terminal with no setup. In most terminals you can also press Shift+Enter, but support varies by terminal emulator: Terminal| Shift+Enter for newline ---|--- -Ghostty, Kitty, iTerm2, WezTerm, Warp, Apple Terminal, Windows Terminal| Works without setup +Ghostty, Kitty, iTerm2, WezTerm, Warp, Windows Terminal| Works without setup Other terminals that support the kitty keyboard protocol, such as foot and Alacritty 0.16 or later| Works without setup. Requires Claude Code v2.1.269 or later VS Code, Cursor, Devin Desktop, Alacritty before 0.16, Zed| Run `/terminal-setup` once gnome-terminal, JetBrains IDEs such as PyCharm and Android Studio| Not available; use Ctrl+J or `\` then Enter @@ -32,11 +28,7 @@ If you are running inside tmux, Shift+Enter also requires the tmux configuration below even when the outer terminal supports it. To bind newline to a different key, or to swap behavior so Enter inserts a newline and Shift+Enter submits, map the `chat:newline` and `chat:submit` actions in your [keybindings file](</docs/en/keybindings>). -## - -​ - -Enable Option key shortcuts on macOS +## Enable Option key shortcuts on macOS Some Claude Code shortcuts use the Option key, such as Option+Enter for a newline or Option+P to switch models. On macOS, most terminals do not send Option as a modifier by default, so these shortcuts do nothing until you enable it. The terminal setting for this is usually labeled “Use Option as Meta Key”; Meta is the historical Unix name for the key now labeled Option or Alt. @@ -54,11 +46,7 @@ For Ghostty, Kitty, and other terminals, look for an Option-as-Alt or Option-as-Meta setting in the terminal’s configuration file. -## - -​ - -Get a terminal bell or notification +## Get a terminal bell or notification When Claude finishes a task or pauses for a permission prompt, and you appear to be away from the terminal, it fires a notification event. See [when each notification type fires](</docs/en/hooks#notification>) for the exact timing. Surfacing this as a terminal bell or desktop notification lets you switch to other work while a long task runs. By default, Claude Code sends a desktop notification in some terminals, and a bell character or nothing in others: @@ -90,11 +78,7 @@ If notifications still do not appear, confirm that your terminal application has notification permission in your OS settings, and if you are running inside tmux, enable passthrough. -### - -​ - -Play a sound with a Notification hook +### Play a sound with a Notification hook In any terminal you can configure a [Notification hook](</docs/en/hooks-guide#get-notified-when-claude-needs-input>) to play a sound or run a custom command when Claude needs your attention. Hooks run alongside the built-in notification rather than replacing it, so terminals that do not receive a desktop notification, such as Warp or the VS Code integrated terminal, can use a hook or set `preferredNotifChannel` to `"terminal_bell"` instead. The example below plays a system sound on macOS. The linked guide has desktop notification commands for macOS, Linux, and Windows. @@ -110,11 +94,7 @@ } } -## - -​ - -See session status in your terminal +## See session status in your terminal If your terminal implements the OSC 7501 Program Status Protocol, it can show whether each interactive Claude Code session is working, waiting on you, or done, which helps when you run long tasks or several sessions at once. There is nothing to turn on in Claude Code. To find out whether your terminal implements the protocol and where it shows the status, check its documentation. If it does and you see no status for a session, check for each of these causes: @@ -125,11 +105,7 @@ The tab title doesn’t start with a status glyph in a terminal that reports support for the protocol. The terminal shows the session’s state itself, so Claude Code leaves out the glyph it puts in front of the title in other terminals. -## - -​ - -Configure tmux +## Configure tmux When Claude Code runs inside tmux, by default Shift+Enter submits instead of inserting a newline, and desktop notifications don’t reach the outer terminal. Add these lines to `~/.tmux.conf`, then run `tmux source-file ~/.tmux.conf` to apply them to the running server: @@ -142,27 +118,15 @@ To send notifications from a visible pane to the outer terminal, keep the `allow-passthrough` line and set [`preferredNotifChannel`](</docs/en/settings-reference#preferrednotifchannel>) to `"iterm2"`, `"kitty"`, or `"ghostty"`. With this sample, a pane in a window you aren’t viewing sends none. The `extended-keys` lines let tmux distinguish Shift+Enter from plain Enter so the newline shortcut works. A [mod’s `Image`](</docs/en/plugins/mods/reference#elements>) needs the `allow-passthrough` and `focus-events` lines, along with the other [requirements for drawing inside tmux](</docs/en/plugins/mods/gallery#draw-an-image-inside-tmux>). After you add the lines, also detach from tmux, attach again, and restart Claude Code. -## - -​ - -Fix Backspace deleting a whole word on Windows +## Fix Backspace deleting a whole word on Windows On Windows, Claude Code reads a Backspace that arrives as `^H` as Ctrl+Backspace, which [deletes the previous word](</docs/en/interactive-mode#text-editing>), except when `TERM_PROGRAM` is `mintty` or `TERM` is `cygwin`. On macOS and Linux, Claude Code reads it as plain Backspace. If each press of Backspace deletes a whole word, your terminal sends `^H` for plain Backspace. Set [`CLAUDE_CODE_BS_AS_CTRL_BACKSPACE=0`](</docs/en/env-vars>). Backspace and Ctrl+H then erase one character each. If Ctrl+Backspace erases only one character on macOS or Linux because your terminal sends `^H` for it, set the variable to `1` instead. -## - -​ - -Match the color theme +## Match the color theme Use the `/theme` command, or the theme picker in `/config`, to choose a Claude Code theme that matches your terminal. Selecting the auto option detects your terminal’s light or dark background, so the theme follows OS appearance changes whenever your terminal does. Claude Code does not control the terminal’s own color scheme, which is set by the terminal application. To customize what appears at the bottom of the interface, configure a [custom status line](</docs/en/statusline>) that shows the current model, working directory, git branch, or other context. -### - -​ - -Create a custom theme +### Create a custom theme In addition to the built-in presets, `/theme` lists any custom themes you have defined and any themes contributed by installed [plugins](</docs/en/plugins/components#themes-and-output-styles>). Select **New custom theme…** at the end of the list to create one interactively: you name the theme, then pick individual color tokens to override. Press `Ctrl+E` while a custom theme is highlighted to edit it. Each custom theme is a JSON file in `~/.claude/themes/`. The filename without the `.json` extension is the theme’s slug, and selecting the theme stores `custom:<slug>` as your theme preference. The file has three optional fields: @@ -206,11 +170,7 @@ } } -#### - -​ - -Text and accent colors +#### Text and accent colors Control the primary brand accent and the foreground text shades used throughout the interface. @@ -225,11 +185,7 @@ `permission`| Dialog borders, including permission prompts and pickers `remember`| Memory and `CLAUDE.md` indicators -#### - -​ - -Status colors +#### Status colors Signal success, failure, and warning states across messages and indicators. @@ -240,11 +196,7 @@ `warning`| Warnings, caution messages, and the auto mode indicator `merged`| Merged pull request status -#### - -​ - -Input box and mode indicators +#### Input box and mode indicators Set the input box border color and the accent shown while a permission mode or indicator is active. @@ -258,11 +210,7 @@ `fastMode`| Fast mode indicator `effortUltra`| The `ultracode` tag on the input box border while [ultracode](</docs/en/model-config#adjust-effort-level>) is on. Your override of this color takes effect on Claude Code v2.1.239 or later -#### - -​ - -Diff rendering +#### Diff rendering Color added and removed code in file edits and reviews. @@ -275,11 +223,7 @@ `diffAddedWord`| Word-level highlight within an added line `diffRemovedWord`| Word-level highlight within a removed line -#### - -​ - -Fullscreen mode +#### Fullscreen mode Claude Code uses `userMessageBackgroundHover`, `selectionBg`, and `composerSidebarBackground` only in [fullscreen rendering mode](</docs/en/fullscreen>). It paints `userMessageBackground`, `bashMessageBackgroundColor`, and `memoryBackgroundColor` in both the default and fullscreen renderers. @@ -292,11 +236,7 @@ `selectionBg`| Background of text selected with the mouse `composerSidebarBackground`| Background of the panel beside the conversation, such as the [diff panel](</docs/en/fullscreen#watch-your-changes-in-the-diff-panel>) or a [mod’s pane](</docs/en/plugins/mods/interface>) -#### - -​ - -Usage meter and speaker labels +#### Usage meter and speaker labels Adjust the bar shown in the `/usage` view and the labels that distinguish your messages from Claude’s. @@ -307,11 +247,7 @@ `briefLabelYou`| Color of the `You` label on your messages `briefLabelClaude`| Color of the `Claude` label on assistant messages -#### - -​ - -Shimmer variants and subagent colors +#### Shimmer variants and subagent colors Several tokens have a paired shimmer variant that supplies the lighter color used in the spinner’s animated gradient. Override the shimmer alongside its base token if the animation looks mismatched. @@ -324,11 +260,7 @@ Each [subagent](</docs/en/sub-agents>) and parallel task is shown in one of eight named colors so you can tell them apart in the transcript. The token names follow the pattern `<color>_FOR_SUBAGENTS_ONLY`, where `<color>` is `red`, `blue`, `green`, `yellow`, `purple`, `orange`, `pink`, or `cyan`. Override these to change what each named color looks like. For example, a subagent with `color: blue` in its definition is drawn using the `blue_FOR_SUBAGENTS_ONLY` value.When [`ultrathink`](</docs/en/model-config#use-ultrathink-for-one-off-deep-reasoning>) can raise a turn’s effort, Claude Code renders the word in the prompt input with a seven-color rainbow gradient. The token names follow the pattern `rainbow_<color>` and `rainbow_<color>_shimmer`, where `<color>` is `red`, `orange`, `yellow`, `green`, `blue`, `indigo`, or `violet`. -## - -​ - -Switch to fullscreen rendering +## Switch to fullscreen rendering In [screen reader mode](</docs/en/accessibility>), this section doesn’t apply. Claude Code always renders as plain scrolling text except in attached [background sessions](</docs/en/agent-view>), and if you run `/tui fullscreen` in any other session, Claude Code prints an explanation instead of switching. If the display flickers or the scroll position jumps while Claude is working, switch to [fullscreen rendering mode](</docs/en/fullscreen>). In this mode you scroll with the mouse or PageUp inside Claude Code rather than with your terminal’s native scrollback; see the [fullscreen page](</docs/en/fullscreen#search-and-review-the-conversation>) for how to search and copy. If flicker is the only problem and your terminal supports synchronized output but isn’t auto-detected, such as Emacs `eat`, set [`CLAUDE_CODE_FORCE_SYNC_OUTPUT=1`](</docs/en/env-vars>) to stop the flicker without changing renderers. Run `/tui fullscreen` to switch and save the preference. Your conversation relaunches intact and future sessions start in fullscreen unless a [fullscreen start fails](</docs/en/fullscreen#fullscreen-renderer-didnt-finish-starting>). You can also set the `CLAUDE_CODE_NO_FLICKER` environment variable before starting Claude Code: @@ -348,62 +280,34 @@ } } -## - -​ - -Cap response width in wide terminals +## Cap response width in wide terminals In a wide terminal, each line of prose in Claude’s responses runs the full width of the window. To wrap the prose at a set number of columns instead, set [`maxProseWidth`](</docs/en/settings-reference#maxprosewidth>) in your settings. -## - -​ - -Paste large content +## Paste large content When you paste more than 800 characters or more than three lines into the prompt, Claude Code collapses the input to a placeholder such as `[Pasted text #1 +120 lines]` so the input box stays usable, and still sends the full content when you submit. For very large inputs such as entire files or long logs, write the content to a file and ask Claude to read it instead of pasting. The conversation transcript stays readable and Claude can refer to the file by path in later turns. The VS Code integrated terminal can also drop characters from very large pastes before they reach Claude Code, so use a file there. If the paste carries [invisible Unicode characters](</docs/en/interactive-mode#invisible-characters-in-prompts>), Claude Code removes them when you press Enter and puts the cleaned prompt back in the input box for you to send with another Enter. -### - -​ - -How Claude treats pasted text +### How Claude treats pasted text When you submit, Claude sees the content behind each `[Pasted text #N]` placeholder marked as text you pasted from somewhere else rather than typed. Claude is told that a paste can contain instructions you didn’t write, and to follow instructions inside it only where the message you typed asks it to. In sessions that don’t [fetch feature flags](</docs/en/env-vars#features-that-need-feature-flag-fetching>), pastes aren’t marked. -### - -​ - -Delete and restore a collapsed paste +### Delete and restore a collapsed paste When you delete with a word or line shortcut such as `Ctrl+W` or `Ctrl+K`, or with a vim delete through an `f`/`t` motion such as `df]`, and the deleted range reaches inside a `[Pasted text #N]` placeholder, Claude Code removes the placeholder whole. To restore it, paste the deletion back with [`Ctrl+Y`](</docs/en/interactive-mode#text-editing>) after a word or line shortcut, or with [`p` in NORMAL mode](</docs/en/interactive-mode#editing-normal-mode>) after a vim delete. -### - -​ - -Recall a prompt that had pasted text +### Recall a prompt that had pasted text Claude Code keeps the content behind each `[Pasted text #N]` placeholder under `~/.claude/paste-cache/`, so when you recall a prompt from [command history](</docs/en/interactive-mode#command-history>) and resubmit it, the full pasted content is sent again, including in a later session. Cache files older than [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>) are deleted under the [retention sweep rules](</docs/en/claude-directory#cleaned-up-automatically>), so a recalled prompt can reference pasted text that no longer exists. When you submit such a prompt, Claude Code doesn’t send the literal `[Pasted text #N]` string, and shows a notification naming the missing paste: * In a plain prompt with text remaining, Claude Code removes the placeholder and sends the remaining text. * In a [shell mode](</docs/en/interactive-mode#shell-mode-with-prefix>) command or a `/` command, where the removal would change what runs, and in any prompt the removal leaves empty, Claude Code cancels the submission and keeps the original text in the input, with the placeholder still in it. Delete the placeholder or edit the command, then resubmit. -## - -​ - -Edit prompts with Vim keybindings +## Edit prompts with Vim keybindings Claude Code includes a Vim-style editing mode for the prompt input. Enable it through `/config` → Editor mode, or by setting [`editorMode`](</docs/en/settings-reference#editormode>) to `"vim"` in `~/.claude/settings.json`. Set Editor mode back to `normal` to turn it off. Vim mode supports a subset of NORMAL- and VISUAL-mode motions and operators, such as `hjkl` navigation, `v`/`V` selection, and `d`/`c`/`y` with text objects. See the [Vim editor mode reference](</docs/en/interactive-mode#vim-editor-mode>) for the full key table. Vim motions aren’t remappable through the keybindings file. To map a two-key INSERT-mode sequence such as `jj` to Escape, set [`vimInsertModeRemaps`](</docs/en/interactive-mode#remap-insert-mode-key-sequences>) in your user settings. Pressing Enter still submits your prompt in INSERT mode, unlike standard Vim. Use `o` or `O` in NORMAL mode, or Ctrl+J, to insert a newline instead. -## - -​ - -Related resources +## Related resources * [Interactive mode](</docs/en/interactive-mode>): full keyboard shortcut reference and the Vim key table * [Keybindings](</docs/en/keybindings>): remap any Claude Code shortcut, including Enter and Shift+Enter
modified Test a mod View current →
Show diff (139 lines)
--- a/test.md +++ b/test.md @@ -1,10 +1,6 @@ You can write automated tests for a mod and run them from your shell with [`claude plugin test`](</docs/en/plugins/mods/reference#commands>). A test fires the events your hooks handle and checks what the hooks did, so you catch a problem before it reaches a session. The first example tests the mod from [Create a mod](</docs/en/plugins/mods/create>). -## - -​ - -Write a test +## Write a test A test loads your mod, sends events through its hooks the way Claude Code would, and checks what the hooks did, without a session, a sign-in, or a network. You run tests from your shell with `claude plugin test`, and each test file imports the test kit, a test library in the `claude-code/testing` module. Give each test file a name that ends in `.test.ts`, such as `first-mod.test.ts`, and save it anywhere in the plugin directory. Every test file needs at least one `test()`, or the run fails with `declares no test(): nothing ran`. A test file can import your mod’s own files and sibling `.ts` helpers, so you can unit test plain functions, such as a game’s rules, without the kit. This test fires two tool calls, runs the `/tally` command from [Create a mod](</docs/en/plugins/mods/create>), and checks that the reply counts both. Its first line is a stub, which answers the tool calls in Claude Code’s place. Save it as `first-mod/tests/first-mod.test.ts`: @@ -40,11 +36,7 @@ Each `$.tool.call` went through the mod’s [`tool.call`](</docs/en/plugins/mods/reference#tools>) hook, which added one to its count and passed the call on to the stub. No `ls` ran and no file was read. `$.command.run` then went to the mod’s [`command.run`](</docs/en/plugins/mods/reference#commands-and-configuration>) hook, and `answer` is the object that hook returned. The command exits with status 1 when a test fails, so it works in CI. If your own mods can’t load in the shell that runs it, it prints a line starting `claude plugin test: hooks modules are turned off` with the reason, and exits with status 1. -### - -​ - -Stub what Claude Code would answer +### Stub what Claude Code would answer No model, store, or tool runs in a test, so wherever your mod expects Claude Code to answer, the test supplies the answer with a stub. A test function receives two arguments for that: @@ -101,11 +93,7 @@ * **`mock.env(on, { CI: 'true' })`** : answers `$.env.get` from those variables. * **`mock.session(on)`** : returns a mock session whose `appended()` method lists the rows your mod added with [`$.session.append`](</docs/en/plugins/mods/reference#session>), oldest first; it requires Claude Code v2.1.293 or later. -### - -​ - -Follow the test kit’s rules +### Follow the test kit’s rules The test kit has a few rules of its own, and breaking one produces the errors new test authors hit first: @@ -145,11 +133,7 @@ When the loop ends, `result` is the object the stub returned, after your `turn.step` hook has had the chance to change it. Here `result.answer` is `'ok'`. * **Fire a tool call with the tool’s name and arguments as fields** , such as `await $.tool.call({ tool: 'Bash', command: 'ls' })`, and register a `tool.call` stub that returns `{ result }`. -### - -​ - -Look up what a stub returns +### Look up what a stub returns Every mods API call your mod makes in a test needs a stub that answers in Claude Code’s place, except the few the kit answers itself: [`$.ui.invalidate`](</docs/en/plugins/mods/interface#redraw-when-something-changes>), [`$.state`](</docs/en/plugins/mods/interface#keep-state>), and `$.session.append` calls. For `$.clock` calls, use `mock.clock(on)`, or your mod’s `$.clock.now()` fails with `no implementation for clock.now`. This table lists the ones mods use most. The first column is the call your mod makes or the event it passes on with `next(e)`. The second is the function to pass to `on` under that name, so the `$.store.get` row becomes `on('store.get', ($, e) => ({ value: saved.get(e.key) }))`. A `'...'` in a stub marks text for you to fill in: @@ -178,28 +162,11 @@ `session.receive`| `($, e) => ({ text: e.text })`. Fire it with `$.session.receive({ origin: { kind: 'peer-send-message' }, text })`. `ui.render`| `() => ({ type: 'Text', props: {}, children: ['...'] })` -### - -​ - -Check a result with `expect` - -The kit has these assertions, and the one you pick goes after the value you’re checking, as in `expect(answer.text).toBe('ok')`: - - * **Equality** : `toBe` for the same value or object, `toEqual` for structure, `toStrictEqual` for structure plus `undefined` fields and the prototype, and `toMatchObject` for the fields you name - * **Text** : `toMatch`, which takes a regular expression or a substring, `toStartWith`, and `toEndWith` - * **Numbers** : `toBeGreaterThan`, `toBeGreaterThanOrEqual`, `toBeLessThan`, `toBeLessThanOrEqual` - * **Contents** : `toContain` for a substring or a member, `toContainEqual` for a member compared by structure, `toHaveLength`, and `toHaveProperty` - * **Presence and type** : `toBeDefined`, `toBeUndefined`, `toBeNull`, `toBeTruthy`, `toBeFalsy`, `toBeNaN`, `toBeInstanceOf` - * **Throwing** : `toThrow`, for a function `expect` calls, or for a promise you check with `.rejects` - -Put `.not` in front of an assertion to check the opposite, and `.resolves` or `.rejects` to check what a promise settles with. When an `expect` fails inside a stub or hook that you passed to `on` as a plain function rather than an async generator, the test fails. The engine skips that hook, and the failure output names it, such as `in the test's store.set hook`. - -## - -​ - -Test a timer +### Check a result with `expect` + +`expect` has its own set of assertions, such as `toEqual` and `toHaveLength`, which go after the value you’re checking, as in `expect(answer.text).toBe('ok')`. For the full list, search `claude-code/index.d.ts` in [the types for your build](</docs/en/plugins/mods/create#get-the-types-for-your-build>) for `type Matchers`. Put `.not` before the assertion to check the opposite. To check what a promise settles with, put `.resolves` or `.rejects` right after `expect(...)` and `await` the line, as in `await expect(promise).rejects.toThrow()`. When an `expect` fails inside a stub or hook that you passed to `on` as a plain function rather than an async generator, the test fails. The engine skips that hook, and the failure output names it, such as `in the test's store.set hook`. + +## Test a timer A mod that runs work on a timer needs a clock the test controls, so the test can move time forward instead of waiting. `const clock = mock.clock(on)` returns a mock clock that starts at `0` and moves only when your test moves it. To start at another time, pass it in milliseconds, as in `mock.clock(on, { now: 5000 })`. The clock has these methods: @@ -258,11 +225,7 @@ The first `expect` shows that the toast doesn’t come early, and the second shows that it comes once. Each `advance` resolves after the timers that came due have run, so the check on the next line sees their effect. -## - -​ - -Test a drawing +## Test a drawing A test can draw one of your mod’s [render sites](</docs/en/plugins/mods/reference#render-sites>), then press, type into, and find the elements it drew. `$.ui.mount` draws the site through your mod’s `ui.render` hook and returns a handle with a method for each of those. To cover several apps in one test, set `surface` to the app to draw for. This test opens the pane from [Build a pane with tabs](</docs/en/plugins/mods/interface#build-a-pane-with-tabs>), switches tabs, presses the button, and checks the count in the terminal and the Desktop app: @@ -322,11 +285,7 @@ Each method resolves after your handler has finished, so you can check the result on the next line. Set `props` to what Claude Code would pass for that site. The [render sites table](</docs/en/plugins/mods/reference#render-sites>) lists each site’s props, and [the types for your build](</docs/en/plugins/mods/create#get-the-types-for-your-build>) have their types. To catch an [element tree](</docs/en/plugins/mods/interface#build-a-tree-from-elements>) that isn’t valid for the app you named in `surface`, check with `find` for an element your hook adds. The test doesn’t check how the app paints a tree, so look at a new layout in a real session too. -### - -​ - -Test a drawing after `/clear` +### Test a drawing after `/clear` Each test starts with every `$.state` value at its default, which is how `/clear` leaves them. To test what your mod does next, skip `session.start`, fire `classic.SessionStart` with `source: 'clear'`, and check what your mod draws. This test checks the module from [Load a saved value again after `/clear`](</docs/en/plugins/mods/interface#load-a-saved-value-again-after-clear>). Add it to the file from Test a drawing, where `PANE` is defined. That file’s first test expects the button to save the count, as the button in [Save from more than one session](</docs/en/plugins/mods/interface#save-from-more-than-one-session>) does: @@ -349,11 +308,7 @@ The test passes when your `classic.SessionStart` hook has copied the stored `7` into `$.state` before the pane draws. Without that hook in your module, the pane draws `Count: 0`, `find` returns `undefined`, and the test fails at `toBeDefined`. -## - -​ - -Test a policy mod +## Test a policy mod A mod your organization lists in [`prependPlugins`](</docs/en/plugins/mods/admin>) can refuse another mod before it loads. To test one, set your mod’s tier and give the test a second mod for yours to allow or refuse: @@ -411,11 +366,7 @@ In your shell, run `claude plugin test` from the `acme-guard` directory. Both tests pass with the policy mod as the admin page shows it. The kit loads every mod at the test’s first call on `$`. When your mod refuses one, that call throws, and the message names the refused mod, the mod that refused it, and your reason. In the second test nothing is refused, so `reader` answers the tool call before it reaches the stub. -## - -​ - -Next steps +## Next steps * [Troubleshoot a mod](</docs/en/plugins/mods/troubleshoot>): find out why a mod does nothing in a session * [Mods reference](</docs/en/plugins/mods/reference>): every event’s input and result, for writing stubs
modified Enterprise deployment overview View current →
Show diff (101 lines)
--- a/third-party-integrations.md +++ b/third-party-integrations.md @@ -1,10 +1,6 @@ Organizations can deploy Claude Code through Anthropic directly or through a cloud provider. This page helps you choose the right configuration. -## - -​ - -Compare deployment options +## Compare deployment options For most organizations, Claude for Teams or Claude for Enterprise provides the best experience. Team members get access to both Claude Code and Claude on the web with a single subscription, centralized billing, and no infrastructure setup required. **Claude for Teams** is self-service and includes collaboration features, admin tools, SSO, billing management, and [server-managed settings](</docs/en/server-managed-settings>) for organization-wide Claude Code configuration. Best for smaller teams that need to get started quickly. **Claude for Enterprise** adds domain capture, role-based permissions, and compliance API access. Best for larger organizations with security and compliance requirements. Learn more about [Team plans](<https://support.claude.com/en/articles/9266767-what-is-the-team-plan>) and [Enterprise plans](<https://support.claude.com/en/articles/9797531-what-is-the-enterprise-plan>). The deployment options compared below cover where model inference runs. To run Claude Code [cloud sessions](</docs/en/claude-code-on-the-web>) on compute your organization operates, see [self-hosted environments](</docs/en/self-hosted-environments>). If your organization has specific infrastructure requirements, compare the options below: Feature| Claude for Teams/Enterprise| Anthropic Console| Amazon Bedrock| Claude Platform on AWS| Google Cloud’s Agent Platform, formerly Vertex AI| Microsoft Foundry ---|---|---|---|---|---|--- @@ -29,11 +25,7 @@ For Amazon Bedrock and Google Vertex AI, you can also run `claude` and select **3rd-party platform** at the login prompt to launch an interactive setup wizard. -## - -​ - -Configure proxies and gateways +## Configure proxies and gateways Most organizations can use a cloud provider directly without additional configuration. However, you may need to configure a corporate proxy or LLM gateway if your organization has specific network or management requirements. These are different configurations that can be used together: @@ -42,65 +34,33 @@ For the per-provider environment variables that route Amazon Bedrock, Microsoft Foundry, or Google Cloud’s Agent Platform through an LLM gateway, see [route to a cloud provider through a gateway](</docs/en/llm-gateway-connect#route-to-a-cloud-provider-through-a-gateway>). Run `/status` in Claude Code to verify which provider, base URL, and proxy a session is using. If your organization uses [customer-managed encryption keys](<https://platform.claude.com/docs/en/manage-claude/cmek>) (CMEK) and routes Claude Code through an LLM gateway or a custom `ANTHROPIC_BASE_URL`, CMEK doesn’t apply to Claude Code’s operational telemetry on those sessions. To turn telemetry off for every developer, deliver `DISABLE_TELEMETRY` through managed settings as shown in [Turn telemetry off for your organization](</docs/en/managed-settings#turn-telemetry-off-for-your-organization>). -## +## Best practices for organizations -​ - -Best practices for organizations - -### - -​ - -Invest in documentation and memory +### Invest in documentation and memory Invest in documentation so that Claude Code understands your codebase. Organizations can deploy CLAUDE.md files at multiple levels. See [where CLAUDE.md files can live](</docs/en/memory#choose-where-to-put-claude-md-files>) and [how to deploy an organization-wide CLAUDE.md](</docs/en/memory#deploy-organization-wide-claude-md>). -### - -​ - -Simplify deployment +### Simplify deployment If you have a custom development environment, creating a “one click” way to install Claude Code is key to growing adoption across an organization. -### - -​ - -Start with guided usage +### Start with guided usage Encourage new users to try Claude Code for codebase Q&A, or on smaller bug fixes or feature requests. Ask Claude Code to make a plan. Check Claude’s suggestions and give feedback if it’s off-track. Over time, as users understand this new paradigm better, then they’ll be more effective at letting Claude Code run more agentically. -### - -​ - -Pin model versions for cloud providers +### Pin model versions for cloud providers If you deploy through [Amazon Bedrock](</docs/en/amazon-bedrock>), [Google Cloud’s Agent Platform](</docs/en/google-vertex-ai>), [Microsoft Foundry](</docs/en/microsoft-foundry>), or [Claude Platform on AWS](</docs/en/claude-platform-on-aws>), pin specific model versions using `ANTHROPIC_DEFAULT_FABLE_MODEL`, `ANTHROPIC_DEFAULT_OPUS_MODEL`, `ANTHROPIC_DEFAULT_SONNET_MODEL`, and `ANTHROPIC_DEFAULT_HAIKU_MODEL`. Without pinning, model aliases resolve to Claude Code’s built-in default for that provider, which can lag the newest release and may not yet be enabled in your account. Pinning lets you control when your users move to a new model. See [Model configuration](</docs/en/model-config#pin-models-for-third-party-deployments>) for what each provider does when the default is unavailable. -### - -​ - -Configure security policies +### Configure security policies Security teams can configure managed permissions for what Claude Code is and is not allowed to do, which cannot be overwritten by local configuration. [Learn more](</docs/en/security>). To limit which of these deployment options a managed machine may use, set [`allowedProviders`](</docs/en/settings-reference#allowedproviders>) in managed settings. For example, `["bedrock"]` allows Amazon Bedrock and nothing else; a Bedrock fleet that also enables the Mantle endpoint lists `"mantle"` too. The entry says which endpoint variables also need a managed `env` pin. Requires Claude Code v2.1.285 or later. -### - -​ - -Use MCP for integrations +### Use MCP for integrations MCP is a great way to give Claude Code more information, such as connecting to ticket management systems or error logs. Have one central team configure MCP servers and check a `.mcp.json` configuration into the codebase so that all users benefit. [Learn more](</docs/en/mcp>). -## - -​ - -Next steps +## Next steps Once you’ve chosen a deployment option and configured access for your team:
modified Track todos View current →
Show diff (101 lines)
--- a/todo-tracking.md +++ b/todo-tracking.md @@ -1,10 +1,6 @@ Claude Code provides the [task-tracking tools](</docs/en/tools-reference#task-tool-availability>) by default only on the models listed under Model availability. Newer models track multi-step work without a written todo list, so on those you don’t need anything on this page for Claude to work through multi-step tasks. In a session that has the task-tracking tools, Claude keeps a written todo list, updating each item’s status as it works. You see each change in the message stream as a structured tool call. Opt a session in only when your application reads those tool calls, whether to log task activity or to render its own progress display. -## - -​ - -Model availability +## Model availability The following tools are available by default only on Claude Opus 4.7, Claude Sonnet 4.6, Claude Haiku 4.5, and earlier models. On every other model, including model IDs Claude Code doesn’t recognize, they aren’t available unless you opt in: @@ -14,7 +10,7 @@ * `TaskUpdate` * `TaskList` -Wherever the tools are available, Claude Code provides the four Task tools, or `TodoWrite` instead when you set `CLAUDE_CODE_ENABLE_TASKS=0`.This default set applies in Claude Code v2.1.268 and later, which the TypeScript Agent SDK bundles from v0.3.268. +Wherever the tools are available, Claude Code provides the four Task tools, or `TodoWrite` instead when you set `CLAUDE_CODE_ENABLE_TASKS=0`. This default set applies in Claude Code v2.1.268 and later, which the TypeScript Agent SDK bundles from v0.3.268. On a model that doesn’t have the tools by default, unless you opt a session in, you see no `tool_use` blocks for them in the message stream. The Agent SDK applies these defaults through the Claude Code binary that it bundles. If you point `pathToClaudeCodeExecutable` (TypeScript) or `cli_path` (Python) at your own Claude Code install, you get whichever tools that install provides, under its own defaults. To see the exact set in a running session, [check which tools are available](</docs/en/tools-reference#check-which-tools-are-available>). To opt a session in, do one of the following: @@ -22,11 +18,7 @@ * List the tools in the `tools` option, which restricts the session’s built-in tools to the ones it names. Include the tools you want alongside the other built-in tools you use * Set `CLAUDE_CODE_ENABLE_TODO_TOOLS=1` in the `env` option, as the examples on this page do. In TypeScript, `env` replaces the subprocess environment, so spread `...process.env` to keep inherited variables. In Python, `env` is merged on top of the inherited environment -## - -​ - -Todo lifecycle +## Todo lifecycle Claude moves each todo through a predictable lifecycle: @@ -35,11 +27,7 @@ 3. **Completed** : Claude marks it completed when the task finishes successfully 4. **Removed** : Claude deletes a todo it no longer needs by setting `status: "deleted"` in a `TaskUpdate` call -## - -​ - -When Claude creates todos +## When Claude creates todos In a session that has the task-tracking tools, Claude creates todos for most multi-step work, such as: @@ -50,11 +38,7 @@ Claude may skip todos for very short or single-step requests. -## - -​ - -Examples +## Examples Before running these examples, install the Claude Agent SDK by following the [quickstart](</docs/en/agent-sdk/quickstart>). Every example on this page shares the same permission setup and exit behavior: @@ -64,11 +48,7 @@ The task system messages, [`SDKTaskNotificationMessage`](</docs/en/agent-sdk/typescript#sdktasknotificationmessage>) (TypeScript) or [`TaskNotificationMessage`](</docs/en/agent-sdk/python#tasknotificationmessage>) (Python) among them, report background tasks such as backgrounded commands and subagents. In the message stream, you see todo activity as `tool_use` blocks in the assistant messages. -### - -​ - -Monitor todo changes +### Monitor todo changes The following example watches the assistant stream for `TaskCreate` and `TaskUpdate` `tool_use` blocks and prints a `+` line with each new task’s subject and an update line with each status change’s task ID and new status. Use this shape when you want a log of task activity rather than a rendered display. The `+` lines don’t include the assigned IDs, so this log can’t match updates back to their creates. To keep that correlation, capture the IDs as Display progress in real time does. The streamed `tool_use` input is the raw shape the model emitted. Claude Code repairs some close-but-incorrect key names before execution, mapping `id` or `task_id` to `taskId` and `active_form` to `activeForm`, but that repair is not reflected in the stream. Read `TaskUpdate` input fields defensively, as both examples on this page do, rather than assuming the canonical name is always present. @@ -139,11 +119,7 @@ asyncio.run(main()) -### - -​ - -Display progress in real time +### Display progress in real time The following example watches the assistant stream for `TaskCreate` and `TaskUpdate` `tool_use` blocks and keeps a map of tasks keyed by task ID in a `TaskTracker` class, rerendering a progress summary on every change. The summary counts completed and in-progress tasks and shows each active item’s `activeForm` label in place of its `subject`. Use this shape when your application maintains a progress display instead of logging each event. The assigned task ID isn’t in the `TaskCreate` input. Claude Code delivers each tool’s structured output on the user message that carries its `tool_result` block, in the `tool_use_result` field. For `TaskCreate`, that object is documented for TypeScript as `TaskCreateOutput` under [Tool Output Types](</docs/en/agent-sdk/typescript#tool-output-types>), and in Python the field is a plain dict of the same shape. The tracker pairs each `tool_result` block with its `tool_use` call by `tool_use_id` and reads `task.id` from the paired message’s `tool_use_result`. Claude can read the list back with `TaskList` and one task’s full details with `TaskGet`. @@ -367,11 +343,7 @@ asyncio.run(main()) -## - -​ - -Related documentation +## Related documentation * [Agent SDK reference - TypeScript](</docs/en/agent-sdk/typescript>): the options, types, and tool schemas for the TypeScript SDK, including the Task tool input and output types * [Agent SDK reference - Python](</docs/en/agent-sdk/python>): the options, types, and tool documentation for the Python SDK
modified Scale to many tools with tool search View current →
--- a/tool-search.md +++ b/tool-search.md @@ -3,21 +3,13 @@ * **Context efficiency:** Tool definitions can consume large portions of the context window (50 tools can use 10-20K tokens), leaving less room for actual work. * **Tool selection accuracy:** Tool selection accuracy degrades with more than 30-50 tools loaded at once. -## - -​ - -How tool search works +## How tool search works Tool search is on by default, with the exceptions listed in Configure tool search. When it is active, tool definitions are withheld from the context window. The agent receives a summary of available tools and searches for relevant ones when the task requires a capability not already loaded. Up to five of the most relevant tools are loaded into context by default, where they stay available for subsequent turns until the SDK compacts the messages where the agent discovered them. After that compaction, the agent searches for those tools again when it next needs them. Tool search adds one extra round-trip each time Claude searches for tools, but for large tool sets this is offset by smaller context on every turn. With fewer than ~10 tools whose definitions fit comfortably in the context window, loading everything upfront is typically faster. For details on the underlying API mechanism, see [Tool search in the API](<https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool>). Tool search isn’t supported on Microsoft Foundry [deployments hosted on Azure](<https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry#hosting-options>), which reject it server-side: the SDK detects the rejection and loads tool definitions upfront for that deployment instead. `ENABLE_TOOL_SEARCH` can’t override this, since the rejection comes from the deployment itself. -## - -​ - -Configure tool search +## Configure tool search Tool search is on by default. For models on the SDK’s unsupported-model list, the SDK loads tool definitions upfront instead, and no `ENABLE_TOOL_SEARCH` value overrides that. On Google Cloud’s Agent Platform, the SDK decides by model generation: @@ -107,11 +99,7 @@ To run this example, replace `https://tools.example.com/mcp` with the URL of your own MCP server. On success the result text prints to the console. Because this is a single-shot `query()` call, the SDK raises after yielding an error result, so the example wraps the loop in a try block. To see why a run failed, check the result message’s `subtype`, such as `error_during_execution`, inside the loop. For more on result messages, see [Handle the result](</docs/en/agent-sdk/agent-loop#handle-the-result>). -## - -​ - -Optimize tool discovery +## Optimize tool discovery The search mechanism matches queries against tool names and descriptions. Names like `search_slack_messages` surface for a wider range of requests than `query_slack`. Descriptions with specific keywords (“Search Slack messages by keyword, channel, or date range”) match more queries than generic ones (“Query Slack”). You can also add a system prompt section listing available tool categories. This gives the agent context about what kinds of tools are available to search for. Pass the text in the `systemPrompt` option of `query()` in TypeScript, or `system_prompt` in Python. Use the `claude_code` preset with `append`, which adds your text to the preset’s prompt instead of replacing it: @@ -137,21 +125,13 @@ For the full set of system prompt options, see [Modifying system prompts](</docs/en/agent-sdk/modifying-system-prompts>). -## - -​ - -Limits +## Limits * **Maximum tools:** 10,000 tools in your catalog * **Search results:** returns up to five most relevant tools per search by default * **Model support:** Opus 4, Sonnet 4, Haiku 4.5, and later models, or Opus 4.5, Sonnet 4.5, Haiku 4.5, and later models on Google Cloud’s Agent Platform. On earlier models the SDK loads tool definitions upfront, as Configure tool search describes. -## - -​ - -Related documentation +## Related documentation * [Tool search in the API](<https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool>): Full API documentation for tool search, including custom implementations * [Connect MCP servers](</docs/en/agent-sdk/mcp>): Connect to external tools via MCP servers
modified Tools reference View current →
Show diff (618 lines)
--- a/tools-reference.md +++ b/tools-reference.md @@ -51,11 +51,7 @@ `Workflow`| Runs a [dynamic workflow](</docs/en/workflows>): a script that orchestrates many subagents in the background and returns one consolidated result| Yes `Write`| Creates or overwrites files. See Write tool behavior| Yes -## - -​ - -Configure tools with permission rules and hooks +## Configure tools with permission rules and hooks For the most part, Claude decides when to use these tools and you don’t need to name them yourself when interacting with Claude. You reference tool names directly when defining permissions and other configuration: @@ -80,11 +76,7 @@ Tools not listed here, such as `ExitPlanMode` or `ShareOnboardingGuide`, accept only the bare tool name with no specifier. An `Edit(...)` allow rule also grants read access to the same path, so you don’t need a matching `Read(...)` rule. A `Read(...)` deny rule also blocks the Edit and Write tools on the same path, including creating a new file there, because both tools change content Claude has to be able to read back. For the Write tool, the `Read` deny check requires Claude Code v2.1.228 or later. Hook `matcher` fields use bare tool names, not the parenthesized rule format. See [matcher patterns](</docs/en/hooks#matcher-patterns>) for the matching rules. For the field names each tool passes to `tool_input` in hooks, see the [PreToolUse input reference](</docs/en/hooks#pretooluse-input>). -## - -​ - -Agent tool behavior +## Agent tool behavior The Agent tool spawns a subagent in a separate context window. The subagent works through its task autonomously, then returns its result to the parent conversation. The parent doesn’t see the subagent’s intermediate tool calls or outputs, only that final result. The same tool can also launch a teammate or a fork: @@ -105,35 +97,19 @@ To [limit what a subagent can reach](</docs/en/sub-agents#control-subagent-capabilities>) in the first place, narrow its `tools` field, for example by leaving Bash off the list, or set deny rules in your settings. -## - -​ - -AskUserQuestion tool behavior - -Claude uses `AskUserQuestion` to ask you multiple-choice questions when it needs a decision or a clarification. Answer by picking an option, or type your own text through the `Other` row or the notes field. When you answer by typing your own text, Claude Code relays the answer with neutral wording so Claude follows what you wrote, including a request to wait or explain first. - -### - -​ - -Question auto-continue timeout +## AskUserQuestion tool behavior + +Claude uses `AskUserQuestion` to ask you multiple-choice questions when it needs a decision or a clarification. Answer by picking an option, or type your own text through the `Other` row or the notes field. + +### Question auto-continue timeout Questions stay open until you answer them. If you want a question you leave unanswered to eventually close and let Claude continue without you, set the [`askUserQuestionTimeout`](</docs/en/settings-reference#askuserquestiontimeout>) setting to `60s`, `5m`, or `10m`, either in your user `settings.json` or from the **Question auto-continue timeout** row in `/config`. After a question sits that long with no input, the dialog closes on its own: it submits any options you’d already selected and tells Claude you may be away from your keyboard, so Claude proceeds on its own judgment and can re-ask later. You see a countdown for the last 20 seconds. Press any key to restart the timer. While your terminal reports that its window is focused, the timer doesn’t count down. The timer never starts for a question Claude asks in a [background session](</docs/en/agent-view>), in [screen reader mode](</docs/en/accessibility>), or while the session is connected to [Remote Control](</docs/en/remote-control>). Those questions wait until you answer them. The timeout applies only to `AskUserQuestion`’s multiple-choice questions; permission prompts, including plan approval, never auto-resolve on idle. -## - -​ - -Bash tool behavior +## Bash tool behavior The Bash tool runs each command in a separate process. -### - -​ - -What persists between commands +### What persists between commands * When Claude runs `cd` in the main session, the new working directory carries over to later Bash commands as long as it stays inside the project directory or an [additional working directory](</docs/en/permissions#working-directories>) you added with `--add-dir`, `/add-dir`, or `additionalDirectories` in settings. This includes commands Claude runs in response to your later messages. * Subagent sessions never carry over working directory changes. @@ -144,11 +120,7 @@ Activate your virtualenv or conda environment before launching Claude Code. To make environment variables persist across Bash commands, set [`CLAUDE_ENV_FILE`](</docs/en/env-vars>) to a shell script before launching Claude Code, or use a [SessionStart hook](</docs/en/hooks#persist-environment-variables>) to populate it dynamically. -### - -​ - -Timeout and output limits +### Timeout and output limits Each command runs under a timeout, and Claude manages it: when it wants longer than the default for a command, it passes the `timeout` parameter with that call. You never set a per-command timeout. Two [environment variables](</docs/en/env-vars>) control what Claude gets for a command that runs in the foreground: @@ -157,11 +129,7 @@ In a session that has a time limit for background commands, `timeout` on a command that Claude starts in the background instead sets how long the command may run there, with that limit’s separate default and maximum. The PowerShell tool follows the same timeout rules and reads the same two variables. -#### - -​ - -Output limits +#### Output limits Claude Code streams a command’s output to a working file as the command runs; a command whose output passes 5 GB is killed. When the command finishes, Claude Code reads the output back from that file, up to the read-back window described below. How much of the output reaches Claude inline depends on whether Claude Code treats the result as a failure: @@ -172,27 +140,15 @@ A command that exits 1 counts as a valid result for the Bash tool only when Claude Code recognizes exit code 1 as a benign outcome for that command: `grep`, `rg`, `egrep`, `fgrep`, `find`, `diff`, `test`, and `[`, plus `git diff` and `git grep`. Every other command that exits 1 counts as a failure, even when exit 1 is a benign informational outcome: no matches for `pgrep` and `jq -e`, files that differ for `cmp`. [`BASH_MAX_OUTPUT_LENGTH`](</docs/en/env-vars>) sets how many characters of output Claude Code reads back from the working file into a command’s result: 30,000 by default, up to a hard ceiling of 150,000. Raise it when your commands routinely overflow that window, such as a verbose build or a full test-suite log. Raising it enlarges the read-back window, which is also the window a failing command’s excerpt is cut from. It doesn’t raise the inline ceilings: a valid result over the inline ceiling arrives as a file path plus preview regardless of this variable. To change how much of a valid result Claude receives inline, set the [`bashOutputMaxChars`](</docs/en/settings-reference#bashoutputmaxchars>) setting instead, up to 128,000 characters. It sizes the inline ceiling and the read-back window together, and Claude Code then ignores `BASH_MAX_OUTPUT_LENGTH`. Requires Claude Code v2.1.261 or later. -### - -​ - -Background commands +### Background commands For long-running processes such as dev servers or watch builds, Claude can set `run_in_background: true` to start the command as a background task and continue working while it runs. List and stop background tasks with `/tasks`. After you stop one there, or from a connected client such as the desktop app, Claude moves on instead of waiting for it. If a subagent started the command, it’s that subagent that moves on. -#### - -​ - -When a background command stops +#### When a background command stops A command that a [foreground subagent](</docs/en/sub-agents#run-subagents-in-foreground-or-background>) started stops when that subagent’s run ends, whether it finished, failed, or was interrupted. A command that the main conversation or a background subagent started keeps running after a final response, until it exits, is stopped, or reaches its time limit. While a command that the main conversation started is still running, a run in non-interactive mode with the `-p` flag [stays open after its result](</docs/en/headless#background-tasks-at-exit>) until that command exits or reaches its time limit. A command that a background subagent started is stopped when the run exits. -#### - -​ - -Time limit for background commands +#### Time limit for background commands In a session that runs unattended, such as a run with the `-p` flag, an Agent SDK application, a CI job, or a cloud session, background Bash and PowerShell commands have a time limit. A local session you work in from a terminal, the desktop app, or the VS Code extension has no time limit on background commands. The time limit requires Claude Code v2.1.285 or later. Before v2.1.288, it applied in every session. The time limit counts from the moment the command enters the background: @@ -201,33 +157,21 @@ In a run with the `-p` flag whose prompt you pass as text rather than with `--input-format stream-json`, both defaults are 10 minutes instead of 30, because the run [waits for background commands after its result](</docs/en/headless#background-tasks-at-exit>). When a background command reaches its time limit, Claude Code stops it and tells Claude why, and Claude can start the command again with a longer `timeout` if the work still needs it. The stop notice reads `Background command "<description>" was stopped after reaching its background time limit`. -#### - -​ - -Raise the time limit for background commands +#### Raise the time limit for background commands Two [environment variables](</docs/en/env-vars>) raise these limits, for Bash and PowerShell commands alike. Both take milliseconds, and neither can shorten a limit: a lower value leaves the defaults and the 2-hour maximum in place. * Set `BASH_DEFAULT_TIMEOUT_MS` above `1800000` to replace the 30-minute default with that value, both for commands Claude starts without a `timeout` and for moved commands. In a `-p` run whose prompt you pass as text, any value above `600000` replaces its 10-minute default * Set `BASH_MAX_TIMEOUT_MS` above `7200000` to raise the 2-hour maximum to that value. Setting `BASH_DEFAULT_TIMEOUT_MS` above `7200000` raises the maximum the same way -#### - -​ - -Foreground commands that move to the background +#### Foreground commands that move to the background When a foreground command reaches its timeout without finishing, Claude Code moves it to the background instead of stopping it, unless the command starts with `sleep`. A moved command’s time limit counts from the move, and a foreground subagent’s moved command still stops when that subagent’s run ends. Setting [`CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1`](</docs/en/env-vars#variables>) or running in [bare mode](</docs/en/headless#start-faster-with-bare-mode>) disables auto-backgrounding, so a command that reaches its timeout stops instead. The result of a command moved to the background states what happened: * When the timeout triggers the move, the result reports it explicitly: `Command did not complete within its 120s timeout and was moved to the background`, with the seconds matching the timeout that applied, followed by the task ID and the path of the file the output is being written to. * A `cd`, `pushd`, `popd`, or `chdir` inside a command that is moved to the background never carries over: the result states `Session cwd remains <dir>; directory changes made by the backgrounded command do not apply to subsequent commands.`, so Claude doesn’t act on a directory change that didn’t happen. -### - -​ - -Memory limit on Linux and WSL +### Memory limit on Linux and WSL On Linux and WSL, set [`CLAUDE_CODE_TOOL_MEMORY_LIMIT`](</docs/en/env-vars#variables>) to a size such as `4G` to cap the memory that Bash, PowerShell, and Monitor tool commands can use, so one runaway build can’t take the memory the rest of the session needs. Requires Claude Code v2.1.233 or later. Before v2.1.246, Monitor tool commands ran outside the cap. @@ -252,11 +196,7 @@ * **Variable unset** : Claude Code takes the set of other capped kinds from configuration Anthropic delivers from the server, and that set can change over time, so set the variable when you need a set that doesn’t change * **Permission-gating hooks** : even with every kind capped, Claude Code excludes from the cap a hook that can block or change the outcome of an action, and any MCP server that such a hook calls, so the kernel killing a permission-gating hook can’t allow the action it was blocking -## - -​ - -Edit tool behavior +## Edit tool behavior The Edit tool performs exact string replacement. It takes an `old_string` and a `new_string` and replaces the first with the second. It doesn’t use regex or fuzzy matching. These checks must pass for an edit to apply. Before any of them, a path matched by a [`Read` deny rule](</docs/en/permissions#tool-specific-permission-rules>) is refused, including creating a new file there. @@ -266,19 +206,11 @@ A file that changed on disk after Claude last read it can still be edited when `old_string` matches the current content exactly and unambiguously and Claude Code can read the file without prompting. Matching against the file’s current content keeps this safe, and the result notes that the file carries other changes so Claude re-reads it before edits that depend on surrounding content. In any other case, such as a stale `old_string` or one that matches more than once without `replace_all`, Claude reads the file again before editing. Claude can also edit a file without a separate Read after viewing it with a Bash command such as `cat` or `grep`. Those commands are `cat`, `nl`, `bat`, `batcat`, `head`, `tail`, `sed -n 'X,Yp'`, `grep`, `egrep`, `fgrep`, and `rg`, each run on one file with no pipes or redirects. If the command printed none of the file’s text, as when a search matches nothing, the read-before-edit check still applies. When Claude views a file this way, Claude Code also loads any [subdirectory `CLAUDE.md`](</docs/en/memory#how-claude-md-files-load>) and [path-scoped rules](</docs/en/memory#path-specific-rules>) that apply to that file. See [Read and Edit permission rules](</docs/en/permissions#read-and-edit>) for which Bash commands your `Read` and `Edit` deny rules cover. -### - -​ - -Non-UTF-8 files +### Non-UTF-8 files Claude can’t use NotebookEdit on a file that isn’t valid UTF-8. The same goes for Edit, unless the file starts with a little-endian UTF-16 byte-order mark. When Claude tries, the tool refuses the change and leaves the file untouched. Refused files include non-ASCII text saved in a legacy encoding such as Windows-1252 or Shift-JIS, binary files, and UTF-8 with an invalid byte sequence. The tools refuse because they save the whole file back as UTF-8, which would replace every byte they can’t decode with the replacement character `U+FFFD`. Instead, the [error Claude receives](</docs/en/errors#file-is-not-valid-utf-8>) tells it to make the change with a shell command that keeps the file’s encoding, or to ask you about converting it to UTF-8 first. Claude can still replace such a file with Write, unless the new content contains `U+FFFD`, the character Read shows Claude in place of bytes it can’t decode. That guard stops Claude from writing back the garbled text it read. When Write does replace the file, it saves the new content as UTF-8, so the file’s original encoding is lost. -## - -​ - -EndConversation tool behavior +## EndConversation tool behavior The EndConversation tool ends the current session. Claude uses it only in two situations: @@ -297,11 +229,7 @@ * **Startup mode** : not a [`--bare`](</docs/en/headless#start-faster-with-bare-mode>) session. Bare mode loads only shell and file tools, so the tool is never registered there. * **Provider** : not available on [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>), or [Microsoft Foundry](</docs/en/microsoft-foundry>), or on sessions signed in through a [cloud gateway](</docs/en/claude-apps-gateway>). -## - -​ - -EnterWorktree tool behavior +## EnterWorktree tool behavior The EnterWorktree tool creates an isolated [git worktree](</docs/en/worktrees>) and switches into it. Given a `path`, it switches into an existing worktree instead of creating a new one. @@ -310,11 +238,7 @@ * **From inside a worktree** : from within a worktree session, only the `path` form is available and the target must be under `.claude/worktrees/` of the session’s repository. The same holds for a subagent with a pinned working directory, such as [`isolation: worktree`](</docs/en/sub-agents#supported-frontmatter-fields>). * **When the tool is missing** : once [`permissions.blockWritesOutsideWorkingDirectories`](</docs/en/settings-reference#permissions-blockwritesoutsideworkingdirectories>) is on, Claude Code removes `EnterWorktree` and `ExitWorktree` or refuses calls to them. To keep working in worktrees, see [Claude has no `EnterWorktree` tool](</docs/en/worktrees#claude-has-no-enterworktree-tool>). -## - -​ - -Glob tool behavior +## Glob tool behavior The Glob tool finds files by name pattern. On Windows, it’s part of the default tool set. On macOS, Linux, and WSL, Claude Code leaves Glob and Grep out of the default tool set, and Claude searches with `find` and `grep` through the Bash tool instead. In Claude’s shell those two commands run embedded versions of `bfs` and `ugrep`, and the searches reach your hooks and permission rules as `Bash` calls. On macOS, Linux, and WSL, you get the Glob and Grep tools back in these cases: @@ -330,11 +254,7 @@ Results are sorted by modification time and capped at 100 files. If the cap is hit, Claude sees a truncation flag in the result and can narrow the pattern. Glob doesn’t respect `.gitignore` by default, so it finds gitignored files alongside tracked ones. This differs from Grep, which skips gitignored files. To make Glob respect `.gitignore`, set `CLAUDE_CODE_GLOB_NO_IGNORE=false` before launching Claude Code. Claude Code decides permission for a Glob call before it checks whether the search directory exists. It still runs the read-permission check for a missing `path` outside the [working directories](</docs/en/permissions#working-directories>), so a permission prompt for a path doesn’t mean the path exists. A `pattern` or `path` value that contains a null byte returns an error asking Claude to remove it. -## - -​ - -Grep tool behavior +## Grep tool behavior The Grep tool searches file contents for patterns. Where Glob finds files by name, Grep finds lines inside them. On macOS, Linux, and WSL, Grep is absent by default under the same conditions as Glob. See Glob tool behavior for when both tools are available. Grep is built on [ripgrep](<https://github.com/BurntSushi/ripgrep>) and uses ripgrep’s regex syntax, not POSIX grep. Patterns that include regex metacharacters need escaping. For example, finding `interface{}` in Go code takes the pattern `interface\{\}`. A pattern, glob, or file type that ripgrep rejects returns an error that includes ripgrep’s diagnostic, so Claude can correct the input and search again. Before v2.1.208, Claude Code reported a rejected input as `No files found` instead of an error, even when the searched-for text existed in the target files. Three output modes control what comes back: @@ -344,11 +264,7 @@ Claude can scope results by file with the `glob` parameter, such as `**/*.tsx`, or by language with the `type` parameter, such as `py` or `rust`. By default, patterns match within a single line. Claude can set `multiline: true` to match across line boundaries. Grep respects `.gitignore`, so gitignored files are skipped. To search a gitignored file, Claude passes its path directly. Claude Code decides permission for a Grep call before it checks whether the search `path` exists. It still runs the read-permission check for a missing `path` outside the [working directories](</docs/en/permissions#working-directories>), so a permission prompt for a path doesn’t mean the path exists. -## - -​ - -LSP tool behavior +## LSP tool behavior The LSP tool gives Claude code intelligence from a running language server. After each file edit, it automatically reports type errors and warnings so Claude can fix issues without a separate build step. Claude can also call it directly to navigate code: @@ -362,11 +278,7 @@ Claude Code keeps the tool inactive until you install a [code intelligence plugin](</docs/en/plugins/code-intelligence>) for your language. In [cloud sessions](</docs/en/claude-code-on-the-web>), Claude Code doesn’t start plugin language servers, so the LSP tool stays inactive there. Claude Code takes the language server’s configuration from the plugin, and you install the server binary yourself. Claude Code returns an error result for each LSP call on a file whose language server it can’t start. -## - -​ - -Monitor tool +## Monitor tool The Monitor tool lets Claude watch something in the background and react when it changes, without pausing the conversation. Ask Claude to: @@ -383,11 +295,7 @@ Plugins can declare monitors that start automatically when the plugin is active, instead of asking Claude to start them. See [plugin monitors](</docs/en/plugins/components#monitors>). -### - -​ - -WebSocket source +### WebSocket source When a server already pushes events over a WebSocket, Claude can connect to it directly instead of writing a polling script. Each kind of socket activity either becomes an event or ends the watch: @@ -405,19 +313,11 @@ The `timeout_ms` deadline applies to a WebSocket watch too: the watch ends at the deadline, and `TaskStop` cancels it early. Without a `Monitor` allow rule, you’re prompted before Claude opens a WebSocket; in [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>) the classifier decides instead, unless an ask rule applies. The prompt doesn’t offer an option to skip future prompts for the same host. -#### - -​ - -Addresses and hosts denied to WebSocket watches +#### Addresses and hosts denied to WebSocket watches Claude Code denies URLs that point at a private, link-local, or cloud-metadata address, including hostnames that your machine resolves to one. Behind a [proxy](</docs/en/network-config#proxy-configuration>), a watch can reach a private, link-local, or cloud-metadata address unless the proxy blocks it, because Claude Code doesn’t check the address the proxy finds. Claude Code also denies hosts in `sandbox.network.deniedDomains`, and when [`allowManagedDomainsOnly`](</docs/en/settings-reference#sandbox-network-allowmanageddomainsonly>) is set in managed settings, any host outside the managed allowlist. If a watch behind a proxy fails with `could not resolve <host>`, restart Claude Code v2.1.319 or later with [`CLAUDE_CODE_PROXY_RESOLVES_HOSTS`](</docs/en/env-vars#variables>) set to `1` so the proxy looks up the hostname. -#### - -​ - -Bash rules that deny or prompt for WebSocket watches +#### Bash rules that deny or prompt for WebSocket watches If Claude Code refuses a `Monitor` call that opens a WebSocket, look for a [deny or ask rule](</docs/en/permissions#manage-permissions>) written `Bash` or `Bash(*)`. Do the same if it prompts for that call despite your `Monitor` allow rule. A rule on every Bash command also covers these WebSocket watches: @@ -426,11 +326,7 @@ To let these watches run, narrow the rule to the commands you mean, such as `Bash(rm *)`. The ask rule, and a deny rule you add during a session, cover these watches in Claude Code v2.1.319 or later. -## - -​ - -NotebookEdit tool behavior +## NotebookEdit tool behavior NotebookEdit modifies a Jupyter notebook one cell at a time, targeting cells by their `cell_id`. It doesn’t perform string replacement across the notebook the way Edit does on plain files. Three edit modes control what happens to the target cell: @@ -440,11 +336,7 @@ NotebookEdit refuses a notebook file that doesn’t decode as UTF-8, under the same rule as Edit, and writes nothing. Permission rules use the `Edit(...)` path format. A rule like `Edit(notebooks/**)` covers NotebookEdit calls on files in that directory. -## - -​ - -PowerShell tool +## PowerShell tool The PowerShell tool lets Claude run PowerShell commands natively. On Windows, this means commands run in PowerShell instead of routing through Git Bash. How the tool becomes available depends on your platform: @@ -454,11 +346,7 @@ Your [PreToolUse hooks](</docs/en/hooks#powershell>) receive the tool’s command string in `tool_input.command`, with the same fields as the Bash tool. Match `Bash|PowerShell` in hooks that inspect shell commands; the [PowerShell hook input section](</docs/en/hooks#powershell>) explains why matching `Bash` alone is not enough. -### - -​ - -Enable the PowerShell tool +### Enable the PowerShell tool Set `CLAUDE_CODE_USE_POWERSHELL_TOOL=1` in your environment or in `settings.json`: @@ -470,11 +358,7 @@ On Windows, set the variable to `0` to turn the tool off. On Linux, macOS, and WSL, the tool requires PowerShell 7 or later: install `pwsh` and ensure it is on your `PATH`. On Windows, Claude Code auto-detects `pwsh.exe` for PowerShell 7+ with a fallback to `powershell.exe` for PowerShell 5.1. When the tool is enabled, Claude treats PowerShell as the primary shell. The Bash tool remains available for POSIX scripts when Git Bash is installed. Claude Code spawns PowerShell with `-ExecutionPolicy Bypass` at process scope only, so `.ps1` scripts and module imports work on default Windows installs without changing the machine’s policy. Process-scope bypass doesn’t override Group Policy `MachinePolicy` or `UserPolicy`, so enterprise policies still apply. To respect the machine’s effective execution policy instead, set `CLAUDE_CODE_POWERSHELL_RESPECT_EXECUTION_POLICY=1`. -### - -​ - -Bash deny rules also turn off the PowerShell tool +### Bash deny rules also turn off the PowerShell tool On Windows with Git Bash installed, denying Bash also turns the PowerShell tool off for the session. This applies to scoped rules such as `Bash(git push *)` as well as a bare `Bash`, and to rules from one of your settings files or `--disallowedTools`. Claude Code does this because a `Bash` rule doesn’t restrict the PowerShell tool, which has [its own permission rules](</docs/en/permissions#powershell>). With PowerShell left on, Claude could run there what your rule denies in Bash. To keep the PowerShell tool on alongside a Bash deny rule, do either of these: @@ -483,11 +367,7 @@ Without one of these, a scoped Bash deny rule leaves the Bash tool available, and Claude Code turns PowerShell off without a warning. A rule that removes the whole Bash tool leaves Claude with no shell tool for the session. -### - -​ - -Shell selection in settings, hooks, and skills +### Shell selection in settings, hooks, and skills Three additional settings control where PowerShell is used: @@ -497,19 +377,11 @@ PowerShell commands follow the same main-session working-directory reset behavior as Bash commands, including the `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR` environment variable. PowerShell commands also receive the variables hooks persist through `CLAUDE_ENV_FILE`, under the conditions in [Persisted variables in PowerShell commands](</docs/en/hooks#persisted-variables-in-powershell-commands>). Requires Claude Code v2.1.296 or later. -### - -​ - -Exit code 1 from searches and `git diff` in PowerShell +### Exit code 1 from searches and `git diff` in PowerShell If a `grep` or `rg` search that matches nothing shows `Error: Exit code 1` when Claude runs it in the PowerShell tool, the search didn’t fail. You don’t need to do anything. The error can appear when the search is part of a longer command. For example, when `rg` exits with code 1, `rg foo | Out-Null` shows the error and `rg foo` doesn’t. The PowerShell tool can count exit code 1 as a normal result from `grep`, `rg`, `egrep`, `fgrep`, `findstr`, `git grep`, and `git diff`. The searches use exit code 1 to report no matches. From `git diff`, exit code 1 means the files differ. A command that shows the error when Claude runs it [counts as failed](</docs/en/skills#when-an-injected-command-fails>) in a skill with `shell: powershell`. -### - -​ - -Windows encoding and exit codes +### Windows encoding and exit codes * Redirection with `>` and `>>` writes UTF-8 files on PowerShell 5.1 * Claude Code encodes text piped to a native command’s standard input as UTF-8 @@ -518,24 +390,16 @@ * If `where.exe` finds no match, or `fc.exe` or `diff.exe` finds that the files differ, the result can show `Error: Exit code 1` though the command didn’t fail. You don’t need to do anything. * If a `robocopy` exit code from 1 through 7 shows as an error, the copy didn’t fail and you don’t need to do anything. `robocopy` exits with code 0 through 7 to report a result, such as files copied, and with 8 or higher when it fails. -### - -​ - -Preview limitations +### Preview limitations The PowerShell tool has the following known limitations during the preview: * PowerShell profiles are not loaded * On Windows, sandboxing is not supported -## - -​ - -Read tool behavior - -The Read tool takes a file path and returns the contents with line numbers. Claude is instructed to always pass absolute paths. Reading an empty file returns a notice that the file exists but its contents are empty, and an `offset` past the last line returns a notice giving the file’s line count. Read handles several file types beyond plain text: +## Read tool behavior + +The Read tool takes a file path and returns the contents with line numbers. Reading an empty file returns a notice that the file exists but its contents are empty, and an `offset` past the last line returns a notice giving the file’s line count. Read handles several file types beyond plain text: * **Images** : PNG, JPEG, GIF, and WebP files are returned as visual content that Claude can see, not as raw bytes. Claude Code resizes and recompresses large images to fit the model’s image size limits before sending them, so Claude may see a downscaled version of a large screenshot. If Claude misses fine pixel-level detail in a large image, ask it to crop the region you care about, such as with ImageMagick via Bash, and then read the crop. Read refuses an image file larger than 128 MB with an error that tells Claude to resize the image or export a smaller copy, then read that copy. If Claude stops at the error instead of doing so, see [File is too large to read as an image](</docs/en/errors#file-is-too-large-to-read-as-an-image>). * **PDFs** : Claude reads short `.pdf` files whole. For PDFs longer than 10 pages, it reads in ranges with a `pages` parameter, such as `"1-5"`, up to 20 pages at a time. Page-range reads render pages with `pdftoppm` from poppler-utils, so install it with `brew install poppler` on macOS or `apt-get install poppler-utils` on Debian and Ubuntu. On Windows and other platforms, install a poppler build that puts `pdftoppm` on your `PATH`. Without it, a page-range read fails with `pdftoppm is not installed`. @@ -543,22 +407,14 @@ Read only reads files, not directories. Claude lists directory contents with a shell command such as `ls`. Read refuses a file whose extension it treats as binary, such as `.xlsx`, `.parquet`, `.heic`, or `.zip`. Claude keeps working after a refusal: the error suggests a skill for that file type if one is available, or else a shell command or script that reads the format. If you [`@`-mention](</docs/en/common-workflows#reference-files-and-directories>) a file that Read refuses, Claude receives the file’s path but not its contents. -### - -​ - -Large files +### Large files Claude can read a text file larger than a single Read call returns. By default one call returns at most 25,000 tokens, or the value you set in [`CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS`](</docs/en/env-vars>), and refuses a whole file over 256 KB, so Claude reads a larger file in pages with `offset` and `limit`. On Claude Code v2.1.296 or later it can instead read the whole file, or a long line range, in one call by setting `allow_large: true` when it needs to, for example because you asked for the entire file. That read is sized against the room left in the session’s [context window](</docs/en/context-window>) instead of the default limits. Images, PDFs, and notebooks keep their limits. What Claude receives when a read goes over the default limits: * **Whole file over the token limit** : the first page of the file, with a `PARTIAL view` notice saying how much of the file it received and how to read more with `offset` and `limit` * **Whole file over 256 KB, or an`offset` or `limit` read over the token limit**: an error telling it to read a portion with `offset` and `limit`, or to search for specific content with Grep instead -## - -​ - -SendFeedback tool behavior +## SendFeedback tool behavior Claude-drafted feedback is a feedback report about Claude Code that Claude writes for you. It requires Claude Code v2.1.238 or later. Claude Code saves each draft on your machine under `~/.claude/feedback/drafts/`, and nothing reaches Anthropic until you send it. Claude drafts one with the SendFeedback tool when: @@ -567,19 +423,11 @@ * You point out a mistake it made, or it notices one * You ask it to file feedback -### - -​ - -What you see when Claude drafts +### What you see when Claude drafts After Claude queues a draft, you see a card above your prompt with the draft’s title. Press `1` to review the draft, press `2` twice to send it as written, or press `0` to dismiss it. A dismissed draft stays in your queue. After you dismiss a card, Claude Code asks whether to turn Claude-drafted feedback off. It stops asking once you’ve declined twice. By default, you see at most three cards in a session; Anthropic can adjust that limit from the server without a release. After the limit, and whenever you set [`feedbackDrafts`](</docs/en/settings-reference#feedbackdrafts>) to `quiet`, you see only a count of queued drafts in the prompt footer. -### - -​ - -Review and edit a draft +### Review and edit a draft Run `/feedback` with no argument to open your queue. It lists every queued draft from all your sessions, including drafts whose cards you dismissed or never saw. Select a draft to open it for review, where you can: @@ -589,11 +437,7 @@ To write a report yourself instead, press `w` for the standard feedback dialog. `/feedback` with text after it, and `/bug`, open that dialog directly. -### - -​ - -Send a draft +### Send a draft When you send a draft, Claude Code submits it the same way as a `/feedback` report, with the same [retention](</docs/en/data-usage#feedback-using-the-%2Ffeedback-command>), and deletes the draft from your machine. When you send from the card, it shows `✓ Sent`; when you send from the queue, it closes with a receipt ID. The report carries: @@ -604,27 +448,15 @@ Claude Code keeps your working directory in the local draft so it can find the transcript, and doesn’t send the directory. In [organizations with Zero Data Retention](</docs/en/zero-data-retention#features-disabled-under-zdr>), and in organizations with the [HIPAA configuration](</docs/en/hipaa-setup>) applied, Claude Code leaves the SendFeedback tool out of your sessions. If a session in an organization with Zero Data Retention still offers the tool, drafts stay on your machine, and sending fails with `Feedback collection is not available for organizations with custom data retention policies.` -### - -​ - -Discard or keep a draft +### Discard or keep a draft When you discard a draft, Claude Code deletes it from your machine. A draft you leave in the queue expires after 30 days, or after [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>) when that’s shorter. The queue holds 10 drafts across all your sessions, and when Claude queues an eleventh, Claude Code deletes the oldest. When you run `/exit` with drafts from the session still in the queue, Claude Code asks whether to review them or discard them before exiting. -### - -​ - -Turn Claude-drafted feedback off +### Turn Claude-drafted feedback off Set **Claude-drafted feedback** to `off` in `/config`, which writes the [`feedbackDrafts`](</docs/en/settings-reference#feedbackdrafts>) setting, or set [`CLAUDE_CODE_SEND_FEEDBACK=0`](</docs/en/env-vars>) for one session. With either, Claude can’t queue drafts. To keep drafting on without cards, set `feedbackDrafts` to `quiet` instead. Administrators can set `feedbackDrafts` in [managed settings](</docs/en/managed-settings>), which takes precedence over your own setting. -### - -​ - -Sessions without Claude-drafted feedback +### Sessions without Claude-drafted feedback Claude Code includes the tool in interactive terminal sessions on your own machine that use the Claude API rather than a cloud provider. It leaves the tool out of: @@ -636,11 +468,7 @@ * Organizations that have turned off product feedback, [organizations with Zero Data Retention](</docs/en/zero-data-retention#features-disabled-under-zdr>), and organizations with the [HIPAA configuration](</docs/en/hipaa-setup>) applied * Sessions where Claude Code has [stopped offering feedback after a refused report](</docs/en/errors#feedback-is-disabled-by-your-organizations-policy>) -## - -​ - -Task tool availability +## Task tool availability The task-tracking tools, `TaskCreate`, `TaskGet`, `TaskUpdate`, `TaskList`, and `TodoWrite`, are available by default only on Opus 4.7, Sonnet 4.6, Haiku 4.5, and earlier models. Wherever the tools are available, you get the four Task tools, or `TodoWrite` instead when you set [`CLAUDE_CODE_ENABLE_TASKS=0`](</docs/en/env-vars>). On every other model, Claude Code leaves the tools out unless you opt in. The same applies to a model ID Claude Code doesn’t recognize, such as a custom model name served through an [LLM gateway](</docs/en/llm-gateway>). On newer models, Claude keeps track of multi-step work without a written checklist, and the tools’ definitions and reminders take up context. Without the tools, Claude adds nothing to the [task list](</docs/en/interactive-mode#task-list>) while it works. If you’d like to use these tools on a model that doesn’t have them by default, do one of the following: @@ -651,11 +479,7 @@ In [background sessions](</docs/en/agent-view>) and in [cloud sessions](</docs/en/claude-code-on-the-web>), Claude Code provides the same tools on every model, listed or not. The default set described here applies in Claude Code v2.1.268 and later. -### - -​ - -Task-tracking tools in subagents and agent teams +### Task-tracking tools in subagents and agent teams A subagent has the task-tracking tools only when your session has them, whatever model the subagent runs. An in-process [agent team](</docs/en/agent-teams>) teammate has the task-tracking tools when your session does. A [split-pane](</docs/en/agent-teams#choose-a-display-mode>) teammate is a separate Claude Code process that [inherits](</docs/en/agent-teams#permissions>) your `--tools` list and deny rules, not `--allowedTools`, so check what you set: @@ -666,11 +490,7 @@ Without the Task tools, an agent coordinates with its team through messages instead of the [shared task list](</docs/en/agent-teams#assign-and-claim-tasks>). -## - -​ - -WebFetch tool behavior +## WebFetch tool behavior WebFetch takes a URL and a prompt describing what to extract. It fetches the page and converts the response to Markdown when the server returns HTML. For most fetches, it then runs the prompt against the content in a separate model call, and Claude receives the result of that call rather than the raw page. The conversion step is not configurable. This makes WebFetch lossy by design. The extraction prompt determines what reaches Claude, so a result that says a page doesn’t mention something may only mean the prompt didn’t ask about it. Ask Claude to fetch again with a more specific prompt, or use `curl` via Bash for the unprocessed page. A few behaviors shape the response Claude receives: @@ -690,29 +510,17 @@ To allow a domain in advance without a prompt, add an allow rule like `WebFetch(domain:example.com)`; `WebFetch(domain:*)` allows every domain. The `auto` and `bypassPermissions` [permission modes](</docs/en/permissions#permission-modes>) skip the prompt, except for a domain an explicit `ask` rule matches. An explicit `WebFetch(domain:...)` rule in `deny`, `ask`, or `allow` takes precedence over the preapproved set, so you can block a preapproved domain or require a prompt for it. When the URL is a claude.ai [artifact](</docs/en/artifacts>) link, Claude Code can also ask for approval to read the artifact itself. For the cases where it asks, see [Read an artifact shared with you](</docs/en/artifacts#read-an-artifact-shared-with-you>). WebFetch sets a `User-Agent` header beginning with `Claude-User`, and an `Accept` header that prefers Markdown over HTML so servers that support content negotiation can return Markdown directly. Sandboxed commands don’t inherit WebFetch’s built-in set of preapproved documentation domains. To let a sandboxed command reach a domain without a prompt, add the domain to [`allowedDomains`](</docs/en/settings-reference#sandbox-network-alloweddomains>) or allow it with a `WebFetch(domain:...)` rule, which the [sandbox also honors](</docs/en/sandboxing#network-isolation>). WebFetch never reads the sandbox allowlist in return, so adding a domain to a sandbox or organization network allowlist doesn’t stop WebFetch from prompting for it. -### - -​ - -WebFetch availability +### WebFetch availability On Claude Code v2.1.285 or later, set [`CLAUDE_CODE_DISABLE_WEB_FETCH`](</docs/en/env-vars#variables>) to `1` to turn WebFetch off. If you sign in with a Team or Enterprise claude.ai account and don’t connect through an [LLM gateway](</docs/en/llm-gateway>), WebFetch also depends on your organization’s policy, which Claude Code requests from `api.anthropic.com` when a session starts. The same goes for a session whose plan Claude Code can’t determine, such as one running under a claude.ai token that another app supplied. If WebFetch is missing from a session, run `/status` in the session. If its `Organization policy` line reports that the policy didn’t load and names web fetch among the features that wait for it, Claude Code is withholding WebFetch until it can confirm that your organization allows it. Outside a session, `claude doctor` makes its own request and prints the same line. Once a policy that allows WebFetch loads, the tool returns without a restart. -## - -​ - -WebSearch tool behavior +## WebSearch tool behavior WebSearch runs a query against Anthropic’s [web search](<https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool>) backend and returns result titles and URLs. It doesn’t fetch the result pages. To read a page Claude finds in search results, it follows up with WebFetch. The tool may issue up to eight backend searches per call, refining the search internally before returning results. Claude can scope results with `allowed_domains` to include only certain hosts, or `blocked_domains` to exclude them. The two lists can’t be combined in a single call. When the search request hits an overloaded API, Claude Code retries it with backoff; a call that still fails returns an error result. WebSearch permission rules take no specifier. A bare `WebSearch` entry in `allow` or `deny` is the only form. The search backend is not configurable. To search with a different provider, add an [MCP server](</docs/en/mcp>) that exposes a search tool. WebSearch is available on the Claude API, [Claude Platform on AWS](</docs/en/claude-platform-on-aws>), and Microsoft Foundry. On Google Cloud’s Agent Platform it works with Opus 4, Sonnet 4, Haiku 4.5, and later models. Amazon Bedrock doesn’t expose the server-side web search tool. -### - -​ - -Session search limit +### Session search limit An interactive terminal session has a limit of 200 WebSearch calls. Searches from the main conversation and from [subagents](</docs/en/sub-agents>), such as a parallel research fan-out, count against the same limit. While a session is at the limit, searches appear in the conversation as calls that did nothing. Claude gets a notice telling it to continue with the information already gathered, say so in its answer, and, if it needs more searches, ask you to raise the limit. To get more searches, raise the cap, wait for the limit to refill, or start a new conversation: @@ -722,11 +530,7 @@ In [non-interactive mode](</docs/en/headless>) with `-p` and in the [Agent SDK](</docs/en/agent-sdk/overview>), the limit applies per turn, not per session. A turn lasts from a message you send until Claude finishes responding. The limit resets when you send the next message after that or start a new `claude -p` run, even with [`--continue` or `--resume`](</docs/en/headless#continue-conversations>). For more searches, raise [`CLAUDE_CODE_MAX_WEB_SEARCHES_PER_SESSION`](</docs/en/env-vars#variables>) or set a refill rate with [`CLAUDE_CODE_WEB_SEARCH_REFILLS_PER_HOUR`](</docs/en/env-vars#variables>). -## - -​ - -Write tool behavior +## Write tool behavior The Write tool creates a new file or overwrites an existing one with the full content provided. It doesn’t append or merge. Write also overwrites an existing file whose bytes don’t decode and saves the new content as UTF-8, as described under non-UTF-8 files. Whether Claude must read an existing file in the current conversation before overwriting it depends on the model and the file: @@ -736,11 +540,7 @@ This constraint doesn’t apply to new files. Before v2.1.228, every model required the read before overwriting an existing file. Viewing the file with Bash also satisfies this requirement under the same rules described in Edit tool behavior. For partial changes to an existing file, Claude uses Edit instead of Write. -## - -​ - -Check which tools are available +## Check which tools are available Your exact tool set depends on your provider, platform, and settings. To check what’s loaded in a running session, ask Claude directly: @@ -750,11 +550,7 @@ The [advisor tool](</docs/en/advisor>) is a [server tool](<https://platform.claude.com/docs/en/agents-and-tools/tool-use/advisor-tool>) that the API runs, rather than a tool that Claude Code implements. It has no name you can reference in permission rules or hook matchers. -## - -​ - -See also +## See also * [MCP servers](</docs/en/mcp>): add custom tools by connecting external servers * [Permissions](</docs/en/permissions>): permission system, rule syntax, and tool-specific patterns
modified Troubleshoot a mod View current →
Show diff (537 lines)
--- a/troubleshoot.md +++ b/troubleshoot.md @@ -1,10 +1,6 @@ When a mod’s module or one of its hooks fails, Claude Code skips it and the session continues, so a broken mod can look like one that does nothing. Start by checking what Claude Code read from your mod and where it reports a problem, then find the symptom or message you have. -## - -​ - -Find out why a mod does nothing +## Find out why a mod does nothing When a mod does nothing, check what Claude Code reads from the mod’s files, and the line it writes when it skips something. For the first, in your shell run [`claude plugin validate`](</docs/en/plugins/mods/create#check-what-claude-code-reads-from-your-mod>) with the mod’s directory, as in `claude plugin validate ./first-mod`. It catches a misspelled event, a bad manifest, and a module Claude Code can’t read, without starting a session. When a module doesn’t load, a hook is skipped, or another mod refuses yours, Claude Code writes one line that names your mod. Where you read that line depends on the session: @@ -12,11 +8,7 @@ * **Any other interactive session, such as one that runs a mod you installed from a marketplace** : the debug log only. To get one, start the session with `claude --debug`. * **A`claude -p` run with `--plugin-dir`**: stderr, in the default text output format. A refusal by another mod goes to the debug log only. -## - -​ - -Check whether mods can load +## Check whether mods can load To check whether your setup lets mods load at all, without installing one, run `claude plugin test` in your shell, from a directory that doesn’t hold a mod. You don’t need a session. The message it prints tells you the state: @@ -29,43 +21,23 @@ An organization can also set `allowManagedModsOnly` to allow only its own mods, which this command doesn’t report. In that case Claude Code refuses a mod you install, and [a message says why](</docs/en/plugins/mods/troubleshoot#messages-from-the-built-in-guard>). -## - -​ - -The mod doesn’t load +## The mod doesn’t load Nothing the mod adds appears: no command, no drawing, and no change in behavior. -### - -​ - -Your version is too old +### Your version is too old See [which version to use and how to check yours](</docs/en/plugins/mods/overview#turn-mods-on-or-off>). -### - -​ - -The `mods active` line doesn’t name the mod +### The `mods active` line doesn’t name the mod Nothing the mod adds appears, and the [`mods active` line](</docs/en/plugins/mods/overview#see-which-mods-a-session-loaded>) in `/plugin` doesn’t name it. The hooks module didn’t load. When Claude Code refused it, the debug log has a line that starts with `hooks module`, the mod’s name, and `not loaded:`, as in `hooks module first-mod@inline not loaded: disableAllHooks in managed settings` for a mod loaded with `--plugin-dir`. Read the reason after the colon. The refusal messages section lists each one. If the log has no such line, work through the other entries in this group. Some settings stop a mod and leave the rest of its plugin working. [Turn mods on or off](</docs/en/plugins/mods/overview#turn-mods-on-or-off>) names them. -### - -​ - -A `claude -p` run prints `hooks module not loaded` +### A `claude -p` run prints `hooks module not loaded` The line starts with the mod’s name and goes to stderr. The hooks module was refused. A non-interactive run has no transcript, so the message goes to stderr. Read the reason after the colon. The refusal messages section lists each one. -### - -​ - -Refusal messages +### Refusal messages Each of these follows `hooks module`, the mod’s name, and `not loaded:` in the debug log. @@ -78,11 +50,7 @@ `installed plugins that are not managed load no hooks module in this mode (--bare)`| You started Claude Code with `--bare` `another plugin of that name loads first`| Another enabled plugin has the same name as your mod and [holds the name](</docs/en/plugins/loading#hooks-when-two-enabled-plugins-share-a-name>), so your hooks module doesn’t load -### - -​ - -Messages from the built-in guard +### Messages from the built-in guard Where the [built-in guard](</docs/en/plugins/mods/admin#know-what-happens-by-default>) loads, it can refuse a mod or one of its answers. Each message names the option your organization’s administrator sets to change the rule. @@ -92,51 +60,27 @@ `tried to lift a deny rule in your settings`| Your mod’s [`tool.check`](</docs/en/plugins/mods/reference#tools>) hook approved a call that a `deny` rule refuses. The call stays denied.| The transcript and the debug log, once for each mod in a session. In a `claude -p` run, the debug log only. `the deny rules in your settings could not be checked for this call, so it is refused`| The guard failed while checking a call that a mod approved, so it refused the call| The reason Claude reads for the denied call -### - -​ - -`validate` passes and lists no `hooks` line +### `validate` passes and lists no `hooks` line `hooks/hooks.json` has no `modules` key, or the key is misspelled. Add `"modules": ["./register.js"]`. -### - -​ - -`hooks module did not load` +### `hooks module did not load` The line starts with the mod’s name, then `hooks module did not load:` and a reason, which gives the file and line when the problem is in your code. Claude Code couldn’t load the module, for example because its top-level code threw. Fix the error the reason names. If the reason ends with `; the version loaded before is unloaded`, no version of the mod is running now. Once you fix the error, run [`/reload-plugins`](</docs/en/plugins/cli-reference#reload-plugins>) in the session to load the mod again. If you installed the mod and didn’t write it, ask its author to fix the error. -### - -​ - -`options do not fit plugin.json userConfig` +### `options do not fit plugin.json userConfig` The line starts with the mod’s name, then `hooks module did not load: options do not fit plugin.json userConfig:` and a reason. An option fails validation against its [`userConfig`](</docs/en/plugins/components#user-configuration>) field, such as a number above the field’s `max`, or a required field has no value. Set or change the value. The end of the line names its `pluginConfigs` entry in `settings.json`. -### - -​ - -`code nested too deep to scan: more than 2000 scopes` +### `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. -### - -​ - -`the engine ran out of stack linking the file and its imports` +### `the engine ran out of stack linking the file and its imports` Code in the hooks module is nested too deeply, or its chain of imports is too long, for Claude Code to load it. The line starts with the mod’s name and `hooks module did not load:`, then gives a file’s name and this reason. In that file and the files its imports reach, find the most deeply nested code and rewrite it to nest less, or shorten the chain of imports. If you didn’t write the mod, ask its author to fix it. -### - -​ - -`the parser stopped` or `the engine ran out of stack loading the file` +### `the parser stopped` or `the engine ran out of stack loading the file` Code in one file of the hooks module is nested so deeply that Claude Code ran out of stack reading it. The line starts with the mod’s name and `hooks module did not load:`, then gives that file’s name and one of these reasons: @@ -145,51 +89,27 @@ The reason gives no line number and doesn’t say what kind of code is nested, so look through the file yourself for its most deeply nested part. Rewrite that part to nest less. If you installed the mod and didn’t write it, ask its author to. -### - -​ - -No mod loads in a directory you opened for the first time +### 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. -### - -​ - -No installed plugin loads at all +### 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 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`. -## - -​ - -A hook is skipped or a mod is unloaded +## A hook is skipped or a mod is unloaded The mod loaded, and then Claude Code skipped one of its hooks or unloaded it. -### - -​ - -`hook skipped` +### `hook skipped` The line names the mod and the event, then says `hook skipped:` and a reason, as in `first-mod: tool.call hook skipped: threw Error: boom`. A hook threw, exceeded its [time limit](</docs/en/plugins/mods/reference#limits>), or returned a result of the wrong shape. The line appears once for each event and kind of failure until the mod reloads. Fix the error. The debug log has a line for every occurrence. -### - -​ - -`no command.run hook answered it` +### `no command.run hook answered it` You run a command your mod added, and the reply names the mod and the command, as in `first-mod registered /tally but no command.run hook answered it`, then tells you to add a hook. Claude Code prints that reply when the command reaches the end of the chain with no answer, which happens in two cases: @@ -198,27 +118,15 @@ If the module already has the hook the reply describes, look for a `hook skipped` line that names `command.run`, which gives the reason. A [test](</docs/en/plugins/mods/test>) that runs the command fails with the same reason. -### - -​ - -`it crashed the hooks worker` +### `it crashed the hooks worker` The line starts with the mod’s name, as in `first-mod was unloaded: it crashed the hooks worker`. Installed mods share one worker thread. The worker stopped responding or crashed, and Claude Code traced that to this mod and unloaded it. A hook that blocks the thread, such as a loop that never awaits, is one cause. Fix the hook. -### - -​ - -`its session.start ran again in a fresh copy` +### `its session.start ran again in a fresh copy` The line starts with the mod’s name and names a `$.prompt.submit`, `$.command.run`, or `$.agent.spawn` call, as in `first-mod: its session.start ran again in a fresh copy; the $.prompt.submit call it had already made was not made again`. Claude Code loaded the mod’s module again, for example after the hooks worker crashed and was replaced, and the fresh copy’s [`session.start`](</docs/en/plugins/mods/reference#session>) hook ran. The call the line names resolved with the result of its first run instead of running again, so your mod doesn’t submit the prompt, run the command, or start the subagent twice. The rest of the hook ran as usual. There’s nothing to fix. Before v2.1.292, the call ran a second time, so the prompt was submitted, the command run, or the subagent started twice. -### - -​ - -`This mod's change didn't load` or `the earlier version is no longer running` +### `This mod's change didn't load` or `the earlier version is no longer running` A change to a [mod Claude wrote in this session](</docs/en/plugins/mods/create#ask-claude-for-a-mod>) couldn’t load. The transcript line starts with the mod’s name and ends with the reason: @@ -227,75 +135,39 @@ Claude doesn’t see this line, so paste it into your next message when you ask Claude for a fix. -### - -​ - -`$.agent.register refused: the hooks module that made the call is no longer loaded` +### `$.agent.register refused: the hooks module that made the call is no longer loaded` The line starts with your mod’s name, as in `first-mod: $.agent.register refused: the hooks module that made the call is no longer loaded (it was reloaded or removed)`, and the agent isn’t registered. Your mod was reloaded or unloaded before the call. A reload loads a fresh copy of the hooks module, and this call came from code still running in the old copy, such as a hook that hadn’t returned yet. If that hook doesn’t catch the rejection, it fails and Claude Code skips it. To register the agent from the copy that stays loaded, make the call in your [`session.start`](</docs/en/plugins/mods/reference#session>) hook, which runs again in each fresh copy after a reload. -### - -​ - -`mods that run in the hooks worker are off for this session` +### `mods that run in the hooks worker are off for this session` The line reads `hooks: mods that run in the hooks worker are off for this session: it crashed 3 times`. The worker stopped three times and Claude Code couldn’t trace the stops to one mod, so it unloaded every mod that isn’t built in, including mods your organization installs. This line reaches the transcript in every interactive session. Run `/reload-plugins` to load them again. -## - -​ - -A tool call is denied +## A tool call is denied The mod loaded and its hooks run, and a tool call it touched is refused. -### - -​ - -`a hook changed this call's input after the model wrote it` +### `a hook changed this call's input after the model wrote it` In auto mode, a denied tool call gives this reason. A hook changed the tool call’s input after the [server-side classifier](</docs/en/permission-modes#server-side-classifier-review>) reviewed it, so that review doesn’t cover what would run. The hook can be a mod’s [`tool.call`](</docs/en/plugins/mods/reference#tools>) or [`turn.step`](</docs/en/plugins/mods/reference#turns>) hook, or a [`PreToolUse`](</docs/en/hooks#pretooluse>) settings hook. The message doesn’t say which. The message tells Claude to issue the call once more as recorded. If that’s denied too, the hook changes the input every time, so turn off the mod or hook, or leave auto mode and approve the call yourself. In [some interactive terminal sessions and VS Code sessions](</docs/en/hooks#pretooluse-updatedinput-in-auto-mode>), the same denial gives the reason `a hook changed this call's input after auto mode reviewed it`. The repeated call there carries the mod’s first change, and a `tool.call` hook still runs on it, but a further change is dropped. You don’t need to change your mod unless Claude tells you in its reply that [auto mode couldn’t check the call](</docs/en/errors#hook-changed-input-after-review>). -### - -​ - -A message about the deny rules in your settings +### A message about the deny rules in your settings `tried to lift a deny rule in your settings` and `the deny rules in your settings could not be checked for this call, so it is refused` both come from the built-in guard. Look them up in Messages from the built-in guard. -## - -​ - -A toast appears after a turn is stopped - -### - -​ - -`Stopped: type a message to continue; a mod cannot resume work after Stop` +## A toast appears after a turn is stopped + +### `Stopped: type a message to continue; a mod cannot resume work after Stop` This toast means that after you stopped the turn, for example with Esc, a mod tried to start work on its own and Claude Code didn’t let it. Nothing needs fixing. After your next message, mods can start work again and [some of that work comes back](</docs/en/plugins/mods/api#work-your-mod-started-before-the-interruption>) on its own. If what you expected from the mod doesn’t come back, ask for it again or run the mod’s command again. If you wrote the mod, see [Calls and background work after the user interrupts a turn](</docs/en/plugins/mods/api#calls-and-background-work-after-the-user-interrupts-a-turn>). -## - -​ - -A drawing doesn’t appear or respond +## A drawing doesn’t appear or respond The mod loaded, and its pane, band, toast, or controls don’t behave as you expect. -### - -​ - -Another mod’s band shows and yours doesn’t +### Another mod’s band shows and yours doesn’t There is one band above the prompt, and every mod shares it. A mod that runs [before yours](</docs/en/plugins/mods/events#the-order-mods-run-in>) replaces your band when it returns a tree without the result of `next(e)` in it. To show both bands, change that mod’s hook, or ask its author to: @@ -304,11 +176,7 @@ To find that mod, write a debug log and search it for `answered ui.render without next()`. A line such as `other-mod (user) answered ui.render without next()` names a mod that returned its tree without calling `next(e)`. It doesn’t name the [render site](</docs/en/plugins/mods/reference#render-sites>), so a pane-only mod can appear too. A mod that calls `next(e)` and drops the result gets no line, so check the hooks before yours too. A mod’s band is also missing when the tree its own hook returned doesn’t validate, and the other mods’ bands stay. To find which mod and why, write a debug log and search it for `ui.render hook skipped`. -### - -​ - -A pane or band is empty or shows Claude Code’s usual content +### A pane or band is empty or shows Claude Code’s usual content The [tree](</docs/en/plugins/mods/interface#build-a-tree-from-elements>) your hook returned didn’t validate. A `hook skipped` line in the transcript or the debug log names your mod and the reason, as in this one for a `Box` in a pane: @@ -316,11 +184,7 @@ Fix what the reason names. If the reason is cut short, write a debug log and search it for `a hook returned a tree that does not validate` to read the rest. If the line instead says `refused:` right after the site’s name, as in `ui.render (Pane) refused:`, see A `ui.render` line says `refused`. -### - -​ - -A `ui.render` line says `refused` +### A `ui.render` line says `refused` `ui.render (<site>) refused:`, or `ui.render (<site>): the chain settled on a tree that does not validate` in the debug log, means the [tree](</docs/en/plugins/mods/interface#build-a-tree-from-elements>) at that site exceeds a [size limit](</docs/en/plugins/mods/reference#limits>). Either line names the [render site](</docs/en/plugins/mods/reference#render-sites>) and then the reason, and the reason names the limit. Change the mods that draw at that site so their [`ui.render`](</docs/en/plugins/mods/reference#interface>) hooks return smaller trees, or ask their authors to. If the transcript line starts with `hooks`, more than one loaded mod has a `ui.render` hook for that site, so check each of those mods’ trees. For several mods whose bands above the prompt nest into a tree more than 32 levels deep, the line reads: @@ -328,11 +192,7 @@ Before v2.1.307, a `refused:` line for any site reported any tree that didn’t validate, and for `Pane` and `AbovePrompt` it ended `; the engine drew its own`. On those releases, fix what the reason names. -### - -​ - -`needs a key`, `is drawn twice`, or `key each once` +### `needs a key`, `is drawn twice`, or `key each once` An element in the tree your `ui.render` hook returns has no valid [`key`](</docs/en/plugins/mods/interface#which-controls-need-a-key>), or two elements share one. Find the message you got: @@ -341,35 +201,19 @@ * **`is drawn twice; each takes its own key`** : two elements of the kind the message names have the same `key`, as in `Input "size" is drawn twice; each takes its own key`. Give each element its own `key`. * **`key each once` from `press` in a [test](</docs/en/plugins/mods/test#test-a-drawing>)**: the drawing has more than one button with the key you passed. Buttons with the same label and no `key` prop share that label as their key. Give each button its own `key`. -### - -​ - -A `ui.render` line says `threw while drawn` +### A `ui.render` line says `threw while drawn` The line names the [render site](</docs/en/plugins/mods/reference#render-sites>), then says `threw while drawn:` and the error, as in `first-mod: ui.render (ToolUse) threw while drawn: <error>; the engine drew its own`. Claude Code hit that error while drawing the tree your [`ui.render`](</docs/en/plugins/mods/reference#interface>) hook returned, or while drawing the site from the [`props` your hook passed to `next`](</docs/en/plugins/mods/interface#change-what-claude-code-already-draws>). The ending `the engine drew its own` means the site shows Claude Code’s usual content. Read the error and fix the value in your hook that caused it. Before v2.1.289, this error in a transcript row ended the session with [`Claude Code exited after an unrecoverable interface error`](</docs/en/errors#exited-after-an-unrecoverable-interface-error>). -### - -​ - -`the module failed without a message` +### `the module failed without a message` A [`Client`](</docs/en/plugins/mods/interface#when-a-client-fails>) failed with an error that has no message, such as `throw new Error()`. The line in its place reads like `my-mod: Client client/spinner.js: the module failed without a message`. Find the throw in your `Client`’s code and give the error a message. The line then shows that message. Before v2.1.289, the line showed `Error` as the reason instead. -### - -​ - -`$.ui.open` runs and no pane appears +### `$.ui.open` runs and no pane appears The call didn’t come from something the user did, and the terminal is narrower than [the width that pane needs](</docs/en/plugins/mods/interface#when-a-pane-waits-for-a-wider-terminal>). Open the pane from a command or a button, or check the call’s `isPlaced` result. See [Open a pane at the right time](</docs/en/plugins/mods/interface#open-a-pane-at-the-right-time>). -### - -​ - -A toast doesn’t appear +### A toast doesn’t appear Your mod calls [`$.ui.toast`](</docs/en/plugins/mods/api#show-something-without-starting-a-turn>) in an interactive terminal session and you don’t see the toast. To confirm that the call ran, look in the debug log for a line with your mod’s name and the toast’s text, as in `$.ui.toast (first-mod): build finished`. Then check for causes such as these: @@ -381,19 +225,11 @@ Before v2.1.290, Claude Code dropped a toast raised within two seconds of the last one it showed for your mod, and the debug log line for the dropped toast said `within 2000ms of the last; dropped`. -### - -​ - -The band shows `plugin panel hidden` +### The band shows `plugin panel hidden` The band is [collapsed](</docs/en/plugins/mods/interface#when-the-user-collapses-the-band>). It collapses when you press Ctrl+X then Ctrl+A, or the keys you bound in their place, and in [fullscreen rendering](</docs/en/fullscreen>) when you click the `[-]` on its first row. It stays collapsed until you expand it or start Claude Code again, and meanwhile no hotkey or `action` binding presses a button in it. To expand the band, press the keys the row names, Ctrl+X then Ctrl+A by default, or in fullscreen rendering click the row. -### - -​ - -Hotkeys do nothing +### Hotkeys do nothing Your pane or band doesn’t have keyboard focus, your button is in a collapsed band, or the drawing is in the VS Code extension, where buttons have no hotkeys. Do the one that matches: @@ -401,11 +237,7 @@ * **The button is in a collapsed band** : the band shows one dim row that starts with `▸ plugin panel hidden`. Press the keys the row names, Ctrl+X then Ctrl+A by default, to expand it. * **In the VS Code extension** : click the button, or press Enter on it once it has focus -### - -​ - -A drawing works in the terminal and not in the Desktop app or VS Code +### A drawing works in the terminal and not in the Desktop app or VS Code Either that app doesn’t draw the site or element, or the session is one where the VS Code extension draws nothing for mods. The mod’s other hooks still run. Check for these causes: @@ -413,43 +245,23 @@ * **The VS Code extension is older than 2.1.299** : the chat panel draws for mods from [extension version](</docs/en/vs-code#install-the-extension>) 2.1.299. Check the version in VS Code’s Extensions view and update the extension there. * **The extension is older than 2.1.304 and the session doesn’t fetch feature flags** : update the extension, or run `claude` in VS Code’s integrated terminal instead. Sessions on Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry skip the fetch. For the others that skip it, such as a [Claude apps gateway](</docs/en/claude-apps-gateway>) session, see [Features that need feature-flag fetching](</docs/en/env-vars#features-that-need-feature-flag-fetching>). -## - -​ - -An edit or a value is lost +## An edit or a value is lost The mod runs, and a change you made or a value it kept isn’t there. -### - -​ - -Your edits don’t take effect +### Your edits don’t take effect You’re editing a plugin you installed. Claude Code runs the cached copy for the installed version. Develop with `--plugin-dir` pointed at your working copy, as in `claude --plugin-dir ./first-mod`, which reloads when you save. -### - -​ - -A value resets when the module reloads +### A value resets when the module reloads Module-level variables are re-initialized on each reload. [Keep the value in `$.state` or `$.store`](</docs/en/plugins/mods/interface#keep-state>). -### - -​ - -A value resets after `/clear`, `/resume`, or `/branch` +### A value resets after `/clear`, `/resume`, or `/branch` A value resets, or a saved value is replaced by its default. Each of those commands resets `$.state` to its defaults, and `session.start` doesn’t fire again. [Load the saved value again](</docs/en/plugins/mods/interface#load-a-saved-value-again-after-clear>) in a `classic.SessionStart` hook. -### - -​ - -A key your `settings.read` hook returns doesn’t take effect +### A key your `settings.read` hook returns doesn’t take effect If you return permission rules or `env` on [Claude Code’s own read](</docs/en/plugins/mods/events#settings-read-hook>), the rules aren’t checked on tool calls and the `env` entries don’t become environment variables. Use a [settings file](</docs/en/settings>) for both, or [`$.env.set`](</docs/en/plugins/mods/api#reach-files-processes-and-the-network>) for `env`. For another key, check [which mods get `settings.read` and from which version](</docs/en/plugins/mods/events#settings-read-hook>), then search the debug log for `settings.read` and look for one of these lines: @@ -464,11 +276,7 @@ If no line explains the key, check the mods that run before yours for a `settings.read` hook that [changes the key](</docs/en/plugins/mods/events#settings-read-example>). Turn that mod off, or ask your organization’s administrator to. If no hook does, set the key in a settings file. -### - -​ - -`the answer for <key> is no value the key can hold` +### `the answer for <key> is no value the key can hold` This debug log line means Claude Code refused the value a [`settings.read`](</docs/en/plugins/mods/events#settings-read-hook>) hook returned for the named key, and that key alone: @@ -481,11 +289,7 @@ While the value doesn’t fit, the key keeps the value merged from the settings sources before any hook answered. The line calls it the settings’ own value. -### - -​ - -`settings.read: refused to the engine` +### `settings.read: refused to the engine` You see this line in the debug log when [Claude Code’s own read](</docs/en/plugins/mods/events#settings-read-hook>) is refused, and Claude Code drops every hook’s value. When a `settings.read` hook refuses that read with [`{ deny: reason }`](</docs/en/plugins/mods/events#settings-read-returns>), the line carries that hook’s reason: @@ -500,11 +304,7 @@ If the line stays with no other mod left, set the keys your hook returns in a [settings file](</docs/en/settings>). Its values hold while the read is refused. -## - -​ - -Read the debug log +## Read the debug log The debug log has a line for every module Claude Code loads or refuses, every hook that fails, and every result it refuses, so it’s where to look when the transcript shows nothing. To write one, in your shell start Claude Code with `--debug`, or with `--debug-file <path>` to choose where it goes: @@ -520,11 +320,7 @@ To write your own lines in the log, call [`$.ui.log`](</docs/en/plugins/mods/api#show-something-without-starting-a-turn>) with a second argument, as in `$.ui.log('message', { to: 'debug' })`. Without the second argument, `$.ui.log` adds a dim line to the transcript. While you edit a mod loaded with `--plugin-dir`, the transcript shows a line for each reload that names the mod and lists its hooks. If a save breaks the module, the line says `reload failed, the previous version stays loaded:` with the reason, and the last working version keeps running until Claude Code next reloads plugins, such as when you run `/reload-plugins`. -## - -​ - -Next steps +## Next steps * [Test a mod](</docs/en/plugins/mods/test>): catch problems before they reach a session * [Troubleshoot plugins](</docs/en/plugins/troubleshooting>): problems with installing and loading a plugin that aren’t specific to mods
modified Troubleshoot installation and login View current →
Show diff (665 lines)
--- a/troubleshoot-install.md +++ b/troubleshoot-install.md @@ -1,10 +1,6 @@ If installation fails or you can’t sign in, find your error below. For runtime issues after Claude Code is working, see [Troubleshooting](</docs/en/troubleshooting>). For configuration problems such as settings not applying or hooks not firing, see [Debug your configuration](</docs/en/debug-your-config>). -## - -​ - -Find your error +## Find your error Match the error message or symptom you’re seeing to a fix: @@ -63,17 +59,9 @@ If you’d rather skip the terminal entirely, the [Claude Code Desktop app](</docs/en/desktop-quickstart>) lets you install and use Claude Code through a graphical interface. Download it for [macOS](<https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code&utm_medium=docs>) or [Windows](<https://claude.com/download?utm_source=claude_code&utm_medium=docs>) and start coding without any command-line setup. On Linux, install the app with apt by following the [Linux install instructions](</docs/en/desktop-linux>). -## - -​ - -Run diagnostic checks - -### - -​ - -Check network connectivity +## Run diagnostic checks + +### Check network connectivity The installer downloads from `downloads.claude.ai`. Verify you can reach it: @@ -112,11 +100,7 @@ $env:HTTPS_PROXY = 'http://proxy.example.com:8080' irm https://claude.ai/install.ps1 | iex -### - -​ - -Verify your PATH +### 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. 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. @@ -208,11 +192,7 @@ 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. -### - -​ - -Check for conflicting installations +### Check for conflicting installations Multiple Claude Code installations can cause version mismatches or unexpected behavior. Check what’s installed: @@ -269,11 +249,7 @@ winget uninstall Anthropic.ClaudeCode -### - -​ - -Check directory permissions +### Check directory permissions An install that fails on permissions names the path it couldn’t create or write. On Windows the install writes under `%USERPROFILE%`, which is writable by your user by default, so this section rarely applies there. On macOS and Linux the install writes to these locations: @@ -294,11 +270,7 @@ sudo mkdir -p ~/.local/bin sudo chown -R $(whoami) ~/.local -### - -​ - -Verify the binary works +### Verify the binary works If `claude --version` prints a version but `claude` crashes or hangs on startup, run these checks to narrow down the cause. If `claude --version` says command not found, go to Verify your PATH first; the commands below assume `claude` is on your PATH. Confirm the binary exists and is executable: @@ -310,7 +282,7 @@ Get-Command claude | Select-Object Source -On Linux, check for missing shared libraries. If `ldd` shows missing libraries, you may need to install system packages. On Alpine Linux and other musl-based distributions, see [Alpine Linux setup](</docs/en/setup#alpine-linux-and-musl-based-distributions>). +On Linux, check for missing shared libraries. If `ldd` shows missing libraries, you may need to install system packages. On Alpine Linux and other musl-based distributions, see Linux musl or glibc binary mismatch. ldd "$(command -v claude)" | grep "not found" @@ -318,19 +290,11 @@ claude --version -## - -​ - -Common installation issues +## Common installation issues These are the most frequently encountered installation problems and their solutions. -### - -​ - -Install script returns HTML instead of a shell script +### Install script returns HTML instead of a shell script 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. @@ -372,11 +336,7 @@ 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`. -### - -​ - -`command not found: claude` after installation +### `command not found: claude` after installation The install finished but `claude` doesn’t work. The exact error varies by platform: @@ -389,11 +349,7 @@ On Windows, if the error started right after Claude Code updated, see restore `claude.exe` from its backup. Otherwise, see Verify your PATH for the fix on each platform. -### - -​ - -`permission denied` when adding to your PATH +### `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`: @@ -406,19 +362,11 @@ Then run the two PATH commands for your shell in Verify your PATH again. -### - -​ - -`curl: (56) Failure writing output to destination` +### `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>). -### - -​ - -Homebrew cask unavailable or outdated +### Homebrew cask unavailable or outdated Homebrew reports `Error: Cask 'claude-code' is unavailable: No Cask with this name exists` when your local copy of the Homebrew cask index predates the cask’s publication. Refresh the index and retry: @@ -427,11 +375,7 @@ 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` +### `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: @@ -439,11 +383,7 @@ Upgrade the cask it prints. If it prints nothing, neither cask is installed. -### - -​ - -TLS or SSL connection errors +### TLS or SSL connection errors Errors such as these mean the TLS handshake failed: @@ -505,19 +445,11 @@ You can also install with `winget install Anthropic.ClaudeCode`, which avoids curl entirely. -### - -​ - -`Failed to fetch version from downloads.claude.ai` +### `Failed to fetch version from downloads.claude.ai` The end of the message gives the reason. If it’s a certificate error such as `unable to verify the first certificate`, see TLS or SSL connection errors. For any other reason, see Check network connectivity. -### - -​ - -The connection dropped while downloading the update +### 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. @@ -530,11 +462,7 @@ * 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 -### - -​ - -Release verification failed for Claude Code +### Release verification failed for Claude Code This message from `claude update` or `claude install` means Claude Code couldn’t confirm that the release it was about to install is genuine, so it installed nothing. Any version you already have keeps working. @@ -547,19 +475,11 @@ With any value, if the message repeats, report the problem and include the full message. -### - -​ - -`Auto-update failed · Run claude doctor` in the session footer +### `Auto-update failed · Run claude doctor` in the session footer This red line means Claude Code tried to update itself in the background and the update didn’t install. You can keep working without doing anything. The line points you to `claude doctor`, whose `Last update attempt: failed (install_failed)` line gives a date but no cause. To finish the update or see why it failed, run `claude update` in your shell instead. If that install fails too, look for the error `claude update` prints under Find your error. -### - -​ - -Wrong install command on Windows +### Wrong install command on Windows If you see `'irm' is not recognized`, `The token '&&' is not a valid statement separator`, `A parameter cannot be found that matches parameter name 'fsSL'`, or `'bash' is not recognized as the name of a cmdlet`, you copied the install command for a different shell or operating system. If the command prints the script’s text instead of installing anything, you ran only part of it. @@ -593,11 +513,7 @@ Whichever installer you use, confirm it worked: open a new terminal and run `claude --version`, which prints a version number such as `2.1.211 (Claude Code)`. -### - -​ - -`running scripts is disabled on this system` +### `running scripts is disabled on this system` Installing or running Claude Code through npm on Windows can fail with a `SecurityError`: @@ -614,22 +530,14 @@ 2. **Call the`.cmd` launcher instead**: `npm.cmd` and `claude.cmd` do the same job, and the policy doesn’t cover them. 3. **Use the[PowerShell installer](</docs/en/setup#install-claude-code>)** instead of npm. It installs a binary rather than a `.ps1` script. -### - -​ - -`The process cannot access the file` during Windows install +### `The process cannot access the file` during Windows install If the PowerShell installer fails with `Failed to download binary: The process cannot access the file ... because it is being used by another process`, the installer couldn’t write to `%USERPROFILE%\.claude\downloads`. This usually means a previous install attempt is still running, or antivirus software is scanning a partially downloaded binary in that folder. Close any other PowerShell windows running the installer and wait for antivirus scans to release the file. Then delete the downloads folder and run the installer again: Remove-Item -Recurse -Force "$env:USERPROFILE\.claude\downloads" irm https://claude.ai/install.ps1 | iex -### - -​ - -`claude.exe` missing after an update on Windows +### `claude.exe` missing after an update on Windows If your terminal reports `'claude' is not recognized` right after Claude Code updated on Windows, check whether `%USERPROFILE%\.local\bin` still contains `claude.exe`. If that directory isn’t on your PATH at all, see Verify your PATH instead. To update on Windows, Claude Code renames the existing `claude.exe` aside to a backup and moves the new version into its place. If moving the new version into place fails and Claude Code can’t rename the backup back either, the directory keeps the backup but has no `claude.exe`. The backup is a file in the same directory whose name begins with `claude.exe.old.` followed by a numeric timestamp. Run the following in PowerShell to rename the newest backup back to `claude.exe`: @@ -641,11 +549,7 @@ Before v2.1.281, Claude Code could delete the backup while `claude.exe` was still missing. -### - -​ - -Install killed on low-memory Linux servers +### Install killed on low-memory Linux servers A `Killed` message during install usually means the Linux out-of-memory (OOM) killer terminated the `claude install` step because the system ran out of free memory. This is common on small VPS and cloud instances. The install script reports the cause and exits with code 137. In this example, the line number and process ID vary by release and run: @@ -670,11 +574,7 @@ 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 +### 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: @@ -686,11 +586,7 @@ * 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. -### - -​ - -Install hangs in Docker +### Install hangs in Docker When installing Claude Code in a Docker container, installing as root into `/` can cause hangs. **Solutions:** @@ -701,11 +597,7 @@ 2. **Give Docker more memory** if using Docker Desktop. Build containers share the memory allocated to the Docker Desktop virtual machine, so open **Settings > Resources** in Docker Desktop, raise the memory limit, and rerun the build. -### - -​ - -`Raw mode is not supported` during install +### `Raw mode is not supported` during install When your organization’s [server-managed settings](</docs/en/server-managed-settings>) include changes that need [security approval](</docs/en/server-managed-settings#security-approval-dialogs>), Claude Code versions before 2.1.246 try to show the approval dialog during `claude install`. The dialog needs a terminal on stdin. When the installer runs `claude install` from a pipe, as `curl -fsSL https://claude.ai/install.sh | bash` does, stdin is the pipe rather than a terminal, so the install fails with an error containing `Raw mode is not supported`. Claude Code v2.1.246 and later don’t show the dialog during `claude install` or `claude update`. The command runs with the settings you last approved, and Claude Code shows the dialog in your next interactive session. If your organization’s startup configuration [waits for the settings fetch](</docs/en/server-managed-settings#enforce-fail-closed-startup>), such as when it sets `forceRemoteSettingsRefresh`, the dialog still appears during these commands, and an install run from a pipe still fails. In every other configuration, rerunning the installer gets past this error, because the script runs the latest release’s `install` command even when you ask it to install an older version. Rerun the command for your platform: @@ -719,11 +611,7 @@ `claude --version` prints the version the rerun installed. -### - -​ - -`claude update` or `claude doctor` hangs +### `claude update` or `claude doctor` hangs `claude update` and `claude doctor` scan your shell configuration files for an outdated `claude` alias: `~/.zshrc`, `~/.bashrc`, and `~/.config/fish/config.fish`, plus on macOS the first of `~/.bash_profile`, `~/.bash_login`, or `~/.profile` that exists. If you set `ZDOTDIR`, the Zsh file is `$ZDOTDIR/.zshrc` instead. When one of those paths is a directory, Claude Code skips it and both commands complete normally. Before v2.1.214, a directory at one of those paths made both commands hang and left the System diagnostics section of `/status` blank. `claude doctor` hung with no output; `claude update` hung right after printing `Checking for updates`. If you hit the hang on an earlier version, find the directory. In this command’s output, a line starting with `d` marks that path as a directory. A `No such file or directory` line means nothing exists at that path and isn’t the cause: @@ -731,19 +619,11 @@ Move the directory aside, or update to v2.1.214 or later. Since `claude update` hangs on the affected versions, update by rerunning the [install script](</docs/en/setup#install-claude-code>) instead. -### - -​ - -Claude Desktop overrides the `claude` command on Windows +### Claude Desktop overrides the `claude` command on Windows If you installed an older version of Claude Desktop, it may register a `Claude.exe` in the `WindowsApps` directory that takes PATH priority over Claude Code CLI. Running `claude` opens the Desktop app instead of the CLI. Update Claude Desktop to the latest version to fix this issue. -### - -​ - -Claude Code on Windows requires either Git for Windows (for bash) or PowerShell +### Claude Code on Windows requires either Git for Windows (for bash) or PowerShell Git for Windows is optional. Claude Code uses the [PowerShell tool](</docs/en/tools-reference#powershell-tool>) when Git Bash is absent, so this error means neither shell was found. **If PowerShell is missing from your PATH** , its default location is `C:\Windows\System32\WindowsPowerShell\v1.0\`. Add that directory to your `PATH`, or install [PowerShell 7](<https://aka.ms/powershell>), which provides `pwsh`. **To install Git for Windows instead** , download it from [git-scm.com/downloads/win](<https://git-scm.com/downloads/win>). During setup, select “Add to PATH.” Restart your terminal after installing. Installing it enables the Bash tool, useful when working with Bash-based scripts and tooling. **If Git is already installed** but Claude Code can’t find it, compare its location against the places Claude Code checks. When `CLAUDE_CODE_GIT_BASH_PATH` isn’t set, Claude Code looks for `bash.exe` in this order: @@ -760,11 +640,7 @@ **If`CLAUDE_CODE_GIT_BASH_PATH` is set to the correct path and the file exists** but Claude Code still doesn’t use it, check the file’s name first. Claude Code accepts only a file named `bash.exe`, `sh.exe`, `bash`, or `sh`; with any other name, such as Git for Windows’ `git-bash.exe` launcher, it ignores the variable and auto-detects Git Bash as if it were unset, logging a warning visible with `--debug`. A path that doesn’t exist gets the same fallback and warning. Before v2.1.219, Claude Code used any existing file as the shell without checking its name, and exited at startup with `Claude Code was unable to find CLAUDE_CODE_GIT_BASH_PATH path` when the path didn’t exist. If the file’s name is right, endpoint security software such as AppLocker, Group Policy software restriction policies, or EDR agents may be interfering. Ask your IT team to allowlist `claude.exe` and the processes it spawns, including `cmd.exe` and `bash.exe`, in your endpoint protection policy. -### - -​ - -Claude Code does not support 32-bit Windows +### Claude Code does not support 32-bit Windows Windows includes two PowerShell entries in the Start menu: `Windows PowerShell` and `Windows PowerShell (x86)`. The x86 entry runs as a 32-bit process and triggers this error even on a 64-bit machine. To check which case you’re in, run this in the same window that produced the error: @@ -772,17 +648,13 @@ If this prints `True`, your operating system is fine. Close the window, open `Windows PowerShell` without the x86 suffix, and run the install command again. If this prints `False`, you are on a 32-bit edition of Windows. Claude Code requires a 64-bit operating system. See the [system requirements](</docs/en/setup#system-requirements>). -### - -​ - -Linux musl or glibc binary mismatch - -If you see errors about missing shared libraries like `libstdc++.so.6` or `libgcc_s.so.1` after installation, the installer may have downloaded the wrong binary variant for your system. - - Error loading shared library libstdc++.so.6: No such file or directory - -This can happen on glibc-based systems that have musl cross-compilation packages installed, causing the installer to misdetect the system as musl. **Solutions:** +### Linux musl or glibc binary mismatch + +If you see errors about missing shared libraries like `ld-linux-x86-64.so.2` or `ld-linux-aarch64.so.1` after installation, the installer may have downloaded the wrong binary variant for your system. + + Error loading shared library ld-linux-x86-64.so.2: No such file or directory + +**Solutions:** 1. **Check which libc your system uses** : @@ -790,25 +662,13 @@ Output mentioning `GNU libc` or `GLIBC` means glibc. Output mentioning `musl` means musl. 2. **If you’re on glibc but got the musl binary** , remove the installation and reinstall. You can also manually download the correct binary using the manifest at `https://downloads.claude.ai/claude-code-releases/{VERSION}/manifest.json`. File a [GitHub issue](<https://github.com/anthropics/claude-code/issues>) with the output of `ldd --version` and `ls /lib/libc.musl*`. - 3. **If you’re actually on musl** , such as Alpine Linux, install the required packages: - - apk add libgcc libstdc++ ripgrep - -On Alpine, `ripgrep` is in the community repository. If `apk` reports that the package is missing, see [Alpine Linux setup](</docs/en/setup#alpine-linux-and-musl-based-distributions>). - -### - -​ - -`Illegal instruction` + 3. **If you’re on musl but got the glibc binary** , [remove the installation](</docs/en/setup#uninstall-claude-code>). On Alpine Linux, first install the packages that [Alpine Linux setup](</docs/en/setup#alpine-linux-and-musl-based-distributions>) names. Then run the [install command](</docs/en/setup#install-claude-code>), which installs the musl binary. + +### `Illegal instruction` If running `claude` or the installer prints `Illegal instruction`, the native binary uses CPU instructions your processor doesn’t support. There are two distinct causes. **Architecture mismatch.** The installer downloaded the wrong binary, for example x86 on an ARM server. Check with `uname -m` on macOS or Linux, or `$env:PROCESSOR_ARCHITECTURE` in PowerShell. If the result doesn’t match the binary you received, [file a GitHub issue](<https://github.com/anthropics/claude-code/issues>) with the output. **Missing AVX instruction set.** If your architecture is correct but you still see `Illegal instruction`, your CPU likely lacks AVX or another instruction the binary requires. This affects roughly pre-2013 Intel and AMD processors, and virtual machines where the hypervisor does not pass AVX through to the guest. On a VPS or VM, run `grep -m1 -ow avx /proc/cpuinfo`; an empty result means AVX is not available to the guest. There is no native-binary workaround; track [issue #50384](<https://github.com/anthropics/claude-code/issues/50384>) for status, and include your CPU model from `grep -m1 "model name" /proc/cpuinfo` on Linux or `sysctl -n machdep.cpu.brand_string` on macOS when reporting. Alternative install methods download the same native binary and won’t resolve either cause. -### - -​ - -`dyld: cannot load` on macOS +### `dyld: cannot load` on macOS If you see `dyld: Symbol not found`, `dyld: cannot load`, or `Abort trap: 6` during installation, the binary is incompatible with your macOS version or hardware. A `Symbol not found` error that references `libicucore` means your macOS version is older than the binary supports: @@ -826,19 +686,11 @@ 1. **Check your macOS version** : Claude Code requires macOS 13.0 or later. Open the Apple menu and select About This Mac to check your version. 2. **Update macOS** if you’re on an older version. The binary uses load commands and system libraries that older macOS versions don’t support. Alternative install methods like Homebrew download the same binary and won’t resolve this error. -### - -​ - -`Bus error` while a session is running +### `Bus error` while a session is running If a running session exits and your shell prints `Bus error`, one cause is that Claude Code could no longer read its own executable file from disk. For example, the file was truncated, or deleted on network storage, while the session ran. Before the shell’s message, Claude Code’s runtime can print a crash report that includes `panic(main thread): Bus error at address` and `oh no: Bun has crashed. This indicates a bug in Bun, not your code.` When the executable became unreadable, the crash comes from the unreadable file, not from a bug in Bun. The report can also be missing, if the runtime couldn’t read the code that prints it either. Start a new session to continue. If Claude Code is installed on network storage, follow [Install on network storage](</docs/en/setup#install-on-network-storage>) so upgrades don’t remove a binary that running sessions still need. -### - -​ - -`Exec format error` on WSL1 +### `Exec format error` on WSL1 If running `claude` in WSL prints `cannot execute binary file: Exec format error`, you’re on WSL1 and hitting a known native-binary regression tracked in [issue #38788](<https://github.com/anthropics/claude-code/issues/38788>). The binary’s program headers changed in a way WSL1’s loader can’t handle. The cleanest fix is to convert your distribution to WSL2 from PowerShell: @@ -852,11 +704,7 @@ Then run `source ~/.bashrc` and retry `claude`. -### - -​ - -npm install errors in WSL +### npm install errors in WSL These issues apply if you installed Claude Code with `npm install -g` inside WSL. If you used the [native installer](</docs/en/setup>), skip this section. On npm 12, install as Fix an npm 12 install describes. **OS or platform detection issues.** If npm reports a platform mismatch during install, WSL is likely picking up the Windows `npm`. Run `npm config set os linux` first, then install with `npm install -g @anthropic-ai/claude-code --force`. Do not use `sudo`. **`exec: node: not found` when running `claude`.** Your WSL environment is likely using the Windows installation of Node.js. Confirm with `which npm` and `which node`: paths starting with `/mnt/c/` are Windows binaries, while Linux paths start with `/usr/`. To fix this, install Node via your Linux distribution’s package manager or via [`nvm`](<https://github.com/nvm-sh/nvm>). **nvm version conflicts.** If you have nvm installed in both WSL and Windows, switching Node versions in WSL may break because WSL imports the Windows PATH by default and the Windows nvm takes priority. The most common cause is that nvm isn’t loaded in your shell. Add the nvm loader to `~/.bashrc` or `~/.zshrc`: @@ -874,21 +722,13 @@ Avoid disabling Windows PATH importing via `appendWindowsPath = false` as this breaks the ability to call Windows executables from WSL. Similarly, avoid uninstalling Node.js from Windows if you use it for Windows development. -### - -​ - -Permission errors during installation +### Permission errors during installation If the native installer fails with permission errors, the target directory may not be writable. See Check directory permissions. If you previously installed with npm and are hitting npm-specific permission errors, switch to the native installer: curl -fsSL https://claude.ai/install.sh | bash -### - -​ - -Native binary not found after npm install +### Native binary not found after npm install The `@anthropic-ai/claude-code` npm package downloads the native binary as a per-platform optional dependency, such as `@anthropic-ai/claude-code-darwin-arm64`. `claude` is a placeholder script until the `@anthropic-ai/claude-code` package’s postinstall step runs and replaces the placeholder with that binary. If either the download or the postinstall step is skipped, the placeholder stays in place, and running `claude` on macOS and Linux prints: @@ -911,11 +751,7 @@ * **Unsupported platform.** Prebuilt binaries are published for `darwin-arm64`, `darwin-x64`, `linux-x64`, `linux-arm64`, `linux-x64-musl`, `linux-arm64-musl`, `win32-x64`, and `win32-arm64`. Claude Code does not ship a binary for other platforms; see the [system requirements](</docs/en/setup#system-requirements>). On FreeBSD, the installer reports the platform as unsupported. Before v2.1.205, it treated FreeBSD as Linux and downloaded a binary that couldn’t run. * **Corporate npm mirror is missing the platform packages.** Ensure your registry mirrors all eight `@anthropic-ai/claude-code-*` platform packages in addition to the meta package. -#### - -​ - -Fix an npm 12 install +#### Fix an npm 12 install If `claude` prints `Error: claude native binary not installed.` after an npm install or update, or on Windows the shell can’t run it, run `npm --version`. A version starting with `12` means that, unless your npm config allows it, npm skipped Claude Code’s postinstall step, which puts the binary in place. For any other version, check the other causes. To fix an npm 12 install, switch to the native installer or allow the step: @@ -934,11 +770,7 @@ 4. If `claude --version` doesn’t print a version number, check the other causes. To undo, set the list again without `@anthropic-ai/claude-code`, or remove the whole list with `npm config delete allow-scripts --location=user`. On npm 12, the error then returns after your next update. -### - -​ - -npm `ENOTEMPTY` error during update or reinstall +### npm `ENOTEMPTY` error during update or reinstall When you run `npm install -g @anthropic-ai/claude-code` over an existing installation, npm can fail while moving the old package directory aside: @@ -969,19 +801,11 @@ Confirm with `claude --version`, which prints a version number such as `2.1.211 (Claude Code)`. -## - -​ - -Login and authentication +## Login and authentication These sections address login failures, OAuth errors, and token issues. -### - -​ - -Reset your login +### Reset your login When login fails and the cause isn’t clear, a clean re-authentication resolves most cases: @@ -991,11 +815,7 @@ If the browser doesn’t open automatically during login, press `c` to copy the OAuth URL to your clipboard, then paste it into a browser manually. This also works when the URL wraps across lines in a narrow or SSH terminal and can’t be clicked directly. -### - -​ - -OAuth error: Invalid code +### OAuth error: Invalid code If you see `OAuth error: Invalid code. Please make sure the full code was copied`, the login code expired or was truncated during copy-paste. **Solutions:** @@ -1003,11 +823,7 @@ * Type `c` to copy the full URL if the browser doesn’t open automatically * If using a remote/SSH session, the browser may open on the wrong machine. Copy the URL displayed in the terminal and open it in your local browser instead. -### - -​ - -403 Forbidden after login +### 403 Forbidden after login If you see `API Error: 403 Request not allowed` after logging in: @@ -1015,22 +831,14 @@ * **Anthropic Console users** : confirm your account has the “Claude Code” or “Developer” role. Admins assign this on the Console’s Members page at [platform.claude.com/settings/members](<https://platform.claude.com/settings/members>). * **Behind a proxy** : corporate proxies can interfere with API requests. See [network configuration](</docs/en/network-config>) for proxy setup. -### - -​ - -Claude Code access has not been granted for this account +### Claude Code access has not been granted for this account If the sign-in page shows `Authorization failed` with the message `Claude Code access has not been granted for this account. Contact your administrator.` after you log in from Claude Code, your Claude Enterprise organization has set your role to Custom and none of the [custom roles](<https://support.claude.com/en/articles/13930452>) assigned to your groups grants Claude Code. On the Custom role, you get access only from those custom roles, so nothing you change in Claude Code resolves this error. To get access: 1. Ask an Owner of your Claude organization to assign a custom role that grants Claude Code access to one of your groups, or to change your role from Custom to a standard role such as User. Owners manage roles in the organization’s [role settings](<https://claude.ai/admin-settings/roles>). 2. After the Owner makes the change, run `claude` and log in again. -### - -​ - -This organization has been disabled with an active subscription +### This organization has been disabled with an active subscription If you see `API Error: 400 ... "This organization has been disabled"` despite having an active Claude subscription, an `ANTHROPIC_API_KEY` environment variable is overriding your subscription. This commonly happens when an old API key from a previous employer or project is still set in your shell profile. When `ANTHROPIC_API_KEY` is present and you have approved it, Claude Code uses that key instead of your subscription’s OAuth credentials. In non-interactive mode with the `-p` flag, the key is always used when present. See [authentication precedence](</docs/en/authentication#authentication-precedence>) for the full resolution order. To use your subscription instead, unset the environment variable and remove it from your shell profile: @@ -1046,11 +854,7 @@ Check `~/.zshrc`, `~/.bashrc`, or `~/.profile` for `export ANTHROPIC_API_KEY=...` lines and remove them to make the change permanent. On Windows, check your PowerShell profile at `$PROFILE` and your User environment variables for `ANTHROPIC_API_KEY`. Run `/status` inside Claude Code to confirm which authentication method is active. -### - -​ - -OAuth login fails in WSL2, SSH, or containers +### OAuth login fails in WSL2, SSH, or containers If no browser opens, or the browser signs you in and then shows a connection error for a `localhost` address, you can finish signing in without fixing either problem. Sign in through the separate login URL that the terminal shows above its paste prompt instead: @@ -1081,11 +885,7 @@ export BROWSER="/mnt/c/Program Files/Google/Chrome/Application/chrome.exe" claude -### - -​ - -Not logged in or token expired +### Not logged in or token expired If Claude Code prompts you to log in again after a session, your OAuth token may have expired. Run `/login` to re-authenticate. If this happens frequently, check that your system clock is accurate, as token validation depends on correct timestamps. Parallel sessions on one machine share a saved login and coordinate its renewal so that only one process refreshes the token at a time. For what the other sessions do after you sign in again in one of them, see [Not logged in](</docs/en/errors#not-logged-in>). Before v2.1.211, waking the machine from sleep could cause two sessions to renew with the same token, which revoked the saved login and prompted every open session to log in again at once. On macOS, Claude Code saves credentials to the login Keychain. When the Keychain rejects the write, such as when it’s locked in an SSH session or its password is out of sync with your account password, Claude Code saves your login to the plaintext `~/.claude/.credentials.json` file instead. A Console login that creates an API key fails until the Keychain is writable again. To make the Keychain writable again and move your login back into the encrypted Keychain: @@ -1115,11 +915,7 @@ Once the Keychain is writable again, Claude Code moves the credentials back the next time it writes a credential. To force it now, run `/logout` and then `/login`. Logging out removes all stored credentials, including the plaintext file’s contents, saved MCP server logins, and plugin sensitive values, so expect to re-authorize MCP servers and re-enter plugin secrets afterwards. Logging in again stores your login in the Keychain. -#### - -​ - -Login fails on a network home directory +#### Login fails on a network home directory When a request fails with `API Error: 401` and your [configuration directory](</docs/en/claude-directory>) is on a network filesystem, check whether that filesystem or your quota on it is full. With no room left, Claude Code can’t save a new or renewed login to the plaintext [`.credentials.json` file](</docs/en/authentication#credential-management>), and `claude auth login` can still print `Login successful.` @@ -1137,11 +933,7 @@ Before v2.1.318, when Claude Code saved the login file on a full network filesystem, it could replace a still-valid stored login with an empty file. Later commands then reported `Not logged in`. -### - -​ - -Bedrock, Agent Platform, or Foundry credentials not loading +### Bedrock, Agent Platform, or Foundry credentials not loading If you configured Claude Code to use a cloud provider and see `Could not load credentials from any providers` on Amazon Bedrock, `Could not load the default credentials` on Google Cloud’s Agent Platform, or `ChainedTokenCredential authentication failed` on Microsoft Foundry, your cloud provider CLI is likely not authenticated in the current shell. For Amazon Bedrock, confirm your AWS credentials are valid: @@ -1157,11 +949,7 @@ If credentials work in your terminal but not in the VS Code or JetBrains extension, the IDE process likely didn’t inherit your shell environment. Set the provider environment variables in the IDE’s own settings, or launch the IDE from a terminal where they’re already exported. See [Amazon Bedrock](</docs/en/amazon-bedrock>), [Google Cloud’s Agent Platform](</docs/en/google-vertex-ai>), or [Microsoft Foundry](</docs/en/microsoft-foundry>) for full provider setup. -## - -​ - -Still stuck +## Still stuck If none of the above resolves your issue:
modified Troubleshoot the Agent SDK View current →
Show diff (140 lines)
--- a/troubleshooting.md +++ b/troubleshooting.md @@ -12,17 +12,9 @@ `Not logged in`, `Invalid API key`, `API Error`, `429`, `There's an issue with the selected model`| [Error reference](</docs/en/errors#find-your-error>) `CLINotFoundError`, `CLIConnectionError`, `ProcessError`, `Claude Code process exited with code N`, `Claude Code returned an error result`, `structured_output` is `None`| CLI startup, CLI process exit, and Structured outputs on this page -## +## CLI startup -​ - -CLI startup - -### - -​ - -CLINotFoundError: Claude Code not found +### CLINotFoundError: Claude Code not found The Python SDK launches the Claude Code CLI as a subprocess. When it can’t find a `claude` executable, connecting fails with a `CLINotFoundError`: @@ -39,11 +31,7 @@ * `Native CLI binary for <platform>-<arch> not found`: the bundled platform package is missing, most often because the install skipped optional dependencies. Reinstall `@anthropic-ai/claude-agent-sdk` without skipping optional dependencies, or point `pathToClaudeCodeExecutable` at a [native install](</docs/en/setup#install-claude-code>). In a single-file executable built with `bun build --compile`, the same message has a different cause and fix. See [Compile to a single executable](</docs/en/agent-sdk/typescript#compile-to-a-single-executable>). * `Claude Code native binary not found at <path>` or `Claude Code executable not found at <path>. Is options.pathToClaudeCodeExecutable set?`: the file at the resolved path is missing, or the process can’t access it. Confirm the file exists at that path and that the process can access it. -### - -​ - -CLIConnectionError: Refusing to execute batch script +### CLIConnectionError: Refusing to execute batch script On Windows, connecting fails with a `CLIConnectionError` when the CLI path the Python SDK uses is a `.bat` or `.cmd` batch script, including the `claude.cmd` shim that an npm install creates: @@ -62,11 +50,7 @@ Before `claude-agent-sdk` 0.2.124, the Python SDK spawned batch scripts through `cmd.exe` without this check. -### - -​ - -CLIConnectionError: Failed to start Claude Code +### CLIConnectionError: Failed to start Claude Code The SDK found a file at the resolved path but couldn’t launch it. Python raises these failures as a `CLIConnectionError`. TypeScript rejects the message iteration with an error carrying no SDK class. The table below maps each message to what it tells you. Match the message you see: @@ -83,11 +67,7 @@ * If you don’t need a custom path, remove `cli_path` in Python or `pathToClaudeCodeExecutable` in TypeScript so the SDK finds a CLI on its own, preferring its bundled copy. * When the failing binary is the SDK’s bundled copy in a container image, reinstall the SDK during the image build so the bundled binary matches the container’s platform, or rebuild the image for the architecture it runs on. The usual cause is a binary that doesn’t match the container’s architecture or libc, or one that lost its execute permission in the image build. -### - -​ - -CLIConnectionError: Not connected +### CLIConnectionError: Not connected Calling a `ClaudeSDKClient` method in Python before the client has connected, or after it has disconnected, raises a `CLIConnectionError` with this message: @@ -95,19 +75,11 @@ Do what the message says. Either call `await client.connect()` before any other client method, or open the client with `async with ClaudeSDKClient() as client:`, which connects on entry. -## - -​ - -CLI process exit +## CLI process exit The entries in this section mean the Claude Code process ended while your application was using it. Which error you see depends on the SDK language and on whether the CLI reported an error result before it exited. -### - -​ - -ProcessError: Command failed with exit code +### ProcessError: Command failed with exit code The Python SDK raises a `ProcessError` when the Claude Code process exits with a nonzero code: @@ -116,11 +88,7 @@ The message states the exit code twice, and the `Error output` line is fixed text rather than your process’s error output. The same fixed text fills the exception’s `stderr` attribute. The exception’s `exit_code` attribute carries the code. To capture what the CLI actually wrote to stderr, pass a `stderr` callback in `ClaudeAgentOptions` and log what it receives. A bare `ProcessError` means the CLI exited without reporting an error result. When the CLI did report one, the SDK raises [`ResultError`](</docs/en/agent-sdk/python#resulterror>) instead, covered in Claude Code returned an error result. `ResultError` subclasses `ProcessError`, so `except ProcessError` catches both. To handle them differently, put the `except ResultError` clause first. Before `claude-agent-sdk` 0.2.140, the Python SDK raised error-result exits as a plain `Exception` rather than a `ResultError`. -### - -​ - -Claude Code process exited with code N +### Claude Code process exited with code N IDE wrappers print this message too, and the [error reference](</docs/en/errors#claude-code-process-exited-with-code-n>) covers it for VS Code and other launchers. This entry covers what your TypeScript SDK code receives. The SDK surfaces a nonzero CLI exit as a plain `Error` that rejects the `for await` loop over `query()`’s messages. There’s no SDK error class to catch, so wrap the loop in `try`/`catch` and match on the message: @@ -128,11 +96,7 @@ When the CLI wrote to stderr, the message ends with the tail of it. To capture the full stream, pass a `stderr` callback in the query options. A process killed by a signal reports `Claude Code process terminated by signal <name>` in the same form. -### - -​ - -Claude Code returned an error result +### Claude Code returned an error result Both SDKs replace the process-exit error with this message when the CLI reported an error result before exiting: @@ -140,27 +104,15 @@ The text after the colon is the CLI’s report of what went wrong, so start there rather than with the exit itself. Python raises this as a [`ResultError`](</docs/en/agent-sdk/python#resulterror>), whose `data` attribute carries the full error result. TypeScript rejects the message loop with a plain `Error` carrying the same message shape. -## +## Structured outputs -​ - -Structured outputs - -### - -​ - -structured_output is None but the result says success +### structured_output is None but the result says success A result message can end with `subtype: "success"` while `structured_output` is `None` in Python or `undefined` in TypeScript. The run completes, but no validated output exists. Treat this result as a failure in application code. The [Error handling](</docs/en/agent-sdk/structured-outputs#error-handling>) section shows this pattern for both SDKs. Then check for these causes: * **A request that Claude declined** : to detect this case in your code, check the result message’s `stop_reason` for `"refusal"`. For what to try next, see [Usage Policy refusal](</docs/en/errors#usage-policy-refusal>). * **A schema no output can satisfy** : for example, a string whose `minLength` is greater than its `maxLength`. If `structured_output` is missing repeatedly with a schema you believe is correct, look for constraints that contradict each other. If you find none, simplify the schema until outputs validate, then reintroduce your constraints one at a time. -## - -​ - -Report a new issue +## Report a new issue If your error isn’t covered here, check the open issues or file a new one in the SDK repositories: [claude-agent-sdk-typescript](<https://github.com/anthropics/claude-agent-sdk-typescript/issues>) or [claude-agent-sdk-python](<https://github.com/anthropics/claude-agent-sdk-python/issues>). Include the full error text and your SDK version.
modified Agent SDK reference - TypeScript View current →
Show diff (3653 lines)
--- a/typescript.md +++ b/typescript.md @@ -1,18 +1,10 @@ -## - -​ - -Installation +## Installation npm install @anthropic-ai/claude-agent-sdk The SDK bundles a native Claude Code binary for your platform as an optional dependency such as `@anthropic-ai/claude-agent-sdk-darwin-arm64`. Most installs need no separate Claude Code install. The SDK version tracks the bundled Claude Code version. SDK v0.3.191 bundles Claude Code v2.1.191, so a feature on this page that requires a Claude Code version needs the SDK release with the same patch number or later. If your package manager skips optional dependencies, the SDK throws `Native CLI binary for <platform>-<arch> not found`; set `pathToClaudeCodeExecutable` to a separately installed `claude` binary instead.If your package manager doesn’t apply npm’s `libc` field, as Yarn 1.x doesn’t, you get both the glibc and musl platform packages on Linux, roughly doubling the install size. On Agent SDK v0.2.141 or later, the SDK still launches the correct variant. To reclaim the space in a container image, delete the platform package that doesn’t match the libc where your app runs; for a glibc runtime on x64, that’s `rm -rf node_modules/@anthropic-ai/claude-agent-sdk-linux-x64-musl`. On a development machine the deletion is temporary, since Yarn reinstalls the package on the next dependency change. -### - -​ - -Compile to a single executable +### Compile to a single executable When you compile your application into a single-file executable with `bun build --compile`, the SDK cannot resolve the bundled CLI binary at runtime. `require.resolve` does not work inside the compiled executable’s `$bunfs` virtual filesystem, so the SDK throws `Native CLI binary for <platform>-<arch> not found`. To work around this, embed the platform binary as a file asset, extract it to a real path at startup with `extractFromBunfs()`, and pass that path to `pathToClaudeCodeExecutable`. The `extractFromBunfs()` helper requires `@anthropic-ai/claude-agent-sdk` v0.3.144 or later. The example below builds for macOS on Apple Silicon: @@ -34,11 +26,7 @@ * To cross-compile, install the non-matching platform package, for example `npm install @anthropic-ai/claude-agent-sdk-linux-x64 --force`. * On Windows, the binary subpath is `claude.exe`, for example `@anthropic-ai/claude-agent-sdk-win32-x64/claude.exe`. -### - -​ - -Import the `/core` entry when you bundle the Agent SDK +### Import the `/core` entry when you bundle the Agent SDK If your application bundles the Agent SDK together with its own dependencies, import from `@anthropic-ai/claude-agent-sdk/core` instead of the package root. The `/core` entry requires TypeScript Agent SDK v0.3.282 or later, and its types require TypeScript 5.0 or later. To keep the code your application loads small, the `/core` entry leaves out some root exports: @@ -47,17 +35,9 @@ The root entry inlines its own copies of `zod` and `@modelcontextprotocol/sdk`. The `/core` entry imports them from your `node_modules` at the ranges the Agent SDK’s `peerDependencies` declare, so a bundle that already includes them doesn’t carry a second copy. Import from either the root or `/core` in a given process, not both: they are separate bundles, and loading both gives you two copies of the Agent SDK’s classes and state. -## - -​ - -Functions - -### - -​ - -`query()` +## Functions + +### `query()` The primary function for interacting with Claude Code. Creates an async generator that streams messages as they arrive. @@ -69,30 +49,18 @@ options?: Options; }): Query; -#### - -​ - -Parameters +#### Parameters Parameter| Type| Description ---|---|--- `prompt`| `string | AsyncIterable<``SDKUserMessage``>`| The input prompt as a string or async iterable for streaming mode `options`| `Options`| Optional configuration object (see Options type below) -#### - -​ - -Returns +#### Returns Returns a `Query` object that extends `AsyncGenerator<``SDKMessage``, void>` with additional methods. -### - -​ - -`startup()` +### `startup()` Pre-warms the CLI subprocess by spawning it and completing the initialize handshake before a prompt is available. The returned `WarmQuery` handle accepts a prompt later and writes it to an already-ready process, so the first `query()` call resolves without paying subprocess spawn and initialization cost inline. If you don’t know the session’s working directory yet, use `prewarm()` instead. @@ -101,30 +69,18 @@ initializeTimeoutMs?: number; }): Promise<WarmQuery>; -#### - -​ - -Parameters +#### Parameters Parameter| Type| Description ---|---|--- `options`| `Options`| Optional configuration object. Same as the `options` parameter to `query()` `initializeTimeoutMs`| `number`| Maximum time in milliseconds to wait for subprocess initialization. Defaults to `60000`. If initialization does not complete in time, the promise rejects with a timeout error -#### - -​ - -Returns +#### Returns Returns a `Promise<``WarmQuery``>` that resolves once the subprocess has spawned and completed its initialize handshake. Of the `hook_progress` messages a `SessionStart` or `Setup` hook emits before the handshake completes, you get only the newest, which carries all of the hook’s output so far. `startup()` holds that message, the hook’s `hook_started` message, and anything else the subprocess emits before the handshake completes. The held messages reach you once you call `.query()` on the `WarmQuery` and iterate the result. -#### - -​ - -Example +#### Example Call `startup()` early, for example on application boot, then call `.query()` on the returned handle once a prompt is ready. This moves subprocess spawn and initialization out of the critical path. @@ -138,11 +94,7 @@ console.log(message); } -### - -​ - -`prewarm()` +### `prewarm()` _Alpha._ Starts a Claude Code process as a spare before you know which session it will serve, so you can bind it to a session later with `claim()`. Use it in an application that boots before the user picks a folder. Requires TypeScript Agent SDK v0.3.282 or later. `prewarm()` completes the same initialize handshake as `startup()`, with the process waiting in `options.cwd` when you set it and otherwise in a private temporary directory under your Claude Code config directory. The session’s working directory, its `SessionStart` hooks, its stdio MCP servers, and its CLAUDE.md and git context wait for the claim. A spare holds roughly 230 to 260 MB of memory while it waits. If your `spawnClaudeCodeProcess` runs Claude Code on another machine or in a container, set `options.cwd` to a directory that exists there for the spare to wait in. @@ -153,11 +105,7 @@ `options` and `initializeTimeoutMs` mean the same as for `startup()`, except that `options.cwd` sets only the directory the spare waits in. The promise resolves with a `SpareProcess` once the process has completed its initialize handshake. `prewarm()` throws if `options` sets `resume`, `continue`, or `forkSession`, because a spare has no session yet. Everything a claim can’t set, such as `mcpServers`, `hooks`, `canUseTool`, `settingSources`, `systemPrompt`, and `plugins`, is fixed for the life of the spare, so keep one spare per distinct set of those options and prewarm again when they change. -#### - -​ - -Example +#### Example Prewarm on application boot, then claim the spare when the user starts a session: @@ -187,11 +135,7 @@ console.error(`Session ended with an error: ${error}`); } -### - -​ - -`tool()` +### `tool()` Creates a type-safe MCP tool definition for use with SDK MCP servers. @@ -203,11 +147,7 @@ extras?: { annotations?: ToolAnnotations; searchHint?: string; alwaysLoad?: boolean } ): SdkMcpToolDefinition<Schema>; -#### - -​ - -Parameters +#### Parameters Parameter| Type| Description ---|---|--- @@ -217,11 +157,7 @@ `handler`| `(args, extra) => Promise<``CallToolResult``>`| Async function that executes the tool logic `extras`| `{ annotations?: ``ToolAnnotations``; searchHint?: string; alwaysLoad?: boolean }`| Optional extras. `annotations` provides MCP behavioral hints to clients. `searchHint` is a one-line capability phrase shown in the deferred-tool list when [tool search](</docs/en/agent-sdk/tool-search>) is active. `alwaysLoad: true` keeps this tool’s full schema in the initial prompt instead of deferring it -#### - -​ - -`ToolAnnotations` +#### `ToolAnnotations` Defined in `@modelcontextprotocol/sdk/types.js`. All fields are optional hints; clients should not rely on them for security decisions. @@ -246,11 +182,7 @@ { annotations: { readOnlyHint: true, openWorldHint: true } } ); -### - -​ - -`createSdkMcpServer()` +### `createSdkMcpServer()` Creates an MCP server instance that runs in the same process as your application. @@ -263,11 +195,7 @@ timeout?: number; }): McpSdkServerConfigWithInstance; -#### - -​ - -Parameters +#### Parameters Parameter| Type| Description ---|---|--- @@ -278,21 +206,13 @@ `options.alwaysLoad`| `boolean`| When `true`, this server’s tools stay in the initial prompt instead of being deferred behind [tool search](</docs/en/agent-sdk/tool-search>). Combines with per-tool `alwaysLoad` in `tool()` `options.timeout`| `number`| Timeout in milliseconds for this server’s tool calls. Claude Code applies it to this server in place of [`MCP_TOOL_TIMEOUT`](</docs/en/env-vars>). Pass a whole number of at least 1000. Claude Code ignores other values. Requires TypeScript Agent SDK v0.3.248 or later -### - -​ - -`listSessions()` +### `listSessions()` Discovers and lists past sessions with light metadata. Filter by project directory or list sessions across all projects. function listSessions(options?: ListSessionsOptions): Promise<SDKSessionInfo[]>; -#### - -​ - -Parameters +#### Parameters Parameter| Type| Default| Description ---|---|---|--- @@ -300,11 +220,7 @@ `options.limit`| `number`| `undefined`| Maximum number of sessions to return `options.includeWorktrees`| `boolean`| `true`| When `dir` is inside a git repository, include sessions from all worktree paths -#### - -​ - -Return type: `SDKSessionInfo` +#### Return type: `SDKSessionInfo` Property| Type| Description ---|---|--- @@ -319,11 +235,7 @@ `tag`| `string | undefined`| User-set session tag (see `tagSession()`) `createdAt`| `number | undefined`| Creation time in milliseconds since epoch, from the first entry’s timestamp -#### - -​ - -Example +#### Example Print the 10 most recent sessions for a project. Results are sorted by `lastModified` descending, so the first item is the newest. Omit `dir` to search across all projects. @@ -335,11 +247,7 @@ console.log(`${session.summary} (${session.sessionId})`); } -### - -​ - -`getSessionMessages()` +### `getSessionMessages()` Reads user and assistant messages from a past session transcript. @@ -348,11 +256,7 @@ options?: GetSessionMessagesOptions ): Promise<SessionMessage[]>; -#### - -​ - -Parameters +#### Parameters Parameter| Type| Default| Description ---|---|---|--- @@ -362,11 +266,7 @@ `options.offset`| `number`| `undefined`| Number of messages to skip from the start `options.includeSystemMessages`| `boolean`| `false`| When `true`, also return system messages such as compact boundaries alongside user and assistant messages -#### - -​ - -Return type: `SessionMessage` +#### Return type: `SessionMessage` Property| Type| Description ---|---|--- @@ -377,11 +277,7 @@ `parent_tool_use_id`| `string | null`| For subagent messages, the `tool_use_id` of the `Agent` or `Skill` tool call that started the subagent. `null` for main-session messages and older sessions `parent_agent_id`| `string | null`| For messages from a [nested subagent](</docs/en/sub-agents#let-subagents-spawn-their-own-subagents>), the `agentId` of the subagent that spawned it. `null` for main-session messages, messages from top-level subagents, and older sessions. Requires Claude Code v2.1.202 or later -#### - -​ - -Example +#### Example import { listSessions, getSessionMessages } from "@anthropic-ai/claude-agent-sdk"; @@ -398,11 +294,7 @@ } } -### - -​ - -`getSessionInfo()` +### `getSessionInfo()` Reads metadata for a single session by ID without scanning the full project directory. @@ -411,11 +303,7 @@ options?: GetSessionInfoOptions ): Promise<SDKSessionInfo | undefined>; -#### - -​ - -Parameters +#### Parameters Parameter| Type| Default| Description ---|---|---|--- @@ -424,11 +312,7 @@ Returns `SDKSessionInfo`, or `undefined` if the session is not found. -### - -​ - -`renameSession()` +### `renameSession()` Renames a session by appending a custom-title entry. Repeated calls are safe; the most recent title wins. @@ -438,11 +322,7 @@ options?: SessionMutationOptions ): Promise<void>; -#### - -​ - -Parameters +#### Parameters Parameter| Type| Default| Description ---|---|---|--- @@ -450,11 +330,7 @@ `title`| `string`| required| New title. Must be non-empty after trimming whitespace `options.dir`| `string`| `undefined`| Project directory path. When omitted, searches all project directories -### - -​ - -`tagSession()` +### `tagSession()` Tags a session. Pass `null` to clear the tag. Repeated calls are safe; the most recent tag wins. @@ -464,11 +340,7 @@ options?: SessionMutationOptions ): Promise<void>; -#### - -​ - -Parameters +#### Parameters Parameter| Type| Default| Description ---|---|---|--- @@ -476,11 +348,7 @@ `tag`| `string | null`| required| Tag string, or `null` to clear `options.dir`| `string`| `undefined`| Project directory path. When omitted, searches all project directories -### - -​ - -`forkSession()` +### `forkSession()` Copies a session’s transcript into a new session so you can take the conversation in another direction while the original stays unchanged. To branch from an earlier point in the conversation, pass `upToMessageId`. @@ -489,11 +357,7 @@ options?: ForkSessionOptions ): Promise<ForkSessionResult>; -#### - -​ - -Parameters +#### Parameters Parameter| Type| Default| Description ---|---|---|--- @@ -508,11 +372,7 @@ * the session cannot be found, or has no messages * `upToMessageId` matches no message in the transcript -### - -​ - -`resolveSettings()` +### `resolveSettings()` Resolves the effective Claude Code settings for a given directory using the same merge engine as the CLI, without spawning the Claude CLI. Use it to inspect what configuration a `query()` call would see before invoking one. @@ -528,11 +388,7 @@ options?: ResolveSettingsOptions ): Promise<ResolvedSettings>; -#### - -​ - -Parameters +#### Parameters `resolveSettings()` accepts a single options object. All fields are optional. @@ -543,11 +399,7 @@ `options.managedSettings`| `Settings`| `undefined`| Policy-tier settings supplied by the embedding host. Follows the same rules as `managedSettings` in `Options`, except that `resolveSettings()` doesn’t execute a configured [`policyHelper`](</docs/en/settings-reference#policyhelper>), so the snapshot can include settings that a live session drops `options.serverManagedSettings`| `Settings`| `undefined`| Server-managed settings payload from `/api/claude_code/settings`. Non-restrictive keys pass through unfiltered -#### - -​ - -Return type: `ResolvedSettings` +#### Return type: `ResolvedSettings` `resolveSettings()` returns an object describing the merged settings and the source that contributed each key. @@ -557,11 +409,7 @@ `provenance`| `Partial<Record<keyof Settings, ProvenanceEntry>>`| For each top-level key in `effective`, which source supplied the value `sources`| `Array<{ source, settings, path?, policyOrigin? }>`| Per-source raw settings, ordered from lowest to highest precedence -#### - -​ - -Example +#### Example The example below resolves settings for a project directory and prints the source that controls the cleanup period. On a machine where no settings file sets `cleanupPeriodDays`, both printed lines show `undefined` for the value, which is the expected output rather than an error. @@ -575,17 +423,9 @@ console.log(`Cleanup period: ${effective.cleanupPeriodDays} days`); console.log(`Set by: ${provenance.cleanupPeriodDays?.source}`); -## - -​ - -Types - -### - -​ - -`Options` +## Types + +### `Options` Configuration object for the `query()` function. @@ -658,11 +498,7 @@ `tools`| `string[] | { type: 'preset'; preset: 'claude_code' }`| `undefined`| Tool configuration. Pass an array of tool names or use the preset to get Claude Code’s default tools `verbatimPrompts`| `boolean`| `false`| Deliver every prompt as written. The SDK sends each user message with `client_composed: true`. See `client_composed` for what Claude Code skips on those messages. Use this option when your prompt text includes content the end user didn’t type. For per-turn control, leave it off and set `client_composed` on individual streamed messages instead. Requires TypeScript Agent SDK v0.3.280 or later and Claude Code v2.1.248 or later; the Claude Code version bundled with those SDK versions satisfies the Claude Code requirement -#### - -​ - -Handle slow or stalled API responses +#### Handle slow or stalled API responses The CLI subprocess reads several environment variables that control API timeouts and stall detection. Pass them through the `env` option: @@ -685,11 +521,7 @@ * `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS`: stall watchdog for subagents. While the stream watchdog is on, the default is `CLAUDE_STREAM_IDLE_TIMEOUT_MS` plus 5 minutes, which comes to `600000` unless you raise that variable. With the stream watchdog off, the default is `600000`. Before v2.1.257, the default was always `600000`. The timer resets on each stream event. On a stall, Claude Code aborts the subagent and reports the stall to the parent. For a background subagent, it also marks the task failed and attaches any partial result. * `CLAUDE_ENABLE_STREAM_WATCHDOG` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: stream watchdog that aborts the request when headers have arrived but the response body stops streaming. The watchdog is on by default for all providers; set `CLAUDE_ENABLE_STREAM_WATCHDOG=0` to disable it. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. After the abort, [Automatic retries](</docs/en/errors#automatic-retries>) covers what Claude Code does, based on how far the response had progressed. While the watchdog waits out a response that a gateway behind `ANTHROPIC_BASE_URL` holds open with keep-alive pings, a host that sets `includePartialMessages` keeps receiving `ping` stream events, so read those frames as liveness rather than timing the session out on silence. Before v2.1.257, the frames stopped 5 minutes after the last real stream event. -### - -​ - -`Query` object +### `Query` object Interface returned by the `query()` function. @@ -746,11 +578,7 @@ close(): void; } -#### - -​ - -Methods +#### Methods Method| Description ---|--- @@ -784,11 +612,7 @@ `backgroundTasks(toolUseId?)`| Moves the running Bash commands and subagents that the turn is waiting on to the background, the same as pressing Ctrl+B in the interactive terminal. See `backgroundTasks()`. Requires TypeScript SDK v0.2.139 or later `close()`| Close the query and terminate the underlying process. Forcefully ends the query and cleans up all resources -#### - -​ - -`setMcpPermissionModeOverride()` +#### `setMcpPermissionModeOverride()` Overrides the permission mode for one MCP server’s tools with a stricter mode than the session’s, or clears the override with `null`. Use it when a session runs in a mode that skips per-action prompts but one server’s tools should still be reviewed. Requires TypeScript SDK v0.3.187 or later. Pass one of three values as `mode`: @@ -798,19 +622,11 @@ The override only takes effect while the session is in a mode that skips per-action prompts: `bypassPermissions` or `auto`. In any other session mode Claude Code ignores the override, so it can never widen what the session allows. The promise resolves with `{ warning }` when no server by that name is known yet. Claude Code stores the override anyway and applies it once a server with that exact name connects, so the warning is a typo check, not a failure. Only available in streaming input mode, the same constraint as `setModel()` and `setPermissionMode()`. -#### - -​ - -`seedReadState()` +#### `seedReadState()` Marks a file as already read so a later Edit doesn’t fail with `File has not been read yet`. Use it when your application has dropped an earlier `Read` result from the conversation context and Claude will edit that file next. Requires TypeScript SDK v0.2.83 or later. Pass `mtime` as the file’s modification time at the moment of that earlier read, in whole milliseconds since the epoch, for example `Math.floor(stat.mtimeMs)`. If the file on disk changed after that time, Claude Code skips the mark. The promise resolves whether or not the file was marked, so a resolved promise doesn’t tell you which happened. -#### - -​ - -`backgroundTasks()` +#### `backgroundTasks()` Moves the running Bash commands and subagents that the turn is waiting on to the background, the same as pressing Ctrl+B in the interactive terminal. Pass the `toolUseId` of a tool call to background only the Bash command or subagent that call started, or omit it to background every foreground task. Requires TypeScript SDK v0.2.139 or later. Each backgrounded tool call returns to Claude immediately with a running-in-the-background result, the turn continues, and Claude Code emits an `SDKTaskNotificationMessage` when the task finishes. In a session where background tasks are enabled, the promise resolves to a boolean: @@ -819,11 +635,7 @@ If background tasks are disabled for the session, such as with [`CLAUDE_CODE_DISABLE_BACKGROUND_TASKS`](</docs/en/env-vars>), the promise rejects instead and nothing is backgrounded. -#### - -​ - -`applyFlagSettings()` +#### `applyFlagSettings()` Changes [settings](</docs/en/settings>) on a running session without restarting the query. Use it when a setting that has no dedicated setter needs to change mid-session, such as tightening `permissions` after the agent reads untrusted input. `setModel()` and `setPermissionMode()` are dedicated setters for those two keys; `applyFlagSettings()` is the general form that accepts any subset of the settings keys, and passing `model` here behaves the same as `setModel()`. Only some keys take effect mid-session: @@ -852,11 +664,7 @@ `applyFlagSettings()` is TypeScript-only. The Python SDK does not expose an equivalent method. -#### - -​ - -`updateSettings()` +#### `updateSettings()` Writes one allowlisted key to a settings file on disk, so the value persists for later sessions that load that source. Each source accepts one key, with a string value: @@ -865,22 +673,14 @@ The call rejects when the request carries any other key, when the session runs over a remote transport, and when the session’s `settingSources` exclude the source you name. Deleting a key isn’t supported. -#### - -​ - -`toggleMcpServer()` +#### `toggleMcpServer()` Disabling a server disconnects it and removes its tools from the session. For servers you added mid-session and for in-process servers, this depends on your Claude Code version: * A stdio, SSE, or HTTP server you added mid-session with `setMcpServers()`: removing its tools requires Claude Code v2.1.285 or later. * An in-process server you created with `createSdkMcpServer()`, whether you passed it in `mcpServers` or with `setMcpServers()`: disconnecting it and removing its tools requires Claude Code v2.1.286 or later. Disabling one also fails its tool calls that are still running, so Claude receives an error result for each of them immediately, without waiting for your handler to return. -### - -​ - -`WarmQuery` +### `WarmQuery` Handle returned by `startup()`. The subprocess is already spawned and initialized, so calling `query()` on this handle writes the prompt directly to a ready process with no startup latency. @@ -889,11 +689,7 @@ close(): void; } -#### - -​ - -Methods +#### Methods Method| Description ---|--- @@ -902,11 +698,7 @@ `WarmQuery` implements `AsyncDisposable`, so it can be used with `await using` for automatic cleanup. -### - -​ - -`SpareProcess` +### `SpareProcess` _Alpha._ Handle returned by `prewarm()`: a started Claude Code process that isn’t bound to a session yet and can be claimed once. Requires TypeScript Agent SDK v0.3.282 or later. @@ -920,11 +712,7 @@ close(): void; } -#### - -​ - -Members +#### Members Member| Description ---|--- @@ -935,11 +723,7 @@ `options.cwd` is required. A claim can also set `additionalDirectories`, `model`, `permissionMode`, `maxThinkingTokens`, a flag-settings overlay in `settings`, `appendSystemPrompt`, `title`, `agents`, and per-session tokens in `env`. Claude Code can refuse a claim, for example for a folder that doesn’t exist or one whose project settings set `env`, `agent`, or `model`. After a refusal, a prompt that `claim()` already sent gets an error result whose text starts with `not_claimed`, and the returned query then throws. Wrap the query’s loop in a try block to continue past the throw. When `claimed` rejects with a message that starts with `option_not_applied`, the session is running without the `model` or `maxThinkingTokens` you asked for. After any other rejection your prompt hasn’t run, so start the session with `query()` instead. -### - -​ - -`SDKControlInitializeResponse` +### `SDKControlInitializeResponse` Return type of `initializationResult()`. Contains session initialization data. @@ -976,11 +760,7 @@ The response always reports `fast_mode_state`, and when something blocks [fast mode](</docs/en/fast-mode>), `fast_mode_disabled_reason` carries the reason code alongside it, so you can explain the blocked state instead of re-deriving availability. Both behaviors require Claude Code v2.1.219 or later. Before v2.1.219, the response omitted `fast_mode_state` when fast mode wasn’t available and never carried a reason. For the reason codes and their meanings, see `fast_mode_disabled_reason` on the result message. The control-response wrapper for a successful `initialize` also carries a `pending_permission_requests` array. The field is on the response wrapper itself, not in the `SDKControlInitializeResponse` payload above. Each entry is a complete `control_request` message with the same `{ type: "control_request", request_id, request }` shape the session streams for permission requests while running. The array lists the permission requests that this Claude Code process has issued and not yet resolved. The SDK reads the array for you and dispatches each entry to your `canUseTool` callback, the same redelivery that `reinitialize()` triggers after a transport gap. Handle repeated request IDs idempotently, because an entry can repeat a request the callback already received before the connection dropped. The array is always present on a successful `initialize` response and is empty when this process has no unresolved permission request. Requires Claude Code v2.1.268 or later. Earlier versions could omit the field, so if you parse the wire protocol yourself, treat a missing field as an older CLI rather than as proof that nothing is pending. -### - -​ - -`SDKControlInterruptResponse` +### `SDKControlInterruptResponse` The interrupt receipt: the value `interrupt()` resolves with on a CLI that advertises the `interrupt_receipt_v1` capability in `SDKSystemMessage.capabilities`. Requires Claude Code v2.1.205 or later. Earlier CLIs answer the interrupt with an empty success payload, so `interrupt()` resolves to `undefined`. @@ -997,11 +777,7 @@ A client that drives the CLI’s control protocol directly, rather than through `interrupt()`, can set `cancel_queued: true` on the `interrupt` control request. Claude Code v2.1.219 and later advertises support with the `interrupt_cancel_queued_v1` capability in `SDKSystemMessage.capabilities`; older CLIs ignore the field and leave queued messages to run as usual. Such an interrupt also cancels every message that would otherwise be listed under `still_queued`: the receipt lists them under `cancelled` instead, `still_queued` is empty, and none of them run. The `cancelled` list carries the same caveats as `still_queued`. The `interrupt()` method never sends `cancel_queued`, so receipts it resolves with don’t carry `cancelled`. The receipt is a snapshot taken at the moment the interrupt is processed, and on a clean interrupt it arrives before the interrupted turn’s `SDKResultMessage`. Read the receipt rather than inspecting the queue after that result: the loop starts the next queued turn immediately, so the queue you inspect after the result has already changed. -### - -​ - -`SDKControlGetContextUsageResponse` +### `SDKControlGetContextUsageResponse` Return type of `getContextUsage()`. With the default `detail`, the response includes the payload Claude Code renders for the `/context` command in an interactive session. Alongside the token counts, that payload carries display fields such as `color` and `gridRows` that Claude Code uses to draw the `/context` usage grid. The method’s optional `detail` argument chooses how Claude Code counts each category. The `detail` argument requires Agent SDK v0.3.257 or later. @@ -1135,11 +911,7 @@ `totalTokens` is the session’s current context usage, and `maxTokens` is the window that usage is measured against. That window is the model’s context window, or the lower auto-compaction window when one applies. `rawMaxTokens` carries the same value as `maxTokens`, and `percentage` is `totalTokens` as a rounded percentage of that window. `apiUsage` holds the usage from the latest API response, not a running total for the session. Claude Code leaves the optional `deferredBuiltinTools`, `systemTools`, and `systemPromptSections` diagnostics unset, so expect them to be absent even though the type declares them. -#### - -​ - -Find a row by ID, a server’s instruction tokens, or an entry’s plugin and file +#### Find a row by ID, a server’s instruction tokens, or an entry’s plugin and file MCP server instructions are the usage notes that connected servers supply and Claude Code adds to context, and the `mcp_instructions` row of `categories` counts their tokens. Use these `getContextUsage()` fields to pick out one `categories` row by `id`, split the `mcp_instructions` tokens by server, or find the plugin and file behind an agent or skill entry: @@ -1157,11 +929,7 @@ // undefined if no connected server supplies instructions const row = usage.categories.find((c) => c.id === "mcp_instructions"); -### - -​ - -`SDKControlReadFileResponse` +### `SDKControlReadFileResponse` Return type of `readFile()`. @@ -1174,11 +942,7 @@ `contents` holds the file text, or base64 data when you requested `encoding: 'base64'`; the response’s `encoding` field is set to `'base64'` in that case. `absPath` is the resolved absolute path. `truncated` is set when the file was longer than the `maxBytes` cap and the contents were cut at that limit. -#### - -​ - -What `readFile()` can read +#### What `readFile()` can read `readFile()` serves a narrower set of files than the Read tool: @@ -1187,11 +951,7 @@ `Read` deny and ask rules still block a matching path, and a broad `Read` allow rule doesn’t open the rest of the filesystem to `readFile()`. For anything else the call resolves with `null`. -### - -​ - -`SDKControlReloadPluginsResponse` +### `SDKControlReloadPluginsResponse` Return type of `reloadPlugins()`. @@ -1228,11 +988,7 @@ `cache_impact` is present only alongside `held: true`. `mcp_servers_added` and `mcp_servers_removed` name the plugin MCP servers the reload would register or drop, as scoped `plugin:<plugin>:<server>` names. The names are plugin-authored, so validate them before showing them. `lsp_tool_change` says whether applying would add or remove the LSP tool, or `null` when it would do neither. The `may-` forms mean the check couldn’t fully see the pending plugin set. -#### - -​ - -Load more plugin folders with `addPlugins` +#### Load more plugin folders with `addPlugins` To load plugin folders that weren’t in the `plugins` option at startup, pass them to `reloadPlugins()` as `addPlugins`, a list of `SdkPluginConfig` entries whose `path` is absolute. Claude Code loads the new folders and reloads the session’s existing plugins in one pass. Each added plugin’s MCP servers connect too, unless you set `skipMcpDiscovery` on that folder’s entry. Requires Agent SDK v0.3.301 or later and Claude Code v2.1.301 or later. This example adds one folder to a running query `q` and prints the install path of every plugin the session has loaded when the call returns: @@ -1257,11 +1013,7 @@ * **The folder doesn’t exist or its plugin failed to load** : `result.error_count` is `1` or higher. The folder stays part of the session even so. After you fix the folder, call `reloadPlugins()` again to load it, this time without listing it in `addPlugins` * **The Claude Code executable is older than v2.1.301** : an executable older than v2.1.301 ignores `addPlugins` and reloads only the plugins the session already had. Check `claude_code_version` on the init message, and run an executable at v2.1.301 or later -### - -​ - -`SDKControlReloadSkillsResponse` +### `SDKControlReloadSkillsResponse` Return type of `reloadSkills()`. @@ -1271,11 +1023,7 @@ `skills` lists the skills available after the reload, in the same `SlashCommand` shape that `supportedCommands()` returns. -### - -​ - -`SDKControlReloadOutputStylesResponse` +### `SDKControlReloadOutputStylesResponse` Return type of `reloadOutputStyles()`. @@ -1285,11 +1033,7 @@ `available_output_styles` lists the names of the built-in and custom output styles available after the reload. -### - -​ - -`SDKControlMcpReadResourceResponse` +### `SDKControlMcpReadResourceResponse` Return type of `readMcpResource()`, carrying the MCP server’s `resources/read` result. Requires TypeScript Agent SDK v0.3.280 or later. @@ -1305,11 +1049,7 @@ Pass `readMcpResource()` the server name as `mcpServerStatus()` reports it and a `ui://` URI, such as the `ui.resourceUri` a tool declares in its `_meta`. The call rejects for any other URI scheme, for an SDK MCP server your application hosts itself, and for a server that isn’t connected. It’s available when the init message’s `capabilities` include `mcp_read_resource_v1`. Each `contents` entry is one content item as the server sent it, minus any `_meta` key under the `com.anthropic/` prefix, which is reserved for Claude Code. `blob` holds base64 data for a binary item, and `_meta` is the item’s own `_meta`, where an MCP Apps server puts the resource’s `ui.csp` and `ui.permissions`. The contents are untrusted third-party HTML, so render them in a sandbox. -### - -​ - -`AgentDefinition` +### `AgentDefinition` Configuration for a subagent defined programmatically. @@ -1351,11 +1091,7 @@ `permissionMode`| No| Permission mode for tool execution within this agent. The [subagent inheritance rules](</docs/en/agent-sdk/permissions#available-modes>) decide when it applies. See `PermissionMode` `criticalSystemReminder_EXPERIMENTAL`| No| Experimental: Critical reminder added to the system prompt -### - -​ - -`AgentMcpServerSpec` +### `AgentMcpServerSpec` Specifies MCP servers available to a subagent. Can be a server name (string referencing a server from the parent’s `mcpServers` config) or an inline server configuration record mapping server names to configs. @@ -1363,11 +1099,7 @@ Where `McpServerConfigForProcessTransport` is `McpStdioServerConfig | McpSSEServerConfig | McpHttpServerConfig | McpSdkServerConfig`. -### - -​ - -`SettingSource` +### `SettingSource` Controls which filesystem-based configuration sources the SDK loads settings from. @@ -1379,19 +1111,11 @@ `'project'`| Shared project settings (version controlled)| `.claude/settings.json` `'local'`| Local project settings, gitignored when Claude Code saves a setting to it| `.claude/settings.local.json` -#### - -​ - -Default behavior +#### Default behavior When `settingSources` is omitted or `undefined`, `query()` loads the same filesystem settings as the Claude Code CLI: user, project, and local. See [What settingSources does not control](</docs/en/agent-sdk/claude-code-features#what-settingsources-does-not-control>) for inputs that are read regardless of this option, and how to disable them. -#### - -​ - -Why use settingSources +#### Why use settingSources **Disable filesystem settings:** @@ -1417,11 +1141,7 @@ To load CLAUDE.md project instructions, include `"project"` in `settingSources`. See [Modify system prompts](</docs/en/agent-sdk/modifying-system-prompts#claude-md-files-for-project-level-instructions>) for how CLAUDE.md loading interacts with the system prompt options. -#### - -​ - -Settings precedence +#### Settings precedence When multiple sources are loaded, settings are merged with this precedence (highest to lowest): @@ -1431,11 +1151,7 @@ Programmatic options such as `agents`, `allowedTools`, and `settings` override user, project, and local filesystem settings. If a managed policy setting and a programmatic option set the same key, the managed value applies, with exceptions such as an `effortLevel` passed to `applyFlagSettings()`. -### - -​ - -`PermissionMode` +### `PermissionMode` type PermissionMode = | "default" // Standard permission behavior @@ -1445,11 +1161,7 @@ | "dontAsk" // Don't prompt for permissions, deny if not pre-approved | "auto"; // A model classifier reviews actions such as shell commands and network requests -### - -​ - -`CanUseTool` +### `CanUseTool` Custom permission function type for controlling tool usage. The function replaces the interactive permission prompt. The SDK calls `canUseTool` when the [permission evaluation flow](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) resolves to a prompt. Calls approved in either of these ways run without calling `canUseTool`: @@ -1490,11 +1202,7 @@ The callback normally resolves the request by returning a `PermissionResult`, which the SDK writes back over its transport as the `control_response`. Return `null` only when your application has already sent the `control_response` for this request over its own channel, echoing `requestId`; the SDK then skips writing the response to its transport. Returning `null` in any other case leaves the tool call blocked indefinitely, because no `control_response` is ever sent and permission prompts don’t time out. The `requestId` option and the `null` return value require Claude Code v2.1.199 or later. -### - -​ - -`PermissionResult` +### `PermissionResult` Result of a permission check. @@ -1514,11 +1222,7 @@ If you return `allow` with more than 4,096 items in `updatedPermissions`, Claude Code treats the result as invalid and denies the tool call. Each update counts as one item, and so does each entry in its `rules` or `directories` list. The denial message ends with `updatedPermissions may hold at most 4096 updates, rules and directories in all.` To have the call allowed, return 4,096 items or fewer. -### - -​ - -`ToolConfig` +### `ToolConfig` Configuration for built-in tool behavior. @@ -1532,11 +1236,7 @@ ---|---|--- `askUserQuestion.previewFormat`| `'markdown' | 'html'`| Opts into the `preview` field on [`AskUserQuestion`](</docs/en/agent-sdk/user-input#question-format>) options and sets its content format. When unset, Claude does not emit previews -### - -​ - -`McpServerConfig` +### `McpServerConfig` Configuration for MCP servers. @@ -1546,11 +1246,7 @@ | McpHttpServerConfig | McpSdkServerConfigWithInstance; -#### - -​ - -`McpStdioServerConfig` +#### `McpStdioServerConfig` type McpStdioServerConfig = { type?: "stdio"; @@ -1559,11 +1255,7 @@ env?: Record<string, string>; }; -#### - -​ - -`McpSSEServerConfig` +#### `McpSSEServerConfig` type McpSSEServerConfig = { type: "sse"; @@ -1571,11 +1263,7 @@ headers?: Record<string, string>; }; -#### - -​ - -`McpHttpServerConfig` +#### `McpHttpServerConfig` type McpHttpServerConfig = { type: "http"; @@ -1583,11 +1271,7 @@ headers?: Record<string, string>; }; -#### - -​ - -`McpSdkServerConfigWithInstance` +#### `McpSdkServerConfigWithInstance` Configuration for an in-process MCP server. It is what `createSdkMcpServer()` returns, plus an optional `tools` list of `McpServerToolPolicy` entries that you add. @@ -1644,11 +1328,7 @@ Include in that call your other in-process servers and any server an earlier `setMcpServers()` call added, or the call disconnects them. -#### - -​ - -`McpServerToolPolicy` +#### `McpServerToolPolicy` One entry in an `McpSdkServerConfigWithInstance`’s `tools` list, naming one of the server’s tools and setting the permission policy for calls to that tool. The list requires Agent SDK v0.3.301 or later and Claude Code v2.1.301 or later. An older Claude Code executable, such as an executable you point `pathToClaudeCodeExecutable` at, ignores the list. Then `always_ask` and `always_deny` aren’t enforced, and each call goes through the [permission flow](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>). @@ -1683,11 +1363,7 @@ Set `destructiveHint` to `true` explicitly in `auto` and `plan` mode. For `always_ask` calls, Claude Code reads an unset `destructiveHint` as `false`, although the default listed under `ToolAnnotations` is `true`. -#### - -​ - -`McpClaudeAIProxyServerConfig` +#### `McpClaudeAIProxyServerConfig` type McpClaudeAIProxyServerConfig = { type: "claudeai-proxy"; @@ -1695,11 +1371,7 @@ id: string; }; -### - -​ - -`SdkPluginConfig` +### `SdkPluginConfig` Configuration for loading plugins in the SDK. @@ -1724,17 +1396,9 @@ For complete information on creating and using plugins, see [Plugins](</docs/en/agent-sdk/plugins>). -## - -​ - -Message Types - -### - -​ - -`SDKMessage` +## Message Types + +### `SDKMessage` Union type of all possible messages returned by the query. @@ -1785,11 +1449,7 @@ * `SDKModelRefusalFallbackMessage`, `subtype: "model_refusal_fallback"`: emitted when the model ends the stream with a refusal and the turn is retried on a fallback model. Carries `original_model` and `fallback_model`. Requires Agent SDK v0.3.170 or later. * `SDKModelRefusalNoFallbackMessage`, `subtype: "model_refusal_no_fallback"`: emitted when the model ends the stream with a refusal and no retry runs, for example because no fallback model is configured. Carries `original_model`. Requires Agent SDK v0.3.193 or later. -### - -​ - -`SDKAssistantMessage` +### `SDKAssistantMessage` Assistant response message. @@ -1825,11 +1485,7 @@ 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. -### - -​ - -`SDKUserMessage` +### `SDKUserMessage` User input message. @@ -1885,11 +1541,7 @@ * Tools from [in-process SDK servers](</docs/en/agent-sdk/custom-tools>) are exempt and deliver the object whole. * A tool whose `tools/list` entry declares an MCP Apps `ui://` resource has a limit of 8,388,608 characters on Claude Code v2.1.295 or later, and versions before v2.1.295 exempt it. -### - -​ - -`SDKUserMessageReplay` +### `SDKUserMessageReplay` Replayed user message with required UUID. @@ -1908,11 +1560,7 @@ A user turn injected from outside the session, one whose `origin` kind is `peer` or `channel`, reaches the stream as a replay whether it was delivered during an active turn or started a new turn while the session was idle. Before v2.1.207, an injected turn delivered while the session was idle produced no message on the stream and only appeared when you re-read the transcript. -### - -​ - -`SDKResultMessage` +### `SDKResultMessage` Final result message. @@ -2041,11 +1689,7 @@ When a `PreToolUse` hook returns `permissionDecision: "defer"`, the result has `stop_reason: "tool_deferred"` and `deferred_tool_use` carries the pending tool’s `id`, `name`, and `input`. Read this field to surface the request in your own UI, then resume with the same `session_id` to continue. See [Defer a tool call for later](</docs/en/hooks#defer-a-tool-call-for-later>) for the full round trip. -#### - -​ - -`user_message_uuid` +#### `user_message_uuid` The `uuid` of the `SDKUserMessage` the turn is answering, echoed so you can match Claude Code’s reply to the message you sent. Claude Code echoes a `uuid` only if you set one on the message. The field is optional on `SDKUserMessage`, and a string prompt passed to `query()` carries none. Which of your messages a turn answers depends on how the turn started: @@ -2069,19 +1713,11 @@ When a [`UserPromptSubmit`](</docs/en/hooks#userpromptsubmit>) hook blocks a message that starts its own turn, or stops it with `continue: false`, you still get a result for that message. It’s a success result with `is_error: false` and `num_turns: 0`, its `result` is the [block message](</docs/en/hooks#what-a-blocked-prompt-leaves-behind>) or [stop message](</docs/en/hooks#json-output>), and it echoes the message’s `uuid` under the same rules as any other result. The result has no `terminal_reason`, and nothing on it besides the `result` text says a hook ended the turn. A message that a hook blocks while another turn is running may get no result: see `user_message_uuids`. -#### - -​ - -`user_message_uuids` +#### `user_message_uuids` The `uuid`s of every message you sent that Claude Code answered in this turn. When you send several messages close together, Claude Code can merge them into one turn, and `user_message_uuid` then names only the last of them. To match the reply to any of the merged messages, look for that message’s `uuid` anywhere in this list. Requires Agent SDK v0.3.259 or later. Claude Code sets the list together with `user_message_uuid` on each reply frame that carries that field and on the result. For the full set of turn frames that echo the answered message’s `uuid`, and the version each requires, see `user_message_uuid`. The list always contains `user_message_uuid` and holds at most 64 entries. When Claude Code picks up a regular message you sent while a turn was running, it adds that message’s `uuid` to the result’s list. When a [`UserPromptSubmit`](</docs/en/hooks#userpromptsubmit>) hook blocks the message at pickup, Claude Code drops it instead: the message never reaches Claude and isn’t kept for a later turn. You get no result for it, and its `uuid` appears in no result’s list. If a hook can block messages, set a timeout on waiting for a result that lists a message you sent while a turn was running. That holds when the hook’s output is a block alone. If the output sets `continue: false`, even beside `decision: "block"`, or the hook is a prompt hook that answers [`ok: false`](</docs/en/hooks#response-schema>) without `continueOnBlock: true`, Claude Code stops the message instead of dropping it. The message waits for its own turn, you get a result for it, and its text stays in the conversation, so Claude sees it on the next turn. When a first reply or result carries `user_message_uuid` without the list, it came from an earlier Claude Code version, so fall back to the single field. -#### - -​ - -`resume_reason` +#### `resume_reason` 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: @@ -2090,22 +1726,14 @@ The value is a short lowercase token, such as `interrupted_turn`. -#### - -​ - -`queued_turn_count` +#### `queued_turn_count` The number of messages you sent with `origin: { kind: "human" }` that are still waiting in the command queue when Claude Code produced the result. Requires Agent SDK v0.3.242 or later. What `0` and an absent field tell you: * **`0`** : Claude Code doesn’t count messages you sent without that `origin`, and doesn’t count task notifications, so a turn can still follow. * **Absent** : the final result that Claude Code emits after a crash or fatal startup error omits the field, and [may carry zeroed totals](</docs/en/agent-sdk/cost-tracking#recover-totals-after-a-session-crash>). -#### - -​ - -`startup_failure_reason` +#### `startup_failure_reason` Why Claude Code refused to start, so your application can offer the fix instead of a retry. Claude Code sets it on the `error_during_execution` result it writes before exiting on a known startup failure. That result carries zeroed totals, and its `errors` array carries the failure message. The field is absent on every other result. Requires Agent SDK v0.3.274 or later. Set `CLAUDE_CODE_STARTUP_FAILURE_RESULTS` to `1` in `env` to receive this result for every `SDKStartupFailureReason` value. Without that variable, Claude Code writes the result only for these failures, and the rest end with stderr output, a non-zero exit, and no result message: @@ -2165,11 +1793,7 @@ `sandbox_required_unavailable`| `failIfUnavailable` is on and the sandbox can’t start. The text in `errors` ends with `Set sandbox.failIfUnavailable=false to allow unsandboxed execution.` Requires Agent SDK v0.3.314 or later `config_file_invalid`| `~/.claude.json` isn’t valid JSON. Claude Code leaves the file unchanged, so a retry fails the same way until someone repairs it. `errors` names the file and says how to restore or repair it. See [Configuration error in ~/.claude.json](</docs/en/errors#configuration-error-in-claude-json>). Requires TypeScript Agent SDK v0.3.318 or later and Claude Code v2.1.318 or later -### - -​ - -`SDKSystemMessage` +### `SDKSystemMessage` System initialization message. @@ -2231,11 +1855,7 @@ `message`| `string`| Display text describing the failure `path`| `string`| Present only when the plugin directory or archive itself failed to load. Its absolute path, with a relative path from your `plugins` option resolved against the `cwd` option -### - -​ - -`SDKPartialAssistantMessage` +### `SDKPartialAssistantMessage` Streaming partial message (only when `includePartialMessages` is true). The `parent_tool_use_id` field is always `null`: stream events are emitted for the main session only. For subagent attribution, use complete messages, which carry `agent_id` and `parent_tool_use_id`, or enable `forwardSubagentText` to receive subagent text and thinking as complete messages. @@ -2253,11 +1873,7 @@ 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`. -### - -​ - -`SDKCompactBoundaryMessage` +### `SDKCompactBoundaryMessage` Message indicating a conversation compaction boundary. @@ -2272,11 +1888,7 @@ }; }; -### - -​ - -`SDKInformationalMessage` +### `SDKInformationalMessage` Generic text banner emitted by the loop. Carries warnings, notices, and other non-error status lines Claude Code raises, and hook feedback such as a `UserPromptSubmit` hook’s block reason. On Claude Code v2.1.227 or later, a hook’s [`systemMessage`](</docs/en/hooks#json-output>) can arrive as this message, with each line prefixed by the hook’s name, such as `PostToolUse:Bash says:`. Each [event’s section](</docs/en/hooks#hook-events>) on the hooks page says how output surfaces. Render `content` as plaintext at the given `level`. @@ -2292,11 +1904,7 @@ session_id: string; }; -### - -​ - -`SDKWorkerShuttingDownMessage` +### `SDKWorkerShuttingDownMessage` Emitted on graceful worker teardown so remote clients can show why the worker exited instead of waiting for heartbeat timeout. The `reason` is a short snake_case string set by the host CLI, such as `"host_exit"` or `"remote_control_disabled"`. Act on this only when streaming live. A resumed session replays past instances of this message, so ignore them in that case. @@ -2308,11 +1916,7 @@ session_id: string; }; -### - -​ - -`SDKPluginInstallMessage` +### `SDKPluginInstallMessage` Plugin installation progress event. Emitted when [`CLAUDE_CODE_SYNC_PLUGIN_INSTALL`](</docs/en/env-vars>) is set, so your Agent SDK application can track marketplace plugin installation before the first turn. The `started` and `completed` statuses bracket the overall install. The `installed` and `failed` statuses report individual marketplaces and include `name`. @@ -2326,11 +1930,7 @@ session_id: string; }; -### - -​ - -`SDKPermissionDeniedMessage` +### `SDKPermissionDeniedMessage` Stream event emitted when the permission system denies a tool call without an interactive prompt. Use it to render the denial in your UI as it happens, rather than only observing the `is_error` tool result that follows. Which denials it reports depends on how the run handles permission prompts: @@ -2363,11 +1963,7 @@ `decision_reason`| `string`| Human-readable reason from the deciding component, when available `message`| `string`| Rejection message returned to the model in the `tool_result` -### - -​ - -`SDKPermissionDenial` +### `SDKPermissionDenial` Information about a denied tool use. @@ -2377,11 +1973,7 @@ tool_input: Record<string, unknown>; }; -### - -​ - -`SDKContextUsage` +### `SDKContextUsage` Structured form of the `/context` report, carried as `context_usage` on the `SDKAssistantMessage` that delivers a `/context` result. Agent SDK v0.3.232 and later export the type. Unlike `SDKControlGetContextUsageResponse`, it carries only the data needed to render the usage breakdown, without display fields such as `color` and `gridRows`. Claude Code computes the report with token-counting API requests that don’t appear in the message stream; see how these requests are handled. @@ -2440,11 +2032,7 @@ Claude Code evolves the type additively, adding new data as optional fields rather than reshaping existing ones. Read the fields you know and ignore any you don’t recognize. -### - -​ - -`SDKContextUsageCategory` +### `SDKContextUsageCategory` One row of the `/context` usage-by-category breakdown. @@ -2469,11 +2057,7 @@ * `buffer`: the compaction reserve * `deferred`: tool schemas Claude Code holds out of the window and excludes from the usage calculation, listed for awareness -### - -​ - -`SDKUsageReport` +### `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. @@ -2538,11 +2122,7 @@ * `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. -### - -​ - -`SDKMessageOrigin` +### `SDKMessageOrigin` Provenance of a user-role message. This appears as `origin` on `SDKUserMessage`. The `SDKResultMessage` for a turn carries the `origin` that Claude Code assigned, so you can tell what triggered that turn. @@ -2586,11 +2166,7 @@ `auto-continuation`| Synthetic turn injected when the session continues without fresh user input, such as a command result that triggers a follow-up prompt. `unclassified`| Message marked as not coming from the user, such as an `SDKUserMessage` you send with `isSynthetic: true`. Requires Claude Code v2.1.223 or later. -### - -​ - -Task-notification subkinds +### Task-notification subkinds When Claude Code delivers a task notification into a session, it sets `subkind` on the notification’s `origin` if Anthropic servers verified where that notification came from. It also sets `subkind` when your application declares the message as a scheduled run itself, which requires TypeScript Agent SDK v0.3.280 or later. `subkind` requires Claude Code v2.1.213 or later, and it takes one of two values: @@ -2599,19 +2175,11 @@ Every other task notification has no `subkind`. That includes [PR activity](</docs/en/claude-code-on-the-web#how-claude-responds-to-pr-activity>) delivered into a session and background events such as a finished task. Messages from the [cross-session `SendMessage` tool](</docs/en/cross-session-messaging>) aren’t task notifications at all: whether they come from a session on the same machine or through Anthropic servers from another machine, Claude Code gives them `kind: "peer"` and the peer origin fields. `fireReason` says why a `scheduled-trigger` notification fired, as a short lowercase token such as `scheduled`, `manual`, `retry`, `catch_up`, or `api`. Anthropic servers set it on a [cloud scheduled task](</docs/en/routines>)’s deliveries, and your application sets it when it declares a scheduled run. It’s absent when neither sent one. Requires TypeScript Agent SDK v0.3.280 or later. A background task can run more than once under the same `task_id`, such as when Claude [resumes a subagent](</docs/en/agent-sdk/subagents#resume-subagents>). Each run has its own `run_id`. When a run’s notification reaches your session as a user message, `runId` on that message’s `task-notification` origin holds the same value. A notification can arrive after the task’s next run has started, and it still carries the earlier run’s ID. To tell which run a turn belongs to, compare `runId`, not `task_id`. Requires TypeScript Agent SDK v0.3.292 or later. -#### - -​ - -Declare a scheduled run +#### Declare a scheduled run If your application runs prompts on its own schedule, declare each run so Claude Code frames the turn to the model as a scheduled task rather than as live input from the user. Start the session with `CLAUDE_CODE_HOST_SCHEDULED_RUN` set to `1` in `env`, then send the run’s `SDKUserMessage` with `origin: { kind: "task-notification", subkind: "scheduled-trigger", fireReason: "scheduled" }` and without `isSynthetic`. Claude Code ignores the declaration in a process started without that variable. It also ignores it in a process whose environment carries [`CLAUDECODE`](</docs/en/env-vars>) or `CLAUDE_CODE_CHILD_SESSION`. Claude Code keeps `fireReason` only when the value is 1 to 32 lowercase letters or underscores. Requires TypeScript Agent SDK v0.3.280 or later. -### - -​ - -Peer origin fields +### Peer origin fields A `peer` origin identifies which agent sent the message: an in-process [teammate](</docs/en/agent-teams>) sending to `main` with `SendMessage`, or a [cross-session peer](</docs/en/cross-session-messaging>), another of your Claude Code sessions. Cross-session peers require Claude Code v2.1.224 or later on macOS and Linux; see [cross-session messaging availability](</docs/en/cross-session-messaging#availability>) for the native Windows requirement. A cross-session peer can run on the same machine, or on [another of your machines](</docs/en/cross-session-messaging#message-sessions-on-other-machines>) when its message arrives through [Remote Control](</docs/en/remote-control>). @@ -2623,19 +2191,11 @@ * `fromSession`: the sender’s host-openable session ID, set by the sender’s host so your UI can link back to the sending session. Like `from`, it is sender-asserted: use it as a navigation target only, and don’t treat it as proof of the sender’s identity. Requires Claude Code v2.1.216 or later. * `verifiedPeerPid`: the process ID of the process that connected to this session’s cross-session messaging socket, verified by the kernel and read from the connection itself, never from the payload. Use it, not `from`, to identify the sender: `from` is forgeable by any same-user process. The field is absent when Claude Code can’t verify it, such as on Windows or non-socket ingress, so an absent value means the sender is unverified. For relayed traffic it identifies the relay rather than the message’s author, and process IDs are recyclable, so treat it as provenance rather than an authentication token. Requires Claude Code v2.1.216 or later. -## - -​ - -Hook Types +## Hook Types For a guide on using hooks with examples and common patterns, see the [Hooks guide](</docs/en/agent-sdk/hooks>). -### - -​ - -`HookEvent` +### `HookEvent` Available hook events. @@ -2674,11 +2234,7 @@ | "FileChanged" | "MessageDisplay"; -### - -​ - -`HookCallback` +### `HookCallback` Hook callback function type. @@ -2688,11 +2244,7 @@ options: { signal: AbortSignal } ) => Promise<HookJSONOutput>; -### - -​ - -`HookCallbackMatcher` +### `HookCallbackMatcher` Hook configuration with optional matcher. @@ -2705,11 +2257,7 @@ To decide what `onFailure` covers, see [Block the action when a callback fails](</docs/en/agent-sdk/hooks#block-the-action-when-a-callback-fails>). -### - -​ - -`HookInput` +### `HookInput` Union type of all hook input types. @@ -2748,11 +2296,7 @@ | FileChangedHookInput | MessageDisplayHookInput; -### - -​ - -`BaseHookInput` +### `BaseHookInput` Base interface that all hook input types extend. @@ -2769,11 +2313,7 @@ The `prompt_id` field is a UUID identifying the user prompt currently being processed. It matches the [`prompt.id` attribute on OpenTelemetry events](</docs/en/monitoring-usage#event-correlation-attributes>) and is absent until the first user input. Requires Claude Code v2.1.196 or later. -#### - -​ - -`PreToolUseHookInput` +#### `PreToolUseHookInput` type PreToolUseHookInput = BaseHookInput & { hook_event_name: "PreToolUse"; @@ -2785,11 +2325,7 @@ `mcp_server` is present when the tool comes from an MCP server; see `McpServerProvenance`. The `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied` inputs carry the same field. The field requires Agent SDK v0.3.274 or later. -#### - -​ - -`PostToolUseHookInput` +#### `PostToolUseHookInput` type PostToolUseHookInput = BaseHookInput & { hook_event_name: "PostToolUse"; @@ -2801,11 +2337,7 @@ mcp_server?: McpServerProvenance; }; -#### - -​ - -`PostToolUseFailureHookInput` +#### `PostToolUseFailureHookInput` type PostToolUseFailureHookInput = BaseHookInput & { hook_event_name: "PostToolUseFailure"; @@ -2818,11 +2350,7 @@ mcp_server?: McpServerProvenance; }; -#### - -​ - -`PostToolBatchHookInput` +#### `PostToolBatchHookInput` Fires once after every tool call in a batch has resolved, before the next model request. `tool_response` carries the serialized `tool_result` content the model sees; the shape differs from `PostToolUseHookInput`’s structured `Output` object. @@ -2838,11 +2366,7 @@ tool_response?: unknown; }; -#### - -​ - -`PermissionDeniedHookInput` +#### `PermissionDeniedHookInput` type PermissionDeniedHookInput = BaseHookInput & { hook_event_name: "PermissionDenied"; @@ -2853,11 +2377,7 @@ mcp_server?: McpServerProvenance; }; -#### - -​ - -`NotificationHookInput` +#### `NotificationHookInput` type NotificationHookInput = BaseHookInput & { hook_event_name: "Notification"; @@ -2866,11 +2386,7 @@ notification_type: string; }; -#### - -​ - -`UserPromptSubmitHookInput` +#### `UserPromptSubmitHookInput` type UserPromptSubmitHookInput = BaseHookInput & { hook_event_name: "UserPromptSubmit"; @@ -2878,11 +2394,7 @@ session_title?: string; }; -#### - -​ - -`UserPromptExpansionHookInput` +#### `UserPromptExpansionHookInput` type UserPromptExpansionHookInput = BaseHookInput & { hook_event_name: "UserPromptExpansion"; @@ -2893,11 +2405,7 @@ prompt: string; }; -#### - -​ - -`SessionStartHookInput` +#### `SessionStartHookInput` type SessionStartHookInput = BaseHookInput & { hook_event_name: "SessionStart"; @@ -2907,22 +2415,14 @@ session_title?: string; }; -#### - -​ - -`SessionEndHookInput` +#### `SessionEndHookInput` type SessionEndHookInput = BaseHookInput & { hook_event_name: "SessionEnd"; reason: ExitReason; // String from EXIT_REASONS array }; -#### - -​ - -`StopHookInput` +#### `StopHookInput` type StopHookInput = BaseHookInput & { hook_event_name: "Stop"; @@ -2932,11 +2432,7 @@ session_crons?: SessionCronSummary[]; }; -#### - -​ - -`StopFailureHookInput` +#### `StopFailureHookInput` type StopFailureHookInput = BaseHookInput & { hook_event_name: "StopFailure"; @@ -2945,11 +2441,7 @@ last_assistant_message?: string; }; -#### - -​ - -`SubagentStartHookInput` +#### `SubagentStartHookInput` type SubagentStartHookInput = BaseHookInput & { hook_event_name: "SubagentStart"; @@ -2957,11 +2449,7 @@ agent_type: string; }; -#### - -​ - -`SubagentStopHookInput` +#### `SubagentStopHookInput` type SubagentStopHookInput = BaseHookInput & { hook_event_name: "SubagentStop"; @@ -2993,11 +2481,7 @@ prompt: string; }; -#### - -​ - -`PreCompactHookInput` +#### `PreCompactHookInput` type PreCompactHookInput = BaseHookInput & { hook_event_name: "PreCompact"; @@ -3005,11 +2489,7 @@ custom_instructions: string | null; }; -#### - -​ - -`PostCompactHookInput` +#### `PostCompactHookInput` type PostCompactHookInput = BaseHookInput & { hook_event_name: "PostCompact"; @@ -3017,11 +2497,7 @@ compact_summary: string; }; -#### - -​ - -`PreModelSwitchHookInput` +#### `PreModelSwitchHookInput` Fires before a requested model switch takes effect. `context_tokens` and the fields after it estimate what re-sending the conversation to the new model costs. For the full field descriptions and blocking semantics, see [PreModelSwitch](</docs/en/hooks#premodelswitch>). @@ -3038,11 +2514,7 @@ pricing: "configured" | "catalog" | "default"; }; -#### - -​ - -`PostModelSwitchHookInput` +#### `PostModelSwitchHookInput` Fires after the session’s model changes. It carries the same fields as `PreModelSwitchHookInput`, with two more `source` values. See [PostModelSwitch](</docs/en/hooks#postmodelswitch>). @@ -3059,11 +2531,7 @@ pricing: "configured" | "catalog" | "default"; }; -#### - -​ - -`PermissionRequestHookInput` +#### `PermissionRequestHookInput` type PermissionRequestHookInput = BaseHookInput & { hook_event_name: "PermissionRequest"; @@ -3073,22 +2541,14 @@ mcp_server?: McpServerProvenance; }; -#### - -​ - -`SetupHookInput` +#### `SetupHookInput` type SetupHookInput = BaseHookInput & { hook_event_name: "Setup"; trigger: "init" | "maintenance"; }; -#### - -​ - -`TeammateIdleHookInput` +#### `TeammateIdleHookInput` type TeammateIdleHookInput = BaseHookInput & { hook_event_name: "TeammateIdle"; @@ -3097,11 +2557,7 @@ team_name: string; }; -#### - -​ - -`TaskCreatedHookInput` +#### `TaskCreatedHookInput` type TaskCreatedHookInput = BaseHookInput & { hook_event_name: "TaskCreated"; @@ -3113,11 +2569,7 @@ team_name?: string; }; -#### - -​ - -`TaskCompletedHookInput` +#### `TaskCompletedHookInput` type TaskCompletedHookInput = BaseHookInput & { hook_event_name: "TaskCompleted"; @@ -3129,11 +2581,7 @@ team_name?: string; }; -#### - -​ - -`ElicitationHookInput` +#### `ElicitationHookInput` type ElicitationHookInput = BaseHookInput & { hook_event_name: "Elicitation"; @@ -3145,11 +2593,7 @@ requested_schema?: Record<string, unknown>; }; -#### - -​ - -`ElicitationResultHookInput` +#### `ElicitationResultHookInput` type ElicitationResultHookInput = BaseHookInput & { hook_event_name: "ElicitationResult"; @@ -3160,11 +2604,7 @@ content?: Record<string, unknown>; }; -#### - -​ - -`ConfigChangeHookInput` +#### `ConfigChangeHookInput` type ConfigChangeHookInput = BaseHookInput & { hook_event_name: "ConfigChange"; @@ -3177,11 +2617,7 @@ file_path?: string; }; -#### - -​ - -`InstructionsLoadedHookInput` +#### `InstructionsLoadedHookInput` type InstructionsLoadedHookInput = BaseHookInput & { hook_event_name: "InstructionsLoaded"; @@ -3198,11 +2634,7 @@ parent_file_path?: string; }; -#### - -​ - -`DirectoryAddedHookInput` +#### `DirectoryAddedHookInput` type DirectoryAddedHookInput = BaseHookInput & { hook_event_name: "DirectoryAdded"; @@ -3212,33 +2644,21 @@ `directory` is the absolute path of the directory that was added. `source` is `"slash_command"` when `/add-dir` added it and `"register_repo_root"` when the SDK control request did. -#### - -​ - -`WorktreeCreateHookInput` +#### `WorktreeCreateHookInput` type WorktreeCreateHookInput = BaseHookInput & { hook_event_name: "WorktreeCreate"; name: string; }; -#### - -​ - -`WorktreeRemoveHookInput` +#### `WorktreeRemoveHookInput` type WorktreeRemoveHookInput = BaseHookInput & { hook_event_name: "WorktreeRemove"; worktree_path: string; }; -#### - -​ - -`CwdChangedHookInput` +#### `CwdChangedHookInput` type CwdChangedHookInput = BaseHookInput & { hook_event_name: "CwdChanged"; @@ -3246,11 +2666,7 @@ new_cwd: string; }; -#### - -​ - -`FileChangedHookInput` +#### `FileChangedHookInput` type FileChangedHookInput = BaseHookInput & { hook_event_name: "FileChanged"; @@ -3258,11 +2674,7 @@ event: "change" | "add" | "unlink"; }; -#### - -​ - -`MessageDisplayHookInput` +#### `MessageDisplayHookInput` type MessageDisplayHookInput = BaseHookInput & { hook_event_name: "MessageDisplay"; @@ -3273,32 +2685,20 @@ delta: string; }; -### - -​ - -`HookJSONOutput` +### `HookJSONOutput` Hook return value. type HookJSONOutput = AsyncHookJSONOutput | SyncHookJSONOutput; -#### - -​ - -`AsyncHookJSONOutput` +#### `AsyncHookJSONOutput` type AsyncHookJSONOutput = { async: true; asyncTimeout?: number; }; -#### - -​ - -`SyncHookJSONOutput` +#### `SyncHookJSONOutput` type SyncHookJSONOutput = { continue?: boolean; @@ -3452,19 +2852,11 @@ }; }; -## - -​ - -Tool Input Types +## Tool Input Types Documentation of input schemas for built-in Claude Code tools. These types are exported from `@anthropic-ai/claude-agent-sdk/sdk-tools` and can be used for type-safe tool interactions. The `StructuredOutput` tool has no type here: Claude Code builds its input schema from the schema you pass to `outputFormat`, so there is nothing fixed to export. See [Recognize the StructuredOutput tool call](</docs/en/agent-sdk/structured-outputs#recognize-the-structuredoutput-tool-call>) for what that call looks like in your message stream. -### - -​ - -`ToolInputSchemas` +### `ToolInputSchemas` Union of tool input types exported from `@anthropic-ai/claude-agent-sdk/sdk-tools`; members include: @@ -3508,11 +2900,7 @@ | WebSearchInput | WorkflowInput; -### - -​ - -Agent +### Agent **Tool name:** `Agent`. The previous name `Task` is still accepted as an alias when this tool is available to the session. The `tools` array in the `SDKSystemMessage` init message lists this tool as `Task` for backward compatibility. @@ -3533,11 +2921,7 @@ Launches a new agent to handle complex, multi-step tasks autonomously. -### - -​ - -AskUserQuestion +### AskUserQuestion **Tool name:** `AskUserQuestion` @@ -3555,11 +2939,7 @@ Asks the user clarifying questions during execution. See [Handle approvals and user input](</docs/en/agent-sdk/user-input#handle-clarifying-questions>) for usage details. -### - -​ - -Bash +### Bash **Tool name:** `Bash` @@ -3573,11 +2953,7 @@ Executes Bash commands with optional timeout and background execution. The working directory persists between commands, including commands run in later turns of a multi-turn session; shell state such as exported environment variables doesn’t. For the limits on which directory changes carry over, see [What persists between commands](</docs/en/tools-reference#what-persists-between-commands>). For what sets the foreground ceiling, see [Timeout and output limits](</docs/en/tools-reference#timeout-and-output-limits>). For the background time limit, see [Time limit for background commands](</docs/en/tools-reference#time-limit-for-background-commands>). -### - -​ - -Monitor +### Monitor **Tool name:** `Monitor` @@ -3599,19 +2975,11 @@ When Monitor runs a command, it follows the same permission rules as Bash. See the [Monitor tool reference](</docs/en/tools-reference#monitor-tool>) for WebSocket permissions, behavior, and provider availability. -### - -​ - -TaskOutput +### TaskOutput Removed in Claude Code v2.1.277, together with its `TaskOutputInput` type. Previously retrieved output from a running or completed background task; Claude reads a background task’s output file with `Read` instead. A `disallowedTools` entry or a deny rule that still names `TaskOutput` is ignored without a warning. -### - -​ - -Edit +### Edit **Tool name:** `Edit` @@ -3624,11 +2992,7 @@ Performs exact string replacements in files. -### - -​ - -Read +### Read **Tool name:** `Read` @@ -3647,11 +3011,7 @@ For a PDF, Claude receives the file’s contents inside the Read call’s `tool_result` content. A read that returns the `pdf` output carries a summary `text` block followed by a `document` block. One that returns the `parts` output carries the summary `text` block followed by one block per extracted page: an `image` block, or a `text` block naming the page when Claude Code couldn’t render it as an image. Before Agent SDK v0.3.242, Claude Code delivered the file’s contents as a separate `user` message after the tool result. -### - -​ - -Write +### Write **Tool name:** `Write` @@ -3662,11 +3022,7 @@ Writes a file to the local filesystem, overwriting if it exists. -### - -​ - -Glob +### Glob **Tool name:** `Glob` @@ -3677,11 +3033,7 @@ Fast file pattern matching that works with any codebase size. -### - -​ - -Grep +### Grep **Tool name:** `Grep` @@ -3705,11 +3057,7 @@ Search tool built on ripgrep with regex support. -### - -​ - -TaskStop +### TaskStop **Tool name:** `TaskStop` @@ -3720,11 +3068,7 @@ Stops a running background task or shell by ID. As of v2.1.198, `task_id` also accepts an agent-team teammate or a named background agent by agent ID or name. -### - -​ - -NotebookEdit +### NotebookEdit **Tool name:** `NotebookEdit` @@ -3738,11 +3082,7 @@ Edits cells in Jupyter notebook files. -### - -​ - -WebFetch +### WebFetch **Tool name:** `WebFetch` @@ -3754,11 +3094,7 @@ Fetches content from a URL and processes it with an AI model. `offset` is the number of characters to skip from the start of the page. Claude sets it to keep reading a long page. The field requires Agent SDK v0.3.290 or later. -### - -​ - -WebSearch +### WebSearch **Tool name:** `WebSearch` @@ -3770,11 +3106,7 @@ Searches the web and returns formatted results. -### - -​ - -Workflow +### Workflow **Tool name:** `Workflow` @@ -3800,11 +3132,7 @@ `title`| `string`| Ignored; the script’s `meta` block sets the title `description`| `string`| Ignored; the script’s `meta` block sets the description -### - -​ - -TodoWrite +### TodoWrite **Tool name:** `TodoWrite` @@ -3826,13 +3154,9 @@ * `TaskUpdate` * `TaskList` -Wherever the tools are available, Claude Code provides the four Task tools, or `TodoWrite` instead when you set `CLAUDE_CODE_ENABLE_TASKS=0`.This default set applies in Claude Code v2.1.268 and later, which the TypeScript Agent SDK bundles from v0.3.268.See [Model availability](</docs/en/agent-sdk/todo-tracking#model-availability>) to opt in. - -### - -​ - -TaskCreate +Wherever the tools are available, Claude Code provides the four Task tools, or `TodoWrite` instead when you set `CLAUDE_CODE_ENABLE_TASKS=0`. This default set applies in Claude Code v2.1.268 and later, which the TypeScript Agent SDK bundles from v0.3.268.See [Model availability](</docs/en/agent-sdk/todo-tracking#model-availability>) to opt in. + +### TaskCreate **Tool name:** `TaskCreate` @@ -3845,11 +3169,7 @@ Creates a single task and returns its assigned ID. -### - -​ - -TaskUpdate +### TaskUpdate **Tool name:** `TaskUpdate` @@ -3867,11 +3187,7 @@ Patches one task by ID. Set `status` to `"deleted"` to remove it. -### - -​ - -TaskGet +### TaskGet **Tool name:** `TaskGet` @@ -3881,11 +3197,7 @@ Returns full details for one task, or `null` when the ID is not found. -### - -​ - -TaskList +### TaskList **Tool name:** `TaskList` @@ -3893,11 +3205,7 @@ Returns a snapshot of all tasks in the current list. -### - -​ - -ExitPlanMode +### ExitPlanMode **Tool name:** `ExitPlanMode` @@ -3912,11 +3220,7 @@ Exits plan mode. The `allowedPrompts` field is deprecated and ignored; Claude Code still accepts it so existing callers and transcripts validate. Before v2.1.205, it requested prompt-based Bash permissions for implementing the plan. -### - -​ - -ListMcpResources +### ListMcpResources **Tool name:** `ListMcpResourcesTool` @@ -3926,11 +3230,7 @@ Lists available MCP resources from connected servers. -### - -​ - -ReadMcpResource +### ReadMcpResource **Tool name:** `ReadMcpResourceTool` @@ -3941,11 +3241,7 @@ Reads a specific MCP resource from a server. -### - -​ - -EnterWorktree +### EnterWorktree **Tool name:** `EnterWorktree` @@ -3956,11 +3252,7 @@ Creates and enters a temporary git worktree for isolated work. Pass `path` to switch into an existing worktree instead of creating a new one. On first entry the target must be a registered worktree of the current repository or, in a multi-repo workspace, of a repository nested inside it; from within a worktree session it must be under `.claude/worktrees/` of the session’s repository. `name` and `path` are mutually exclusive. -### - -​ - -ExitWorktree +### ExitWorktree **Tool name:** `ExitWorktree` @@ -3971,11 +3263,7 @@ Exits the current git worktree and returns to the original working directory. The `keep` action leaves the worktree and branch on disk, while `remove` deletes both. `discard_changes` must be `true` when removing a worktree that has uncommitted files or unmerged commits. -### - -​ - -EnterPlanMode +### EnterPlanMode **Tool name:** `EnterPlanMode` @@ -3983,11 +3271,7 @@ Enters plan mode, where Claude researches and presents a plan before making changes. -### - -​ - -CronCreate +### CronCreate **Tool name:** `CronCreate` @@ -4000,11 +3284,7 @@ Schedules a prompt to run on a 5-field cron schedule in local time. Set `recurring` to `false` to fire once at the next match. Jobs are session-scoped by default, and resuming with `--resume` or `--continue` restores jobs that haven’t expired. See [Session-scoped scheduled tasks](</docs/en/scheduled-tasks>). Setting `durable` to `true` requests persistence to `.claude/scheduled_tasks.json` so the job survives restarts. Durable scheduling isn’t available in every session: when it isn’t, Claude Code accepts `durable: true` but creates the job session-only. Read the output’s `durable` field to see whether the job persisted. -### - -​ - -CronDelete +### CronDelete **Tool name:** `CronDelete` @@ -4014,11 +3294,7 @@ Deletes a scheduled cron job by the ID returned from `CronCreate`. -### - -​ - -CronList +### CronList **Tool name:** `CronList` @@ -4026,11 +3302,7 @@ Lists the scheduled cron jobs: durable jobs from `.claude/scheduled_tasks.json` and session-only jobs from the current session. -### - -​ - -ScheduleWakeup +### ScheduleWakeup **Tool name:** `ScheduleWakeup` @@ -4044,11 +3316,7 @@ Schedules a one-shot wake-up that fires the given prompt after a delay. This tool backs the self-paced `/loop` command. The runtime clamps `delaySeconds` to between 60 and 3600 seconds. The `delaySeconds`, `reason`, `prompt`, and `noop` fields are required unless `stop` is true. `noop: true` reports a wake-up where nothing changed. Setting `stop: true` cancels the pending wakeup and ends the self-paced `/loop`. The `stop` field requires Claude Code v2.1.202 or later. See the [ScheduleWakeup row in the tools reference](</docs/en/tools-reference>). -### - -​ - -RemoteTrigger +### RemoteTrigger **Tool name:** `RemoteTrigger` @@ -4077,11 +3345,7 @@ This tool is available only when the session is authenticated with a claude.ai account on a plan with cloud scheduled tasks enabled. It is absent when your organization’s policy disables [cloud sessions](</docs/en/claude-code-on-the-web>). On Claude Code v2.1.227 or later, the tool is also absent when an Owner has [turned off scheduled tasks for the organization](</docs/en/routines#routines-are-disabled-by-your-organizations-policy>). -### - -​ - -PushNotification +### PushNotification **Tool name:** `PushNotification` @@ -4092,19 +3356,11 @@ Sends a proactive push notification to the user. Keep `message` under 200 characters because mobile operating systems truncate longer text. See the [PushNotification row in the tools reference](</docs/en/tools-reference>) for provider availability; push delivery runs through Anthropic-hosted infrastructure that isn’t accessible from Amazon Bedrock, Claude Platform on AWS, Google Cloud’s Agent Platform, or Microsoft Foundry. -### - -​ - -REPL +### REPL Removed in v2.1.275. Through v2.1.274, an experimental `REPL` tool could be turned on with `CLAUDE_CODE_REPL=1` in the `env` option. -### - -​ - -ReportFindings +### ReportFindings **Tool name:** `ReportFindings` @@ -4131,11 +3387,7 @@ * `verdict`: set when a verify pass ran; absent on inline-only reviews. * `outcome`: set only when re-reporting after applying fixes. -### - -​ - -Artifact +### Artifact **Tool name:** `Artifact` @@ -4169,11 +3421,7 @@ The types are exported, but the tool is off by default in Agent SDK sessions. Publishing also requires every condition in the [artifacts availability table](</docs/en/artifacts#availability>), which sessions authenticated with an API key don’t meet. -### - -​ - -Projects +### Projects **Tool name:** `Projects` @@ -4200,11 +3448,7 @@ * `project_write`: creates or replaces a doc at `path` from exactly one of `content`, which carries inline text, or `local_path`, which names a file inside the working directory. `present_to_user: true` marks the written doc as the deliverable the user needs to see. * `project_delete`: deletes a doc by `path`. -### - -​ - -ReadMcpResourceDir +### ReadMcpResourceDir **Tool name:** `ReadMcpResourceDirTool` @@ -4215,11 +3459,7 @@ Lists the direct children of a directory resource on an MCP server. Only usable against a server that has declared support for directory listing; the listing isn’t recursive. Directory listing isn’t enabled in every session: when it’s off, the call returns an empty `resources` list and the `error` field reports that directory listing isn’t enabled. -### - -​ - -RefreshMcpTools +### RefreshMcpTools **Tool name:** `RefreshMcpTools` @@ -4229,11 +3469,7 @@ Re-queries the tool list of connected MCP servers and applies any changes. The types are exported, but Claude Code registers the tool only when you set `CLAUDE_CODE_ENABLE_REFRESH_MCP_TOOLS=1` in the `env` option, and only in sessions with at least one MCP server. Requires Claude Code v2.1.211 or later. -### - -​ - -ShowOnboardingRolePicker +### ShowOnboardingRolePicker **Tool name:** `ShowOnboardingRolePicker` @@ -4241,11 +3477,7 @@ Renders a clickable role-picker chip row during Cowork onboarding so the user can pick their role and get a matching plugin installed. Takes no arguments; the role list is defined by the client. The call blocks until the user responds. -### - -​ - -McpInput +### McpInput **Tool name:** dynamic MCP tool names of the form `mcp__<server>__<tool>` @@ -4255,19 +3487,11 @@ MCP tool arguments are an open object: each server defines its own parameters, so the type places no constraints on field names or values. Consult the server’s own tool schema for the fields a specific tool accepts. -## - -​ - -Tool Output Types +## Tool Output Types Documentation of output schemas for built-in Claude Code tools. These types are exported from `@anthropic-ai/claude-agent-sdk/sdk-tools` and represent the actual response data returned by each tool. -### - -​ - -`ToolOutputSchemas` +### `ToolOutputSchemas` Union of tool output types exported from `@anthropic-ai/claude-agent-sdk/sdk-tools`; members include: @@ -4311,11 +3535,7 @@ | WebSearchOutput | WorkflowOutput; -### - -​ - -Agent +### Agent **Tool name:** `Agent`. The previous name `Task` is still accepted as an alias when this tool is available to the session. @@ -4388,11 +3608,7 @@ Returns the result from the subagent. Discriminated on the `status` field: `"completed"` for finished tasks, `"async_launched"` for background tasks, and `"remote_launched"` for tasks Claude Code dispatched to a cloud session, where `sessionUrl` links to that session and `taskId` identifies it. On the `completed` variant, `resolvedModel` names the model the subagent started on, which can differ from the requested `model` input when [`availableModels`](</docs/en/model-config#restrict-model-selection>) or another override applies. This field requires Claude Code v2.1.174 or later. On `async_launched`, it names the model in use when the task moved to the background. `modelsUsed` lists the models the subagent used, in order. The field is present only when a mid-run swap happened, and a model appears again when the run swapped back to it. On `async_launched`, the list covers the models used before backgrounding. Both `modelsUsed` and the backgrounding behavior of `resolvedModel` require Claude Code v2.1.212 or later. If Claude Code [kept the subagent’s isolated worktree](</docs/en/worktrees#isolate-subagents-with-worktrees>), `worktreePath` on the `completed` result is where to find it. `worktreeBranch` is its branch, present when Claude Code created the worktree with git. Claude Code fills `usage` and `totalTokens` from the subagent’s final API request, not from the whole run, so `usage.service_tier` is the service tier string the API reported on that request. When present, `usage.output_tokens_details.thinking_tokens` is the number of that request’s output tokens that were thinking tokens. The `output_tokens_details` field requires TypeScript SDK v0.3.228 or later, which bundles Claude Code v2.1.228. The `fallback_credit` field requires TypeScript SDK v0.3.285 or later, which bundles Claude Code v2.1.285. `usage.output_tokens_details` matches `Usage.output_tokens_details` in meaning, scoped to that final request, but every level of it is optional here. Guard both the object and the field, for example `usage.output_tokens_details?.thinking_tokens ?? 0`, rather than reading it directly. Before v2.1.207, the published type was narrower. It omitted `worktreePath`, `worktreeBranch`, `citations`, `toolStats.frameCount`, and the `inference_geo`, `speed`, and `iterations` usage fields, and it typed `service_tier` as `"standard" | "priority" | "batch"`. Fields the type marks optional can be absent on results recorded by earlier versions. -### - -​ - -AskUserQuestion +### AskUserQuestion **Tool name:** `AskUserQuestion` @@ -4411,11 +3627,7 @@ Returns the questions asked and the user’s answers. `response` is set when the user typed a freeform reply instead of answering the structured questions; when present, Claude receives “The user responded: …” instead of the per-question answer list. -### - -​ - -Bash +### Bash **Tool name:** `Bash` @@ -4460,11 +3672,7 @@ `timedOutAfterMs` is the timeout in milliseconds, set when the command reached its timeout and moved to the background rather than starting there explicitly. `backgroundCwdHint` is set when the backgrounded command contained a directory-change builtin such as `cd`, `pushd`, `popd`, or `chdir`, and notes that the session working directory didn’t change. Both fields require Claude Code v2.1.210 or later. When a subagent running in the foreground owns a backgrounded command, the command [ends when that subagent’s run ends](</docs/en/tools-reference#when-a-background-command-stops>). Claude Code sets `backgroundEndsWithFinalResponse` to `true` on such commands, and omits the field when the command survives the turn, as commands started by the main conversation or by background subagents do. The field requires Claude Code v2.1.227 or later. Claude Code sets `gitOperation.commit.branch` to the branch named in git’s commit summary line, and omits it for a commit made on a detached HEAD. The field requires Agent SDK v0.3.227 or later. Claude Code reports a `gh pr reopen` command as the `reopened` PR action, which requires Agent SDK v0.3.234 or later. -### - -​ - -Monitor +### Monitor **Tool name:** `Monitor` @@ -4476,11 +3684,7 @@ Returns the background task ID for the running monitor. Use this ID with `TaskStop` to cancel the watch early. -### - -​ - -Edit +### Edit **Tool name:** `Edit` @@ -4511,11 +3715,7 @@ Returns the structured diff of the edit operation. -### - -​ - -Read +### Read **Tool name:** `Read` @@ -4589,11 +3789,7 @@ Returns file contents in a format appropriate to the file type. Discriminated on the `type` field. -### - -​ - -Write +### Write **Tool name:** `Write` @@ -4627,11 +3823,7 @@ * On an overwrite, `originalFile` carries the previous content, except when that content is larger than about 10 MB: Claude Code then skips the diff and returns `originalFile` null and `structuredPatch` empty * `structuredPatch` is also empty when the write changed nothing or the diff timed out -### - -​ - -Glob +### Glob **Tool name:** `Glob` @@ -4646,11 +3838,7 @@ Returns file paths matching the glob pattern, sorted by modification time. `totalMatches` and `countIsComplete` require Claude Code v2.1.191 or later. `totalMatches` reports the number of matching files before truncation. When `countIsComplete` is false, `totalMatches` is a lower bound because the underlying search truncated its own output. -### - -​ - -Grep +### Grep **Tool name:** `Grep` @@ -4669,11 +3857,7 @@ Returns search results. The shape varies by `mode`: file list, content with matches, or match counts. In `count` mode, `numFiles` and `numMatches` are totals over the full result set, not the paginated slice. Before v2.1.208, a `head_limit` or `offset` that truncated the listed entries also truncated those totals. `totalFiles` requires Claude Code v2.1.208 or later and reports the total number of results before `head_limit` and `offset` pagination in `files_with_matches` mode. `totalLines` requires Claude Code v2.1.210 or later and reports the total number of lines before pagination in `content` mode. -### - -​ - -TaskStop +### TaskStop **Tool name:** `TaskStop` @@ -4686,11 +3870,7 @@ Returns confirmation after stopping the background task. -### - -​ - -NotebookEdit +### NotebookEdit **Tool name:** `NotebookEdit` @@ -4709,11 +3889,7 @@ Returns the result of the notebook edit with original and updated file contents. -### - -​ - -WebFetch +### WebFetch **Tool name:** `WebFetch` @@ -4733,11 +3909,7 @@ Returns the fetched content with HTTP status and metadata. `artifactRead` is Claude Code’s own record of an artifact read, present only when Claude fetched an artifact the session can publish to. Claude Code reads it back when a session resumes so a later publish builds on the right version; your code doesn’t need to act on it. `slug` names the artifact, `ver` is the version the read put on record and is absent when it recorded none, and `seeded: false` marks a read whose full source didn’t reach Claude. The `seeded` field requires Agent SDK v0.3.239 or later. -### - -​ - -WebSearch +### WebSearch **Tool name:** `WebSearch` @@ -4756,11 +3928,7 @@ Returns search results from the web. -### - -​ - -Workflow +### Workflow **Tool name:** `Workflow` @@ -4794,11 +3962,7 @@ `warning`| `string`| Non-blocking heads-up, such as local git state diverging from the pushed branch a cloud session will clone `error`| `string`| Set when the script fails its syntax check. When present, the run did not start despite the launched status -### - -​ - -TodoWrite +### TodoWrite **Tool name:** `TodoWrite` @@ -4825,13 +3989,9 @@ * `TaskUpdate` * `TaskList` -Wherever the tools are available, Claude Code provides the four Task tools, or `TodoWrite` instead when you set `CLAUDE_CODE_ENABLE_TASKS=0`.This default set applies in Claude Code v2.1.268 and later, which the TypeScript Agent SDK bundles from v0.3.268.See [Model availability](</docs/en/agent-sdk/todo-tracking#model-availability>) to opt in. - -### - -​ - -TaskCreate +Wherever the tools are available, Claude Code provides the four Task tools, or `TodoWrite` instead when you set `CLAUDE_CODE_ENABLE_TASKS=0`. This default set applies in Claude Code v2.1.268 and later, which the TypeScript Agent SDK bundles from v0.3.268.See [Model availability](</docs/en/agent-sdk/todo-tracking#model-availability>) to opt in. + +### TaskCreate **Tool name:** `TaskCreate` @@ -4844,11 +4004,7 @@ Returns the created task with its assigned ID. -### - -​ - -TaskUpdate +### TaskUpdate **Tool name:** `TaskUpdate` @@ -4865,11 +4021,7 @@ Returns the update result, including which fields changed. -### - -​ - -TaskGet +### TaskGet **Tool name:** `TaskGet` @@ -4886,11 +4038,7 @@ Returns the full task record, or `null` when the ID is not found. -### - -​ - -TaskList +### TaskList **Tool name:** `TaskList` @@ -4906,11 +4054,7 @@ Returns a snapshot of all tasks in the current list. -### - -​ - -ExitPlanMode +### ExitPlanMode **Tool name:** `ExitPlanMode` @@ -4926,11 +4070,7 @@ Returns the plan state after exiting plan mode. -### - -​ - -ListMcpResources +### ListMcpResources **Tool name:** `ListMcpResourcesTool` @@ -4944,11 +4084,7 @@ Returns an array of available MCP resources. -### - -​ - -ReadMcpResource +### ReadMcpResource **Tool name:** `ReadMcpResourceTool` @@ -4964,11 +4100,7 @@ Returns the contents of the requested MCP resource. -### - -​ - -EnterWorktree +### EnterWorktree **Tool name:** `EnterWorktree` @@ -4980,11 +4112,7 @@ Returns information about the git worktree. -### - -​ - -ExitWorktree +### ExitWorktree **Tool name:** `ExitWorktree` @@ -5001,11 +4129,7 @@ Returns the action taken and details about the worktree that was exited. -### - -​ - -EnterPlanMode +### EnterPlanMode **Tool name:** `EnterPlanMode` @@ -5015,11 +4139,7 @@ Returns a confirmation that plan mode was entered. -### - -​ - -CronCreate +### CronCreate **Tool name:** `CronCreate` @@ -5033,11 +4153,7 @@ Returns the job ID, a human-readable schedule, and the next run time. `nextFireAt` gives it in epoch milliseconds, with [jitter](</docs/en/scheduled-tasks#jitter>) already applied, so it’s when the job is set to run. The field requires TypeScript Agent SDK v0.3.299 or later and Claude Code v2.1.299 or later. -### - -​ - -CronDelete +### CronDelete **Tool name:** `CronDelete` @@ -5047,11 +4163,7 @@ Returns the ID of the deleted job. -### - -​ - -CronList +### CronList **Tool name:** `CronList` @@ -5069,11 +4181,7 @@ Returns the scheduled cron jobs: durable jobs from `.claude/scheduled_tasks.json` and session-only jobs from the current session. A session-only job carries `durable: false`; jobs read from disk omit the field. `nextFireAt` is the job’s next run time in epoch milliseconds, [jitter](</docs/en/scheduled-tasks#jitter>) included. No value is earlier than the `CronList` call: a job whose time [passed without a run](</docs/en/scheduled-tasks#how-scheduled-tasks-run>) carries the call’s time. The field requires TypeScript Agent SDK v0.3.299 or later and Claude Code v2.1.299 or later. -### - -​ - -ScheduleWakeup +### ScheduleWakeup **Tool name:** `ScheduleWakeup` @@ -5087,11 +4195,7 @@ Returns when the wake-up will fire as an epoch millisecond timestamp, the delay actually used, and whether the requested delay was clamped. The `stopped` field is `true` when the call ended the loop with `stop: true`. It requires Claude Code v2.1.202 or later. The `cancelledWakeups` field counts how many pending wakeups a `stop: true` call cancelled. A value of 0 means nothing was pending, and a recurring `/loop` cron isn’t cancelled by `stop: true`. It requires Claude Code v2.1.206 or later. -### - -​ - -RemoteTrigger +### RemoteTrigger **Tool name:** `RemoteTrigger` @@ -5103,11 +4207,7 @@ Returns the API response status and body for the trigger operation. -### - -​ - -PushNotification +### PushNotification **Tool name:** `PushNotification` @@ -5121,11 +4221,7 @@ Returns delivery details, including whether a push or local notification was sent and why delivery was skipped. -### - -​ - -ReportFindings +### ReportFindings **Tool name:** `ReportFindings` @@ -5146,11 +4242,7 @@ Returns the number of findings reported, the `level` value Claude passed, and the findings echoed back for the result body. Requires Claude Code v2.1.196 or later. The echoed `short_summary` field requires Claude Code v2.1.212 or later. -### - -​ - -Artifact +### Artifact **Tool name:** `Artifact` @@ -5185,11 +4277,7 @@ Returns the published page’s `url` and the local `path` that was published for the publish action, with `updated` set to true when the publish redeployed an existing artifact, and `warnings` carrying any publish-time advisories. The list action returns the `artifacts` rows instead, with `truncated` set when more artifacts exist than the requested limit. On listings whose scope isn’t `"mine"`, each row carries `rel` marking whether the user owns the artifact or it was shared with them, and the output’s `scope` records which non-default scope produced the listing; both are absent on default listings. A list result also reports `total`, the number of artifacts that match the listed scope, including ones beyond `limit`. When `total_at_least` is set, that number is a lower bound and more artifacts may exist. Both fields require Agent SDK v0.3.292 or later. -### - -​ - -Projects +### Projects **Tool name:** `Projects` @@ -5249,11 +4337,7 @@ Discriminated on the `method` field, mirroring the input. `project_read` returns small text docs inline in `content` and writes larger docs to a `local_file` path instead; `project_search` returns RAG `hits` with `rag: true` when the project’s index is available and falls back to a `docs` path list otherwise. -### - -​ - -ReadMcpResourceDir +### ReadMcpResourceDir **Tool name:** `ReadMcpResourceDirTool` @@ -5268,11 +4352,7 @@ Returns the direct children of the directory resource. Subdirectories appear with mimeType `"inode/directory"`; `error` carries a human-readable message when the server couldn’t list the directory. -### - -​ - -RefreshMcpTools +### RefreshMcpTools **Tool name:** `RefreshMcpTools` @@ -5287,11 +4367,7 @@ Returns one entry per server: `refreshed` means the re-queried tool list was applied, `error` means the re-query failed and the previous tool set was kept, and `not_connected` means the server has no live connection to query. -### - -​ - -ShowOnboardingRolePicker +### ShowOnboardingRolePicker **Tool name:** `ShowOnboardingRolePicker` @@ -5302,11 +4378,7 @@ Returns the user’s selection: `role` when they picked a role chip or typed one, and `dismissed: true` when they closed the picker. An empty object means the user approved the call without picking a role. -### - -​ - -McpOutput +### McpOutput **Tool name:** dynamic MCP tool names of the form `mcp__<server>__<tool>` @@ -5322,17 +4394,9 @@ MCP tool results are returned as a string or an array of content blocks, depending on the server. The trailing plain-object branch in the exported type is a schema-generation artifact. For a result that also carries `structuredContent` or resource links, see `tool_use_result`, which holds this value in its `content` member. At runtime the value may also be `undefined`, although the exported type doesn’t model this. -## - -​ - -Permission Types - -### - -​ - -`PermissionUpdate` +## Permission Types + +### `PermissionUpdate` Operations for updating permissions. @@ -5371,19 +4435,11 @@ destination: PermissionUpdateDestination; }; -### - -​ - -`PermissionBehavior` +### `PermissionBehavior` type PermissionBehavior = "allow" | "deny" | "ask"; -### - -​ - -`PermissionUpdateDestination` +### `PermissionUpdateDestination` type PermissionUpdateDestination = | "userSettings" // Global user settings @@ -5392,28 +4448,16 @@ | "session" // Current session only | "cliArg"; // CLI argument -### - -​ - -`PermissionRuleValue` +### `PermissionRuleValue` type PermissionRuleValue = { toolName: string; ruleContent?: string; }; -## - -​ - -Other Types - -### - -​ - -`ApiKeySource` +## Other Types + +### `ApiKeySource` Where the API key for the session’s requests came from, reported as `apiKeySource` on the `SDKSystemMessage` init message. @@ -5439,11 +4483,7 @@ Agent SDK v0.3.234 and later list these four values in the type. The type also keeps `user`, `project`, `org`, `temporary`, and `oauth` so older code still compiles, and Claude Code doesn’t report them. -### - -​ - -`SdkBeta` +### `SdkBeta` Available beta features that can be enabled via the `betas` option. See [Beta headers](<https://platform.claude.com/docs/en/api/beta-headers>) for more information. @@ -5451,11 +4491,7 @@ On the Claude API, the `context-1m-2025-08-07` beta is retired for Claude Sonnet 4.5 and Claude Sonnet 4. If you still pass it with either model, requests that exceed the standard 200K-token context window return an error, so remove it from `betas`. To run a session with a 1M-token context window, set `model` to a model that [runs with the 1M window by default](</docs/en/model-config#extended-context>), such as `claude-sonnet-5-5` or `claude-opus-5-5`. For a model that reaches 1M only through its `[1m]` variant, append the suffix to the model ID, as in `claude-opus-4-6[1m]`. -### - -​ - -`SlashCommand` +### `SlashCommand` Information about an available command. @@ -5469,11 +4505,7 @@ `builtin` is `true` on a row when the command is Claude Code’s own and typing `/name` runs it. It’s absent for a command defined by a user, project, plugin, or MCP server, and for a bundled command that one of those [replaces by name](</docs/en/skills#resolve-skills-that-share-a-name>). Requires Agent SDK v0.3.277 or later. -### - -​ - -`ModelInfo` +### `ModelInfo` Information about an available model. @@ -5501,11 +4533,7 @@ `supportsFastMode`| `boolean | undefined`| Whether this model supports fast mode `supportsAutoMode`| `boolean | undefined`| Whether this model supports auto mode -### - -​ - -`AgentInfo` +### `AgentInfo` Information about an available subagent that can be invoked via the Agent tool. @@ -5521,11 +4549,7 @@ `description`| `string`| Description of when to use this agent `model`| `string | undefined`| Model this agent uses: an alias or model ID, or `'inherit'` for the parent’s model. When it’s `undefined`, Claude Code picks the model in the [subagent model order](</docs/en/sub-agents#choose-a-model>) -### - -​ - -`McpServerProvenance` +### `McpServerProvenance` The MCP server that serves an `mcp__*` tool, and where that server’s definition came from. The `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied` hook inputs carry it as `mcp_server`, and the `CanUseTool` options carry it as `mcpServer`. Both omit it for tools that don’t come from an MCP server. @@ -5547,11 +4571,7 @@ Base trust decisions on `source`, not on `name` or the `mcp__<server>__` tool-name prefix. For any source other than `sdk`, `name` is untrusted text: escape it before display. `McpServerProvenance` and the fields that carry it require Agent SDK v0.3.274 or later. -### - -​ - -`McpServerStatus` +### `McpServerStatus` Status of a connected MCP server. @@ -5585,11 +4605,7 @@ Claude Code sends `_meta` only when the `capabilities` array of the `system` message with subtype `init` lists `mcp_tool_ui_meta_v1`. You don’t turn `mcp_tool_ui_meta_v1` on yourself. -#### - -​ - -When a tool’s `_meta.ui` holds only `visibility` +#### When a tool’s `_meta.ui` holds only `visibility` If your server declares `ui.resourceUri` for a tool but the `_meta.ui` your application receives holds only `visibility`, the `ui` object the server sent failed one of Claude Code’s checks. Compare the `_meta` in your server’s `tools/list` response against the checks for each key: @@ -5602,11 +4618,7 @@ When Claude Code is left with no `ui` member and no `ui/resourceUri` string to send, the `tools` entry has no `_meta` at all. -### - -​ - -`McpServerStatusConfig` +### `McpServerStatusConfig` The configuration of an MCP server as reported by `mcpServerStatus()`. This is the union of all MCP server transport types. @@ -5619,11 +4631,7 @@ See `McpServerConfig` for details on each transport type. -### - -​ - -`AccountInfo` +### `AccountInfo` Account information for the authenticated user. @@ -5635,11 +4643,7 @@ apiKeySource?: string; }; -### - -​ - -`ModelUsage` +### `ModelUsage` Per-model usage statistics returned in result messages. The `costUSD` value is a client-side estimate. See [Track cost and usage](</docs/en/agent-sdk/cost-tracking>) for billing caveats. @@ -5660,19 +4664,11 @@ `thinkingTokens` counts the thinking tokens this model generated. `outputTokens` already includes them, so don’t add the two together. The field is absent until a turn runs on a Claude Code version that records it, so a resumed session that began on an earlier version reports a partial count. `thinkingTokens` requires Agent SDK v0.3.257 or later. The `canonicalModel` and `provider` fields require Claude Code v2.1.218 or later. `canonicalModel` is the canonical model ID that the pricing lookup uses; it can differ from the raw model string that keys the entry, for example when that string is a provider-specific ID or an alias. `provider` names the API backend that served the model, such as `firstParty`, `bedrock`, `vertex`, `foundry`, `anthropicAws`, `mantle`, or `gateway`. `costBasis` names the price table that priced the model’s latest request: `list` for list price, `managed` for a [`modelPricing`](</docs/en/settings-reference#modelpricing>) table, or `unknown` when neither matched the model ID. The field requires Claude Code v2.1.246 or later. -### - -​ - -`ConfigScope` +### `ConfigScope` type ConfigScope = "local" | "user" | "project"; -### - -​ - -`NonNullableUsage` +### `NonNullableUsage` A version of `Usage` with every nullable field made non-nullable except `fallback_credit`, which can still be `null`. @@ -5682,11 +4678,7 @@ : NonNullable<Usage[K]>; }; -### - -​ - -`Usage` +### `Usage` Token usage statistics. This is the `BetaUsage` type from `@anthropic-ai/sdk`. @@ -5717,11 +4709,7 @@ Whether `Usage` carries `fallback_credit` depends on your installed `@anthropic-ai/sdk`, which added it in 0.115.0. -### - -​ - -`CallToolResult` +### `CallToolResult` MCP tool result type (from `@modelcontextprotocol/sdk/types.js`). `structuredContent` is a JSON object that can be returned alongside `content`, including image blocks. See [Return structured data](</docs/en/agent-sdk/custom-tools#return-structured-data>). @@ -5734,11 +4722,7 @@ isError?: boolean; }; -### - -​ - -`SDKMcpResourceLink` +### `SDKMcpResourceLink` One file an MCP tool returned by reference. Claude Code builds each entry from a `resource_link` block in the tool’s result and delivers the list as `resourceLinks` on `SDKUserMessage.tool_use_result`, or as `resource_links` on `SDKTaskNotificationMessage` when the call finished in the background. Requires Agent SDK v0.3.257 or later. @@ -5764,11 +4748,7 @@ `size`| `number | undefined`| Size in bytes, when the server set one `annotations`| `Record<string, unknown> | undefined`| The block’s MCP annotations object, when the server set one -### - -​ - -`ThinkingConfig` +### `ThinkingConfig` Controls Claude’s thinking/reasoning behavior. Takes precedence over the deprecated `maxThinkingTokens`. @@ -5781,11 +4761,7 @@ For `disabled`, see [where you can’t turn thinking off](</docs/en/model-config#where-you-cant-turn-thinking-off>). The optional `display` field controls whether thinking text is returned `"summarized"` or `"omitted"`. On Claude Opus 4.7 and later, the API default is `"omitted"`, so set `"summarized"` to receive thinking content in `thinking` blocks. On providers such as Amazon Bedrock and Google Cloud’s Agent Platform, Claude Code doesn’t pass `display` for earlier models it recognizes. Those are Opus 4.6, Sonnet 4.6, Haiku 4.5, and earlier models, which use their default. -### - -​ - -`SpawnedProcess` +### `SpawnedProcess` Interface for custom process spawning (used with `spawnClaudeCodeProcess` option). `ChildProcess` already satisfies this interface. @@ -5812,11 +4788,7 @@ off(event: "error", listener: (error: Error) => void): void; } -### - -​ - -`SpawnOptions` +### `SpawnOptions` Options passed to the custom spawn function. @@ -5830,11 +4802,7 @@ The `signal` field tells your spawn function when to tear down the process. Pass it as the `signal` option to Node’s `spawn()`, or pass it to your VM or container teardown handler.This signal does not fire the instant `Options.abortController` aborts. The SDK first closes the process’s stdin and waits about two seconds so the CLI can shut down cleanly, then aborts this signal. To react the moment the caller aborts instead, listen on your own `Options.abortController.signal`, which your spawn function can reference from its enclosing scope. -### - -​ - -`McpSetServersResult` +### `McpSetServersResult` Result of a `setMcpServers()` operation. @@ -5858,11 +4826,7 @@ * `Blocked by enterprise policy (allowedMcpServers/deniedMcpServers)`: the server isn’t in `added`. A [`deniedMcpServers`](</docs/en/managed-mcp#policy-based-control-with-allowlists-and-denylists>) entry matches it, or an `allowedMcpServers` list is set and omits it. If that list is in a settings file you load through `settingSources`, edit the file. If it’s in managed settings, ask your administrators to change it. * `Blocked by enterprise managed policy`: the server is in `added`, with a `failed` row in `mcpServerStatus()`. Ask an administrator which policy blocks it. -### - -​ - -`RewindFilesResult` +### `RewindFilesResult` Result of a `rewindFiles()` operation. @@ -5877,11 +4841,7 @@ `skippedLinks` counts the tracked paths the rewind refused to restore or delete for link safety: a symlink, hard link, or other non-regular file at the tracked path, a parent directory that no longer resolves to where it pointed when the checkpoint was taken, or a backup that couldn’t be read safely. The field requires Claude Code v2.1.216 or later. A preview call with `rewindFiles(userMessageId, { dryRun: true })` never sets it. -### - -​ - -`SDKStatusMessage` +### `SDKStatusMessage` Status update message (for example, compacting). @@ -5894,11 +4854,7 @@ session_id: string; }; -### - -​ - -`SDKTaskNotificationMessage` +### `SDKTaskNotificationMessage` Notification when a background task completes, fails, or is stopped. Background tasks include `run_in_background` Bash commands, Monitor watches, and background subagents. For the `run_id` and `ambient` fields, see `SDKTaskStartedMessage`, which defines them and their version requirements. @@ -5925,11 +4881,7 @@ `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. -### - -​ - -`SDKToolUseSummaryMessage` +### `SDKToolUseSummaryMessage` Summary of tool usage in a conversation. @@ -5941,11 +4893,7 @@ session_id: string; }; -### - -​ - -`SDKHookStartedMessage` +### `SDKHookStartedMessage` Emitted when a hook begins executing. Claude Code delivers this message, `SDKHookProgressMessage`, and `SDKHookResponseMessage` to the message stream immediately, including while a `SessionStart` or `Setup` hook is still running during session startup. Claude Code v2.1.169 through v2.1.203 delivered these messages in one batch after a `SessionStart` or `Setup` hook completed; v2.1.204 restored live delivery. If you start the session with `startup()`, these messages reach you once you call `.query()` and iterate the result. @@ -5959,11 +4907,7 @@ session_id: string; }; -### - -​ - -`SDKHookProgressMessage` +### `SDKHookProgressMessage` Emitted while a hook is running, with stdout/stderr output. @@ -5980,11 +4924,7 @@ session_id: string; }; -### - -​ - -`SDKHookResponseMessage` +### `SDKHookResponseMessage` Emitted when a hook finishes executing. @@ -6003,11 +4943,7 @@ session_id: string; }; -### - -​ - -`SDKToolProgressMessage` +### `SDKToolProgressMessage` Emitted periodically while a tool is executing to indicate progress. @@ -6038,11 +4974,7 @@ * Clear the indicator when a later `tool_progress` for the same `parent_tool_use_id` arrives with neither `subagent_retry` nor `heartbeat: true`, or when the tool’s result message arrives. Frames with `heartbeat: true` report liveness only, so keep the indicator when one arrives. `attempt` can exceed `max_retries` under persistent retry, so don’t derive clearing from the counters. * Treat `error_category` as a token for choosing your own message text, not as display text. The values are `rate_limit`, `overloaded`, `authentication_failed`, `server_error`, `cloud_credential_error`, and `unknown`. Handle a value you don’t recognize the way you handle `unknown`, because later releases can add values. -### - -​ - -`SDKAuthStatusMessage` +### `SDKAuthStatusMessage` Emitted during authentication flows. @@ -6055,11 +4987,7 @@ session_id: string; }; -### - -​ - -`SDKTaskStartedMessage` +### `SDKTaskStartedMessage` Emitted when a task begins. `task_type` names the kind of task, such as `"local_bash"` for Bash commands and Monitor watches, `"local_agent"` for subagents, `"mcp_task"` for [background MCP tool calls](</docs/en/mcp#automatic-backgrounding-of-long-tool-calls>), or `"remote_agent"`. @@ -6104,11 +5032,7 @@ The parent can be a foreground task or one that already ended, so treat an ID you don’t recognize as no parent. -### - -​ - -`SDKTaskProgressMessage` +### `SDKTaskProgressMessage` Emitted periodically while a subagent or background task is running. For the `run_id` field, see `SDKTaskStartedMessage`, which defines it and its version requirement. For a subagent task, the `summary` field carries a model-generated progress summary and is populated only when `agentProgressSummaries` is enabled. For a [backgrounded MCP tool call](</docs/en/mcp#automatic-backgrounding-of-long-tool-calls>), `summary` carries the MCP server’s latest reported progress and doesn’t depend on that option. @@ -6131,11 +5055,7 @@ session_id: string; }; -### - -​ - -`SDKTaskUpdatedMessage` +### `SDKTaskUpdatedMessage` Emitted when a background task’s state changes, such as when it transitions from `running` to `completed`. Merge `patch` into your local task map keyed by `task_id`. The `end_time` field is a Unix epoch timestamp in milliseconds, comparable with `Date.now()`. For the `run_id` field, see `SDKTaskStartedMessage`, which defines it and its version requirement. @@ -6156,11 +5076,7 @@ session_id: string; }; -### - -​ - -`SDKBackgroundTasksChangedMessage` +### `SDKBackgroundTasksChangedMessage` Emitted whenever the set of live background tasks changes: a task starts, completes, or is killed; a foreground agent is backgrounded; or a task’s `description`, `ambient`, or `parent_task_id` field changes. For the `run_id` and `parent_task_id` fields on each entry, see `SDKTaskStartedMessage`, which defines them and their version requirements. The `tasks` array is the full live set. Replace any cached set with each payload instead of pairing `task_started` and `task_notification` events, so the next membership change corrects any event you missed. When a task ends, its `task_updated` and `task_notification` arrive before the `background_tasks_changed` that drops it from the list. Ordering relative to the per-task events is otherwise unspecified. Nothing is emitted at startup. Reset to an empty set whenever the session’s CLI process starts or restarts and let the next membership change repopulate it. When you send a repeated `initialize` control request to a running session, such as with `reinitialize()` after a transport gap, Claude Code follows the response with a snapshot of the current live set, even when it is empty. A reconnecting host therefore learns what is running without waiting for the next membership change. Before Agent SDK v0.3.239, Claude Code sent no snapshot after a repeated `initialize`. Requires Claude Code v2.1.203 or later. @@ -6182,11 +5098,7 @@ `subagent_type` names the subagent type on entries whose `task_type` is `"local_agent"`, such as `general-purpose` or a custom subagent’s name. The field requires Agent SDK v0.3.293 or later. -### - -​ - -`SDKThinkingTokensMessage` +### `SDKThinkingTokensMessage` Emitted while Claude is producing a thinking block, including a redacted one. `estimated_tokens` is a running estimate of the thinking tokens generated so far in the current block, and `estimated_tokens_delta` is the increment carried by this frame. Use these estimates for progress display. When the model or provider reports a breakdown, the final count for the top-level agent loop is the result message’s `usage.output_tokens_details.thinking_tokens`, which [doesn’t include subagent tokens](</docs/en/agent-sdk/cost-tracking#get-the-total-cost-of-a-query>). Requires Claude Code v2.1.153 or later. @@ -6200,11 +5112,7 @@ session_id: string; }; -### - -​ - -`SDKSessionStateChangedMessage` +### `SDKSessionStateChangedMessage` Emitted when Claude Code reports the session’s state. To receive these messages, set [`CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS=1`](</docs/en/env-vars#variables>). Claude Code can report the same state more than once, so read a message as the session’s current state rather than as a transition. The `state` field carries one of these values: @@ -6222,11 +5130,7 @@ session_id: string; }; -### - -​ - -`SDKFilesPersistedEvent` +### `SDKFilesPersistedEvent` Emitted when file checkpoints are persisted to disk. @@ -6240,11 +5144,7 @@ session_id: string; }; -### - -​ - -`SDKRateLimitEvent` +### `SDKRateLimitEvent` Emitted when the session encounters a rate limit. @@ -6265,11 +5165,7 @@ When `errorCode` is `"credits_required"`, the rejection is from a claude.ai subscription whose included usage is exhausted, and the session cannot continue until the user buys usage credits. `canUserPurchaseCredits` indicates whether the authenticated user can buy credits for the account, and `hasChargeableSavedPaymentMethod` indicates whether a saved payment method is on file. All three fields are absent on rate-limit events that are not credits-required rejections. Requires Claude Code v2.1.181 or later. On a warning about a plan usage limit, where `status` is `"allowed_warning"`, `overageEnabled` reports whether the account has [usage credits](</docs/en/costs#add-usage-credits-to-your-subscription>) turned on. Requires Claude Code v2.1.295 or later. -### - -​ - -`SDKLocalCommandOutputMessage` +### `SDKLocalCommandOutputMessage` Claude Code doesn’t emit this message type. When you send a command such as `/context` or `/usage` as a prompt, its output arrives as an `SDKAssistantMessage`. @@ -6281,11 +5177,7 @@ session_id: string; }; -### - -​ - -`SDKCommandsChangedMessage` +### `SDKCommandsChangedMessage` Emitted when the set of available commands changes mid-session, such as when Claude Code discovers skills as the agent enters a subdirectory. The `commands` array is the full updated list, so replace any cached command list with this payload. Calling `supportedCommands()` after this message returns the same updated list, because the method tracks the latest push; this requires Agent SDK v0.3.216 or later. In earlier SDK versions, `supportedCommands()` returns the snapshot captured at initialization and never reflects mid-session changes. Claude Code also emits this message when an MCP server’s [prompts](</docs/en/mcp#use-mcp-prompts-as-commands>) join or leave the list, for example when a server finishes connecting after the session starts. This requires Claude Code v2.1.281 or later. @@ -6297,11 +5189,7 @@ session_id: string; }; -### - -​ - -`SDKPromptSuggestionMessage` +### `SDKPromptSuggestionMessage` Emitted after a turn when `promptSuggestions` is enabled and Claude Code generated a suggestion for that turn. Contains the predicted next user prompt. For the turns that get none, see [When Claude Code skips suggestions](</docs/en/interactive-mode#when-claude-code-skips-suggestions>). @@ -6312,11 +5200,7 @@ session_id: string; }; -### - -​ - -`SDKConversationResetMessage` +### `SDKConversationResetMessage` Emitted when the session’s conversation is replaced without ending the session. In a `query()` call, only `/clear` and its aliases produce this message. Mount an empty transcript under `new_conversation_id` and discard any cached session title. @@ -6338,11 +5222,7 @@ The `trigger`, `user_message_uuid`, and `timestamp` fields require Claude Code v2.1.281 or later. The SDK’s published typings declare `SDKConversationResetMessage` in Claude Code v2.1.203 and later. Before v2.1.203, `SDKMessage` referenced the type without declaring it, so narrowing on `type === "conversation_reset"` failed to typecheck when `skipLibCheck` was disabled. -### - -​ - -`BUILTIN_TOOL_NAMES` and `LEGACY_TOOL_NAME_ALIASES` +### `BUILTIN_TOOL_NAMES` and `LEGACY_TOOL_NAME_ALIASES` Use these two constants to check tool names that your application’s users enter. Both spell each name the way you write it in permission rules, hook matchers, and the `tools` and `disallowedTools` options. Import them from `@anthropic-ai/claude-agent-sdk` or from `@anthropic-ai/claude-agent-sdk/core`. They require Agent SDK v0.3.301 or later and are alpha. The SDK’s type declarations give `BUILTIN_TOOL_NAMES` a readonly tuple type and `LEGACY_TOOL_NAME_ALIASES` a string-to-string record type: @@ -6354,11 +5234,7 @@ You can confirm a name with either of two tests: `BUILTIN_TOOL_NAMES` includes it, or `Object.hasOwn(LEGACY_TOOL_NAME_ALIASES, name)` returns `true`. A name that fails both can still be valid, because `BUILTIN_TOOL_NAMES` leaves out MCP tools and some built-in tools. If you build a deny list from `BUILTIN_TOOL_NAMES`, Claude can still use the tools the constant leaves out. To deny every tool, set [`disallowedTools: ["*"]`](</docs/en/agent-sdk/permissions#allow-and-deny-rules>) instead. Finding a name in `BUILTIN_TOOL_NAMES` doesn’t tell you the session has that tool: `TodoWrite` is listed even though it’s [disabled by default](</docs/en/tools-reference>). To see which tools a session has, read the `tools` array of its `SDKSystemMessage`. That array includes MCP tools and lists the Agent tool as `Task`, so map each name through `LEGACY_TOOL_NAME_ALIASES` before comparing it with `BUILTIN_TOOL_NAMES`. -### - -​ - -`AbortError` +### `AbortError` Custom error class for abort operations. @@ -6366,17 +5242,9 @@ `AbortError` is the only error class in the SDK’s typed API. Other failures, such as the Claude Code process exiting or failing to launch, reject the message iteration with errors that carry no SDK class to match on. [Troubleshooting](</docs/en/agent-sdk/troubleshooting>) keys those errors by message, with the cause and fix for each. -## - -​ - -Sandbox Configuration - -### - -​ - -`SandboxSettings` +## Sandbox Configuration + +### `SandboxSettings` Configuration for sandbox behavior. Use this to enable command sandboxing and configure network restrictions programmatically. @@ -6410,11 +5278,7 @@ The sandbox depends on platform support and, on Linux, tools like `bubblewrap` and `socat`. When `enabled` is `true` and the sandbox can’t start, `query()` reports a `result` message with `subtype: "error_during_execution"` and the reason in `errors`. For a single message `query()` call, the SDK throws after yielding that error result, so wrap the loop in a try block to continue past it. See [Handle the result](</docs/en/agent-sdk/agent-loop#handle-the-result>) for the error contract.To run unsandboxed instead, set `failIfUnavailable: false`. -#### - -​ - -Example usage +#### Example usage import { query } from "@anthropic-ai/claude-agent-sdk"; @@ -6441,11 +5305,7 @@ **Unix socket security:** The `allowUnixSockets` option can grant access to system services that reach outside the sandbox. For example, allowing `/var/run/docker.sock` effectively grants full host system access through the Docker API, bypassing sandbox isolation. Only allow Unix sockets that are strictly necessary and understand the security implications of each. -### - -​ - -`SandboxNetworkConfig` +### `SandboxNetworkConfig` Network-specific configuration for sandbox mode. These settings apply to sandboxed Bash commands when `enabled` is `true` in the parent `SandboxSettings`. They do not restrict the WebFetch tool, which uses [permission rules](</docs/en/permissions#webfetch>) instead. @@ -6475,11 +5335,7 @@ The built-in sandbox proxy enforces `allowedDomains` based on the requested hostname. By default, the proxy doesn’t terminate or inspect TLS traffic, so techniques such as [domain fronting](<https://en.wikipedia.org/wiki/Domain_fronting>) can potentially bypass `allowedDomains`. See [Sandboxing security limitations](</docs/en/sandboxing#security-limitations>) for details and [Secure deployment](</docs/en/agent-sdk/secure-deployment#traffic-forwarding>) for configuring a TLS-terminating proxy. -### - -​ - -`SandboxFilesystemConfig` +### `SandboxFilesystemConfig` Filesystem-specific configuration for sandbox mode. @@ -6495,11 +5351,7 @@ `denyWrite`| `string[]`| `[]`| File path patterns to deny write access to. To block sandboxed writes to a file in the session’s working directory, list its absolute path. `denyRead`| `string[]`| `[]`| File path patterns to deny read access to -### - -​ - -Permissions Fallback for Unsandboxed Commands +### Permissions Fallback for Unsandboxed Commands When `allowUnsandboxedCommands` is enabled, the model can request to run commands outside the sandbox by setting `dangerouslyDisableSandbox: true` in the tool input. These requests fall back to the existing permissions system, meaning your `canUseTool` handler is invoked, allowing you to implement custom authorization logic. Your `excludedCommands` entries instead take a call out of the sandbox with no model involvement; [`sandbox.excludedCommands`](</docs/en/settings-reference#sandbox-excludedcommands>) covers when an entry applies. In the example below, `isCommandAuthorized` stands in for an authorization check you define. @@ -6536,11 +5388,7 @@ Commands running with `dangerouslyDisableSandbox: true` have full system access. Ensure your `canUseTool` handler validates these requests carefully.If `permissionMode` is set to `bypassPermissions` and `allowUnsandboxedCommands` is enabled, the model can autonomously execute commands outside the sandbox without approval prompts, apart from the [actions no mode auto-approves](</docs/en/permission-modes#actions-no-mode-auto-approves>). This combination effectively allows the model to escape sandbox isolation silently. -## - -​ - -See also +## See also * [SDK overview](</docs/en/agent-sdk/overview>) \- General SDK concepts * [Python SDK reference](</docs/en/agent-sdk/python>) \- Python SDK documentation
modified TypeScript SDK V2 session API (removed) View current →
Show diff (173 lines)
--- a/typescript-v2-preview.md +++ b/typescript-v2-preview.md @@ -6,11 +6,7 @@ * `session.send()`: Send a message * `session.stream()`: Get the response -## - -​ - -Installation +## Installation Agent SDK 0.2.x is the last version that includes the V2 interface. The package version jumped from 0.2.x directly to 0.3.142, so the removal version above and the install pin below describe the same boundary. To install the last V2-compatible release, pin the major and minor version: @@ -18,17 +14,9 @@ The SDK bundles a native Claude Code binary for your platform as an optional dependency, so most installs need no separate Claude Code install. See the [quickstart’s install note](</docs/en/agent-sdk/quickstart>) for the installs that need one. -## - -​ - -Quick start - -### - -​ - -One-shot prompt +## Quick start + +### One-shot prompt For simple single-turn queries where you don’t need to maintain a session, use `unstable_v2_prompt()`. This example sends a math question and logs the answer: @@ -41,11 +29,7 @@ console.log(result.result); } -### - -​ - -Basic session +### Basic session For interactions beyond a single prompt, create a session. V2 separates sending and streaming into distinct steps: @@ -72,11 +56,7 @@ } } -### - -​ - -Multi-turn conversation +### Multi-turn conversation Sessions persist context across multiple exchanges. To continue a conversation, call `send()` again on the same session. Claude remembers the previous turns. This example asks a math question, then asks a follow-up that references the previous answer: @@ -111,11 +91,7 @@ } } -### - -​ - -Session resume +### Session resume If you have a session ID from a previous interaction, you can resume it later. This is useful for long-running workflows or when you need to persist conversations across application restarts. This example creates a session, stores its ID, closes it, then resumes the conversation: @@ -163,11 +139,7 @@ if (text) console.log("Resumed response:", text); } -### - -​ - -Cleanup +### Cleanup Sessions can be closed manually or automatically using [`await using`](<https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html#using-declarations-and-explicit-resource-management>), a TypeScript 5.2+ feature for automatic resource cleanup. If you’re using an older TypeScript version or encounter compatibility issues, use manual cleanup instead. The examples below show only the cleanup pattern and don’t send any messages, so running them produces no output. **Automatic cleanup (TypeScript 5.2+):** @@ -188,17 +160,9 @@ // ... use the session ... session.close(); -## - -​ - -API reference - -### - -​ - -`unstable_v2_createSession()` +## API reference + +### `unstable_v2_createSession()` Creates a new session for multi-turn conversations. @@ -207,11 +171,7 @@ // Additional options supported }): SDKSession; -### - -​ - -`unstable_v2_resumeSession()` +### `unstable_v2_resumeSession()` Resumes an existing session by ID. @@ -223,11 +183,7 @@ } ): SDKSession; -### - -​ - -`unstable_v2_prompt()` +### `unstable_v2_prompt()` One-shot convenience function for single-turn queries. @@ -239,11 +195,7 @@ } ): Promise<SDKResultMessage>; -### - -​ - -SDKSession interface +### SDKSession interface interface SDKSession { readonly sessionId: string; @@ -252,22 +204,14 @@ close(): void; } -## - -​ - -Feature availability +## Feature availability The V2 session API does not support every V1 feature. The following require the [V1 SDK](</docs/en/agent-sdk/typescript>): * Session forking (`forkSession` option) * Some advanced streaming input patterns -## - -​ - -See also +## See also * [TypeScript SDK reference (V1)](</docs/en/agent-sdk/typescript>) \- Full V1 SDK documentation * [SDK overview](</docs/en/agent-sdk/overview>) \- General SDK concepts
modified Find bugs with ultrareview View current →
Show diff (158 lines)
--- a/ultrareview.md +++ b/ultrareview.md @@ -8,11 +8,7 @@ Ultrareview requires authentication with a claude.ai account because it runs as a cloud session on Anthropic’s infrastructure. If you are signed in with an API key only, run `/login` and authenticate with claude.ai first. Ultrareview is not available when using Claude Code with Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry, and it is not available to organizations that have enabled Zero Data Retention or have the [HIPAA configuration](</docs/en/hipaa-setup>) applied. In these cases, `/code-review ultra` runs a local review in your session instead. Organizations that use [customer-managed encryption keys](<https://platform.claude.com/docs/en/manage-claude/cmek>) (CMEK) can’t run ultrareview. To review your changes locally, run `/code-review`. -## - -​ - -Run ultrareview from the CLI +## Run ultrareview from the CLI Start a review from any git repository: @@ -20,11 +16,7 @@ Without arguments, ultrareview reviews the diff between your current branch and the default branch, including uncommitted and staged changes. For a branch review, Claude Code bundles the repository state and uploads it to a cloud sandbox under the rules for [uploading a local repository to a cloud session](</docs/en/claude-code-on-the-web#send-local-repositories-without-github>), which cover the size limits, the checkout requirements, and what happens to uncommitted changes in files named like credentials or keys, such as `.env` and `*.tfvars` files. When you review a pull request, Claude Code uploads nothing from your machine. Before launching, Claude Code shows a confirmation dialog with the review scope, your remaining free runs, and the estimated cost; for a branch review, the scope includes the file and line count. After you confirm, the review continues in the background while you keep using your session. The command runs only when you invoke it with `/code-review ultra`; Claude doesn’t start an ultrareview on its own. -### - -​ - -Review against a different base +### Review against a different base To compare against a base other than the default branch, pass the branch name. This example reviews your current branch against `develop` instead: @@ -32,11 +24,7 @@ The base branch doesn’t need to exist in your local clone; Claude Code fetches it from `origin`. If the name has a typo, Claude Code suggests the closest branch name in the error. A commit id or tag also works as the base, and the review then covers the changes on your branch since that commit. -### - -​ - -Review a pull request +### Review a pull request To review a pull request on `github.com` instead of a local branch, pass the PR number: @@ -44,11 +32,7 @@ The command also accepts `#1234`, `PR 1234`, and pasted PR URLs; a pasted URL must point to the repository in your current directory. PR mode needs a repository on `github.com`. For a repository on a [GitHub Enterprise Server](</docs/en/github-enterprise-server>) instance, run `/code-review ultra` without a PR number to review your local branch instead. In PR mode, the cloud sandbox clones the pull request from `github.com` instead of uploading your working tree. It uses the GitHub account connected to your Claude account, so that account needs read access to the repository. Run [`/web-setup`](</docs/en/web-quickstart#connect-from-your-terminal>) to connect your GitHub CLI login to your Claude account. -### - -​ - -Post findings to the pull request +### Post findings to the pull request On Claude Code v2.1.227 or later, when you review a pull request on `github.com`, you can have Claude post the finished findings to the PR as a single plain comment from your own GitHub account. The comment isn’t a review or an approval, and it ends with a “Generated by Claude Code” note. When you review a branch, Claude Code shows the findings in your session only. Claude Code never posts unless you choose to on that run, and `--no-post` is the default. Posting is a choice you make for each run: @@ -61,11 +45,7 @@ * **Already posted** : an earlier post of the same review already put the comment on the PR, so Claude links you to the pull request instead of posting again. * **Failed** : Claude tells you why, and the findings stay in your terminal so you can post them by hand. -### - -​ - -Pass a request in plain words +### Pass a request in plain words You can also describe what you’re working on in plain words: @@ -75,11 +55,7 @@ If your repository is too large to bundle, Claude Code prompts you to use PR mode instead. For a repository on `github.com`, push your branch and open a draft PR, then run `/code-review ultra <PR-number>`. -### - -​ - -Diff limits and fallbacks +### Diff limits and fallbacks Ultrareview checks the diff before any review work runs and tells you when it can’t review it as-is: @@ -88,11 +64,7 @@ * **First commit** : a repository’s first commit has nothing earlier to compare with, so ultrareview reviews every file in it after you confirm in the launch dialog. If you have untracked files, it refuses instead and tells you to `git add` the ones you want reviewed. The same size limits apply. A first commit is reviewed whole only after that confirmation, so the `claude ultrareview` subcommand and `claude -p` refuse it and point you to an interactive session instead. Requires Claude Code v2.1.277 or later * **No merge base** : when your branch shares no history with the base branch, or the repository has no base branch to compare with, ultrareview reviews every tracked file in the repository instead. The fallback requires a full clone and applies the same size limits. It launches only when you confirm in the launch dialog or run the `claude ultrareview` subcommand yourself. In `claude -p` and anywhere else neither happens, ultrareview refuses, says the review would cover every file, and points you to an interactive session. On a checkout with no branches or other refs, such as a detached HEAD created by checking out `FETCH_HEAD` after fetching a URL, Claude Code [refuses the review](</docs/en/errors#your-checkout-has-no-branches>) and suggests creating a branch first -## - -​ - -Pricing and free runs +## Pricing and free runs Ultrareview is a premium feature that bills against usage credits rather than your plan’s included usage. @@ -108,11 +80,7 @@ Because ultrareview always bills as usage credits outside the free runs, your account or organization must have usage credits turned on before you can launch a paid review. If usage credits aren’t turned on, Claude Code blocks the launch. If you can manage billing for your account, Claude Code links you to the billing settings where you can turn on usage credits. You can also run `/usage-credits` to check or change your usage-credits setting. Claude Code asks you to confirm usage-credits billing once per conversation: when you start a new conversation, for example with `/clear`, Claude Code shows the confirmation again for the next paid review. -## - -​ - -Track a running review +## Track a running review A review typically takes 5 to 15 minutes. The review runs as a background task, so you can keep working in your session or start other commands. If you chose to post the findings to the pull request, keep the session open until the review finishes; if the session ends first, Claude Code posts nothing. Use `/tasks` to see running and completed reviews, open the detail view for a review, or stop a review that is in progress. If you stop a review, Claude Code archives the cloud session and doesn’t return partial findings. Claude can also tell you that a review was stopped or that its session wasn’t found: @@ -122,11 +90,7 @@ When the review finishes, Claude Code shows the verified findings as a notification in your session. Each finding includes the file location and an explanation of the issue so you can ask Claude to fix it directly. -## - -​ - -Run ultrareview non-interactively +## Run ultrareview non-interactively Use the `claude ultrareview` subcommand to start an ultrareview from CI or a script without an interactive session. The subcommand launches the same review as `/code-review ultra`, blocks until the remote review finishes, and prints the findings to stdout. If the run exits with `Error: Workspace not trusted`, see Trust the folder before the review runs. @@ -159,11 +123,7 @@ For automatic reviews on GitHub pull requests, [Code Review](</docs/en/code-review>) integrates with your repository directly and posts findings as inline PR comments without a CLI step. -### - -​ - -Trust the folder before the review runs +### Trust the folder before the review runs When `claude ultrareview` asks `Trust <folder>? [y/N]`, answer `y` to [trust the folder](</docs/en/permissions#project-allow-rules-and-workspace-trust>). Trust it only if you trust its code, because git and Claude Code can then run programs named in its git configuration and project settings. When it can’t ask you, such as in a CI job or with output sent to a file, it exits with [`Error: Workspace not trusted`](</docs/en/errors#workspace-not-trusted-when-running-claude-ultrareview>). Append `--trust-workspace` to trust the folder for that run: @@ -171,11 +131,7 @@ To review an untrusted pull request, run `claude ultrareview <PR number> --trust-workspace` from a branch you trust. The PR is cloned in the cloud, so you don’t need its branch locally. -## - -​ - -How ultrareview compares to /code-review +## How ultrareview compares to /code-review Both reviews examine code, but you use them at different stages of your workflow. @@ -190,11 +146,7 @@ Use `/code-review` for fast feedback as you work, or pass a PR number to review a teammate’s pull request before approving it. Use `/code-review ultra` before merging a substantial change when you want a deeper pass that catches issues a local review might miss. -## - -​ - -Related resources +## Related resources * [Use Claude Code in the cloud](</docs/en/claude-code-on-the-web>): learn how cloud sessions and cloud sandboxes work * [Manage costs effectively](</docs/en/costs>): track usage and set spending limits
modified Handle approvals and user input View current →
Show diff (176 lines)
--- a/user-input.md +++ b/user-input.md @@ -1,10 +1,6 @@ While working on a task, Claude sometimes needs to check in with users. It might need permission before deleting files, or need to ask which database to use for a new project. Your application needs to surface these requests to users so Claude can continue with their input. Claude requests user input in two situations: when it needs **permission to use a tool** (like deleting files or running commands), and when it has **clarifying questions** (via the `AskUserQuestion` tool). Both trigger your `canUseTool` callback, which pauses execution until you return a response. This is different from normal conversation turns where Claude finishes and waits for your next message. For clarifying questions, Claude generates the questions and options. Your role is to present them to users and return their selections. You can’t add your own questions to this flow; if you need to ask users something yourself, do that separately in your application logic. The callback can stay pending indefinitely. Execution remains paused until your callback returns. If a user might take longer to respond than your process can reasonably stay running, register a [`PreToolUse` hook](</docs/en/agent-sdk/hooks>) that returns the [`defer` decision](</docs/en/hooks#defer-a-tool-call-for-later>) instead of waiting in the callback, so the process can exit and resume later from the persisted session. This guide shows you how to detect each type of request and respond appropriately. -## - -​ - -Detect when Claude needs input +## Detect when Claude needs input Pass a `canUseTool` callback in your query options. The callback fires whenever Claude needs user input, receiving the tool name and input as arguments: @@ -39,11 +35,7 @@ You can also use the [`PermissionRequest` hook](</docs/en/agent-sdk/hooks#available-hooks>) to send external notifications (Slack, email, push) when Claude is waiting for approval. -## - -​ - -Handle tool approval requests +## Handle tool approval requests Once you’ve passed a `canUseTool` callback in your query options, it fires when Claude wants to use a tool that nothing earlier in the permission flow has approved. In some configurations, such as `dontAsk` mode, Claude Code doesn’t call it; the last step of [How permissions are evaluated](</docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) lists them and says what happens to the call instead. Your callback receives three arguments: @@ -176,11 +168,7 @@ This example uses a `y/n` flow where any input other than `y` is treated as a denial. In practice, you might build a richer UI that lets users modify the request, provide feedback, or redirect Claude entirely. See Respond to tool requests for all the ways you can respond. -### - -​ - -Respond to tool requests +### Respond to tool requests Your callback returns one of two response types: @@ -356,11 +344,7 @@ For a complete change of direction (not just a nudge), use [streaming input](</docs/en/agent-sdk/streaming-vs-single-mode>) to send Claude a new instruction directly. This bypasses the current tool request and gives Claude entirely new instructions to follow. -## - -​ - -Handle clarifying questions +## Handle clarifying questions When Claude needs more direction on a task with multiple valid approaches, it calls the `AskUserQuestion` tool. This triggers your `canUseTool` callback with `toolName` set to `AskUserQuestion`. The input contains Claude’s questions as multiple-choice options, which you display to the user and return their selections. @@ -503,11 +487,7 @@ } }; -### - -​ - -Question format +### Question format The input contains Claude’s generated questions in a `questions` array. Each question has these fields: @@ -534,11 +514,7 @@ ] } -#### - -​ - -Option previews (TypeScript) +#### Option previews (TypeScript) `toolConfig.askUserQuestion.previewFormat` adds a `preview` field to each option so your app can show a visual mockup alongside the label. Without this setting, Claude does not generate previews and the field is absent. @@ -575,11 +551,7 @@ "preview": "<div style=\"padding:12px;border:1px solid #ddd;border-radius:8px\"><div style=\"font-size:12px;color:#666\">Active users</div><div style=\"font-size:28px;font-weight:600\">1,284</div></div>" } -### - -​ - -Response format +### Response format Return an `answers` object mapping each question’s `question` field to the selected option’s `label`: @@ -601,11 +573,7 @@ } } -#### - -​ - -Support free-text input +#### Support free-text input Claude’s predefined options won’t always cover what users want. To let users type their own answer: @@ -614,11 +582,7 @@ See the complete example below for a full implementation. -### - -​ - -Complete example +### Complete example Claude asks clarifying questions when it needs user input to proceed. For example, when asked to help decide on a tech stack for a mobile app, Claude might ask about cross-platform vs native, backend preferences, or target platforms. These questions help Claude make decisions that match the user’s preferences rather than guessing. This example handles those questions in a terminal application. Here’s what happens at each step: @@ -777,28 +741,16 @@ main(); -## - -​ - -Limitations +## Limitations * **Subagents** : `AskUserQuestion` is not currently available in subagents spawned via the Agent tool * **Question limits** : each `AskUserQuestion` call supports 1-4 questions with 2-4 options each -## - -​ - -Other ways to get user input +## Other ways to get user input The `canUseTool` callback and `AskUserQuestion` tool cover most approval and clarification scenarios, but the SDK offers other ways to get input from users: -### - -​ - -Streaming input +### Streaming input Use [streaming input](</docs/en/agent-sdk/streaming-vs-single-mode>) when you need to: @@ -808,11 +760,7 @@ Streaming input is ideal for conversational UIs where users interact with the agent throughout execution, not just at approval checkpoints. -### - -​ - -Custom tools +### Custom tools Use [custom tools](</docs/en/agent-sdk/custom-tools>) when you need to: @@ -822,11 +770,7 @@ Custom tools give you full control over the interaction, but require more implementation work than using the built-in `canUseTool` callback. -## - -​ - -Related resources +## Related resources * [Configure permissions](</docs/en/agent-sdk/permissions>): set up permission modes and rules * [Control execution with hooks](</docs/en/agent-sdk/hooks>): run custom code at key points in the agent lifecycle
modified Voice dictation View current →
Show diff (123 lines)
--- a/voice-dictation.md +++ b/voice-dictation.md @@ -1,10 +1,6 @@ Speak your prompts instead of typing them in the Claude Code CLI. Your speech is transcribed live into the prompt input, so you can mix voice and typing in the same message. Enable dictation with `/voice`, then either hold a key while you speak or tap once to start and again to send. In hold mode, dictation also works in [agent view](</docs/en/agent-view#peek-and-reply>). Hold your push-to-talk key while the dispatch input or a peek-panel reply is focused to dictate to a background session. -## - -​ - -Requirements +## Requirements Voice dictation streams your recorded audio to Anthropic’s servers for transcription. Audio is not processed locally. It needs all of the following: @@ -14,11 +10,7 @@ Transcription does not consume Claude messages or tokens and does not count toward the limits shown in `/usage`. See [data usage](</docs/en/data-usage>) for how Anthropic handles your data. Audio recording uses a built-in native module on macOS, Linux, and Windows. On Linux, if the native module cannot load, Claude Code falls back to `arecord` from ALSA utils or `rec` from SoX. If neither is available, `/voice` prints an install command for your package manager. The Claude Code [VS Code extension](</docs/en/vs-code>) also supports voice dictation with the same claude.ai account requirement. It is not available in VS Code Remote sessions, including SSH, Dev Containers, and Codespaces, because the microphone is on your local machine and the extension runs on the remote host. -## - -​ - -Enable voice dictation +## Enable voice dictation Run `/voice` to enable dictation. When you enable it, Claude Code runs a microphone check. On macOS, this triggers the system microphone permission prompt for your terminal if it has never been granted. @@ -45,11 +37,7 @@ For the first three sessions with voice dictation enabled, the input footer shows a `hold space to speak` hint when the prompt is empty. The hint reflects your current `voice:pushToTalk` binding and updates if you rebind the dictation key. The hint text is the same in both modes, and it does not appear if you have a [custom status line](</docs/en/statusline>) configured. Transcription is tuned for coding vocabulary in both modes. Common development terms like `regex`, `OAuth`, `JSON`, and `localhost` are recognized correctly, and your current project name and git branch name are added as recognition hints automatically. -## - -​ - -Hold to record +## Hold to record Hold mode is push-to-talk: recording runs while you hold the key and stops when you release it. This is the default mode. Hold `Space` to start recording. Claude Code detects a held key by watching for rapid key-repeat events from your terminal, so there is a brief warmup before recording begins. The footer shows `keep holding…` during warmup, then `listening…` once recording is active. While recording, the prompt cursor becomes a bar that rises and falls with your microphone level, unless you have [`prefersReducedMotion`](</docs/en/settings-reference#prefersreducedmotion>) turned on. The first couple of key-repeat characters type into the input during warmup and are removed automatically when recording activates. A single `Space` tap still types a space, since hold detection only triggers on rapid repeat. Holding or tapping `Space` starts dictation only where the keypress would otherwise type into the prompt. In the [transcript viewer](</docs/en/interactive-mode#transcript-viewer>), `Space` pages through the conversation, and in [vim mode](</docs/en/interactive-mode#vim-editor-mode>) outside INSERT it is a command. A rebound modifier combination like `meta+k` never types text, so it starts dictation from those places too. @@ -63,27 +51,15 @@ By default, when you release the key, Claude Code inserts the transcript and waits for you to press `Enter`. Set `"autoSubmit": true` in the `voice` settings object to send the prompt automatically when you release the key, as long as the transcript is at least three words long. -## - -​ - -Tap to record and send +## Tap to record and send Tap mode toggles recording with a single keypress: tap once to start, speak, then tap again to send the prompt. There is no warmup, and you don’t need to keep the key held. Enable tap mode with `/voice tap`. With the prompt input empty, tap `Space` to start recording. The footer shows `● REC · tap to send` while recording. Tap `Space` again to stop. Claude Code inserts the transcript and submits the prompt automatically when the transcript is at least three words long. Shorter transcripts are inserted but not submitted, so an accidental tap does not send a stray word. The three-word threshold counts words for languages written without spaces. Japanese, Chinese, and Thai transcripts count individual words, so they auto-submit in tap mode and in hold mode with `autoSubmit`. The first tap only starts recording when the prompt input is empty, so you can still type spaces normally while composing a message. The second tap stops recording regardless of input contents. Recording also stops automatically after 15 seconds of silence or two minutes total. -## - -​ - -Cancel a recording +## Cancel a recording Press `Esc` or `Ctrl+C` to cancel a dictation instead of finalizing it. Claude Code stops the microphone, discards the transcript, and restores the prompt to what it held before the recording started. Both keys also cancel while a finished recording’s transcript is still processing. A prompt you edited or submitted during processing stays as you left it. Neither key does anything else in the press that cancels: `Esc` doesn’t interrupt Claude’s response, and `Ctrl+C` doesn’t clear the prompt or count as the first of the [two presses that exit Claude Code](</docs/en/interactive-mode#general-controls>). -## - -​ - -Change the dictation language +## Change the dictation language Voice dictation uses the same [`language` setting](</docs/en/settings-reference#language>) that controls Claude’s response language. If that setting is empty, dictation defaults to English. In the VS Code extension, if `language` is empty, dictation uses VS Code’s `accessibility.voice.speechLanguage` setting before defaulting to English. @@ -120,11 +96,7 @@ If your `language` setting is not in the supported list, `/voice` warns you on enable and falls back to English for dictation. Claude’s text responses are not affected by this fallback. -## - -​ - -Rebind the dictation key +## Rebind the dictation key The dictation key is bound to `voice:pushToTalk` in the `Chat` context and defaults to `Space`. The same binding controls both hold and tap modes. Rebind it in [`~/.claude/keybindings.json`](</docs/en/keybindings>): @@ -142,11 +114,7 @@ The `voice:pushToTalk` action uses one key at a time. When you bind a custom key, it replaces the default `Space` binding rather than adding a second trigger, so the `"space": null` line in this example is for clarity and can be omitted without changing behavior. In hold mode, avoid binding a bare letter key like `v` since hold detection relies on key-repeat and the letter types into the prompt during warmup. Use `Space`, or use a modifier combination like `meta+k` to start recording on the first keypress with no warmup. Tap mode has no warmup, so most keys work. Some keys are not delivered to terminal applications and can’t be bound at all. For example, `Caps Lock` shows an error if you try to bind it. See [customize keyboard shortcuts](</docs/en/keybindings>) for the full keybinding syntax and the list of reserved shortcuts. -## - -​ - -Troubleshooting +## Troubleshooting Common issues when voice dictation does not activate or record: @@ -168,11 +136,7 @@ * **`Dictation stopped: no speech recognized for 15 seconds` or `Dictation stopped at its 2-minute limit`**: in the VS Code extension, a recording ends after 15 seconds with no recognized words, or two minutes after it starts. If you were speaking during those 15 seconds, try the fixes for `No speech detected`. Words already recognized stay in the prompt box and aren’t sent. To add more, click the microphone button again. * **Transcription is garbled or in the wrong language** : dictation defaults to English. If you are dictating in another language, set it in `/config` first. See Change the dictation language. -### - -​ - -Terminal not listed in macOS Microphone settings +### Terminal not listed in macOS Microphone settings If your terminal app does not appear under System Settings → Privacy & Security → Microphone, there is no toggle you can enable. Reset the permission state for your terminal so the next `/voice` run triggers a fresh macOS permission prompt. @@ -196,11 +160,7 @@ Start Claude Code and run `/voice`. macOS prompts for microphone access; allow it. -## - -​ - -See also +## See also * [Customize keyboard shortcuts](</docs/en/keybindings>): rebind `voice:pushToTalk` and other CLI keyboard actions * [All settings](</docs/en/settings-reference#voice>): the `voice`, `language`, and other settings keys
modified Use Claude Code in VS Code View current →
Show diff (809 lines)
--- a/vs-code.md +++ b/vs-code.md @@ -6,11 +6,7 @@ * Access conversation history * Open multiple conversations in separate tabs or windows -## - -​ - -Prerequisites +## Prerequisites Before installing, make sure you have: @@ -19,11 +15,7 @@ The extension bundles its own copy of the CLI (command-line interface) for the chat panel. To run `claude` in VS Code’s integrated terminal, you also need the [standalone CLI install](</docs/en/setup>). See VS Code extension vs. Claude Code CLI for details. -## - -​ - -Install the extension +## Install the extension Click the link for your IDE to install directly: @@ -42,11 +34,7 @@ If the extension doesn’t appear after installation, restart VS Code or run “Developer: Reload Window” from the Command Palette. -## - -​ - -Get started +## Get started Once installed, you can start using Claude Code through the VS Code interface: @@ -93,11 +81,7 @@ Run “Claude Code: Open Walkthrough” from the Command Palette for a guided tour of the basics. -## - -​ - -Use the prompt box +## Use the prompt box The prompt box supports several features: @@ -138,67 +122,39 @@ * **Extended thinking** : lets Claude spend more time reasoning through complex problems. To turn it off or back on, use the **Thinking** switch in the Model section of the command menu (`/`). On models where [thinking can’t be turned off](</docs/en/model-config#extended-thinking>), the menu has no **Thinking** switch and thinking stays on. A thinking block that shows only a label, such as `Thought for 12s`, has no text and doesn’t open when you click it. To see thinking summaries, set [`showThinkingSummaries`](</docs/en/settings-reference#showthinkingsummaries>) to `true` in `~/.claude/settings.json`, then run **Developer: Reload Window** from the Command Palette. Thinking blocks you already have stay empty. In responses after the reload, click a block or press `Ctrl+O` to expand them all. * **Multi-line input** : press `Shift+Enter` to add a new line without sending. This also works in the “Other” free-text input of question dialogs. -### - -​ - -Reference files and folders +### Reference files and folders Use @-mentions to give Claude context about specific files or folders. When you type `@` followed by a file or folder name, Claude reads that content and can answer questions about it or make changes to it. Claude Code supports fuzzy matching, so you can type partial names to find what you need: Explain the logic in @auth (fuzzy matches auth.js, AuthService.ts, etc.) What's in @src/components/ (include a trailing slash for folders) -### - -​ - -Read specific pages of a PDF +### Read specific pages of a PDF For large PDFs, you can ask Claude to read specific pages instead of the whole file. Ask for a single page, a range like pages 1-10, or an open-ended range like page 3 onward. Reading specific pages requires [poppler-utils](</docs/en/tools-reference#read-tool-behavior>) on the machine where Claude Code runs. -### - -​ - -Include terminal output in prompts +### Include terminal output in prompts Reference terminal output in your prompts using `@terminal:name` where `name` is the terminal’s title. This lets Claude see command output, error messages, or logs without copy-pasting. -### - -​ - -Attach images and files +### Attach images and files * To attach an image, paste it from your clipboard into the prompt box. * To attach files, hold `Shift` while dragging them into the prompt box. * To remove an attachment from context, click the X on it. -### - -​ - -Paste text +### Paste text Text you paste stays visible in the prompt box, rather than collapsing to a placeholder as it does [in the terminal](</docs/en/terminal-config#paste-large-content>). In sessions where Claude Code [marks pasted text](</docs/en/terminal-config#how-claude-treats-pasted-text>), Claude still sees a large paste as text you pasted rather than typed. Claude Code also removes [invisible Unicode characters](</docs/en/interactive-mode#invisible-characters-in-prompts>) from text you paste into the prompt box and from anything else you send: * If a notice such as `Removed 3 invisible characters from the pasted text` appears when you paste, the text went in without those characters. * If a notice about removed characters appears when you send, nothing was sent. The cleaned text is back in the prompt box. Send again to send the text as shown. -### - -​ - -Automatic context from your selection and open file +### Automatic context from your selection and open file When you select text in the editor, Claude can see your highlighted code automatically. The prompt box footer shows how many lines are selected. Claude also sees which file you have open in the editor, even when nothing is selected, and the prompt box shows its name. Press `Option+K` (Mac) / `Alt+K` (Windows/Linux) to insert an @-mention with the file path and line numbers, for example `@app.ts#5-10`. -#### - -​ - -Keep your selection and open file out of your messages +#### Keep your selection and open file out of your messages To stop selected text or your open file from going into your messages, turn off the matching setting in VS Code’s settings: @@ -207,11 +163,7 @@ To add text as an @-mention with Attach Selection off, select it and press `Option+K` on Mac or `Alt+K` on Windows and Linux. Both settings also apply when you run `claude` in VS Code’s integrated terminal. -#### - -​ - -Selected text from excluded or ignored files +#### Selected text from excluded or ignored files In the chat panel, the extension withholds selected text from some files: @@ -220,11 +172,7 @@ This filter covers the chat panel only. When Claude Code runs in the integrated terminal, Claude can receive text you select in these files. To keep a file’s contents from Claude there, add a [`Read` deny rule](</docs/en/permissions#read-and-edit>). -### - -​ - -LaTeX math in responses +### LaTeX math in responses The chat panel shows LaTeX math in Claude’s responses as typeset formulas. Math rendering requires Claude Code v2.1.301 or later. In terminal mode, math isn’t typeset. The panel typesets both display math and inline math: @@ -233,11 +181,7 @@ The panel tries to tell math apart from other uses of the same characters, so text such as `$HOME`, a price like `$5`, or `sed 's/\(foo\)/\1/'` isn’t typeset. Neither is text inside a code span or inside any code block other than a fenced `math` block. If a formula shows as written when you expected it typeset, see A formula shows as raw LaTeX. When you select and copy text that includes a typeset formula, you get the formula’s TeX source in `$…$` or `$$…$$` delimiters rather than the drawn symbols. **Copy response** and `/copy` give you the response as Claude wrote it, TeX source included. -### - -​ - -Resume past conversations +### Resume past conversations Click the **Session history** button at the top of the Claude Code panel to access your conversation history. You can search by keyword or browse by time. Click any conversation to resume it. If the conversation is already open in another tab of the current window, clicking it switches to that tab. When a notice says the conversation is still open somewhere else, see how to continue it in this window. If the conversation opens with no messages showing, see why a resumed conversation is blank at first. For more on resuming sessions, see [Manage sessions](</docs/en/sessions>). @@ -256,11 +200,7 @@ * You have `claudeCode.claudeProcessWrapper` configured * A [deny rule](</docs/en/permissions#manage-permissions>) removes the [`ExitPlanMode`](</docs/en/tools-reference>) tool -#### - -​ - -The conversation is still open somewhere else +#### The conversation is still open somewhere else To continue in this window when a notice says the conversation is still open somewhere else, click **Open here anyway** after the step for your case: @@ -273,11 +213,7 @@ With `claudeProcessWrapper` set, the extension skips this check and opens the conversation directly. -### - -​ - -Resume cloud sessions from claude.ai +### Resume cloud sessions from claude.ai If you run [cloud sessions](</docs/en/claude-code-on-the-web>), you can resume them directly in VS Code. This requires signing in with **Claude.ai Subscription** , not Anthropic Console. @@ -303,11 +239,7 @@ The Web tab also lists your [Remote Control](</docs/en/remote-control>) sessions. If you click one that ran in the folder you have open, the extension opens that local conversation instead of downloading a copy. The extension focuses the tab already showing it, if there is one. If the extension can’t rule out that another Claude process has the conversation open, you get a downloaded copy instead. If any part of a conversation fails to download, an error appears and no copy is saved. Select the session again to retry. If you select a session that has no conversation to download yet, an error tells you where to continue it instead. -### - -​ - -Check account and usage +### Check account and usage Run `/usage` to open the Account & usage dialog, which shows your signed-in account and your usage. The usage figures match how you signed in: @@ -320,11 +252,7 @@ For more on tracking and reducing usage, see [Track your costs](</docs/en/costs#track-your-costs>). -### - -​ - -Rewind with checkpoints +### Rewind with checkpoints The VS Code extension supports checkpoints, which track Claude’s file edits and let you rewind to a previous state. Hover over any message to reveal the rewind button, then choose from three options: @@ -334,19 +262,11 @@ For full details on how checkpoints work and their limitations, see [Checkpointing](</docs/en/checkpointing>). -## - -​ - -Customize your workflow +## Customize your workflow You can reposition the Claude panel, run multiple conversations, group or filter the sessions list, or switch to terminal mode. -### - -​ - -Choose where Claude lives +### Choose where Claude lives You can drag the Claude panel to reposition it anywhere in VS Code. Grab the panel’s tab or title bar and drag it to: @@ -358,11 +278,7 @@ Use the sidebar for your main Claude session and open additional tabs for side tasks. Claude remembers your preferred location. The Activity Bar sessions list icon is separate from the Claude panel. The sessions list is always visible in the Activity Bar, while the Claude panel icon only appears there when the panel is docked to the left sidebar. -### - -​ - -Continue conversations after a reload +### Continue conversations after a reload After you run **Developer: Reload Window** or restart VS Code, check where the conversation was open: @@ -371,27 +287,15 @@ If a notice in place of the prompt box says the conversation is still open somewhere else, see how to continue the conversation here. If the messages stay blank at first, see why they’re blank and when they appear. -#### - -​ - -Interrupted steps after a reload +#### Interrupted steps after a reload If the reload interrupted Claude mid-step, Claude continues that step when the conversation comes back, and a notice in the chat marks the continuation. Requires Claude Code v2.1.274 or later. If the step was interrupted more than an hour ago or the session is open elsewhere, the conversation comes back idle instead. When a notice in the chat includes `plan mode is now off, so Claude did not continue on its own`, the step was interrupted in plan mode. To keep planning, select **Plan** in the mode indicator before you send your next message. -#### - -​ - -Turn off continuation after a reload +#### Turn off continuation after a reload To stop Claude from continuing an interrupted step after a reload, open the [Continue After Reload setting](<vscode://settings/claudeCode.continueAfterReload>) and uncheck it. If you set [`CLAUDE_CODE_RESUME_INTERRUPTED_TURN`](</docs/en/env-vars#variables>) or any other `CLAUDE_CODE_RESUME_` variable in VS Code’s environment or in the `environmentVariables` setting, it has no effect in the panel. That’s because the extension removes those variables before it starts the panel’s sessions. -#### - -​ - -A conversation was not reopened +#### A conversation was not reopened After a reload, a new chat with a notice like this above its prompt box means the panel left your conversation closed because the conversation’s last two opens didn’t finish: @@ -403,19 +307,11 @@ * **If the panel stops responding while the conversation loads** : reload the window. A new chat opens. * **To leave it closed** : keep working in the new chat. The notice disappears once you send a prompt. -### - -​ - -Run multiple conversations +### Run multiple conversations Use **Open in New Tab** or **Open in New Window** from the Command Palette to start additional conversations. Each conversation maintains its own history and context, allowing you to work on different tasks in parallel. When using tabs, a small colored dot on the spark icon indicates status: blue means a permission request is pending, orange means Claude finished while the tab was hidden. -### - -​ - -Organize sessions into groups +### Organize sessions into groups In the sessions list in the Activity Bar, you can collect related sessions into named, collapsible groups. Requires Claude Code v2.1.229 or later. @@ -426,11 +322,7 @@ The extension saves groups per workspace folder, so they survive window reloads and appear in every window where you open the same folder. When you search the list, the extension shows matches in one flat list across all groups. -### - -​ - -Filter the sessions list +### Filter the sessions list To narrow a long sessions list in the Activity Bar, use the two filter controls at the top of the list. Requires Claude Code v2.1.271 or later. Archived sessions don’t appear while either filter is on. @@ -439,27 +331,15 @@ When **Active** is on and you check a status, **Open** , or **Closed** , the list also shows every session that matches your checks. The filters you set persist across window reloads. -### - -​ - -Switch to terminal mode +### Switch to terminal mode By default, the extension opens a graphical chat panel. If you prefer the CLI-style interface, open the [Use Terminal setting](<vscode://settings/claudeCode.useTerminal>) and check the box. You can also press `Cmd+,` on Mac or `Ctrl+,` on Windows/Linux to open VS Code settings, go to **Extensions > Claude Code**, and check **Use Terminal**. -## - -​ - -Manage plugins +## Manage plugins The VS Code extension includes a graphical interface for installing and managing [plugins](</docs/en/plugins/overview>). Type `/plugins` in the prompt box to open the **Manage plugins** interface. -### - -​ - -Install plugins +### Install plugins The plugin dialog shows two tabs: **Plugins** and **Marketplaces**. In the Plugins tab: @@ -478,22 +358,14 @@ Once the install finishes, a form asks for any of the plugin’s [configuration options](</docs/en/plugins/components#user-configuration>) that aren’t set yet. To review or change the options later, click the gear icon on the plugin’s row. Sensitive text fields are masked, and a secret you saved earlier shows **(unchanged)**. Leave the field blank to keep the saved value. After you save changes, the open sessions reload their plugins and the dialog shows **Restart Claude to apply plugin changes**. -### - -​ - -Uninstall plugins +### Uninstall plugins Each installed row names the [scope](</docs/en/plugins/install#choose-an-install-scope>) it’s installed at. To uninstall that installation, click the row’s trash icon. A dimmed trash icon marks a row you can’t uninstall from this workspace, such as a plugin your organization manages or one installed for another project. The extension asks first in two cases: * **A plugin your project’s shared`.claude/settings.json` turns on**: choose **Disable for me** , which keeps the plugin installed for your collaborators, or **Uninstall for everyone** , which removes the project’s installation with [`--keep-data`](</docs/en/plugins/cli-reference#what-an-uninstall-deletes-and-keeps>), so the plugin’s saved data directory stays. If you already turned the plugin off for yourself, the trash icon removes your own installation without the question. * **Otherwise, the last installation of a plugin with saved data** : choose whether to keep or delete the data; **Keep** is the default -### - -​ - -Share a plugin install link +### Share a plugin install link To send someone straight to installing a specific plugin, give them the extension’s `install-plugin` URL. Opening it launches or focuses VS Code, opens the Claude Code panel, and opens the **Manage plugins** dialog on that plugin’s scope choice. Nothing installs until the person picks a scope. If the plugin’s marketplace isn’t configured in their Claude Code yet, the dialog first asks them to add it. @@ -520,11 +392,7 @@ GitHub READMEs, issues, and some other Markdown hosts strip links whose scheme isn’t `http` or `https`, so a `vscode://` link there renders as plain text. Put the URL in a code block on those hosts, as [The link renders as plain text instead of being clickable](</docs/en/deep-links#the-link-renders-as-plain-text-instead-of-being-clickable>) describes for `claude-cli://` links. -### - -​ - -Manage marketplaces +### Manage marketplaces Switch to the **Marketplaces** tab to add or remove plugin sources: @@ -538,11 +406,7 @@ For more about the plugin system, see [Plugins](</docs/en/plugins/overview>) and [Plugin marketplaces](</docs/en/plugins/overview>). -### - -​ - -Plugins that draw in the panel +### Plugins that draw in the panel A plugin that contains a [mod](</docs/en/plugins/mods/overview>) can draw in the chat panel. Drawing requires extension version 2.1.299 or later. A session that [doesn’t fetch feature flags](</docs/en/env-vars#features-that-need-feature-flag-fetching>), such as one on Amazon Bedrock, needs 2.1.304 or later. From such a plugin you can see: @@ -558,11 +422,7 @@ To stop a plugin from drawing, turn the plugin off in the plugin dialog. -## - -​ - -Automate browser tasks with Chrome +## Automate browser tasks with Chrome Connect Claude to your Chrome browser to test web apps, debug with console logs, and automate browser workflows without leaving VS Code. This requires the [Claude in Chrome extension](<https://chromewebstore.google.com/detail/claude/fcoeoabgfenejglbffodgkkbkcdhcgfn>) version 1.0.36 or later. Type `@browser` in the prompt box followed by what you want Claude to do: @@ -574,19 +434,11 @@ * [Permission prompts in VS Code sessions](</docs/en/chrome#permission-prompts-in-vs-code-sessions>): when Claude Code asks you before a browser action * [Use Claude Code with Chrome](</docs/en/chrome>): setup instructions, the full list of capabilities, and troubleshooting -## - -​ - -Work with git +## Work with git Claude Code integrates with git to help with version control workflows directly in VS Code. Ask Claude to commit changes, create pull requests, or work across branches. To start Claude in an isolated worktree with its own files and branch, see [Run parallel sessions with worktrees](</docs/en/worktrees>). -### - -​ - -Create commits and pull requests +### Create commits and pull requests Claude can stage changes, write commit messages, and create pull requests based on your work: @@ -596,27 +448,15 @@ When creating pull requests, Claude generates descriptions based on the actual code changes and can add context about testing or implementation decisions. -### - -​ - -Reopen a conversation that moved into a worktree +### Reopen a conversation that moved into a worktree On a reopened conversation, the **This session is in worktree** banner means the conversation’s working directory is the [worktree](</docs/en/worktrees>) it names, not the folder this window has open. To open the worktree in a new VS Code window, click **Open worktree** on the banner. A conversation moves into a worktree when, for example, you [ask Claude to work in one](</docs/en/worktrees#ask-claude-to-create-a-worktree>). When you reopen it, or the panel reopens it after a window reload, it resumes in the worktree if Claude Code created the worktree under `.claude/worktrees/` and it still exists. Before Claude Code v2.1.300, an empty conversation opened instead. On those versions, update the extension. -## - -​ - -Run work in the background +## Run work in the background Send a long-running command or subagent to the background, then check on it from the prompt box. -### - -​ - -Move a running command or subagent to the background +### Move a running command or subagent to the background When a command or a [subagent](</docs/en/sub-agents>) keeps Claude waiting longer than you want, click **Run in background** below its tool call in the conversation. Requires Claude Code v2.1.287 or later. @@ -625,38 +465,22 @@ To check on the task or stop it in the meantime, type `/tasks` in the prompt box to open the agent map. A subagent keeps its place in the tree of agents there, and a command is listed below the agents with its latest output on its card. -#### - -​ - -The Run in background action is missing under a subagent +#### The Run in background action is missing under a subagent By default in VS Code, subagents don’t show this action. To see why for one subagent, open its card in the agent map and read the `Spawned by` line: * **`Spawned by the main agent`** : the subagent started in the background, so Claude isn’t waiting for it and you don’t need to do anything. To have Claude wait for subagents instead, see [Let Claude wait for a subagent](</docs/en/sub-agents#let-claude-wait-for-a-subagent>). * **`Spawned by` names another subagent**: the action appears only for subagents the main agent spawned, not a [nested subagent](</docs/en/sub-agents#let-subagents-spawn-their-own-subagents>) another subagent waits for. To end the nested subagent early, click **Stop agent** on its card. The waiting subagent then carries on without that result. -### - -​ - -Monitor background processes +### Monitor background processes Type `/tasks` in the prompt box to open the agent map, which lists the session’s background tasks, such as a dev server Claude left running as a background shell command. Click a task to open its card, where you can stop it. Requires Claude Code v2.1.277 or later. For a background shell command, or a [monitor](</docs/en/tools-reference#monitor-tool>) that runs a command, the card also shows the command’s latest output and refreshes it while the command runs. -#### - -​ - -See a background subagent’s tool calls +#### See a background subagent’s tool calls When a subagent shows as one status line with no tool calls, type `/tasks` in the prompt box to open the agent map and click the subagent there. The subagent is running in the background, and its card shows its tool calls and a button that opens its transcript. -## - -​ - -VS Code commands and shortcuts +## VS Code commands and shortcuts To open the Command Palette, press `Cmd+Shift+P` on Mac or `Ctrl+Shift+P` on Windows/Linux. Type “Claude Code” there to see the extension’s Command Palette commands. Some shortcuts depend on which panel is “focused” (receiving keyboard input). When your cursor is in a code file, the editor is focused. When your cursor is in Claude’s prompt box, Claude is focused. Use `Cmd+Esc` / `Ctrl+Esc` to toggle between them. @@ -683,11 +507,7 @@ Show Logs| -| View extension debug logs Logout| -| Sign out of your Anthropic account -### - -​ - -Launch a VS Code tab from other tools +### Launch a VS Code tab from other tools The extension registers a URI handler at `vscode://anthropic.claude-code/open`. Use it to open a new Claude Code tab from your own tooling: a shell alias, a browser bookmarklet, or any script that can open a URL. If VS Code isn’t already running, opening the URL launches it first. If VS Code is already running, the URL opens in whichever window is currently focused. Invoke the handler with your operating system’s URL opener. @@ -724,11 +544,7 @@ The extension also handles `vscode://anthropic.claude-code/install-plugin`, which opens the plugin dialog on one plugin. To launch a terminal session instead of a VS Code tab, use the CLI’s `claude-cli://` handler. See [Launch sessions from links](</docs/en/deep-links>). -## - -​ - -Configure settings +## Configure settings You configure the extension in two places, VS Code’s extension settings and the Claude Code settings file: @@ -737,11 +553,7 @@ Add `"$schema": "https://json.schemastore.org/claude-code-settings.json"` to your `settings.json` to get autocomplete and inline validation for all available settings directly in VS Code. -### - -​ - -Extension settings +### Extension settings VS Code reads `initialPermissionMode` from your user settings and ignores workspace values. Before v2.1.225, VS Code defaulted the setting to `default` and applied workspace values. @@ -771,11 +583,7 @@ `allowDangerouslySkipPermissions`| `false`| Adds Bypass permissions to the mode selector. Use it only in sandboxes with no internet access. `claudeProcessWrapper`| -| Executable used to launch the Claude process. The bundled binary path is passed as an argument when present. Set this to a separately installed `claude` binary if the extension build doesn’t include one for your platform. -## - -​ - -Use third-party providers +## Use third-party providers By default, Claude Code connects directly to Anthropic’s API. If your organization uses Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry to access Claude, configure the extension to use your provider instead: @@ -799,11 +607,7 @@ On a third-party provider, the extension doesn’t offer features that require a claude.ai account, such as plan usage bars, [voice dictation](</docs/en/voice-dictation>), and the Web tab for cloud sessions. For what the Account & usage dialog shows on these sign-ins, see Check account and usage. A claude.ai sign-in left over from an earlier `/login` stays unused: the extension doesn’t send it with any request. -## - -​ - -Use a screen reader +## Use a screen reader The extension’s chat panel works with screen readers. You don’t need to turn anything on: the extension announces conversation activity for every user, with no visual change. This is separate from the CLI’s opt-in [screen reader mode](</docs/en/accessibility>), which adapts the terminal interface. Screen reader support in the chat panel requires Claude Code v2.1.236 or later. During a conversation, the extension announces: @@ -815,11 +619,7 @@ While Claude works, your screen reader reads a text label in place of the progress spinner’s animation. When you reopen a session or switch to another one, the extension announces nothing: restored history, pending permission prompts, and in-progress status stay silent until something new happens. -### - -​ - -Use the chat panel from the keyboard +### Use the chat panel from the keyboard Each turn in the transcript starts with a visually hidden heading labeled with the prompt that started the turn. Use your screen reader’s heading navigation to jump between turns. Within a turn, your screen reader announces whose message you’re on as you move through it: @@ -833,11 +633,7 @@ * With that option focused, press the `Left` or `Right` arrow key. The extension announces each destination as you move to it. The arrow keys require Claude Code v2.1.268 or later. * Click the destination in the label. -## - -​ - -VS Code extension vs. Claude Code CLI +## VS Code extension vs. Claude Code CLI Claude Code is available as both a VS Code extension (graphical panel) and a CLI (command-line interface in the terminal). Some features are only available in the CLI. If you need a CLI-only feature, run `claude` in VS Code’s integrated terminal. This requires the [standalone CLI install](</docs/en/setup>): the extension does not add `claude` to your PATH. See Run CLI in VS Code. @@ -849,11 +645,7 @@ `!` Bash shortcut| Yes| No Tab completion| Yes| No -### - -​ - -Run CLI in VS Code +### Run CLI in VS Code To use the CLI while staying in VS Code, press `Ctrl+`` on Windows/Linux or `Cmd+`` on Mac to open the integrated terminal, then run `claude`. To get features like diff viewing and diagnostic sharing, connect the CLI to the extension from the integrated terminal or an external terminal: @@ -862,19 +654,11 @@ Installing the extension does not put `claude` on your shell PATH. The extension bundles a private copy of the CLI for its chat panel, but typing `claude` in a terminal requires the [standalone CLI install](</docs/en/setup>). Run the install once and the commands on this page, including `claude mcp add` and `claude --resume`, work in any terminal. If `claude` is still not found after installing, [verify your PATH](</docs/en/troubleshoot-install#verify-your-path>). -### - -​ - -Switch between extension and CLI +### Switch between extension and CLI The extension and CLI share the same conversation history. To continue an extension conversation in the CLI, run `claude --resume` in the terminal. This opens an interactive picker where you can search for and select your conversation. -## - -​ - -Connect to external tools with MCP +## Connect to external tools with MCP MCP (Model Context Protocol) servers give Claude access to external tools, databases, and APIs. To manage MCP servers without leaving VS Code, type `/mcp` in the chat panel. From the dialog that opens, you can: @@ -893,11 +677,7 @@ To find servers to connect, see [Find and build MCP servers](</docs/en/mcp#find-and-build-mcp-servers>). -## - -​ - -The built-in IDE MCP server +## The built-in IDE MCP server When the extension is active, it runs a local MCP server that the CLI connects to automatically. Through this server, the CLI: @@ -946,11 +726,7 @@ The Quick Pick confirmation is separate from `PreToolUse` hooks. An allowlist entry for `mcp__ide__executeCode` lets Claude _propose_ running a cell; the Quick Pick inside VS Code is what lets it _actually_ run. -## - -​ - -Fix common issues +## Fix common issues Sign-in, network, and launch errors have their own entries on the install troubleshooting and error reference pages. Find what you see in the table, then follow the link. @@ -967,21 +743,13 @@ `The Claude Code program for this computer, the <build> build, could not be found`| [The Claude Code program for this computer could not be found](</docs/en/errors#the-claude-code-program-for-this-computer-could-not-be-found>) `claude` isn’t found in VS Code’s integrated terminal| Run CLI in VS Code -### - -​ - -Extension won’t install +### Extension won’t install * Ensure you have a compatible version of VS Code (1.94.0 or later) * Check that VS Code has permission to install extensions * Try installing directly from the [Visual Studio Marketplace](<https://marketplace.visualstudio.com/items?itemName=anthropic.claude-code>) -### - -​ - -Spark icon not visible +### Spark icon not visible The Spark icon appears in the **Editor Toolbar** (top-right of editor) when you have a file open. If you don’t see it: @@ -993,11 +761,7 @@ Alternatively, click **✻ Claude Code** in the **Status Bar** at the bottom-right corner of the window. This works even without a file open. You can also use the **Command Palette** (`Cmd+Shift+P` / `Ctrl+Shift+P`) and type “Claude Code”. -### - -​ - -Cmd+Esc does nothing on macOS +### Cmd+Esc does nothing on macOS On macOS Tahoe and later, the system Game Overlay shortcut is bound to `Cmd+Esc` by default and intercepts the keypress before it reaches VS Code. To free the shortcut: @@ -1007,11 +771,7 @@ Alternatively, rebind the extension to a different key: open the VS Code [Keyboard Shortcuts editor](<https://code.visualstudio.com/docs/configure/keybindings>) (`Cmd+K Cmd+S`), search for `Claude Code: Focus input`, and assign a new binding. -### - -​ - -Ctrl+J adds a new line in the prompt box +### Ctrl+J adds a new line in the prompt box To stop `Ctrl+J` from adding a new line in the prompt box, [unbind the key](</docs/en/keybindings#unbind-default-shortcuts>) in Claude Code’s `keybindings.json` file. The extension reads this file in version 2.1.309 or later, so update an older extension in the Extensions view first. This example is the whole file with the one entry that unbinds the key, `"ctrl+j": null` in a `Chat` block: @@ -1040,38 +800,22 @@ If the log has no such warning, check that the file is in your Claude Code configuration directory and that its `Chat` block sets `"ctrl+j"` to `null`. [Report the issue](<https://github.com/anthropics/claude-code/issues>) if `Ctrl+J` still adds a line. -### - -​ - -The Claude Code panel is blank or couldn’t load +### The Claude Code panel is blank or couldn’t load If the Claude Code panel opens but shows nothing at all, not even the prompt box, update the extension to v2.1.309 or later in the Extensions view. Then run **Developer: Reload Window** from the Command Palette. If you then see a `Claude Code couldn’t load` notice, work through the steps it lists in order. If the panel still doesn’t load, open the extension’s log and [report the issue](<https://github.com/anthropics/claude-code/issues>) with a copy of it: * **Still blank on v2.1.309 or later** : open the log with **Claude Code: Show Logs** from the Command Palette * **The notice’s steps didn’t help** : click **Show logs** in the notice to open the log -### - -​ - -A resumed conversation is blank at first +### A resumed conversation is blank at first When you resume a past conversation or one comes back after a reload, its messages can stay blank while the conversation’s Claude Code process starts. After about a second, `Waiting for your plugins…` appears in the empty space. You don’t need to do anything. The messages appear once the process has started and confirmed that no plugin needs to check them first, or after 20 seconds if starting takes longer. -### - -​ - -The panel stops responding each time a reload reopens a conversation +### The panel stops responding each time a reload reopens a conversation If the whole panel crashes, freezes, or shows only `Something went wrong` each time you reload and your conversation comes back, update the extension to v2.1.301 or later. Then reload the window or restart VS Code again. After the conversation fails to finish opening twice in a row, you get a new chat in its place, with a notice that it was not reopened. -### - -​ - -A formula shows as raw LaTeX +### A formula shows as raw LaTeX If none of the math in Claude’s responses is typeset, check the extension’s version in the Extensions view, because math rendering requires version 2.1.301 or later. If you use terminal mode, which doesn’t typeset math whatever the version, uncheck the [Use Terminal setting](<vscode://settings/claudeCode.useTerminal>) so that Claude Code opens in the chat panel instead. If one formula shows as written while others near it are typeset, check it for these causes: @@ -1087,11 +831,7 @@ * **The formula is too large** : a formula longer than 8,192 characters, or one whose typeset output would be far larger than its TeX source, shows as written. Ask Claude to split it into smaller formulas or to write it more compactly. * **The formula follows a large amount of math** : within one block of text in a response, the panel typesets formulas in order up to a limit. A later formula that would go past the limit shows as written. Ask Claude to send the formula you need again by itself. -### - -​ - -Dictation or the Web tab fails behind a TLS-inspecting proxy +### Dictation or the Web tab fails behind a TLS-inspecting proxy When dictation or the Web tab fails with a certificate error such as `unable to get local issuer certificate`, set [`NODE_EXTRA_CA_CERTS`](</docs/en/network-config#custom-ca-certificates>) in the `env` block of `~/.claude/settings.json`. Set it to the path of a PEM file with your proxy’s root CA certificate, which your IT team can give you. The failure appears on the microphone button or Web tab, or in the logs: @@ -1124,11 +864,7 @@ `env` in `~/.claude/settings.json`| Correct the value or the file it names, then start a recording or click **Reconnect** again VS Code’s `claudeCode.environmentVariables` setting, `~/.claude.json`, a project’s `.claude/settings.json` or `.claude/settings.local.json`, or managed settings| A value set here doesn’t apply to dictation or the Web tab. Set the variable in `env` in `~/.claude/settings.json` as well -### - -​ - -Claude Code never responds +### Claude Code never responds If Claude Code isn’t responding to your prompts: @@ -1138,11 +874,7 @@ If problems persist, [file an issue on GitHub](<https://github.com/anthropics/claude-code/issues>) with details about the error. -## - -​ - -Uninstall the extension +## Uninstall the extension To uninstall the Claude Code extension: @@ -1175,11 +907,7 @@ For additional help, see the [troubleshooting guide](</docs/en/troubleshooting>). -## - -​ - -Next steps +## Next steps Now that you have Claude Code set up in VS Code:
modified Get started with Claude Code in the cloud View current →
Show diff (224 lines)
--- a/web-quickstart.md +++ b/web-quickstart.md @@ -9,11 +9,7 @@ For work that needs your local config, tools, or environment, running Claude Code locally or using [Remote Control](</docs/en/remote-control>) is a better fit. -## - -​ - -How sessions run +## How sessions run The steps below describe Anthropic-hosted sessions. In a [self-hosted environment](</docs/en/self-hosted-environments>), the clone and everything after it run on your organization’s own runners, where network boundaries, setup, and push behavior are operator-configured. When you submit a task: @@ -24,11 +20,7 @@ The session doesn’t close when the branch is pushed. PR creation and further edits all happen within the same conversation. -## - -​ - -Compare ways to run Claude Code +## Compare ways to run Claude Code Claude Code behaves the same everywhere. What changes is where the session runs and whether your local configuration is available: @@ -45,11 +37,7 @@ See the [terminal quickstart](</docs/en/quickstart>), [Desktop app](</docs/en/desktop>), or [Remote Control](</docs/en/remote-control>) docs to set up local sessions. -## - -​ - -Connect GitHub +## Connect GitHub Connecting GitHub is a one-time step. If you already use the GitHub CLI, you can do this from your terminal instead of the browser. @@ -78,11 +66,7 @@ **Default** uses [**Limited** network access](</docs/en/cloud-environments#access-levels>): sessions reach [common package registries](</docs/en/cloud-environments#default-allowed-domains>) and other allowlisted domains. See [Installed tools](</docs/en/cloud-environments#installed-tools>) for what’s available without any configuration.For a first project, the **Default** environment works as is. To change its network access, add environment variables, or run a [setup script](</docs/en/cloud-environments#setup-scripts>) before sessions start, [edit it or create additional environments](</docs/en/cloud-environments#configure-your-environment>). -### - -​ - -Connect from your terminal +### Connect from your terminal If you already use the GitHub CLI (`gh`), you can connect GitHub for cloud sessions from your terminal. This requires the [Claude Code CLI](</docs/en/quickstart>). On Team and Enterprise plans, `/web-setup` is available only after an Owner turns on [Quick setup](</docs/en/claude-code-on-the-web#quick-setup-for-team-and-enterprise>). When you run `/web-setup`, Claude Code reads the token that `gh auth token` prints, asks you to confirm, and sends the token to Anthropic. Anthropic stores it encrypted with your claude.ai account, and your cloud sessions use it for GitHub access until you remove it. A cloud session you start yourself can then access any repository that token can access, with no Claude GitHub App installation. Threads in a [project](</docs/en/claude-projects#set-up-github-access>) still need the Claude GitHub App. If you already connected GitHub in the browser, `/web-setup` warns you that continuing replaces that connection for your cloud sessions. @@ -112,19 +96,11 @@ Confirm the prompt to send your `gh` token to your Claude account. On success, Claude Code prints `Connected as <your-github-username>` and opens [claude.ai/code](<https://claude.ai/code>) in your browser.If you don’t have a cloud environment yet, `/web-setup` creates one with the default **Limited** network access and no setup script. You can [edit the environment or add variables](</docs/en/cloud-environments#configure-your-environment>) afterward. Once `/web-setup` completes, you can start cloud sessions from your terminal with [`--cloud`](</docs/en/claude-code-on-the-web#from-terminal-to-cloud>) or set up recurring tasks with [`/schedule`](</docs/en/routines>). -#### - -​ - -Remove the `/web-setup` token +#### Remove the `/web-setup` token To remove the token from your Claude account, disconnect GitHub at [claude.ai/customize/connectors](<https://claude.ai/customize/connectors>). Disconnecting deletes the GitHub credentials your cloud sessions use, whether they came from the browser or from `/web-setup`, so cloud sessions lose GitHub access until you connect again. Your local `gh` stays signed in, and the token remains valid on GitHub. To invalidate the token itself, revoke it on GitHub. If you signed in to `gh` through the browser, the token belongs to the **GitHub CLI** entry under [**Settings > Applications > Authorized OAuth Apps**](<https://github.com/settings/applications>) on GitHub, and revoking that entry also signs the GitHub CLI out on your machines. Cloud sessions then lose GitHub access until you run `gh auth login` and `/web-setup` again. -## - -​ - -Start a task +## Start a task With GitHub connected and an environment created, you’re ready to submit tasks. @@ -158,11 +134,7 @@ Claude clones the repositories, runs your setup script if configured, and starts working. Each task gets its own session and its own branch, so you don’t need to wait for one to finish before starting another. -## - -​ - -Pre-fill sessions +## Pre-fill sessions You can prefill the prompt, repositories, and environment for a new session by adding query parameters to the [claude.ai/code](<https://claude.ai/code>) URL. Use this to build integrations such as a button in your issue tracker that opens Claude Code with the issue description as the prompt. @@ -177,11 +149,7 @@ https://claude.ai/code?prompt=Fix%20the%20login%20bug&repositories=acme/webapp -## - -​ - -Review and iterate +## Review and iterate When Claude finishes, review the changes, leave feedback on specific lines, and keep going until the diff looks right. @@ -217,76 +185,40 @@ The session stays live after the PR is created. Paste CI failure output or reviewer comments into the chat and ask Claude to address them. To have Claude monitor the PR automatically, see [Auto-fix pull requests](</docs/en/claude-code-on-the-web#auto-fix-pull-requests>). -## - -​ - -Troubleshoot setup - -### - -​ - -No repositories appear after connecting GitHub +## Troubleshoot setup + +### No repositories appear after connecting GitHub If you connected GitHub in the browser, sessions can clone any public repository, but a private repository appears only when the Claude GitHub App is installed on the account or organization that owns it and the installation’s repository access includes it. [Install the Claude GitHub App](<https://github.com/apps/claude/installations/new>) there, or ask an organization owner to install or approve it. If you connected with `/web-setup`, sessions reach every repository your `gh` token can access. Run `gh repo view OWNER/REPO` in your shell to check that your GitHub CLI login can see the repository, and run `/web-setup` again if you’ve switched `gh` accounts since connecting. -### - -​ - -The page only shows a GitHub login button +### The page only shows a GitHub login button To work in a GitHub repository in a cloud session, connect your GitHub account, or run `/web-setup` from your terminal if you use the GitHub CLI. If you’d rather not connect GitHub at all, see [Remote Control](</docs/en/remote-control>) to run Claude Code on your own machine and monitor it from your browser or phone. -### - -​ - -”Claude Code isn’t available on your account” +### ”Claude Code isn’t available on your account” Your seat in the selected organization doesn’t include Claude Code. If you belong to another organization, click **Switch organization** on that page. Otherwise, ask an Owner of the organization to assign you a [seat that includes Claude Code](<https://support.claude.com/en/articles/11845131-use-claude-code-with-your-team-or-enterprise-plan>). -### - -​ - -`/web-setup` says “Not signed in to Claude” +### `/web-setup` says “Not signed in to Claude” If `/web-setup` responds with “Not signed in to Claude. Run /login first.”, the CLI doesn’t have a valid claude.ai sign-in. This can also happen when a previous sign-in has expired. Run `/login`, sign in with your claude.ai account, then run `/web-setup` again. -### - -​ - -`/web-setup` warns that your token doesn’t have the `workflow` scope +### `/web-setup` warns that your token doesn’t have the `workflow` scope If `/web-setup` says your GitHub CLI token doesn’t have the `workflow` scope, you can continue, but GitHub can reject some pushes made with that token, such as pushes that change GitHub Actions workflow files. To add the scope, run `gh auth refresh -s workflow` in your shell, then run `/web-setup` again. -### - -​ - -`/web-setup` shows “No commands match” or “Unknown command” +### `/web-setup` shows “No commands match” or “Unknown command” `/web-setup` runs inside the Claude Code CLI, not your shell. Launch `claude` first, then type `/web-setup` at the prompt. If you typed it inside Claude Code and the command menu shows `No commands match "/web-setup"`, or submitting it returns `Unknown command: /web-setup`, the command is hidden because a requirement isn’t met. The cause is usually that you’re authenticated with an API key or third-party provider instead of a claude.ai subscription. Run `/login` to sign in with your claude.ai account. On Team and Enterprise plans, the command is hidden by default: the [Quick setup toggle](</docs/en/claude-code-on-the-web#quick-setup-for-team-and-enterprise>) is off until an Owner turns it on. While it’s off, connect GitHub from the browser instead. The command is also hidden in two other cases: * An administrator has disabled cloud sessions for your organization. In this case, submitting `/web-setup` returns [`Cloud sessions are disabled by your organization's policy`](</docs/en/errors#cloud-sessions-are-disabled-by-your-organizations-policy>). Before v2.1.268, this case also returned `Unknown command: /web-setup`. * Your Enterprise organization has [Zero Data Retention](</docs/en/zero-data-retention>) enabled, or has the [HIPAA configuration](</docs/en/hipaa-setup>) applied. Either one makes cloud sessions unavailable. -### - -​ - -”Could not create a cloud environment” or “No cloud environment available” when using `--cloud` +### ”Could not create a cloud environment” or “No cloud environment available” when using `--cloud` Cloud session features create a default cloud environment automatically if you don’t have one. If you see “Could not create a cloud environment”, automatic creation failed. If you see “No cloud environment available”, your CLI predates automatic creation. In either case, run `/web-setup` in the Claude Code CLI, or add an environment from the [environment selector](</docs/en/cloud-environments#configure-your-environment>) at [claude.ai/code](<https://claude.ai/code>). -### - -​ - -Setup script failed +### Setup script failed The [setup script](</docs/en/cloud-environments#setup-scripts>) exited with a non-zero status, so the session failed to start or started without whatever the script failed to install. If the session started, you can keep working in it. Common causes: @@ -296,11 +228,7 @@ To debug, add `set -x` at the top of the script to see which command failed. For non-critical commands, append `|| true` so they don’t fail the script. After you fix the cause, start a new session so the script runs again. If what failed to start was a run of a [cloud scheduled task](</docs/en/routines>), click **Run now** on the task’s detail page instead of starting a new session. -### - -​ - -New sessions hang or time out during setup +### New sessions hang or time out during setup If new sessions stall on the setup script step or fail with a generic container error before the script finishes, the script is likely exceeding the roughly five-minute time budget for building the [environment cache](</docs/en/cloud-environments#environment-caching>). Heavy steps such as pulling large Docker images, syncing full dependency trees, or downloading model weights often push the total over the limit, especially when they run one after another. To fix this, trim the script so it reliably finishes in under five minutes: @@ -308,19 +236,11 @@ * Move the largest downloads out of the setup script and into a [SessionStart hook](</docs/en/cloud-environments#setup-scripts-vs-sessionstart-hooks>) that launches them in the background, so the session becomes usable while they finish. * Remove long retry sleeps from the setup script, since a stalled retry loop counts against the budget. -### - -​ - -Session keeps running after closing the tab +### Session keeps running after closing the tab This is by design. Closing the tab or navigating away doesn’t stop the session. It continues running in the background until Claude finishes the current task, then idles. From the sidebar, you can [archive a session](</docs/en/claude-code-on-the-web#archive-sessions>) to hide it from your list, or [delete it](</docs/en/claude-code-on-the-web#delete-sessions>) to remove it permanently. -## - -​ - -Next steps +## Next steps Now that you can submit and review tasks, these pages cover what comes next: starting cloud sessions from your terminal, scheduling recurring work, and giving Claude standing instructions.
modified Orchestrate subagents at scale with dynamic workflows View current →
Show diff (421 lines)
--- a/workflows.md +++ b/workflows.md @@ -2,11 +2,7 @@ A dynamic workflow is a JavaScript script that orchestrates many [subagents](</docs/en/sub-agents>) at once. Claude writes the script for the task you describe, and a runtime executes it in the background while your session stays responsive. Reach for a workflow when a task needs more agents than one conversation can coordinate, or when you want the orchestration codified as a script you can read and rerun. Examples include a codebase-wide bug sweep, a 500-file migration, a research question that needs sources cross-checked against each other, and a hard plan worth drafting from several independent angles before you commit to one. -## - -​ - -When to use a workflow +## When to use a workflow [Subagents](</docs/en/sub-agents>), [skills](</docs/en/skills>), [agent teams](</docs/en/agent-teams>), and workflows can all run a multi-step task. The difference is who holds the plan: @@ -21,11 +17,7 @@ A workflow moves the plan into code. With subagents, skills, and agent teams, Claude is the orchestrator: it decides turn by turn what to spawn or assign next, and every result goes into a context window. A workflow script holds the loop, the branching, and the intermediate results itself, so Claude’s context holds only the final answer. Moving the plan into code also lets a workflow apply a repeatable quality pattern, not just run more agents: it can have independent agents adversarially review each other’s findings before they’re reported, or draft a plan from several angles and weigh them against each other, so you get a more trustworthy result than a single pass. -## - -​ - -Run a bundled workflow +## Run a bundled workflow The quickest way to see a workflow in action is to run `/deep-research`, the built-in workflow Claude Code includes for investigating a question across many sources. You’ll see agents work through a set of phases in the background while your session stays free, and get one report at the end instead of a turn-by-turn transcript. @@ -61,11 +53,7 @@ To run a workflow for your own task, have Claude write one, and once a run does what you wanted you can save it as a command of your own. -### - -​ - -Bundled workflows +### Bundled workflows Claude Code includes `/deep-research` as a built-in workflow: @@ -73,13 +61,9 @@ ---|--- `/deep-research <question>`| Fans out web searches on a question across several angles, fetches and cross-checks the sources it finds, votes on each claim, and returns a cited report with claims that didn’t survive cross-checking filtered out. Requires the [WebSearch tool](</docs/en/tools-reference#websearch-tool-behavior>) to be available -`/deep-research` runs only when you invoke it. Workflows you save yourself become commands the same way and appear in `/` autocomplete alongside the bundled ones. - -### - -​ - -Watch the run +Workflows you save yourself become commands the same way and appear in `/` autocomplete alongside the bundled ones. + +### Watch the run Workflows run in the background, so the session stays responsive while agents work. Run `/workflows` at any time to list running and completed workflows, then select one to open its progress view. When the session has only one run, `/workflows` skips the list and opens that run. To stop a running workflow from the list without opening it, select it and press `x`. The progress view shows each phase with its agent counts. The footer lists the key for each action: @@ -97,11 +81,7 @@ The agent detail lists the agent’s prompt, its recent tool calls, and its result. Each call shows its state, such as still running or failed. When the agent keeps a task list of its own, the detail shows it too, with each task’s status. Press `Enter` to expand the detail. The prompt and result then show in full, and each listed call shows its input and the start of its result. -## - -​ - -Have Claude write a workflow +## Have Claude write a workflow You can have Claude write a workflow for your task in two ways: @@ -110,11 +90,7 @@ You can also run a workflow command that already exists: a bundled workflow like `/deep-research`, or one you’ve saved. -### - -​ - -Ask for a workflow in your prompt +### Ask for a workflow in your prompt To run a single task as a workflow without changing the session’s effort level, include the keyword `ultracode` in your prompt. Asking in your own words, for example “use a workflow” or “run a workflow”, also works: Claude treats a direct request as the same opt-in. @@ -122,19 +98,11 @@ Claude Code highlights the keyword in your input and Claude writes a workflow script for the task instead of working through it turn by turn. The keyword only chooses how Claude structures the work: the agents’ tool calls receive the same permission checks and [sandboxing](</docs/en/sandboxing>) as any other tool call in the session. If the run does what you wanted, you can save it as a command afterward. If you already have an orchestrator built another way, such as a folder of subagent prompts or a skill that fans work out, you can point Claude at it and ask for a workflow that does the same thing. -#### - -​ - -Dismiss or turn off the keyword +#### Dismiss or turn off the keyword If you didn’t mean to start a workflow, press `Option+W` on macOS or `Alt+W` on Windows and Linux to dismiss the highlight for this prompt, or press backspace while the cursor is right after the highlighted keyword. To stop the keyword from triggering at all, turn off Ultracode keyword trigger in `/config`. -#### - -​ - -Where the keyword works +#### Where the keyword works The keyword is an opt-in only in a prompt you type yourself: at the interactive prompt, in an IDE extension panel, in a [Remote Control](</docs/en/remote-control>) client, or in an Agent SDK application that stamps your keyboard input’s [`origin`](</docs/en/agent-sdk/typescript#sdkmessageorigin>) as `{ kind: "human" }`. It doesn’t start a workflow when it reaches the session another way: @@ -143,11 +111,7 @@ * a scheduled task prompt * a webhook payload or pull request comment relayed into the conversation -### - -​ - -Let Claude decide with ultracode +### Let Claude decide with ultracode Ultracode is a Claude Code setting that turns on automatic workflow orchestration for the session, at whichever [effort level](</docs/en/model-config#adjust-effort-level>) the session runs at. With it on, Claude plans a workflow for each substantive task instead of waiting for you to ask. Turn it on at the Claude Code prompt: @@ -161,11 +125,7 @@ `/effort ultracode` lasts for the current session; to have every session start with it, set the [`ultracode`](</docs/en/settings-reference#ultracode>) setting. Turn it off with `/effort ultracode off` when you return to routine work. The `/effort` slider offers the toggle only [when ultracode is available](</docs/en/model-config#when-ultracode-is-available>). Before v2.1.284, `/effort ultracode` set the session to `xhigh`, and `/effort ultracode off` failed with `Invalid argument`. -### - -​ - -Approve the plan before it runs +### Approve the plan before it runs In the CLI, the per-run prompt shows the planned phases and these options: @@ -193,11 +153,7 @@ In the Desktop app, an approval card shows the workflow name, the phase list, and a token-usage caution, with **Once** , **Always** , and **Deny** actions. The progress view appears in the Background tasks side pane. The subagents the workflow spawns use your [permission rules](</docs/en/settings-reference#permission-settings>), and Claude Code picks their permission mode by the rules under [which permission mode a subagent runs in](</docs/en/sub-agents#permission-modes>). To avoid prompts on a long run, add the tools the agents need to your allow rules before starting. -### - -​ - -Save the workflow for reuse +### Save the workflow for reuse When Claude writes a workflow for a task you’ll repeat, you can save that run’s script as a command. A process like a review you run on every branch then runs the same orchestration each time. Run `/workflows`, select the run you want to keep, and press `s`. In the save dialog, Tab toggles between the two save locations: @@ -211,19 +167,11 @@ In a monorepo with several `.claude/` directories, you can keep workflows alongside the package they apply to. Saving to the project location writes to the closest `.claude/workflows/` directory that already exists between your working directory and the repository root, or to the repository root if none exists yet. Project workflows also load from every `.claude/workflows/` along that path, and when more than one defines the same name Claude Code runs the one closest to the working directory. If a project workflow and a personal workflow share a name, the project one runs. -### - -​ - -Distribute a workflow in a plugin +### Distribute a workflow in a plugin To share a workflow across teams or repositories, include it in a [plugin](</docs/en/plugins/overview>). Place the script in a `workflows/` directory at the plugin root, or point to a different location with the [`workflows` manifest field](</docs/en/plugins/manifest-reference#fields>). Plugin workflows are namespaced by the plugin name. A plugin called `acme-tools` containing a script whose `meta.name` is `release-audit` runs as `/acme-tools:release-audit`. -### - -​ - -Pass input to a saved workflow +### Pass input to a saved workflow A saved workflow can accept input through the `args` parameter. The script reads it as a global named `args`. Use this to supply a research question, a list of target paths, or a configuration object at invocation time instead of editing the script for each run. The following prompt runs a saved workflow with a list of issue numbers: @@ -231,79 +179,47 @@ Claude passes the list as structured data, so the script can call array and object methods on `args` directly without parsing it first. If `args` is omitted, the global is `undefined` inside the script. -## - -​ - -Example workflow prompts +## Example workflow prompts A workflow fits best when the task is larger than one agent can hold in context, or when the same step needs to run across many items. The prompts below show common shapes. Each one asks Claude to write and run a workflow for that task; you don’t write the script yourself. -### - -​ - -Audit many files for the same issue +### Audit many files for the same issue Fan out one agent per file, then collect and verify the findings. use a workflow to audit every route handler under src/routes/ for missing authentication checks, and adversarially verify each finding before reporting it -### - -​ - -Keep fixing until a check passes +### Keep fixing until a check passes Run a checker, fix what failed, and repeat until it passes or stops making progress. use a workflow to run npx tsc --noEmit and keep fixing the reported errors until the type check passes or two rounds in a row make no progress -### - -​ - -Migrate many files in parallel +### Migrate many files in parallel Discover the files to migrate, transform each one in an isolated copy so edits don’t conflict, and verify each result. use a workflow to migrate every component under src/components/ from JavaScript to TypeScript, working on each file in its own isolated copy -### - -​ - -Review every changed file and write one summary +### Review every changed file and write one summary Run a reviewer per file, then pass all the findings to one agent that ranks and deduplicates them. use a workflow to review every file changed in this PR for correctness issues, then merge the per-file findings into one ranked summary -### - -​ - -Research a topic across many sources +### Research a topic across many sources Fan out readers across changelogs, issues, and docs, then synthesize. The bundled `/deep-research` workflow does this; you can also describe a narrower version. use a workflow to research how our three competitors handle rate limiting: read their public docs and recent changelog entries in parallel, then compare the approaches -### - -​ - -Find issues until the list stops growing +### Find issues until the list stops growing Keep searching in rounds and stop when new rounds turn up nothing new. use a workflow to find flaky tests in this repo: run the suite repeatedly, record which tests fail intermittently, and stop once two rounds in a row find nothing new -### - -​ - -What the saved script looks like +### What the saved script looks like When you save a workflow, the file in `.claude/workflows/` holds a `meta` block followed by a script body that orchestrates subagents. You usually don’t need to edit it, but here is the shape of a small one so you can recognize what Claude generated: @@ -324,11 +240,7 @@ The body is plain JavaScript with top-level `await`. `agent()` spawns one subagent, `pipeline()` runs one per item in a list, and `parallel()` runs a set of agent tasks at the same time and waits for all of them. An `agent()` call resolves to `null` if you stop it mid-run or it hits an unrecoverable API error. `pipeline()` keeps each `null` in the results array, which is why the example ends with `.filter(Boolean)` to drop those entries, including the slot of an agent that stalled on every attempt. In [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>), the prompt your script passes to `agent()` doesn’t count as a request from you when the classifier reviews that subagent’s actions, because Claude Code marks it as text the script computed. If you pass a `schema` on an `agent()` call, that subagent returns JSON matching the shape instead of prose. Claude Code checks the schema before starting the subagent: when it can prove the schema contradicts itself, the call fails with an error naming the contradiction, and the subagent never starts. One contradiction it can prove is a `required` key that `additionalProperties: false` rules out. If the subagent’s output still fails validation after five attempts, the call fails with an error that includes the last validation failure. To change the attempt count, set [`MAX_STRUCTURED_OUTPUT_RETRIES`](</docs/en/env-vars>). -### - -​ - -Edit a saved script +### Edit a saved script To change a workflow you saved, edit its `.js` file or ask Claude to make the change. Before you edit or ask, run the `/workflow-authoring` [bundled skill](</docs/en/skills#bundled-skills>) to load the script-writing reference Claude works from. The skill requires Claude Code v2.1.248 or later. To run the edited version in the current session, run [`/reload-skills`](</docs/en/commands#all-commands>) to re-read the workflow directories, then run `/<name>` again. Claude Code applies these rules to each part of the file when it loads and runs the script: @@ -339,27 +251,15 @@ You can also edit the script of a single run rather than the saved copy. Resume after a pause covers which agents run again when you relaunch an edited script. For the Workflow tool’s inputs, see its entry in the [Agent SDK reference](</docs/en/agent-sdk/typescript#workflow>). -## - -​ - -How a workflow runs +## How a workflow runs The workflow runtime executes the script in an isolated environment, separate from your conversation. Intermediate results stay in script variables instead of landing in Claude’s context. Unless Claude starts a run from a script file’s path, Claude Code writes the run’s script to a file under your session’s directory in `~/.claude/projects/`. Claude receives the script’s path when the run starts, so you can ask for it. You can open that file to read the orchestration Claude wrote, diff it against a previous run’s script, or edit it and ask Claude to relaunch from the edited version. Claude can start a workflow only from a script file the session is already allowed to read. To run a script kept outside your working directory, add its directory with [`/add-dir`](</docs/en/permissions#working-directories>) or a [Read allow rule](</docs/en/permissions#read-and-edit>) first. The runtime tracks each agent’s result as the run progresses, which is what makes a run resumable within the same session. -### - -​ - -Prompt caching in a fan-out +### Prompt caching in a fan-out Agents in the same run can read each other’s [prompt cache](</docs/en/prompt-caching#subagents-and-the-cache>). Two agents that run with the same model, effort level, agent type, tools, output schema, and working directory build the same tools-and-system-prompt prefix, so an agent that starts after a matching sibling’s response has begun reads that sibling’s cache on its first request. A workflow agent’s requests fall outside the main conversation’s [cache TTL bucket](</docs/en/prompt-caching#which-ttl-each-request-gets>), so its cache holds for five minutes by default, including on a Claude subscription. To keep it for an hour, set [`subagentPromptCacheTtl`](</docs/en/settings-reference#subagentpromptcachettl>) to `1h`. The API bills 1-hour cache writes at a higher rate. When a fan-out starts several matching agents at once, Claude Code holds all but the first until the first agent’s response begins, then releases the held agents together so their first requests read the shared prefix instead of each processing it uncached. Claude Code caps the hold at [`CLAUDE_CODE_WORKFLOW_PREFIX_STAGGER_MS`](</docs/en/env-vars>) milliseconds, `5000` by default. Set it to `0` to disable the hold. -### - -​ - -Behavior and limits +### Behavior and limits The runtime applies the following constraints: @@ -373,27 +273,15 @@ Up to 4,096 items in a single `parallel()` or `pipeline()` call: the runtime rejects a longer list with an error| A silent cap would drop part of the workload without telling the script 1,000 agents total per run| Prevents runaway loops -## - -​ - -Manage runs +## Manage runs Once a run starts, you manage it from the `/workflows` view, or by expanding its progress line in the task panel below the input box. When you stop a run, it stays in the task panel while any of its agents’ processes are still running. If you stop it again, Claude Code re-signals those processes. -### - -​ - -Resume after a pause +### Resume after a pause Resume a paused run from `/workflows` by selecting it and pressing `p`. For a run you stopped, ask Claude to relaunch the workflow with the same script. If agents from the stopped run haven’t exited yet, Claude Code refuses the relaunch until they have, so a second copy of those agents can’t run alongside them. -#### - -​ - -Which agents run again +#### Which agents run again Claude Code replays the run in the order agents start, and each agent either returns its saved result or runs again: @@ -404,11 +292,7 @@ That last case means a **Failed** agent in the middle of a fan-out reruns work that already finished. If a script starts A, B, C, and D in that order and B is **Failed** , relaunching returns A from cache and runs B, C, and D again. If you edit a script that started A, B, C, and D so that it starts A, C, B, and D, the second agent to start is now C, where the previous run started B. Relaunching returns A from cache and runs C, B, and D again. -#### - -​ - -Resume after you leave the session +#### Resume after you leave the session If you background your session or exit Claude Code while a workflow run is in progress, the run doesn’t continue on its own. The run continues only when Claude relaunches it with a `Workflow` call, which replays the run from its saved results. @@ -418,11 +302,7 @@ In a [cloud session](</docs/en/claude-code-on-the-web>), Claude Code also saves the run’s results with the session’s conversation history, which survives when the session’s VM is reclaimed. When you [reopen such a session](</docs/en/claude-code-on-the-web#environment-expired>) and ask Claude to relaunch the workflow, completed agents still return their saved results. In local and cloud sessions alike, when Claude relaunches an earlier run and Claude Code can’t find that run’s saved results at all, the relaunch fails with a `nothing to resume` error instead of starting the run over on its own. Ask Claude to start the workflow over as a new run. -### - -​ - -When a run hits your usage limit +### When a run hits your usage limit When an agent hits your claude.ai [usage limit](</docs/en/interactive-mode#wait-for-a-usage-limit-to-reset>), the run pauses rather than failing that agent. The agents that hit the limit wait for the reset, and no new agents start. Shortly after the limit resets, the waiting agents run again and the run continues on its own. Requires Claude Code v2.1.271 or later, or [v2.1.319 or later](</docs/en/desktop#claude-code-version-in-the-code-tab>) in the Desktop [Code tab](</docs/en/desktop>). On earlier versions, the affected agents fail. While the run waits, its progress line in the task panel and the `/workflows` header show when the limit resets. In the Code tab, the run shows a line such as `Paused at usage limit · continues after 3:45 PM if the app stays open`. Keep the app open. The run pauses only when all of these hold; when one doesn’t, the affected agent fails instead: @@ -436,11 +316,7 @@ To finish a run whose agents failed at the limit, ask Claude to relaunch the workflow after the limit resets. -### - -​ - -When an agent stalls and restarts +### When an agent stalls and restarts An agent whose output stops arriving for long enough starts over from the same prompt. In `/workflows`, its name gains a `(retry 1)` suffix and its detail shows `attempt 2 (stalled)`. The restart is automatic, so you don’t need to do anything. The new attempt starts without the stalled attempt’s transcript. Files the stalled attempt already changed stay changed, and the tokens it spent stay in the run’s total. The stall window is how long Claude Code waits for output from an agent before it ends the attempt. Time the agent spends waiting on its own tool calls or on a usage-limit reset doesn’t count toward the stall window. An agent restarts at most five times, counting any restart you ask for with `r`. If the sixth attempt stalls as well, the `agent()` call fails, and the start of the error says why: @@ -460,11 +336,7 @@ To try again, ask Claude to relaunch the workflow. Resume after a pause covers what runs again. -### - -​ - -Cost +### Cost A workflow spawns many agents, so a single run can use meaningfully more tokens than working through the same task in conversation. Runs count toward your plan’s usage and rate limits. To gauge the spend before committing to a large task, run the workflow on a small slice first: one directory instead of the whole repo, or a narrow question instead of a broad one. The `/workflows` view shows each agent’s token usage as the run progresses, and you can stop the run there at any time, usually without losing completed work. Resume after a pause covers what a stopped run keeps. The runtime’s agent caps limit how many agents a single run can spawn, which bounds the cost of a runaway script. To keep runs to fewer agents, choose the `small` size guideline. Claude Code also flags a run that grows unusually large. When a workflow schedules more than 25 agents, or its projected token total passes 1.5 million, its progress line in the task panel below the input box shows a `Large workflow` warning. The warning points you to `/workflows`, where you can stop the run. The warning is advisory: it doesn’t pause or limit the run. Two settings change when you see it: @@ -478,11 +350,7 @@ When your organization’s [`availableModels` allowlist](</docs/en/model-config#restrict-model-selection>) blocks a model the script requests for an agent, that agent runs on a substituted model instead, following the same [substitution rules as subagents](</docs/en/sub-agents#choose-a-model>). -### - -​ - -Set a size guideline +### Set a size guideline A size guideline tells Claude how many agents to aim for when it writes a dynamic workflow. Claude Code sends the guideline to Claude as advice, not a cap, so a prompt that calls for a different scale still overrides it. Each value maps to an agent count: @@ -495,11 +363,7 @@ The default is `medium`, or `small` when you’re signed in on a Pro plan with Claude Code v2.1.271 or later. Until you choose a value, the `/config` row marks the value as the default, and the workflow’s `Running in background` line names the size in force. To change the guideline, pick a value for the Dynamic workflow size setting in `/config`, or run `/config workflowSizeGuideline=small`. You can also set the [`workflowSizeGuideline` key](</docs/en/settings-reference#workflowsizeguideline>) in any settings file; that value takes precedence over `/config`, and Claude Code hides the `/config` row while a settings file provides one. Changes take effect on the next prompt. The runtime agent caps still apply regardless of the setting. -### - -​ - -Turn workflows off +### Turn workflows off Workflows are available in the CLI, the Desktop app, the IDE extensions, [non-interactive mode](</docs/en/headless>) with `claude -p`, and the [Agent SDK](</docs/en/agent-sdk/overview>). The same disable settings apply on every surface. To turn workflows off for yourself: @@ -514,11 +378,7 @@ A run that was already in progress keeps going. Turning workflows off also makes ultracode unavailable. No managed setting rules out ultracode alone: wherever it’s [available](</docs/en/model-config#when-ultracode-is-available>), users can turn it on with `/effort ultracode`. An [effort cap](</docs/en/model-config#organization-effort-limits>) lowers the effort level a session with ultracode on runs at, but doesn’t turn ultracode off. -## - -​ - -Related resources +## Related resources * [Run agents in parallel](</docs/en/agents>): compare subagents, agent view, agent teams, and workflows * [Create custom subagents](</docs/en/sub-agents>): the worker primitive workflows orchestrate
modified Run parallel sessions with worktrees View current →
Show diff (352 lines)
--- a/worktrees.md +++ b/worktrees.md @@ -7,11 +7,7 @@ Worktrees are one of several ways to run Claude in parallel. They isolate file edits. [Subagents](</docs/en/sub-agents>) split work up inside one session, and [cross-session messaging](</docs/en/cross-session-messaging>) lets Claude pass findings between the sessions in your worktrees. See [Run agents in parallel](</docs/en/agents>) to compare the approaches, or skip ahead to Isolate subagents with worktrees to use worktrees and subagents together. Most sessions need only the first two sections: start Claude in a worktree, then clean up when you exit. Return to the rest of the page when you need to resume a session, change how worktrees are created, or debug a failure. -## - -​ - -Start Claude in a worktree +## Start Claude in a worktree Pass `--worktree` or `-w` with a name to create an isolated worktree and start Claude in it. By default, the worktree is created under `.claude/worktrees/<name>/` at your repository root, on a new branch named `worktree-<name>`: @@ -21,19 +17,11 @@ Add `.claude/worktrees/` to your `.gitignore` so worktree contents don’t appear as untracked files in your main checkout. -### - -​ - -Set up the worktree environment +### Set up the worktree environment A worktree is a fresh checkout, so initialize your development environment there: ask Claude to install dependencies, or run your project’s setup yourself in the worktree directory under `.claude/worktrees/`. To carry gitignored files such as `.env` into every new worktree automatically, add a `.worktreeinclude` file. -### - -​ - -Ask Claude to create a worktree +### Ask Claude to create a worktree You can also ask Claude to “work in a worktree” during a session, and it creates one with the [`EnterWorktree`](</docs/en/tools-reference#enterworktree-tool-behavior>) tool. Once in a worktree, Claude can switch directly to another one under `.claude/worktrees/` by calling `EnterWorktree` with the target path; the previous worktree stays on disk untouched. When Claude enters a path outside the repository’s `.claude/worktrees/` directory, Claude Code asks for your approval first. The move takes the session’s working directory, write access, and project configuration such as `CLAUDE.md` and settings to that location. An `EnterWorktree` [permission rule](</docs/en/permissions>) or choosing “don’t ask again” doesn’t suppress this prompt; only `bypassPermissions` mode skips it. @@ -42,11 +30,7 @@ * **`${CLAUDE_PROJECT_DIR}` stays put**: it still points at the project root where the session started, so a hook command such as `${CLAUDE_PROJECT_DIR}/.claude/hooks/check-style.sh` still runs the script in the main checkout. * **`cwd` follows Claude**: the `cwd` field in the hook’s [input JSON](</docs/en/hooks#common-input-fields>) is the worktree root, and it moves again when Claude runs `cd`. Read it when a hook needs the worktree path. -#### - -​ - -Claude has no `EnterWorktree` tool +#### Claude has no `EnterWorktree` tool If you ask Claude to work in a worktree and it has no `EnterWorktree` or `ExitWorktree` tool, check whether [`permissions.blockWritesOutsideWorkingDirectories`](</docs/en/settings-reference#permissions-blockwritesoutsideworkingdirectories>) is on. Once the key is on, Claude Code removes both worktree tools or refuses calls to them. You can keep working in worktrees while the key is on: @@ -58,11 +42,7 @@ To get the tools back, run `/status` in the session to list the [setting sources it loaded](</docs/en/settings#check-what-loaded>), and remove the key from every file that sets it. Then restart Claude Code. If managed settings set the key, ask your administrator whether the policy should change. -## - -​ - -Clean up worktrees +## Clean up worktrees When you exit an interactive worktree session, Claude checks the worktree for work that removal would delete: changed or untracked files, uncommitted work inside checked-out submodules, and new commits. These rules apply to worktrees Claude created with git. For a worktree your [WorktreeCreate hook](</docs/en/hooks#worktreecreate>) created, see [WorktreeRemove](</docs/en/hooks#worktreeremove>) instead. @@ -73,11 +53,7 @@ Non-interactive runs with `-p` have no exit prompt, so Claude doesn’t clean up their worktrees, and Claude Code leaves the lock it took on each one at creation in place until a later session’s stale-lock sweep releases it. To remove one, run `git worktree remove`; if git refuses because the worktree is locked, run `git worktree unlock` on it first. On Windows, removing a worktree doesn’t delete files outside it. If a folder inside the worktree is a link to somewhere else, such as an NTFS junction or a directory symlink, Claude Code deletes only the link. -## - -​ - -Resume a worktree session +## Resume a worktree session When you resume a session that ended inside a worktree without exiting it, Claude Code returns the session to that worktree. This holds for interactive resumes, for `--continue` and `--resume` in [non-interactive mode](</docs/en/headless>) with `-p`, and for the Agent SDK. `--continue` picks the most recent session recorded under the directory you launch from. Back inside the worktree, Claude can leave with the [`ExitWorktree`](</docs/en/tools-reference>) tool when the session has that tool. Before returning the session to its worktree, Claude Code verifies that the worktree is still a checkout separate from the main one, and declines to re-enter a worktree that fails the check. For a git worktree, the check reads its git metadata. A worktree without git metadata, such as one a `WorktreeCreate` hook created, can pass the check; the cases Claude Code still refuses are listed with their recoveries under Claude Code refuses to use a worktree. For the messages and how to recover from each, see The session resumes outside its worktree. Where you launch from, and how you resume, change what Claude Code re-enters: @@ -89,11 +65,7 @@ When Claude enters or exits a worktree that Claude Code created with git, the transcript follows. Claude Code records the session under the session’s new working directory, the same way [`/cd`](</docs/en/commands>) does, so `/desktop` and `--resume` find it there. Exiting moves it back the same way. A worktree created by a `WorktreeCreate` hook keeps its transcript at the launch directory. -## - -​ - -How Claude Code enforces isolation +## How Claude Code enforces isolation While a session is isolated in a worktree, Claude Code blocks the tool calls the checks below define. The same rules apply whether you started the session with `--worktree`, Claude entered a worktree with `EnterWorktree`, or you resumed a worktree session. The same enforcement covers every subagent Claude spawns from the isolated session. It applies whether the session is interactive or runs in the [background](</docs/en/agent-view#how-file-edits-are-isolated>). Subagents that run in their own worktree carry the same checks. Their version history is under [Write subagent files](</docs/en/sub-agents#write-subagent-files>). Claude Code applies four checks: @@ -104,11 +76,7 @@ These checks read the path an edit targets, the directory a command runs in, and the text of the command. None of them tracks which files a shell command writes, so a command that writes into the main checkout without running git there, such as `cp` or a shell redirect, isn’t refused by them. Claude Code treats that command like any other shell command under your [permissions](</docs/en/permissions>) and [sandboxing](</docs/en/sandboxing>) settings. The checks apply to the repository you launched Claude Code from. They also cover the main checkout a linked worktree is linked from. For PowerShell commands, Claude Code applies only the working-directory check. Claude sees each refusal as a tool error that names the worktree and says how to proceed. For a refused command, see [what the refusal message means and how to clear it](</docs/en/errors#command-blocked-by-the-worktree-isolation-checks>). -## - -​ - -Isolate subagents with worktrees +## Isolate subagents with worktrees Subagents can run in their own worktrees so parallel edits don’t conflict. Ask Claude to “use worktrees for your agents”, or make the isolation permanent for a [custom subagent](</docs/en/sub-agents#supported-frontmatter-fields>) by adding `isolation: worktree` to its frontmatter. This subagent in `.claude/agents/` always runs in its own worktree: @@ -123,11 +91,7 @@ Each subagent gets a temporary worktree that Claude Code removes automatically when the subagent finishes without changes; a worktree with changes stays on disk until the periodic sweep below can remove it without losing work. For a worktree your [WorktreeCreate hook](</docs/en/hooks#worktreecreate>) created, see [WorktreeRemove](</docs/en/hooks#worktreeremove>) instead. Subagent worktrees use the same base branch as `--worktree`, so they branch from your repository’s default branch unless `worktree.baseRef` is set to `"head"`. A subagent in its own worktree takes the instruction files it [starts with](</docs/en/sub-agents#what-loads-at-startup>) from your main conversation, not from its worktree. When that worktree is in the default location under `.claude/worktrees/`, the subagent also doesn’t load the `CLAUDE.md` file or `.claude/rules/` directory at the worktree’s root as it reads files there, even if those differ on the worktree’s branch. -### - -​ - -Clean up subagent and background-session worktrees +### Clean up subagent and background-session worktrees Claude Code runs a periodic sweep that removes worktrees that Claude created for subagents and [background sessions](</docs/en/agent-view#how-file-edits-are-isolated>) once they are older than your [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>) setting, following the [retention sweep rules](</docs/en/claude-directory#cleaned-up-automatically>). When you [background](</docs/en/agent-view#send-the-session-to-the-background>) a `--worktree` session, its worktree becomes a background-session worktree that the sweep can remove. The sweep leaves a worktree in place in these cases: @@ -139,27 +103,15 @@ Claude Code writes a marker into the git metadata of every worktree it creates with git, and the sweep keeps any worktree without one, including a worktree a `WorktreeCreate` hook created. -#### - -​ - -Worktree locks and manual removal +#### Worktree locks and manual removal While an agent is running, Claude Code holds a `git worktree lock` on its worktree so that concurrent cleanup can’t remove it, and releases the lock when the agent finishes. Claude Code holds the same lock on the worktree it created for a backgrounded session while the session runs, so the sweep leaves the worktree in place and `git worktree remove` refuses to remove it. The sweep also releases a lock Claude Code set for a session whose process has exited, so a killed background session doesn’t leave its worktree permanently locked. The sweep never releases a lock you set yourself with `git worktree lock`. To clean up a worktree that the sweep keeps, run `git worktree remove`, adding `--force` if the worktree has uncommitted changes or untracked files. If git refuses because the worktree is locked, run `git worktree unlock` on it first. -## - -​ - -Customize worktree creation +## Customize worktree creation Claude Code’s defaults for creating worktrees cover most sessions: it creates them under `.claude/worktrees/`, branches them from your repository’s default branch, and checks out only tracked files. The options in this section change those defaults. -### - -​ - -Choose the base branch +### Choose the base branch New worktrees branch from the repository’s default branch, so most sessions don’t need this setting. Set `worktree.baseRef` in [settings](</docs/en/settings-reference#worktree>) to branch from your current work instead. The setting accepts two values: @@ -180,11 +132,7 @@ } } -### - -​ - -Branch from a pull request +### Branch from a pull request To branch from a specific pull request or merge request, pass `--worktree` the number prefixed with `#`, a GitHub pull request URL, or a GitLab merge request URL such as `https://gitlab.com/group/repo/-/merge_requests/123`. Claude Code fetches that change’s head commit from `origin` and creates the worktree at `.claude/worktrees/pr-<number>`. Quote the argument so your shell doesn’t treat `#` as the start of a comment: @@ -198,11 +146,7 @@ This fetch never waits for input in your terminal. If git or ssh would ask for a password, a key passphrase, or confirmation of a new SSH host, the fetch fails instead and Claude Code exits with an `Error creating worktree: Failed to fetch PR/MR #<number>` message. A key that `ssh-agent` holds still works, so load your key there and run `git fetch` once by hand to record a new host before you start. Before v2.1.233, Claude Code accepted only `#<number>` and GitHub-style pull request URLs for `--worktree`, and always fetched `pull/<number>/head`. -### - -​ - -Copy gitignored files into worktrees +### Copy gitignored files into worktrees A worktree is a fresh checkout, so untracked files like `.env` or `.env.local` from your main repository are not present. To copy them automatically when Claude creates a worktree, add a `.worktreeinclude` file to your project root. The file uses `.gitignore` syntax. Only files that match a pattern and are also gitignored are copied, so tracked files are never duplicated. If you write a pattern that starts with `**/` and the files you want are inside a directory that is gitignored as a whole, Claude Code copies them only when that directory itself matches the pattern, or when the first name after the `**/` is one of the names in the directory’s path. For example, if you write `**/.claude/skills/*.md`, that first name is `.claude`, so Claude Code copies the matching files out of an ignored `.claude/` directory. To copy files out of an ignored directory that a `**/` pattern doesn’t reach, name the directory in the pattern instead: write `vendor/**/config.json` rather than `**/config.json`. Before v2.1.239, Claude Code copied files out of a wholly ignored directory for a `**/` pattern only when the directory itself matched the pattern. This `.worktreeinclude` copies two env files and a secrets config into each new worktree: @@ -214,11 +158,7 @@ This applies to every worktree Claude Code creates with git: `--worktree` worktrees, subagent worktrees, and parallel sessions in the [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>). With a `WorktreeCreate` hook, copy the files inside the hook script. -### - -​ - -Reuse a worktree name +### Reuse a worktree name If a worktree with the name you pass to `--worktree` already exists, Claude Code opens it instead of creating a new one. If Claude Code stops with an error containing `belongs to a different repository` or `is a leftover worktree`, see The worktree directory `belongs to a different repository`. With the default `"fresh"` base, a reopened worktree resets to the repository’s default branch instead of continuing at its old tip when all of the following hold: @@ -233,19 +173,11 @@ * `worktree.baseRef` is `"head"`. * The name is a pull request or merge request reference. -### - -​ - -Replace worktree creation with a hook +### Replace worktree creation with a hook Configure a [`WorktreeCreate` hook](</docs/en/hooks#worktreecreate>) to replace the default `git worktree` logic entirely, including placing worktrees somewhere other than `.claude/worktrees/`. For a complete example, see Non-git version control. -## - -​ - -What worktrees share with the main checkout +## What worktrees share with the main checkout A worktree gets its own files and branch, but it shares the following with the main checkout: @@ -256,11 +188,7 @@ All of these apply whether you create the worktree with `--worktree` or with `git worktree add`. In a worktree session you start from the [desktop app](</docs/en/desktop#run-a-session-in-its-own-worktree>), Claude Code reads project configuration such as settings, hooks, skills, agents, commands, and [`.mcp.json`](</docs/en/mcp#project-scope>) servers from the main checkout’s root. Hook commands run in that root, and `${CLAUDE_PROJECT_DIR}` points at it. To reach the files Claude is working on, read the worktree’s path from the hook’s [`cwd` input field](</docs/en/hooks#common-input-fields>). `CLAUDE.md` files and `.claude/rules/` still load from the worktree. -## - -​ - -Manage worktrees manually +## Manage worktrees manually Create worktrees with Git directly when you need to check out a specific existing branch or place the worktree outside the repository. Create a worktree on a new branch: @@ -285,11 +213,7 @@ See the [Git worktree documentation](<https://git-scm.com/docs/git-worktree>) for the full command reference. -## - -​ - -Non-git version control +## Non-git version control Worktree isolation uses git by default. For SVN, Perforce, Mercurial, or other systems, configure [`WorktreeCreate` and `WorktreeRemove` hooks](</docs/en/hooks#worktreecreate>) to provide custom creation and cleanup logic. Because the hook replaces the default git behavior, `.worktreeinclude` is not processed when you use `--worktree`. Copy any local configuration files inside your hook script instead. This `WorktreeCreate` hook reads the worktree name from the JSON on stdin with `jq`, checks out a fresh SVN working copy, and prints the directory path so Claude Code can use it as the session’s working directory. Add the configuration to your [`settings.json`](</docs/en/settings#where-settings-live>): @@ -310,43 +234,23 @@ Pair it with a `WorktreeRemove` hook to clean up when the session ends. See the [hooks reference](</docs/en/hooks#worktreecreate>) for the input schema and a removal example. A `WorktreeCreate` hook also lets you run [`/batch`](</docs/en/commands#all-commands>) outside a git repository. Each `/batch` subagent then publishes its change with your project’s version-control commands and, when it can’t open a pull request, reports what it published instead. Running `/batch` outside a git repository requires Claude Code v2.1.281 or later. -## - -​ - -Troubleshooting +## Troubleshooting Claude Code reports the errors below when it creates a worktree, enters one at startup, or returns a resumed session to one. -### - -​ - -Claude Code can’t enter the worktree at startup +### Claude Code can’t enter the worktree at startup When Claude Code can’t enter the worktree directory at startup, it prints an error naming the path and exits with code 1. This can happen when a [`WorktreeCreate` hook](</docs/en/hooks#worktreecreate>) prints something other than the directory it created, or when the directory was deleted after it was set up. -### - -​ - -Worktree creation fails on a symlinked path +### Worktree creation fails on a symlinked path Claude Code refuses to create a worktree when `.claude`, `.claude/worktrees`, or the worktree directory itself is a symlink, and the error names the symlinked path. Remove the symlink and retry. Before v2.1.212, if the repository already contained a committed symlink at one of those paths, worktree creation followed it and could create files outside the repository. -### - -​ - -A worktree Claude Code created has the original content of replaced objects +### A worktree Claude Code created has the original content of replaced objects If your repository uses [`git replace`](<https://git-scm.com/docs/git-replace>), the files in a worktree that Claude Code creates hold the original objects’ content rather than the replacements your `refs/replace/` entries name. Claude Code runs the git commands that check out the worktree’s files with `GIT_NO_REPLACE_OBJECTS=1`, ignoring any value you exported for that variable. To get the replaced content, create the worktree yourself with `git worktree add` and start Claude Code inside it. -### - -​ - -Git LFS files are pointer files in a worktree Claude Code created +### Git LFS files are pointer files in a worktree Claude Code created If you set up [Git LFS](<https://git-lfs.com>) with `git lfs install --local`, a worktree that Claude Code creates contains LFS pointer files instead of the real files. The `--local` flag writes the LFS filter into the repository’s own `.git/config` rather than your global git config. A plain `git lfs install` writes to your global config and isn’t affected. The same applies to any other [filter driver](<https://git-scm.com/docs/gitattributes>) defined in the repository’s own config. Claude Code skips the repository’s own filter drivers when it creates a worktree because a filter driver is a shell command, and anything that can write to the repository, including Claude, could have put one there. Before v2.1.247, Claude Code ran those drivers during worktree creation. To get the real files, run `git lfs pull` inside the worktree. In four rare cases, Claude Code creates no worktree at all: it can’t tell which filter drivers the repository’s config defines, or it finds a setting there it can’t switch off. Match the error to its fix: @@ -355,19 +259,11 @@ * **`The repository git config has a conditional include (includeIf)`** : move the settings the `includeIf` in `.git/config` pulls in directly into that file, remove the `includeIf`, and retry. An `includeIf` in your global git config doesn’t trigger this. * **`Git was not run: the repository's own git config sets<key>`**: the message names a key that points Git LFS at a program to run, such as `lfs.customtransfer.<name>.path` or `lfs.standalonetransferagent`. If that setting is yours, move it to your global git config. If you don’t recognize it, remove it from the repository’s git config, since a tool or checkout you don’t trust may have written it. Retry once the key is gone from the repository’s config. -### - -​ - -Worktree creation fails in a partial clone +### Worktree creation fails in a partial clone An error containing `This repository is a partial clone` means Claude Code couldn’t fetch every git object the worktree’s starting commit needs. Take the step in the message’s sentence ending in `try again`. Then retry from the shell where you took it: run `claude --worktree`, or start `claude` there and ask again. -### - -​ - -`Can only use --worktree in a git repository` +### `Can only use --worktree in a git repository` This error means you passed `--worktree` in a directory that isn’t a git checkout, and no `WorktreeCreate` hook is active. @@ -375,19 +271,11 @@ * In a checkout of another version control system, set up the hook the message suggests. * To work in the directory directly, start Claude without `--worktree`. -### - -​ - -The worktree directory `belongs to a different repository` +### The worktree directory `belongs to a different repository` The errors `belongs to a different repository` and `is a leftover worktree` both mean git ties the directory for the worktree name you passed to another location. This can happen after you copy or move a project. Pass a different worktree name. If the directory has no work to keep and you didn’t copy or move a project, you can remove it and retry the same name. After a copy or move, that retry can fail with `is already checked out elsewhere in this repository`, so use a different name. -### - -​ - -Claude Code refuses to use a worktree +### Claude Code refuses to use a worktree An error starting `Refusing to use <path> as an isolation worktree` means Claude Code checked the directory’s git identity before adopting it as a session’s or subagent’s isolated checkout, and declined it. The check runs whether Claude Code is creating the worktree, entering an existing one, or reusing one from an earlier run. In most cases the rest of the message says the directory’s git metadata resolves into the main checkout: for example, its `.git` file points at the main repository’s own `.git` directory, or git resolves its working tree to the main checkout through a `core.worktree` redirect. From such a directory, an ordinary git command such as `git reset --hard` would act on the main checkout instead of the worktree. Claude Code also refuses when the directory has a `.git` entry it can’t read, rather than assuming the worktree is safe. A directory with no git metadata at all, such as one your `WorktreeCreate` hook creates, passes the check only when no git repository contains it. If the hook creates the directory inside a repository, git resolves it to that repository’s checkout and Claude Code refuses it with the `git resolves its working tree to` message, so have the hook create its directories outside any repository. Claude Code leaves the refused directory in place, since it may hold work. Match the message to its recovery, whether it follows `Refusing to use <path>` or appears in a resume message; some endings occur only in resume messages: @@ -398,11 +286,7 @@ * **Says`its recorded path has a network spelling`**: Claude Code never resumes into a worktree at a network path. Recreate the worktree at a local path. * **Any other ending** : the message names the problem and its fix, such as removing a `core.worktree` redirect or recreating the worktree; follow it. Before deleting a directory whose message says its git identity could not be verified, address the named cause first, for example a symbolic link in the worktree’s path or git itself failing to run, since the directory may be healthy. When you do recreate, salvage any changes you need from the old directory first; it stays on disk. -### - -​ - -The session resumes outside its worktree +### The session resumes outside its worktree When you resume a session interactively and Claude Code can’t return it to its worktree, Claude Code says so with one of the messages below. When Claude Code clears the worktree binding, it records the clear in the session transcript. If you [suppress transcript writes](</docs/en/sessions#where-transcripts-are-stored>), the message says instead that the binding could not be cleared and that Claude Code will re-check the worktree on a later resume. @@ -422,11 +306,7 @@ The refusal ending embedded in each error is shared with the interactive notices, so it still matches its entry under Claude Code refuses to use a worktree. In the stream-json result, [`startup_failure_reason`](</docs/en/agent-sdk/typescript#startup_failure_reason>) is `worktree_unverified` for the `could not verify worktree` error and `worktree_resume_refused` for the `cannot resume into worktree` and `The worktree binding is kept` errors. An application can branch on it instead of matching the error text. Before v2.1.274, the result carried no `startup_failure_reason` field. -## - -​ - -See also +## See also Worktrees handle file isolation. The related pages below cover delegating work into those isolated checkouts, passing findings between them, and switching between the sessions you create:
modified Zero data retention View current →
--- a/zero-data-retention.md +++ b/zero-data-retention.md @@ -11,37 +11,21 @@ ZDR for Claude Code on Claude for Enterprise applies only to Anthropic’s direct platform. For Claude deployments on Amazon Bedrock, Google Cloud’s Agent Platform, or Microsoft Foundry, refer to those platforms’ data retention policies. -## - -​ - -ZDR scope +## ZDR scope ZDR covers Claude Code inference on Claude for Enterprise. ZDR is enabled on a per-organization basis. Each new organization requires ZDR to be enabled separately by your Anthropic account team. ZDR does not automatically apply to new organizations created under the same account. Contact your account team to enable ZDR for any new organizations. -### - -​ - -Route Claude Code traffic to your ZDR organization +### Route Claude Code traffic to your ZDR organization ZDR applies to requests that authenticate into a ZDR-enabled organization. If a developer signs in to Claude Code with a personal account or with an API key from a different organization, those sessions are not covered. To require that developers’ claude.ai logins belong to your ZDR organization, deploy the `forceLoginMethod` and `forceLoginOrgUUID` managed settings; see [Restrict login to your organization](</docs/en/authentication#restrict-login-to-your-organization>), which also explains how these keys treat Claude Console logins. -### - -​ - -What ZDR covers +### What ZDR covers ZDR covers model inference calls made through Claude Code on Claude for Enterprise. When you use Claude Code in your terminal, the prompts you send and the responses Claude generates are not retained by Anthropic. This applies to every model available to your ZDR organization. Some models require data retention by default; see Model availability under ZDR. -### - -​ - -What ZDR does not cover +### What ZDR does not cover ZDR does not extend to the following, even for organizations with ZDR enabled. Except where a row says otherwise, these features follow [standard data retention policies](</docs/en/data-usage#data-retention>): @@ -54,11 +38,7 @@ User and seat management| Administrative data such as account emails and seat assignments is retained under standard policies. Third-party integrations| Data processed by third-party tools, MCP servers, or other external integrations is not covered by ZDR. Review those services’ data handling practices independently. -## - -​ - -Features disabled under ZDR +## Features disabled under ZDR When ZDR is enabled for a Claude Code organization on Claude for Enterprise, certain features that require storing prompts or completions are automatically disabled at the backend level: @@ -74,26 +54,14 @@ These features are blocked in the backend regardless of client-side display. If you see a disabled feature in the Claude Code terminal during startup, attempting to use it returns an error indicating the organization’s policies do not allow that action. Future features may also be disabled if they require storing prompts or completions. -### - -​ - -Model availability under ZDR +### Model availability under ZDR Claude Fable 5.2, Fable 5.1, and Fable 5 are [Covered Models](<https://support.claude.com/en/articles/15425695-covered-models>) that [require data retention](<https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#model-specific-data-retention-requirements>) by default, and whether a ZDR organization or workspace can use them is governed by the Covered Models policies rather than by Claude Code. Where your organization can’t use them, the models are either absent from the `/model` picker or shown as disabled, and the server rejects requests for them regardless of client configuration. Other models remain available under ZDR. Fable models aren’t the default, and the `best` alias resolves to Opus. -## - -​ - -Data retention for policy violations +## Data retention for policy violations Even with ZDR enabled, Anthropic may retain data where required by law or to address Usage Policy violations. If a session is flagged for a policy violation, Anthropic may retain the associated inputs and outputs for up to 2 years, consistent with Anthropic’s standard ZDR policy. -## - -​ - -Request ZDR +## Request ZDR To request ZDR for Claude Code on Claude for Enterprise, [contact sales](<https://www.anthropic.com/contact-sales?utm_source=claude_code&utm_medium=docs&utm_content=zero_data_retention_request>) or your Anthropic account team. Your account team will submit the request internally, and Anthropic will review and enable ZDR on your organization after confirming eligibility. All enablement actions are audit-logged. If you are currently using ZDR for Claude Code via pay-as-you-go API keys, you can transition to Claude for Enterprise to gain access to administrative features while maintaining ZDR for Claude Code. Contact your account team to coordinate the migration.