# Claude Code CLI

All documentation for Claude Code CLI.


---
## admin-setup-9ffdbf6b0c.md

> ## Documentation Index
> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Set up Claude Code for your organization

> A decision map for administrators deploying Claude Code, covering API providers, managed settings, policy enforcement, usage monitoring, and data handling.

Claude Code enforces organization policy through managed settings that take precedence over local developer configuration. You deliver those settings from the Claude admin console, your mobile device management (MDM) system, or a file on disk. The settings control which tools, commands, servers, and network destinations Claude can reach.

This page walks through the deployment decisions in order. Each row links to the section below and to the reference page for that area.

<Note>
  SSO, SCIM provisioning, and seat assignment are configured at the Claude account level. See the [Claude Enterprise Administrator Guide](https://claude.com/resources/tutorials/claude-enterprise-administrator-guide) and [seat assignment](../17-Billing-Plans/use-claude-code-with-your-team-or-enterprise-plan.md) for those steps.
</Note>

| Decision                                                                | What you're choosing                                | Reference                                                                                                                                |
| :---------------------------------------------------------------------- | :-------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------- |
| [Choose your API provider](#choose-your-api-provider)                   | Where Claude Code authenticates and how it's billed | [Authentication](../13-Enterprise-Admin/authentication-claude-code-docs-2c6ada8385.md), [Bedrock](../20-Models/claude-code-on-amazon-bedrock-claude-code-docs-435e92efd0.md), [Vertex AI](../20-Models/claude-code-on-google-vertex-ai-claude-code-docs-2acd050a7a.md), [Foundry](../20-Models/claude-code-on-microsoft-foundry-claude-code-docs-ee35d755a6.md) |
| [Decide how settings reach devices](#decide-how-settings-reach-devices) | How managed policy reaches developer machines       | [Server-managed settings](../13-Enterprise-Admin/configure-server-managed-settings-claude-code-docs-d6a169b0bf.md), [Settings files](/en/settings#settings-files)                                    |
| [Decide what to enforce](#decide-what-to-enforce)                       | Which tools, commands, and integrations are allowed | [Permissions](configure-permissions-claude-code-docs-7b0e64d485.md), [Sandboxing](../22-Safety-Policy/sandboxing-claude-code-docs-5f97cd27c4.md)                                                                             |
| [Set up usage visibility](#set-up-usage-visibility)                     | How you track spend and adoption                    | [Analytics](../13-Enterprise-Admin/track-team-usage-with-analytics-claude-code-docs-35e754aabf.md), [Monitoring](../13-Enterprise-Admin/monitoring-claude-code-docs-72c46f3dc8.md), [Costs](../17-Billing-Plans/manage-costs-effectively-claude-code-docs-7c26178a4f.md)                                                       |
| [Review data handling](#review-data-handling)                           | Data retention and compliance posture               | [Data usage](../22-Safety-Policy/data-usage-claude-code-docs-06b2864aaa.md), [Security](../22-Safety-Policy/security-claude-code-docs-7538e94c51.md)                                                                                   |

## Choose your API provider

Claude Code connects to Claude through one of several API providers. Your choice affects billing, authentication, and which compliance posture you inherit.

| Provider                      | Choose this when                                                                                                                      |
| :---------------------------- | :------------------------------------------------------------------------------------------------------------------------------------ |
| Claude for Teams / Enterprise | You want Claude Code and claude.ai under one per-seat subscription with no infrastructure to run. This is the default recommendation. |
| Claude Console                | You're API-first or want pay-as-you-go billing                                                                                        |
| Amazon Bedrock                | You want to inherit existing AWS compliance controls and billing                                                                      |
| Google Vertex AI              | You want to inherit existing GCP compliance controls and billing                                                                      |
| Microsoft Foundry             | You want to inherit existing Azure compliance controls and billing                                                                    |

For the full provider comparison covering authentication, regions, and feature parity, see the [enterprise deployment overview](enterprise-deployment-overview-claude-code-docs-6eae0ecba2.md). Each provider's auth setup is in [Authentication](../13-Enterprise-Admin/authentication-claude-code-docs-2c6ada8385.md).

Proxy and firewall requirements in [Network configuration](enterprise-network-configuration-claude-code-docs.md) apply regardless of provider. If you want a single endpoint in front of multiple providers or centralized request logging, see [LLM gateway](../13-Enterprise-Admin/llm-gateway-configuration-claude-code-docs-7a1628ac88.md).

## Decide how settings reach devices

Managed settings define policy that takes precedence over local developer configuration. Claude Code looks for them in four places and uses the first one it finds on a given device.

| Mechanism               | Delivery                                                                                                                                                                                              | Priority | Platforms      |
| :---------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------- | :------------- |
| Server-managed          | Claude.ai admin console                                                                                                                                                                               | Highest  | All            |
| plist / registry policy | macOS: `com.anthropic.claudecode` plist<br />Windows: `HKLM\SOFTWARE\Policies\ClaudeCode`                                                                                                             | High     | macOS, Windows |
| File-based managed      | macOS: `/Library/Application Support/ClaudeCode/managed-settings.json`<br />Linux and WSL: `/etc/claude-code/managed-settings.json`<br />Windows: `C:\Program Files\ClaudeCode\managed-settings.json` | Medium   | All            |
| Windows user registry   | `HKCU\SOFTWARE\Policies\ClaudeCode`                                                                                                                                                                   | Lowest   | Windows only   |

Server-managed settings reach devices at authentication time and refresh hourly during active sessions, with no endpoint infrastructure. They require a Claude for Teams or Enterprise plan, so deployments on other providers need one of the file-based or OS-level mechanisms instead.

If your organization mixes providers, configure [server-managed settings](../13-Enterprise-Admin/configure-server-managed-settings-claude-code-docs-d6a169b0bf.md) for Claude.ai users plus a [file-based or plist/registry fallback](/en/settings#settings-files) so other users still receive managed policy.

The plist and HKLM registry locations work with any provider and resist tampering because they require admin privileges to write. The Windows user registry at HKCU is writable without elevation, so treat it as a convenience default rather than an enforcement channel.

By default WSL reads only the Linux file path at `/etc/claude-code`. To extend your Windows registry and `C:\Program Files\ClaudeCode` policy to WSL on the same machine, set [`wslInheritsWindowsSettings: true`](/en/settings#available-settings) in either of those admin-only Windows sources.

Whichever mechanism you choose, managed values take precedence over user and project settings. 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.

See [Server-managed settings](../13-Enterprise-Admin/configure-server-managed-settings-claude-code-docs-d6a169b0bf.md) and [Settings files and precedence](/en/settings#settings-files).

## 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.

| Control                                                                                | What it does                                                                  | Key settings                                                                  |
| :------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------- | :---------------------------------------------------------------------------- |
| [Permission rules](configure-permissions-claude-code-docs-7b0e64d485.md)                                                    | Allow, ask, or deny specific tools and commands                               | `permissions.allow`, `permissions.deny`                                       |
| [Permission lockdown](/en/permissions#managed-only-settings)                           | Only managed permission rules apply; disable `--dangerously-skip-permissions` | `allowManagedPermissionRulesOnly`, `permissions.disableBypassPermissionsMode` |
| [Sandboxing](../22-Safety-Policy/sandboxing-claude-code-docs-5f97cd27c4.md)                                                           | OS-level filesystem and network isolation with domain allowlists              | `sandbox.enabled`, `sandbox.network.allowedDomains`                           |
| [Managed policy CLAUDE.md](/en/memory#deploy-organization-wide-claude-md)              | Org-wide instructions loaded in every session, cannot be excluded             | File at the managed policy path                                               |
| [MCP server control](/en/mcp#managed-mcp-configuration)                                | Restrict which MCP servers users can add or connect to                        | `allowedMcpServers`, `deniedMcpServers`, `allowManagedMcpServersOnly`         |
| [Plugin marketplace control](/en/plugin-marketplaces#managed-marketplace-restrictions) | Restrict which marketplace sources users can add and install from             | `strictKnownMarketplaces`, `blockedMarketplaces`                              |
| [Hook restrictions](/en/settings#hook-configuration)                                   | Only managed hooks load; restrict HTTP hook URLs                              | `allowManagedHooksOnly`, `allowedHttpHookUrls`                                |
| [Version floor](claude-code-settings-claude-code-docs-d4420b4b52.md)                                                          | Prevent auto-update from installing below an org-wide minimum                 | `minimumVersion`                                                              |

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](../22-Safety-Policy/security-claude-code-docs-7538e94c51.md).

## Set up usage visibility

Choose monitoring based on what you need to report on.

| Capability          | What you get                                         | Availability   | Where to start                           |
| :------------------ | :--------------------------------------------------- | :------------- | :--------------------------------------- |
| Usage monitoring    | OpenTelemetry export of sessions, tools, and tokens  | All providers  | [Monitoring usage](../13-Enterprise-Admin/monitoring-claude-code-docs-72c46f3dc8.md) |
| Analytics dashboard | Per-user metrics, contribution tracking, leaderboard | Anthropic only | [Analytics](../13-Enterprise-Admin/track-team-usage-with-analytics-claude-code-docs-35e754aabf.md)               |
| Cost tracking       | Spend limits, rate limits, and usage attribution     | Anthropic only | [Costs](../17-Billing-Plans/manage-costs-effectively-claude-code-docs-7c26178a4f.md)                       |

Cloud providers expose spend through AWS Cost Explorer, GCP Billing, or Azure Cost Management. Claude for Teams and Enterprise plans include a usage dashboard at [claude.ai/analytics/claude-code](https://claude.ai/analytics/claude-code).

## Review data handling

On Team, Enterprise, Claude API, and cloud provider plans, Anthropic does not train models on your code or prompts. Your API provider determines retention and compliance posture.

| Topic                     | What to know                                                                    | Where to start                                 |
| :------------------------ | :------------------------------------------------------------------------------ | :--------------------------------------------- |
| Data usage policy         | What Anthropic collects, how long it's retained, what's never used for training | [Data usage](../22-Safety-Policy/data-usage-claude-code-docs-06b2864aaa.md)                   |
| Zero Data Retention (ZDR) | Nothing stored after the request completes. Available on Claude for Enterprise  | [Zero data retention](../22-Safety-Policy/zero-data-retention-claude-code-docs-6ec9ee63f1.md) |
| Security architecture     | Network model, encryption, authentication, audit trail                          | [Security](../22-Safety-Policy/security-claude-code-docs-7538e94c51.md)                       |

If you need request-level audit logging or to route traffic by data sensitivity, place an [LLM gateway](../13-Enterprise-Admin/llm-gateway-configuration-claude-code-docs-7a1628ac88.md) between developers and your provider. For regulatory requirements and certifications, see [Legal and compliance](../22-Safety-Policy/legal-and-compliance-claude-code-docs-2d64f2bee3.md).

## Verify and onboard

After configuring managed settings, have a developer run `/status` inside Claude Code. The output includes a line beginning with `Enterprise managed settings` followed by the source in parentheses, one of `(remote)`, `(plist)`, `(HKLM)`, `(HKCU)`, or `(file)`. See [Verify active settings](/en/settings#verify-active-settings).

Share these resources to help developers get started:

* [Quickstart](../01-Getting-Started/quickstart-claude-code-docs-a21b84bdea.md): first-session walkthrough from install to working with a project
* [Common workflows](common-workflows-c909406123.md): patterns for everyday tasks like code review, refactoring, and debugging
* [Claude 101](https://anthropic.skilljar.com/claude-101) and [Claude Code in Action](https://anthropic.skilljar.com/claude-code-in-action): self-paced Anthropic Academy courses

For login issues, point developers to [authentication troubleshooting](/en/troubleshooting#authentication-issues). The most common fixes are:

* Run `/logout` then `/login` to switch accounts
* Run `claude update` if the enterprise auth option is missing
* Restart the terminal after updating

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

With provider and delivery mechanism chosen, move on to detailed configuration:

* [Server-managed settings](../13-Enterprise-Admin/configure-server-managed-settings-claude-code-docs-d6a169b0bf.md): deliver managed policy from the Claude admin console
* [Settings reference](claude-code-settings-claude-code-docs-d4420b4b52.md): every setting key, file location, and precedence rule
* [Amazon Bedrock](../20-Models/claude-code-on-amazon-bedrock-claude-code-docs-435e92efd0.md), [Google Vertex AI](../20-Models/claude-code-on-google-vertex-ai-claude-code-docs-2acd050a7a.md), [Microsoft Foundry](../20-Models/claude-code-on-microsoft-foundry-claude-code-docs-ee35d755a6.md): provider-specific deployment
* [Claude Enterprise Administrator Guide](https://claude.com/resources/tutorials/claude-enterprise-administrator-guide): SSO, SCIM, seat management, and rollout playbook


---
## amazon-bedrock-0f0d5f108c.md

> ## Documentation Index
> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Claude Code on Amazon Bedrock

> Learn about configuring Claude Code through Amazon Bedrock, including setup, IAM configuration, and troubleshooting.

export const ContactSalesCard = ({surface}) => {
  const utm = content => `utm_source=claude_code&utm_medium=docs&utm_content=${surface}_${content}`;
  const iconArrowRight = (size = 13) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <line x1="5" y1="12" x2="19" y2="12" />
      <polyline points="12 5 19 12 12 19" />
    </svg>;
  const STYLES = `
.cc-cs {
  --cs-slate: #141413;
  --cs-clay: #d97757;
  --cs-clay-deep: #c6613f;
  --cs-gray-000: #ffffff;
  --cs-gray-700: #3d3d3a;
  --cs-border-default: rgba(31, 30, 29, 0.15);
  font-family: inherit;
}
.dark .cc-cs {
  --cs-slate: #f0eee6;
  --cs-gray-000: #262624;
  --cs-gray-700: #bfbdb4;
  --cs-border-default: rgba(240, 238, 230, 0.14);
}
.cc-cs-card {
  display: flex; align-items: center; justify-content: space-between;
  gap: 16px; padding: 14px 16px; margin: 0;
  background: var(--cs-gray-000); border: 0.5px solid var(--cs-border-default);
  border-radius: 8px; flex-wrap: wrap;
}
.cc-cs-text { font-size: 13px; color: var(--cs-gray-700); line-height: 1.5; flex: 1; min-width: 240px; }
.cc-cs-text strong { font-weight: 550; color: var(--cs-slate); }
.cc-cs-actions { display: flex; align-items: center; gap: 8px; flex-shrink: 0; }
.cc-cs-btn-clay {
  display: inline-flex; align-items: center; gap: 8px;
  background: var(--cs-clay-deep); color: #fff; border: none;
  border-radius: 8px; padding: 8px 14px;
  font-size: 13px; font-weight: 500;
  transition: background-color 0.15s; white-space: nowrap;
}
.cc-cs-btn-clay:hover { background: var(--cs-clay); }
.cc-cs-btn-ghost {
  display: inline-flex; align-items: center; gap: 8px;
  background: transparent; color: var(--cs-gray-700);
  border: 0.5px solid var(--cs-border-default);
  border-radius: 8px; padding: 8px 14px;
  font-size: 13px; font-weight: 500;
}
.cc-cs-btn-ghost:hover { background: rgba(0, 0, 0, 0.04); }
.dark .cc-cs-btn-ghost:hover { background: rgba(255, 255, 255, 0.04); }
@media (max-width: 720px) {
  .cc-cs-actions { width: 100%; }
}
`;
  return <div className="cc-cs not-prose">
      <style>{STYLES}</style>
      <div className="cc-cs-card">
        <div className="cc-cs-text">
          <strong>Deploying Claude Code across your organization?</strong> Talk to sales about enterprise plans, SSO, and centralized billing.
        </div>
        <div className="cc-cs-actions">
          <a href={`https://claude.com/pricing?${utm('view_plans')}#plans-business`} className="cc-cs-btn-ghost">
            View plans
          </a>
          <a href={`https://claude.com/contact-sales?${utm('contact_sales')}`} className="cc-cs-btn-clay">
            Contact sales {iconArrowRight()}
          </a>
        </div>
      </div>
    </div>;
};

export const Experiment = ({flag, treatment, children}) => {
  const VID_KEY = 'exp_vid';
  const CONSENT_COUNTRIES = new Set(['AT', 'BE', 'BG', 'HR', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 'DE', 'GR', 'HU', 'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'PL', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE', 'RE', 'GP', 'MQ', 'GF', 'YT', 'BL', 'MF', 'PM', 'WF', 'PF', 'NC', 'AW', 'CW', 'SX', 'FO', 'GL', 'AX', 'GB', 'UK', 'AI', 'BM', 'IO', 'VG', 'KY', 'FK', 'GI', 'MS', 'PN', 'SH', 'TC', 'GG', 'JE', 'IM', 'CA', 'BR', 'IN']);
  const fnv1a = s => {
    let h = 0x811c9dc5;
    for (let i = 0; i < s.length; i++) {
      h ^= s.charCodeAt(i);
      h += (h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24);
    }
    return h >>> 0;
  };
  const bucket = (seed, vid) => fnv1a(fnv1a(seed + vid) + '') % 10000 < 5000 ? 'control' : 'treatment';
  const [decision] = useState(() => {
    const params = new URLSearchParams(location.search);
    const preBucketed = document.documentElement.dataset['gb_' + flag.replace(/-/g, '_')];
    const force = params.get('gb-force');
    if (force) {
      for (const p of force.split(',')) {
        const [k, v] = p.split(':');
        if (k === flag) return {
          variant: v || 'treatment',
          track: false
        };
      }
    }
    if (navigator.globalPrivacyControl) {
      return {
        variant: 'control',
        track: false
      };
    }
    const prefsMatch = document.cookie.match(/(?:^|; )anthropic-consent-preferences=([^;]+)/);
    if (prefsMatch) {
      try {
        if (JSON.parse(decodeURIComponent(prefsMatch[1])).analytics !== true) {
          return {
            variant: 'control',
            track: false
          };
        }
      } catch {
        return {
          variant: 'control',
          track: false
        };
      }
    } else {
      const country = params.get('country')?.toUpperCase() || (document.cookie.match(/(?:^|; )cf_geo=([A-Z]{2})/) || [])[1];
      if (!country || CONSENT_COUNTRIES.has(country)) {
        return {
          variant: 'control',
          track: false
        };
      }
    }
    let vid;
    try {
      const ajsMatch = document.cookie.match(/(?:^|; )ajs_anonymous_id=([^;]+)/);
      if (ajsMatch) {
        vid = decodeURIComponent(ajsMatch[1]).replace(/^"|"$/g, '');
      } else {
        vid = localStorage.getItem(VID_KEY);
        if (!vid) {
          vid = crypto.randomUUID();
        }
        document.cookie = `ajs_anonymous_id=${vid}; domain=.claude.com; path=/; Secure; SameSite=Lax; max-age=31536000`;
      }
      try {
        localStorage.setItem(VID_KEY, vid);
      } catch {}
    } catch {
      return {
        variant: 'control',
        track: false
      };
    }
    const variant = preBucketed === '1' ? 'treatment' : preBucketed === '0' ? 'control' : bucket(flag, vid);
    return {
      variant,
      track: true,
      vid
    };
  });
  useEffect(() => {
    if (!decision.track) return;
    fetch('https://api.anthropic.com/api/event_logging/v2/batch', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'x-service-name': 'claude_code_docs'
      },
      body: JSON.stringify({
        events: [{
          event_type: 'GrowthbookExperimentEvent',
          event_data: {
            device_id: decision.vid,
            anonymous_id: decision.vid,
            timestamp: new Date().toISOString(),
            experiment_id: flag,
            variation_id: decision.variant === 'treatment' ? 1 : 0,
            environment: 'production'
          }
        }]
      }),
      keepalive: true
    }).catch(() => {});
  }, []);
  return decision.variant === 'treatment' ? treatment : children;
};

<Experiment flag="docs-contact-sales-cta" treatment={<ContactSalesCard surface="bedrock" />} />

## Prerequisites

Before configuring Claude Code with Bedrock, ensure you have:

* An AWS account with Bedrock access enabled
* Access to desired Claude models (for example, Claude Sonnet 4.6) in Bedrock
* AWS CLI installed and configured (optional - only needed if you don't have another mechanism for getting credentials)
* Appropriate IAM permissions

To sign in with your own Bedrock credentials, follow [Sign in with Bedrock](#sign-in-with-bedrock) below. To deploy Claude Code across a team, use the [manual setup](#set-up-manually) steps and [pin your model versions](#4-pin-model-versions) before rolling out.

## Sign in with Bedrock

If you have AWS credentials and want to start using Claude Code through Bedrock, the login wizard walks you through it. You complete the AWS-side prerequisites once per account; the wizard handles the Claude Code side.

<Steps>
  <Step title="Enable Anthropic models in your AWS account">
    In the [Amazon Bedrock console](https://console.aws.amazon.com/bedrock/), open the Model catalog, select an Anthropic model, and submit the use case form. Access is granted immediately after submission. See [Submit use case details](#1-submit-use-case-details) for AWS Organizations and [IAM configuration](#iam-configuration) for the permissions your role needs.
  </Step>

  <Step title="Start Claude Code and choose Bedrock">
    Run `claude`. At the login prompt, select **3rd-party platform**, then **Amazon Bedrock**.
  </Step>

  <Step title="Follow the wizard prompts">
    Choose how you authenticate to AWS: an AWS profile detected from your `~/.aws` directory, a Bedrock API key, an access key and secret, or credentials already in your environment. The wizard picks up your region, verifies which Claude models your account can invoke, and lets you pin them. It saves the result to the `env` block of your [user settings file](claude-code-settings-claude-code-docs-d4420b4b52.md), so you don't need to export environment variables yourself.
  </Step>
</Steps>

After you've signed in, run `/setup-bedrock` any time to reopen the wizard and change your credentials, region, or model pins.

## Set up manually

To configure 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

First-time users of Anthropic models are required to submit use case details before invoking a model. This is done once per AWS account.

1. Ensure you have the right IAM permissions described below
2. Navigate to the [Amazon Bedrock console](https://console.aws.amazon.com/bedrock/)
3. Select an Anthropic model from the **Model catalog**
4. Complete the use case form. Access is granted immediately after submission.

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

Claude Code uses the default AWS SDK credential chain. Set up your credentials using one of these methods:

**Option A: AWS CLI configuration**

```bash theme={null}
aws configure
```

**Option B: Environment variables (access key)**

```bash theme={null}
export AWS_ACCESS_KEY_ID=your-access-key-id
export AWS_SECRET_ACCESS_KEY=your-secret-access-key
export AWS_SESSION_TOKEN=your-session-token
```

**Option C: Environment variables (SSO profile)**

```bash theme={null}
aws sso login --profile=<your-profile-name>

export AWS_PROFILE=your-profile-name
```

**Option D: AWS Management Console credentials**

```bash theme={null}
aws login
```

[Learn more](https://docs.aws.amazon.com/signin/latest/userguide/command-line-sign-in.html) about `aws login`.

**Option E: Bedrock API keys**

```bash theme={null}
export AWS_BEARER_TOKEN_BEDROCK=your-bedrock-api-key
```

Bedrock API keys provide a simpler authentication method without needing full AWS credentials. [Learn more about Bedrock API keys](https://aws.amazon.com/blogs/machine-learning/accelerate-ai-development-with-amazon-bedrock-api-keys/).

#### 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](claude-code-settings-claude-code-docs-d4420b4b52.md) for file locations).

When Claude Code detects that your AWS credentials are expired (either locally based on their timestamp or when Bedrock returns a credential error), it will automatically run your configured `awsAuthRefresh` and/or `awsCredentialExport` commands to obtain new credentials before retrying the request.

##### Example configuration

```json theme={null}
{
  "awsAuthRefresh": "aws sso login --profile myprofile",
  "env": {
    "AWS_PROFILE": "myprofile"
  }
}
```

##### Configuration settings explained

**`awsAuthRefresh`**: Use this for commands that modify the `.aws` directory, such as updating credentials, SSO cache, or config files. The command's output is displayed to the user, but interactive input isn't supported. This works well for browser-based SSO flows where the CLI displays a URL or code and you complete authentication in the browser.

**`awsCredentialExport`**: Only use this if you can't modify `.aws` and must directly return credentials. Output is captured silently and not shown to the user. The command must output JSON in this format:

```json theme={null}
{
  "Credentials": {
    "AccessKeyId": "value",
    "SecretAccessKey": "value",
    "SessionToken": "value"
  }
}
```

### 3. Configure Claude Code

Set the following environment variables to enable Bedrock:

```bash theme={null}
# Enable Bedrock integration
export CLAUDE_CODE_USE_BEDROCK=1
export AWS_REGION=us-east-1  # or your preferred region

# Optional: Override the region for the small/fast model (Haiku).
# Also applies to Bedrock Mantle.
export ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION=us-west-2

# Optional: Override the Bedrock endpoint URL for custom endpoints or gateways
# export ANTHROPIC_BEDROCK_BASE_URL=https://bedrock-runtime.us-east-1.amazonaws.com
```

When enabling Bedrock for Claude Code, keep the following in mind:

* `AWS_REGION` is a required environment variable. Claude Code does not read from the `.aws` config file for this setting.
* When using Bedrock, the `/login` and `/logout` commands are disabled since authentication is handled through AWS credentials.
* You can use settings files for environment variables like `AWS_PROFILE` that you don't want to leak to other processes. See [Settings](claude-code-settings-claude-code-docs-d4420b4b52.md) for more information.

### 4. Pin model versions

<Warning>
  Pin specific model versions when deploying to multiple users. Without pinning, model aliases such as `sonnet` and `opus` resolve to the latest version, which may not yet be available in your Bedrock account when Anthropic releases an update. Claude Code [falls back](#startup-model-checks) to the previous version at startup when the latest is unavailable, but pinning lets you control when your users move to a new model.
</Warning>

Set these environment variables to specific Bedrock model IDs.

Without `ANTHROPIC_DEFAULT_OPUS_MODEL`, the `opus` alias on Bedrock resolves to Opus 4.6. Set it to the Opus 4.7 ID to use the latest model:

```bash theme={null}
export ANTHROPIC_DEFAULT_OPUS_MODEL='us.anthropic.claude-opus-4-7'
export ANTHROPIC_DEFAULT_SONNET_MODEL='us.anthropic.claude-sonnet-4-6'
export ANTHROPIC_DEFAULT_HAIKU_MODEL='us.anthropic.claude-haiku-4-5-20251001-v1:0'
```

These variables use cross-region inference profile IDs (with the `us.` prefix). If you use a different region prefix or application inference profiles, adjust accordingly. For current and legacy model IDs, see [Models overview](../20-Models/about-claude-models-overview-2bbf09ff82.md). See [Model configuration](/en/model-config#pin-models-for-third-party-deployments) for the full list of environment variables.

Claude Code uses these default models when no pinning variables are set:

| Model type       | Default value                                  |
| :--------------- | :--------------------------------------------- |
| Primary model    | `us.anthropic.claude-sonnet-4-5-20250929-v1:0` |
| Small/fast model | `us.anthropic.claude-haiku-4-5-20251001-v1:0`  |

To customize models further, use one of these methods:

```bash theme={null}
# Using inference profile ID
export ANTHROPIC_MODEL='global.anthropic.claude-sonnet-4-6'
export ANTHROPIC_DEFAULT_HAIKU_MODEL='us.anthropic.claude-haiku-4-5-20251001-v1:0'

# Using application inference profile ARN
export ANTHROPIC_MODEL='arn:aws:bedrock:us-east-2:your-account-id:application-inference-profile/your-model-id'

# Optional: Disable prompt caching if needed
export DISABLE_PROMPT_CACHING=1

# Optional: Request 1-hour prompt cache TTL instead of the 5-minute default
export ENABLE_PROMPT_CACHING_1H=1
```

<Note>[Prompt caching](../10-Prompting-Guides/build-with-claude-prompt-caching-bf7c54aa4c.md) may not be available in all regions. Cache writes with a 1-hour TTL are billed at a higher rate than 5-minute writes.</Note>

#### 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](/en/settings#settings-files) instead.

This example maps four Opus versions to distinct ARNs so users can switch between them without bypassing your organization's inference profiles:

```json theme={null}
{
  "modelOverrides": {
    "claude-opus-4-7": "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/opus-47-prod",
    "claude-opus-4-6": "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/opus-46-prod",
    "claude-opus-4-5-20251101": "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/opus-45-prod",
    "claude-opus-4-1-20250805": "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/opus-41-prod"
  }
}
```

When a user selects one of these versions in `/model`, Claude Code calls Bedrock with the mapped ARN. Versions without an override fall back to the built-in Bedrock model ID or any matching inference profile discovered at startup. See [Override model IDs per version](/en/model-config#override-model-ids-per-version) for details on how overrides interact with `availableModels` and other model settings.

## Startup model checks

When Claude Code starts with Bedrock configured, it verifies that the models it intends to use are accessible in your account. This check requires Claude Code v2.1.94 or later.

If you have pinned a model version that is older than the current Claude Code default, and your account can invoke the newer version, Claude Code prompts you to update the pin. Accepting writes the new model ID to your [user settings file](claude-code-settings-claude-code-docs-d4420b4b52.md) and restarts Claude Code. Declining is remembered until the next default version change. Pins that point to an [application inference profile ARN](#map-each-model-version-to-an-inference-profile) are skipped, since those are managed by your administrator.

If you have not pinned a model and the current default is unavailable in your account, Claude Code falls back to the previous version for the current session and shows a notice. The fallback is not persisted. Enable the newer model in your Bedrock account or [pin a version](#4-pin-model-versions) to make the choice permanent.

## IAM configuration

Create an IAM policy with the required permissions for Claude Code:

```json theme={null}
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowModelAndInferenceProfileAccess",
      "Effect": "Allow",
      "Action": [
        "bedrock:InvokeModel",
        "bedrock:InvokeModelWithResponseStream",
        "bedrock:ListInferenceProfiles"
      ],
      "Resource": [
        "arn:aws:bedrock:*:*:inference-profile/*",
        "arn:aws:bedrock:*:*:application-inference-profile/*",
        "arn:aws:bedrock:*:*:foundation-model/*"
      ]
    },
    {
      "Sid": "AllowMarketplaceSubscription",
      "Effect": "Allow",
      "Action": [
        "aws-marketplace:ViewSubscriptions",
        "aws-marketplace:Subscribe"
      ],
      "Resource": "*",
      "Condition": {
        "StringEquals": {
          "aws:CalledViaLast": "bedrock.amazonaws.com"
        }
      }
    }
  ]
}
```

For more restrictive permissions, you can limit the Resource to specific inference profile ARNs.

For details, see [Bedrock IAM documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/security-iam.html).

<Note>
  Create a dedicated AWS account for Claude Code to simplify cost tracking and access control.
</Note>

## 1M token context window

Claude Opus 4.7, Opus 4.6, and Sonnet 4.6 support the [1M token context window](../04-API-Reference/Guides/build-with-claude-context-windows-13ca780d1d.md#1m-token-context-window) on Amazon Bedrock. Claude Code automatically enables the extended context window when you select a 1M model variant.

The [setup wizard](#sign-in-with-bedrock) 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](/en/model-config#pin-models-for-third-party-deployments) for details.

## 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/), publish a version, then add the Guardrail headers to your [settings file](claude-code-settings-claude-code-docs-d4420b4b52.md). Enable Cross-Region inference on your Guardrail if you're using cross-region inference profiles.

Example configuration:

```json theme={null}
{
  "env": {
    "ANTHROPIC_CUSTOM_HEADERS": "X-Amzn-Bedrock-GuardrailIdentifier: your-guardrail-id\nX-Amzn-Bedrock-GuardrailVersion: 1"
  }
}
```

## Use the Mantle endpoint

Mantle is an Amazon Bedrock endpoint that serves Claude models through the native Anthropic API shape rather than the Bedrock Invoke API. It uses the same AWS credentials, IAM permissions, and `awsAuthRefresh` configuration described earlier on this page.

<Note>
  Mantle requires Claude Code v2.1.94 or later. Run `claude --version` to check.
</Note>

### Enable Mantle

With AWS credentials already configured, set `CLAUDE_CODE_USE_MANTLE` to route requests to the Mantle endpoint:

```bash theme={null}
export CLAUDE_CODE_USE_MANTLE=1
export AWS_REGION=us-east-1
```

Claude Code constructs the endpoint URL from `AWS_REGION`. To override it 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

Mantle uses model IDs prefixed with `anthropic.` and without a version suffix, for example `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:

```bash theme={null}
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 Bedrock Invoke API.

```bash theme={null}
export CLAUDE_CODE_USE_BEDROCK=1
export CLAUDE_CODE_USE_MANTLE=1
```

To surface a Mantle model in the `/model` picker, list its ID in `availableModels` in your [settings file](claude-code-settings-claude-code-docs-d4420b4b52.md). This setting also restricts the picker to the listed entries, so include every alias you want to keep available:

```json theme={null}
{
  "availableModels": ["opus", "sonnet", "haiku", "anthropic.claude-haiku-4-5"]
}
```

Entries with the `anthropic.` prefix are added as custom picker options and routed to Mantle. Replace `anthropic.claude-haiku-4-5` with the model ID your account has been granted. See [Restrict model selection](/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

If your organization routes model traffic through a centralized [LLM gateway](../13-Enterprise-Admin/llm-gateway-configuration-claude-code-docs-7a1628ac88.md) that injects AWS credentials server-side, disable client-side authentication so Claude Code sends requests without SigV4 signatures or `x-api-key` headers:

```bash theme={null}
export CLAUDE_CODE_USE_MANTLE=1
export CLAUDE_CODE_SKIP_MANTLE_AUTH=1
export ANTHROPIC_BEDROCK_MANTLE_BASE_URL=https://your-gateway.example.com
```

### Mantle environment variables

These variables are specific to the Mantle endpoint. See [Environment variables](env-vars-5c624d392b.md) for the full list.

| Variable                                | Purpose                                                             |
| :-------------------------------------- | :------------------------------------------------------------------ |
| `CLAUDE_CODE_USE_MANTLE`                | Enable the Mantle endpoint. Set to `1` or `true`.                   |
| `ANTHROPIC_BEDROCK_MANTLE_BASE_URL`     | Override the default Mantle endpoint URL                            |
| `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 Bedrock) |

## Troubleshooting

### Authentication loop with SSO and corporate proxies

If browser tabs spawn repeatedly when using AWS SSO, remove the `awsAuthRefresh` setting from your [settings file](claude-code-settings-claude-code-docs-d4420b4b52.md). This can occur when corporate VPNs or TLS inspection proxies interrupt the SSO browser flow. Claude Code treats the interrupted connection as an authentication failure, re-runs `awsAuthRefresh`, and loops indefinitely.

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`.

### Region issues

If you encounter region issues:

* Check model availability: `aws bedrock list-inference-profiles --region your-region`
* Switch to a supported region: `export AWS_REGION=us-east-1`
* Consider using inference profiles for cross-region access

If you receive an error "on-demand throughput isn’t supported":

* Specify the model as an [inference profile](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html) ID

Claude Code uses the Bedrock [Invoke API](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithResponseStream.html) and does not support the Converse API.

### 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](claude-code-settings-claude-code-docs-d4420b4b52.md).

A `403` from the Mantle endpoint with valid credentials means 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 is not served on Mantle. Mantle has its own model lineup separate from the standard Bedrock catalog, so inference profile IDs such as `us.anthropic.claude-sonnet-4-6` will not work. Use a Mantle-format ID, or enable [both endpoints](#run-mantle-alongside-the-invoke-api) so Claude Code routes each request to the endpoint where the model is available.

## Additional resources

* [Bedrock documentation](https://docs.aws.amazon.com/bedrock/)
* [Bedrock pricing](https://aws.amazon.com/bedrock/pricing/)
* [Bedrock inference profiles](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html)
* [Bedrock token burndown and quotas](https://docs.aws.amazon.com/bedrock/latest/userguide/quotas-token-burndown.html)
* [Claude Code on Amazon Bedrock: Quick Setup Guide](https://community.aws/content/2tXkZKrZzlrlu0KfH8gST5Dkppq/claude-code-on-amazon-bedrock-quick-setup-guide)
* [Claude Code Monitoring Implementation (Bedrock)](https://github.com/aws-solutions-library-samples/guidance-for-claude-code-with-amazon-bedrock/blob/main/assets/docs/MONITORING.md)


---
## analytics-5356b88d0a.md

> ## Documentation Index
> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Track team usage with analytics

> View Claude Code usage metrics, track adoption, and measure engineering velocity in the analytics dashboard.

Claude Code provides analytics dashboards to help organizations understand developer usage patterns, track contribution metrics, and measure how Claude Code impacts engineering velocity. Access the dashboard for your plan:

| Plan                          | Dashboard URL                                                              | Includes                                                                              | Read more                                            |
| ----------------------------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ---------------------------------------------------- |
| Claude for Teams / Enterprise | [claude.ai/analytics/claude-code](https://claude.ai/analytics/claude-code) | Usage metrics, contribution metrics with GitHub integration, leaderboard, data export | [Details](#access-analytics-for-team-and-enterprise) |
| API (Claude Console)          | [platform.claude.com/claude-code](https://platform.claude.com/claude-code) | Usage metrics, spend tracking, team insights                                          | [Details](#access-analytics-for-api-customers)       |

## 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:

* **Usage metrics**: lines of code accepted, suggestion accept rate, daily active users and sessions
* **Contribution metrics**: PRs and lines of code shipped with Claude Code assistance, with [GitHub integration](#enable-contribution-metrics)
* **Leaderboard**: top contributors ranked by Claude Code usage
* **Data export**: download contribution data as CSV for custom reporting

### Enable contribution metrics

<Note>
  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.
</Note>

Usage and adoption data is available for all Claude for Teams and Claude for Enterprise accounts. Contribution metrics require additional setup to connect your GitHub organization.

You need the Owner role to configure analytics settings. A GitHub admin must install the GitHub app.

<Warning>
  Contribution metrics are not available for organizations with [Zero Data Retention](../22-Safety-Policy/zero-data-retention-claude-code-docs-6ec9ee63f1.md) enabled. The analytics dashboard will show usage metrics only.
</Warning>

<Steps>
  <Step title="Install the GitHub app">
    A GitHub admin installs the Claude GitHub app on your organization's GitHub account at [github.com/apps/claude](https://github.com/apps/claude).
  </Step>

  <Step title="Enable Claude Code analytics">
    A Claude Owner navigates to [claude.ai/admin-settings/claude-code](https://claude.ai/admin-settings/claude-code) and enables the Claude Code analytics feature.
  </Step>

  <Step title="Enable GitHub analytics">
    On the same page, enable the "GitHub analytics" toggle.
  </Step>

  <Step title="Authenticate with GitHub">
    Complete the GitHub authentication flow and select which GitHub organizations to include in the analysis.
  </Step>
</Steps>

Data typically appears within 24 hours after enabling, with daily updates. If no data appears, you may see one of these messages:

* **"GitHub app required"**: install the GitHub app to view contribution metrics
* **"Data processing in progress"**: check back in a few days and confirm the GitHub app is installed if data doesn't appear

Contribution metrics support GitHub Cloud and GitHub Enterprise Server.

### Review summary metrics

<Note>
  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.
</Note>

The dashboard displays these summary metrics at the top:

* **PRs with CC**: total count of merged pull requests that contain at least one line of code written with Claude Code
* **Lines of code with CC**: total lines of code across all merged PRs that were written with Claude Code assistance. Only "effective lines" are counted: lines with more than 3 characters after normalization, excluding empty lines and lines with only brackets or trivial punctuation.
* **PRs with Claude Code (%)**: percentage of all merged PRs that contain Claude Code-assisted code
* **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 written by Claude Code that users have accepted in their sessions. This excludes rejected suggestions and does not track subsequent deletions.

### Explore the charts

The dashboard includes several charts to visualize trends over time.

#### 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

This chart displays individual developer activity over time:

* **PRs per user**: total number of PRs merged per day divided by daily active users
* **users**: daily active users

Use this to understand how individual productivity changes as Claude Code adoption increases.

#### View pull requests breakdown

The Pull requests chart shows a daily breakdown of merged PRs:

* **PRs with CC**: pull requests containing Claude Code-assisted code
* **PRs without CC**: pull requests without Claude Code-assisted code

Toggle to **Lines of code** view to see the same breakdown by lines of code rather than PR count.

#### Find top contributors

The Leaderboard shows the top 10 users ranked by contribution volume. Toggle between:

* **Pull requests**: shows PRs with Claude Code vs All PRs for each user
* **Lines of code**: shows lines with Claude Code vs All lines for each user

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

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.

#### Tagging criteria

PRs are tagged as "with Claude Code" if they contain at least one line of code written during a Claude Code session. The system uses conservative matching: only code where there is high confidence in Claude Code's involvement is counted as assisted.

#### Attribution process

When a pull request is merged:

1. Added lines are extracted from the PR diff
2. Claude Code sessions that edited matching files within a time window are identified
3. PR lines are matched against Claude Code output using multiple strategies
4. Metrics are calculated for AI-assisted lines and total lines

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

Sessions from 21 days before to 2 days after the PR merge date are considered for attribution matching.

#### Excluded files

Certain files are automatically excluded from analysis because they are auto-generated:

* Lock files: package-lock.json, yarn.lock, Cargo.lock, and similar
* Generated code: Protobuf outputs, build artifacts, minified files
* Build directories: dist/, build/, node\_modules/, target/
* Test fixtures: snapshots, cassettes, mock data
* Lines over 1,000 characters, which are likely minified or generated

#### Attribution notes

Keep these additional details in mind when interpreting attribution data:

* Code substantially rewritten by developers, with more than 20% difference, is not attributed to Claude Code
* 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

Use contribution metrics to demonstrate ROI, identify adoption patterns, and find team members who can help others get started.

#### Monitor adoption

Track the Adoption chart and user counts to identify:

* Active users who can share best practices
* Overall adoption trends across your organization
* Dips in usage that may indicate friction or issues

#### Measure ROI

Contribution metrics help answer "Is this tool worth the investment?" with data from your own codebase:

* Track changes in PRs per user over time as adoption increases
* 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

The Leaderboard helps you find team members with high Claude Code adoption who can:

* Share prompting techniques and workflows with the team
* Provide feedback on what's working well
* Help onboard new users

#### Access data programmatically

To query this data through GitHub, search for PRs labeled with `claude-code-assisted`.

## 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, which is granted to Developer, Billing, Admin, Owner, and Primary Owner roles.

<Note>
  Contribution metrics with GitHub integration are not currently available for API customers. The Console dashboard shows usage and spend metrics only.
</Note>

The Console dashboard displays:

* **Lines of code accepted**: total lines of code written by Claude Code that users have accepted in their sessions. This excludes rejected suggestions and does not track subsequent deletions.
* **Suggestion accept rate**: percentage of times users accept code editing tool usage, including Edit, Write, and NotebookEdit tools.
* **Activity**: daily active users and sessions shown on a chart.
* **Spend**: daily API costs in dollars alongside user count.

### View team insights

The team insights table shows per-user metrics:

* **Members**: all users who have authenticated to Claude Code. API key users display by key identifier, OAuth users display by email address.
* **Spend this month**: per-user total API costs for the current month.
* **Lines this month**: per-user total of accepted code lines for the current month.

<Note>
  Spend figures in the Console dashboard are estimates for analytics purposes. For actual costs, refer to your billing page.
</Note>

## Related resources

* [Monitoring with OpenTelemetry](../13-Enterprise-Admin/monitoring-claude-code-docs-72c46f3dc8.md): export real-time metrics and events to your observability stack
* [Manage costs effectively](../17-Billing-Plans/manage-costs-effectively-claude-code-docs-7c26178a4f.md): set spend limits and optimize token usage
* [Permissions](configure-permissions-claude-code-docs-7b0e64d485.md): configure roles and permissions


---
## authentication-ce6fdcb8aa.md

> ## Documentation Index
> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication

> Log in to Claude Code and configure authentication for individuals, teams, and organizations.

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 Vertex AI, or Microsoft Foundry.

## Log in to Claude Code

After [installing Claude Code](/en/setup#install-claude-code), run `claude` in your terminal. On first launch, Claude Code opens a browser window for you to log in.

If the browser doesn't open automatically, press `c` to copy the login URL to your clipboard, then paste it into your browser.

If your browser shows a login code instead of redirecting back after you sign in, paste it into the terminal at the `Paste code here if prompted` prompt.

You can authenticate with any of these account types:

* **Claude Pro or Max subscription**: log in with your Claude.ai account. Subscribe at [claude.com/pricing](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=authentication_pro_max).
* **Claude for Teams or Enterprise**: log in with the Claude.ai account your team admin invited you to.
* **Claude Console**: log in with your Console credentials. Your admin must have [invited you](#claude-console-authentication) first.
* **Cloud providers**: if your organization uses [Amazon Bedrock](../20-Models/claude-code-on-amazon-bedrock-claude-code-docs-435e92efd0.md), [Google Vertex AI](../20-Models/claude-code-on-google-vertex-ai-claude-code-docs-2acd050a7a.md), or [Microsoft Foundry](../20-Models/claude-code-on-microsoft-foundry-claude-code-docs-ee35d755a6.md), set the required environment variables before running `claude`. No browser login is needed.

To log out and re-authenticate, type `/logout` at the Claude Code prompt.

If you're having trouble logging in, see [authentication troubleshooting](/en/troubleshooting#authentication-issues).

## Set up team authentication

For teams and organizations, you can configure Claude Code access in one of these ways:

* [Claude for Teams or Enterprise](#claude-for-teams-or-enterprise), recommended for most teams
* [Claude Console](#claude-console-authentication)
* [Amazon Bedrock](../20-Models/claude-code-on-amazon-bedrock-claude-code-docs-435e92efd0.md)
* [Google Vertex AI](../20-Models/claude-code-on-google-vertex-ai-claude-code-docs-2acd050a7a.md)
* [Microsoft Foundry](../20-Models/claude-code-on-microsoft-foundry-claude-code-docs-ee35d755a6.md)

### 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.

* **Claude for Teams**: self-service plan with collaboration features, admin tools, and billing management. Best for smaller teams.
* **Claude for Enterprise**: adds SSO, domain capture, role-based permissions, compliance API, and managed policy settings for organization-wide Claude Code configurations. Best for larger organizations with security and compliance requirements.

<Steps>
  <Step title="Subscribe">
    Subscribe to [Claude for Teams](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=authentication_teams_step#team-&-enterprise) or contact sales for [Claude for Enterprise](https://anthropic.com/contact-sales?utm_source=claude_code\&utm_medium=docs\&utm_content=authentication_enterprise_step).
  </Step>

  <Step title="Invite team members">
    Invite team members from the admin dashboard.
  </Step>

  <Step title="Install and log in">
    Team members install Claude Code and log in with their Claude.ai accounts.
  </Step>
</Steps>

### Claude Console authentication

For organizations that prefer API-based billing, you can set up access through the Claude Console.

<Steps>
  <Step title="Create or use a Console account">
    Use your existing Claude Console account or create a new one.
  </Step>

  <Step title="Add users">
    You can add users through either method:

    * Bulk invite users from within the Console: Settings -> Members -> Invite
    * [Set up SSO](../21-Account-Support/setting-up-single-sign-on-sso.md)
  </Step>

  <Step title="Assign roles">
    When inviting users, assign one of:

    * **Claude Code** role: users can only create Claude Code API keys
    * **Developer** role: users can create any kind of API key
  </Step>

  <Step title="Users complete setup">
    Each invited user needs to:

    * Accept the Console invite
    * [Check system requirements](/en/setup#system-requirements)
    * [Install Claude Code](/en/setup#install-claude-code)
    * Log in with Console account credentials
  </Step>
</Steps>

### Cloud provider authentication

For teams using Amazon Bedrock, Google Vertex AI, or Microsoft Foundry:

<Steps>
  <Step title="Follow provider setup">
    Follow the [Bedrock docs](../20-Models/claude-code-on-amazon-bedrock-claude-code-docs-435e92efd0.md), [Vertex docs](../20-Models/claude-code-on-google-vertex-ai-claude-code-docs-2acd050a7a.md), or [Microsoft Foundry docs](../20-Models/claude-code-on-microsoft-foundry-claude-code-docs-ee35d755a6.md).
  </Step>

  <Step title="Distribute configuration">
    Distribute the environment variables and instructions for generating cloud credentials to your users. Read more about how to [manage configuration here](claude-code-settings-claude-code-docs-d4420b4b52.md).
  </Step>

  <Step title="Install Claude Code">
    Users can [install Claude Code](/en/setup#install-claude-code).
  </Step>
</Steps>

## Credential management

Claude Code securely manages your authentication credentials:

* **Storage location**: on macOS, credentials are stored in the encrypted macOS Keychain. On Linux and Windows, credentials are stored in `~/.claude/.credentials.json`, or under `$CLAUDE_CONFIG_DIR` if that variable is set. On Linux, the file is written with mode `0600`; on Windows, it inherits the access controls of your user profile directory.
* **Supported authentication types**: Claude.ai credentials, Claude API credentials, Azure Auth, Bedrock Auth, and Vertex Auth.
* **Custom credential scripts**: the [`apiKeyHelper`](/en/settings#available-settings) setting can be configured to run a shell script that returns an API key.
* **Refresh intervals**: by default, `apiKeyHelper` is called after 5 minutes or on HTTP 401 response. Set `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` environment variable for custom refresh intervals.
* **Slow helper notice**: if `apiKeyHelper` takes longer than 10 seconds to return a key, Claude Code displays a warning notice in the prompt bar showing the elapsed time. If you see this notice regularly, check whether your credential script can be optimized.

`apiKeyHelper`, `ANTHROPIC_API_KEY`, and `ANTHROPIC_AUTH_TOKEN` apply to terminal CLI sessions only. Claude Desktop and remote sessions use OAuth exclusively and do not call `apiKeyHelper` or read API key environment variables.

### Authentication precedence

When multiple credentials are present, Claude Code chooses one in this order:

1. Cloud provider credentials, when `CLAUDE_CODE_USE_BEDROCK`, `CLAUDE_CODE_USE_VERTEX`, or `CLAUDE_CODE_USE_FOUNDRY` is set. See [third-party integrations](enterprise-deployment-overview-claude-code-docs-6eae0ecba2.md) for setup.
2. `ANTHROPIC_AUTH_TOKEN` environment variable. Sent as the `Authorization: Bearer` header. Use this when routing through an [LLM gateway or proxy](../13-Enterprise-Admin/llm-gateway-configuration-claude-code-docs-7a1628ac88.md) that authenticates with bearer tokens rather than Anthropic API keys.
3. `ANTHROPIC_API_KEY` environment variable. Sent as the `X-Api-Key` header. Use this for direct Anthropic API access with a key from the [Claude Console](../04-API-Reference/Other/platform-claude-com.md). In interactive mode, you are prompted once to approve or decline the key, and your choice is remembered. To change it later, use the "Use custom API key" toggle in `/config`. In non-interactive mode (`-p`), the key is always used when present.
4. [`apiKeyHelper`](/en/settings#available-settings) script output. Use this for dynamic or rotating credentials, such as short-lived tokens fetched from a vault.
5. `CLAUDE_CODE_OAUTH_TOKEN` environment variable. A long-lived OAuth token generated by [`claude setup-token`](#generate-a-long-lived-token). Use this for CI pipelines and scripts where browser login isn't available.
6. Subscription OAuth credentials from `/login`. This is the default for Claude Pro, Max, Team, and Enterprise users.

If you have an active Claude subscription but also have `ANTHROPIC_API_KEY` set in your environment, the API key takes precedence once approved. This can cause authentication failures if the key belongs to a disabled or expired organization. Run `unset ANTHROPIC_API_KEY` to fall back to your subscription, and check `/status` to confirm which method is active.

[Claude Code on the Web](claude-code-on-the-web-69d53821d4.md) always uses your subscription credentials. `ANTHROPIC_API_KEY` and `ANTHROPIC_AUTH_TOKEN` in the sandbox environment do not override them.

### 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`:

```bash theme={null}
claude setup-token
```

The command walks you through OAuth authorization and prints a token to the terminal. It does not save the token anywhere; copy it and set it as the `CLAUDE_CODE_OAUTH_TOKEN` environment variable wherever you want to authenticate:

```bash theme={null}
export CLAUDE_CODE_OAUTH_TOKEN=your-token
```

This token authenticates with your Claude subscription and requires a Pro, Max, Team, or Enterprise plan. It is scoped to inference only and cannot establish [Remote Control](continue-local-sessions-from-any-device-with-remote-control-claude-code-docs-c1c03fd914.md) sessions.

[Bare mode](/en/headless#start-faster-with-bare-mode) does not read `CLAUDE_CODE_OAUTH_TOKEN`. If your script passes `--bare`, authenticate with `ANTHROPIC_API_KEY` or an `apiKeyHelper` instead.


---
## authentication-claude-code-docs.md

# Authentication


Log in to Claude Code and configure authentication for individuals, teams, and organizations.


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 Vertex AI, or Microsoft Foundry.

## 

Log in to Claude Code

After [installing Claude Code](/docs/en/setup#install-claude-code), run `claude` in your terminal. On first launch, Claude Code opens a browser window for you to log in. If the browser doesn’t open automatically, press `c` to copy the login URL to your clipboard, then paste it into your browser. You can authenticate with any of these account types:

- **Claude Pro or Max subscription**: log in with your Claude.ai account. Subscribe at [claude.com/pricing](https://claude.com/pricing?utm_source=claude_code&utm_medium=docs&utm_content=authentication_pro_max).
- **Claude for Teams or Enterprise**: log in with the Claude.ai account your team admin invited you to.
- **Claude Console**: log in with your Console credentials. Your admin must have [invited you](#claude-console-authentication) first.
- **Cloud providers**: if your organization uses [Amazon Bedrock](/docs/en/amazon-bedrock), [Google Vertex AI](/docs/en/google-vertex-ai), or [Microsoft Foundry](/docs/en/microsoft-foundry), set the required environment variables before running `claude`. No browser login is needed.

To log out and re-authenticate, type `/logout` at the Claude Code prompt. If you’re having trouble logging in, see [authentication troubleshooting](/docs/en/troubleshooting#authentication-issues).

## 

Set up team authentication

For teams and organizations, you can configure Claude Code access in one of these ways:

- [Claude for Teams or Enterprise](#claude-for-teams-or-enterprise), recommended for most teams
- [Claude Console](#claude-console-authentication)
- [Amazon Bedrock](/docs/en/amazon-bedrock)
- [Google Vertex AI](/docs/en/google-vertex-ai)
- [Microsoft Foundry](/docs/en/microsoft-foundry)

### 

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.

- **Claude for Teams**: self-service plan with collaboration features, admin tools, and billing management. Best for smaller teams.
- **Claude for Enterprise**: adds SSO, domain capture, role-based permissions, compliance API, and managed policy settings for organization-wide Claude Code configurations. Best for larger organizations with security and compliance requirements.

1

[](#)

Subscribe

Subscribe to [Claude for Teams](https://claude.com/pricing?utm_source=claude_code&utm_medium=docs&utm_content=authentication_teams_step#team-&-enterprise) or contact sales for [Claude for Enterprise](https://anthropic.com/contact-sales?utm_source=claude_code&utm_medium=docs&utm_content=authentication_enterprise_step).

2

[](#)

Invite team members

Invite team members from the admin dashboard.

3

[](#)

Install and log in

Team members install Claude Code and log in with their Claude.ai accounts.

### 

Claude Console authentication

For organizations that prefer API-based billing, you can set up access through the Claude Console.

1

[](#)

Create or use a Console account

Use your existing Claude Console account or create a new one.

2

[](#)

Add users

You can add users through either method:

- Bulk invite users from within the Console: Settings -\> Members -\> Invite
- [Set up SSO](../21-Account-Support/setting-up-single-sign-on-sso.md)

3

[](#)

Assign roles

When inviting users, assign one of:

- **Claude Code** role: users can only create Claude Code API keys
- **Developer** role: users can create any kind of API key

4

[](#)

Users complete setup

Each invited user needs to:

- Accept the Console invite
- [Check system requirements](/docs/en/setup#system-requirements)
- [Install Claude Code](/docs/en/setup#install-claude-code)
- Log in with Console account credentials

### 

Cloud provider authentication

For teams using Amazon Bedrock, Google Vertex AI, or Microsoft Foundry:

1

[](#)

Follow provider setup

Follow the [Bedrock docs](/docs/en/amazon-bedrock), [Vertex docs](/docs/en/google-vertex-ai), or [Microsoft Foundry docs](/docs/en/microsoft-foundry).

2

[](#)

Distribute configuration

Distribute the environment variables and instructions for generating cloud credentials to your users. Read more about how to [manage configuration here](/docs/en/settings).

3

[](#)

Install Claude Code

Users can [install Claude Code](/docs/en/setup#install-claude-code).

## 

Credential management

Claude Code securely manages your authentication credentials:

- **Storage location**: on macOS, credentials are stored in the encrypted macOS Keychain.
- **Supported authentication types**: Claude.ai credentials, Claude API credentials, Azure Auth, Bedrock Auth, and Vertex Auth.
- **Custom credential scripts**: the [`apiKeyHelper`](/docs/en/settings#available-settings) setting can be configured to run a shell script that returns an API key.
- **Refresh intervals**: by default, `apiKeyHelper` is called after 5 minutes or on HTTP 401 response. Set `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` environment variable for custom refresh intervals.


---
## auto-compact-deep-dive.md

# Auto-Compact Deep Dive — Window vs Percentage Override

**Topic**: `CLAUDE_CODE_AUTO_COMPACT_WINDOW` vs `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE`
**Binary**: Claude Code 2.1.75
**Status**: Both active, fully implemented

---

## TL;DR

- **`CLAUDE_CODE_AUTO_COMPACT_WINDOW`** = "Pretend the context window is this size" (caps max window)
- **`CLAUDE_AUTOCOMPACT_PCT_OVERRIDE`** = "Trigger compaction at X% of (possibly capped) window"
- They **compose**: window override runs first, percentage applies to the result
- **Order matters**: Window cap → percentage calculation → 13K safety headroom
- For **Opus 1M**, use both: `WINDOW=350000` + `PCT=85` to maintain 200K-like behavior

---

## The Calculation Pipeline

### Step 1: `BB(model)` — Calculate Effective Window

```javascript
function BB(H) {  // H = model
  let buffer = Math.min(PnH(H), 20000),        // Reserved buffer (~20K)
      baseWindow = LY(H, Qw()),                 // Model's native context window
      override = process.env.CLAUDE_CODE_AUTO_COMPACT_WINDOW;

  if (override) {
    let parsed = parseInt(override, 10);
    if (!isNaN(parsed) && parsed > 0)
      baseWindow = Math.min(baseWindow, parsed);  // ← CAP DOWN (never extends)
  }

  return baseWindow - buffer;  // Effective window
}
```

**Key**: `Math.min(native, override)` — only applies if override is LOWER than native.

---

### Step 2: `bQH(model)` — Calculate Auto-Compact Threshold

```javascript
function bQH(H) {  // H = model
  let effectiveWindow = BB(H),                  // From step 1
      safeThreshold = effectiveWindow - 13000,  // Leave 13K headroom
      pctOverride = process.env.CLAUDE_AUTOCOMPACT_PCT_OVERRIDE;

  if (pctOverride) {
    let pct = parseFloat(pctOverride);
    if (!isNaN(pct) && pct > 0 && pct <= 100) {
      let pctThreshold = Math.floor(effectiveWindow * (pct / 100));
      return Math.min(pctThreshold, safeThreshold);  // ← Never exceed safe headroom
    }
  }

  return safeThreshold;  // Default: effectiveWindow - 13K
}
```

**Key**: Percentage is calculated on the **capped window** (if window override is active).

---

### Step 3: `PKH(tokens, model)` — Check Thresholds

```javascript
function PKH(H, $) {  // H = current tokens, $ = model
  let autoCompactThreshold = bQH($),             // From step 2
      effectiveWindow = BB($),                   // From step 1
      percentLeft = Math.max(0, Math.round((effectiveWindow - H) / effectiveWindow * 100)),

      warningThreshold = effectiveWindow - 20000,
      errorThreshold = effectiveWindow - 20000,
      isAboveAutoCompactThreshold = oy() && H >= autoCompactThreshold,

      blockingLimit = effectiveWindow - 3000,
      blockingOverride = process.env.CLAUDE_CODE_BLOCKING_LIMIT_OVERRIDE,
      actualBlockingLimit = blockingOverride
                            ? parseInt(blockingOverride, 10)
                            : blockingLimit,
      isAtBlockingLimit = H >= actualBlockingLimit;

  return {
    percentLeft,
    isAboveWarningThreshold,
    isAboveErrorThreshold,
    isAboveAutoCompactThreshold,  // ← Triggers auto-compact
    isAtBlockingLimit
  };
}
```

---

## Default Behavior (No Overrides)

### Sonnet 4.6 (200K context)

```
Model native window:    200,000 tokens
Buffer:                 -20,000 tokens
─────────────────────────────────────
Effective window:       180,000 tokens
Safe headroom:          -13,000 tokens
─────────────────────────────────────
Threshold:              167,000 tokens  (~93%)
```

**Auto-compact triggers at 167K tokens** (~93% of effective window).

---

### Opus 1M (1M context)

```
Model native window:  1,000,000 tokens
Buffer:                 -20,000 tokens
─────────────────────────────────────
Effective window:       980,000 tokens
Safe headroom:          -13,000 tokens
─────────────────────────────────────
Threshold:              967,000 tokens  (~99%)
```

**Auto-compact triggers at 967K tokens** (~99% of effective window).

⚠️ **Problem**: Compacting at 99% means:
- Massive conversation history to summarize
- Slow compaction (takes minutes)
- Risk of memory exhaustion
- Poor compaction quality (too much context)

---

## Percentage Override Only

### Example: `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=85`

#### Sonnet 4.6 (200K)

```
Effective window:       180,000 tokens
Percentage threshold:   floor(180,000 × 0.85) = 153,000
Safe headroom:          180,000 - 13,000      = 167,000
─────────────────────────────────────
Actual threshold:       min(153,000, 167,000) = 153,000 tokens  (~85%)
```

**Auto-compact at 153K** (~85% of effective window). ✅ Good.

---

#### Opus 1M (1M)

```
Effective window:       980,000 tokens
Percentage threshold:   floor(980,000 × 0.85) = 833,000
Safe headroom:          980,000 - 13,000      = 967,000
─────────────────────────────────────
Actual threshold:       min(833,000, 967,000) = 833,000 tokens  (~85%)
```

**Auto-compact at 833K** (~85% of effective window).

⚠️ **Still problematic**: 833K is **4.8x larger** than the 200K experience. Compaction will be slow and may fail.

---

## Window Override Only

### Example: `CLAUDE_CODE_AUTO_COMPACT_WINDOW=350000`

#### Sonnet 4.6 (200K)

```
Model native window:    200,000 tokens
Override:               350,000 tokens
Capped window:          min(200,000, 350,000) = 200,000  ← NO EFFECT
─────────────────────────────────────
(Same as default — 167K threshold)
```

**No change.** Window override is higher than native, so `Math.min()` picks native.

---

#### Opus 1M (1M)

```
Model native window:  1,000,000 tokens
Override:               350,000 tokens
Capped window:          min(1,000,000, 350,000) = 350,000  ← CAPPED
Buffer:                                           -20,000
─────────────────────────────────────
Effective window:                                 330,000 tokens
Safe headroom:                                    -13,000 tokens
─────────────────────────────────────
Threshold:                                        317,000 tokens  (~96% of capped)
```

**Auto-compact at 317K** (~96% of the capped window).

✅ **Better**, but still using fixed 13K headroom on a 330K window → 96% is late.

---

## Both Overrides (Recommended)

### Example: `CLAUDE_CODE_AUTO_COMPACT_WINDOW=350000` + `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=85`

#### Sonnet 4.6 (200K)

```
Capped window:          min(200,000, 350,000) = 200,000  ← NO EFFECT
Effective window:       180,000
Threshold:              floor(180,000 × 0.85) = 153,000 tokens  (~85%)
```

Same as percentage-only case. Window override ignored.

---

#### Opus 1M (1M)

```
Model native window:  1,000,000 tokens
Override:               350,000 tokens
Capped window:          min(1,000,000, 350,000) = 350,000  ← CAPPED
Buffer:                                           -20,000
─────────────────────────────────────
Effective window:                                 330,000 tokens
Percentage threshold:   floor(330,000 × 0.85)   = 280,500
Safe headroom:          330,000 - 13,000        = 317,000
─────────────────────────────────────
Actual threshold:       min(280,500, 317,000)   = 280,500 tokens  (~85% of capped)
```

**Auto-compact at 280.5K** (~85% of the capped 350K window).

✅ **Excellent**: Similar to the 200K experience (153K @ 85%) but with room for larger individual inputs.

---

## Comparison Table

| Model | Window Override | PCT Override | Threshold | vs 200K Default |
|-------|----------------|--------------|-----------|-----------------|
| **Sonnet 4.6** (200K) | — | — | **167K** | Baseline (93%) |
| **Sonnet 4.6** (200K) | — | 85 | **153K** | -14K (-8%) |
| **Sonnet 4.6** (200K) | 350K | 85 | **153K** | No change (override ignored) |
| **Opus 1M** (1M) | — | — | **967K** | +800K (+579%) 🔴 |
| **Opus 1M** (1M) | — | 85 | **833K** | +666K (+480%) 🔴 |
| **Opus 1M** (1M) | 500K | — | **467K** | +300K (+280%) ⚠️ |
| **Opus 1M** (1M) | 500K | 85 | **408K** | +241K (+244%) ⚠️ |
| **Opus 1M** (1M) | **350K** | **85** | **280K** | **+113K (+168%)** ✅ |
| **Opus 1M** (1M) | **300K** | **85** | **238K** | **+71K (+142%)** ✅ |

---

## Why `Math.min()` Matters

### Common Mistake

"I'll set `CLAUDE_CODE_AUTO_COMPACT_WINDOW=1000000` to use the full 1M context!"

**Result**: No effect. `Math.min(1000000, 1000000) = 1000000` — same as native.

### Correct Use

The override is a **ceiling**, not a floor:
- Set it **lower** than native to cap the window
- Set it **higher** than native → ignored (no effect)

---

## Recommended Settings

### For 200K Models (Sonnet 4.6, Opus 4.6, Haiku 4.5)

```bash
# Percentage override only
export CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=85

# Window override has no effect (200K < any reasonable override)
```

**Threshold**: 153K tokens (~85% of 180K effective window)

---

### For 1M Models (Sonnet 1M, Opus 1M)

```bash
# Recommended: Cap window + percentage
export CLAUDE_CODE_AUTO_COMPACT_WINDOW=350000
export CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=85
```

**Threshold**: 280.5K tokens (~85% of capped 350K window)

**Rationale**:
- Maintains similar compaction frequency as 200K models
- Allows larger individual inputs (files, tool results)
- Prevents runaway context accumulation
- Faster compaction (less history to summarize)

---

### Alternative: More Aggressive

```bash
# Tighter control
export CLAUDE_CODE_AUTO_COMPACT_WINDOW=300000
export CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=85
```

**Threshold**: 238K tokens (~85% of capped 300K window)

**Rationale**: Even closer to the 200K experience (153K → 238K is only +55%).

---

## Edge Cases

### What if I set window to 150K (below native 200K)?

```
Sonnet 4.6:
  Capped window:    min(200,000, 150,000) = 150,000  ← CAPPED
  Effective:        150,000 - 20,000     = 130,000
  Threshold (85%):  floor(130,000 × 0.85) = 110,500
```

**Result**: Auto-compact at 110.5K — more aggressive than default. Valid use case for CI/CD or short sessions.

---

### What if I set percentage to 99?

```
Opus 1M with WINDOW=350K:
  Effective:        330,000
  Threshold (99%):  floor(330,000 × 0.99) = 326,700
  Safe headroom:    330,000 - 13,000      = 317,000
  Actual:           min(326,700, 317,000) = 317,000  ← Headroom wins
```

**Result**: Safety headroom (13K) overrides the percentage. Max threshold is always `effectiveWindow - 13K`.

---

### What if I disable auto-compact entirely?

```bash
export DISABLE_AUTO_COMPACT=1
```

**Result**: Overrides are ignored. Manual compaction only (`/compact`). Risky — you can OOM.

---

## Debugging

### Check Current Settings

```bash
# Env vars
env | grep -i "COMPACT\|AUTOCOMPACT"

# Computed values (from logs)
# Run a session and look for:
v(`autocompact: tokens=${currentTokens} threshold=${threshold} effectiveWindow=${effectiveWindow}`)
```

### Example Log Output

```
autocompact: tokens=165000 threshold=153000 effectiveWindow=180000
```

Decode:
- `tokens=165000` — current conversation size
- `threshold=153000` — will compact at this level
- `effectiveWindow=180000` — 200K - 20K buffer

---

## Implementation Details

### Constants

```javascript
var lh6 = 20000,   // Buffer size
    KUA = 13000,   // Safe headroom
    nh6 = 20000,   // Warning threshold offset
    ih6 = 20000,   // Error threshold offset
    qUA = 3000;    // Blocking limit headroom
```

### Related Functions

- `BB(model)` — Effective window calculation
- `bQH(model)` — Auto-compact threshold
- `PKH(tokens, model)` — Threshold checks
- `rh6(messages, model, source, freed)` — Auto-compact decision
- `Inf(...)` — Auto-compact execution

---

## Testing

### Verify Window Override

```bash
# Set a low override
export CLAUDE_CODE_AUTO_COMPACT_WINDOW=100000

# Start a session with a 200K model
# Expect auto-compact to trigger around 68K tokens
# (100K - 20K buffer = 80K effective, 80K - 13K = 67K threshold)
```

### Verify Percentage Override

```bash
# Set a high percentage
export CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=95

# Start a session with a 200K model
# Expect auto-compact to trigger around 167K tokens
# (95% of 180K effective = 171K, capped by 13K headroom → 167K)
```

---

## Related

- [analysis.md](./analysis.md) — Main 2.1.75 analysis
- [opus-1m-migration.md](./opus-1m-migration.md) — Opus 1M migration details
- [env-vars.md](./env-vars.md) — Environment variable reference


---
## auto-memory-internals.md

# Claude Code 2.1.76 — Auto-Memory Internals

How the post-sampling hook system and auto-memory extraction work under the hood.

---

## System Overview

```
Main Query Loop (3896.js)
│
│  user sends message
│  ↓
│  LLM sampling → response messages (e)
│  ↓
│  if (e.length > 0)
│      Zif([...existingMessages, ...newMessages], systemPrompt, userCtx, sysCtx, toolCtx, querySource)
│          │
│          ↓
│      Post-Sampling Hook Registry (Wif[])
│          │
│          └── g9_ (auto-memory extraction)
│                  │
│                  ├── gate checks (feature flag, thresholds)
│                  ├── reads current MEMORY.md
│                  ├── builds extraction prompt
│                  └── forks sub-query (AT) → writes updated MEMORY.md
```

---

## 1. Post-Sampling Hook Framework

**File**: `3887.js`

The hook system is a simple observer pattern — a push-only array of async callbacks.

```javascript
var Wif = [];   // hook registry

// Register a hook
function Tif(callback) {
    Wif.push(callback);
}

// Dispatch to all hooks (called after every LLM turn)
async function Zif(messages, systemPrompt, userContext, systemContext, toolUseContext, querySource) {
    let ctx = {
        messages,        // full conversation history (old + new)
        systemPrompt,    // current system prompt
        userContext,      // user-level context (CLAUDE.md, etc.)
        systemContext,    // system-level context
        toolUseContext,   // tool state (readFileState, etc.)
        querySource       // "repl_main_thread", "session_memory", "agent", etc.
    };
    for (let hook of Wif)
        try {
            await hook(ctx);
        } catch (err) {
            fH(err instanceof Error ? err : Error(`Post-sampling hook failed: ${err}`));
        }
}
```

### Key Properties

- **Sequential execution**: Hooks run one at a time (`for...of` + `await`), not in parallel
- **Error isolation**: Each hook is wrapped in try/catch — one failing hook doesn't block others
- **No return value**: Hooks are fire-and-forget; they can't modify the conversation flow
- **No priority/ordering**: Hooks execute in registration order (FIFO push)
- **Errors go to ring buffer**: Failed hooks report via `fH()` (error reporting system, 100-entry ring buffer)

### Call Site

In `3896.js`, inside the main query generator:

```javascript
// After LLM sampling produces assistant messages (e):
if (e.length > 0)
    Zif([...u, ...e], A, L, D, Y, M);
```

Where `u` = existing conversation messages, `e` = new assistant response messages.
Only fires when the model actually produced output (no-op on empty responses or errors).

---

## 2. Hook Registration

**File**: `4557.js`

Only one hook is currently registered: `g9_` (auto-memory extraction).

```javascript
function nX8() {
    if (L8()) return;     // skip if headless/simple mode (CLAUDE_CODE_SIMPLE)
    if (!$h()) return;    // skip if auto-compact disabled (DISABLE_COMPACT / DISABLE_AUTO_COMPACT)
    Tif(g9_);             // register the auto-memory hook
}
```

`nX8()` is called during session initialization. The hook is only registered when:
1. **Not in simple/headless mode** — `L8()` returns false
2. **Auto-compact enabled** — `$h()` returns true (respects `DISABLE_COMPACT` and `DISABLE_AUTO_COMPACT` env vars plus the `autoCompactEnabled` setting)

---

## 3. Auto-Memory Extraction Hook (g9_)

**File**: `4558.js`

This is the core logic. When the hook fires, it decides whether to extract memories from the conversation and write them to `summary.md`.

```javascript
g9_ = Tx(async function({ messages, toolUseContext, querySource }) {
    // ── Gate 1: Only run on main REPL thread ──
    if (querySource !== "repl_main_thread") return;

    // ── Gate 2: Feature flag must be on ──
    if (!b9_()) return;   // _A("tengu_session_memory", false)

    // ── Gate 3: Init config, check thresholds ──
    U9_();                // load config from tengu_sm_config
    if (!B9_(messages)) return;  // token + tool-call threshold check

    // ── Mark extraction in progress ──
    nnf();   // jR$ = Date.now()  (locks out concurrent extractions)

    // ── Read current memory file ──
    let toolCtx = gQH(toolUseContext);  // snapshot tool context
    let { memoryPath, currentMemory } = await p9_(toolCtx);

    // ── Build extraction prompt ──
    let prompt = await Kif(currentMemory, memoryPath);

    // ── Fork sub-query: extract and write memories ──
    await AT({
        promptMessages: [U$({ content: prompt })],
        cacheSafeParams: bu(hook_context),
        canUseTool: d9_(memoryPath),      // ONLY allow Write to the memory file
        querySource: "session_memory",
        forkLabel: "session_memory",
        overrides: { readFileState: toolCtx.readFileState }
    });

    // ── Log telemetry ──
    Q("tengu_session_memory_extraction", {
        input_tokens, output_tokens,
        cache_read_input_tokens, cache_creation_input_tokens,
        config_min_message_tokens_to_init,
        config_min_tokens_between_update,
        config_tool_calls_between_updates
    });

    // ── Update state ──
    tnf(jJ(messages));  // record token count at extraction time
    F9_(messages);      // update UUID bookmark
    inf();              // clear in-progress lock (jR$ = undefined)
});
```

---

## 4. Threshold System (B9_)

**File**: `4557.js` + `3879.js`

The hook doesn't fire every turn. `B9_()` enforces three thresholds:

```javascript
function B9_(messages) {
    let tokenCount = jJ(messages);  // total tokens in conversation

    // First-time init: have we hit minimum tokens?
    if (!snf()) {                             // snf() = Qnf (has init fired?)
        if (!Hif(tokenCount)) return false;   // tokenCount >= minimumMessageTokensToInit?
        enf();                                // mark init complete
    }

    // Recurring: enough tokens since last extraction?
    let tokenThresholdMet = $if(tokenCount);  // tokenCount - cnf >= minimumTokensBetweenUpdate?

    // Recurring: enough tool calls since last extraction?
    let toolCallThresholdMet = m9_(messages, lX8) >= Aif();  // count tool_use blocks since bookmark

    // Has assistant made tool calls in last message?
    let lastMsgHasToolUse = snH(messages);

    // Trigger if: (both thresholds met) OR (token threshold met AND no pending tool use)
    if (tokenThresholdMet && toolCallThresholdMet || tokenThresholdMet && !lastMsgHasToolUse) {
        lX8 = messages[messages.length - 1]?.uuid;  // bookmark current position
        return true;
    }
    return false;
}
```

### Default Thresholds

**File**: `3880.js`

```javascript
CnH = {
    minimumMessageTokensToInit:  10000,  // 10k tokens before first extraction
    minimumTokensBetweenUpdate:  5000,   // 5k tokens between extractions
    toolCallsBetweenUpdates:     3        // 3 tool calls between extractions
};
```

These can be overridden via the `tengu_sm_config` GrowthBook feature flag (object with same keys).

### State Variables

**File**: `3879.js`

```javascript
var cnf = 0;          // token count at last extraction
var Qnf = false;      // has first extraction fired?
var jR$ = undefined;   // timestamp when extraction started (concurrency lock)
var IWH = {...CnH};   // active config (defaults + overrides)
```

### Concurrency Protection

```javascript
function nnf() { jR$ = Date.now(); }   // mark extraction in-progress
function inf() { jR$ = undefined; }     // mark extraction complete

// rnf() — wait for in-progress extraction (with timeouts)
async function rnf() {
    let start = Date.now();
    while (jR$) {
        if (Date.now() - jR$ > 60000) return;   // extraction timeout: 60s
        if (Date.now() - start > 15000) return;  // wait timeout: 15s
        await new Promise(r => setTimeout(r, 1000));  // poll every 1s
    }
}
```

---

## 5. Memory File Location

**File**: `4468.js`

```javascript
function Um$() {
    return path.join(configDir(), sessionId(), "session-memory") + path.sep;
}

function XWH() {
    return path.join(Um$(), "summary.md");
}
```

Result: `~/.claude/projects/<project-hash>/<session-id>/session-memory/summary.md`

On first extraction, if the file doesn't exist, it's created with the default template via `flag: "wx"` (exclusive create — won't overwrite).

---

## 6. Extraction Prompt

**File**: `3880.js`

The extraction prompt (`fif()`) instructs the forked sub-query to update the memory file. Key rules:

1. **Scope**: Only analyze the user conversation — exclude system prompt, CLAUDE.md, and the note-taking instructions themselves
2. **Tool restriction**: Only use `Edit` tool on the memory file path (enforced by `d9_()`)
3. **Structure preservation**: Never modify section headers or italic description lines
4. **Per-section limit**: ~2,000 tokens per section (`JR$ = 2000`)
5. **Total file limit**: ~12,000 tokens (`Lif = 12000`)
6. **Parallel edits**: Make all Edit tool calls in a single parallel message, then stop
7. **Priority**: Always keep "Current State" up to date

### Customization

Users can override both the template and extraction prompt:

```
~/.claude/session-memory/config/template.md   → custom memory file template
~/.claude/session-memory/config/prompt.md      → custom extraction prompt
```

If these files exist, they're loaded instead of the defaults. If they fail to load (non-ENOENT error), the error is reported via `fH()` and defaults are used as fallback.

### Oversized File Handling

`sS6()` checks section sizes and total file size, appending condensation instructions:

- If any section exceeds 2,000 tokens: instructs the model to condense it
- If total file exceeds 12,000 tokens: **CRITICAL** instruction to aggressively shorten

### Default Template Sections

```markdown
# Session Title
# Current State
# Task specification
# Files and Functions
# Workflow
# Errors & Corrections
# Codebase and System Documentation
# Learnings
# Key results
# Worklog
```

---

## 7. Tool Restriction (d9_)

**File**: `4557.js`

The forked sub-query is sandboxed — it can only use one tool on one file:

```javascript
function d9_(memoryPath) {
    return async (tool, input) => {
        if (tool.name === Cf &&                // Cf = Edit tool name
            typeof input === "object" &&
            input !== null &&
            "file_path" in input) {
            let filePath = input.file_path;
            if (typeof filePath === "string" && filePath === memoryPath)
                return { behavior: "allow", updatedInput: input };
        }
        return {
            behavior: "deny",
            message: `only ${Cf} on ${memoryPath} is allowed`,
            decisionReason: { type: "other", reason: `only ${Cf} on ${memoryPath} is allowed` }
        };
    };
}
```

This ensures the memory extraction sub-query:
- Can ONLY use the Edit tool (not Read, Bash, Write, or any other tool)
- Can ONLY edit the specific memory file path
- Cannot read files, run commands, or modify anything else

---

## 8. Forked Sub-Query (AT)

**File**: `3900.js`

`AT()` creates an isolated LLM sub-query that shares the parent's conversation context but has its own tool permissions and query source:

```javascript
function AT({
    promptMessages,       // the extraction prompt
    cacheSafeParams,      // cache config from parent
    canUseTool,           // d9_(memoryPath) — restricted tool access
    querySource,          // "session_memory"
    forkLabel,            // "session_memory"
    overrides,            // { readFileState } from parent context
    maxOutputTokens,      // optional limit
    maxTurns,             // optional turn limit
    onMessage,            // optional message callback
    skipTranscript,       // don't save to transcript
    skipCacheWrite        // don't cache results
}) { ... }
```

The sub-query runs the same model as the main conversation, but:
- Uses a separate abort controller (doesn't affect main conversation if it fails)
- Has its own tool permission function (`canUseTool`)
- Is labeled `"session_memory"` for telemetry and to prevent recursive extraction
- Shares the parent's read file state so it knows what files have been read

---

## 9. Telemetry

### Event: `tengu_session_memory_extraction`
Fired after each successful extraction:
```javascript
{
    input_tokens: number,
    output_tokens: number,
    cache_read_input_tokens: number,
    cache_creation_input_tokens: number,
    config_min_message_tokens_to_init: number,    // active threshold
    config_min_tokens_between_update: number,     // active threshold
    config_tool_calls_between_updates: number     // active threshold
}
```

### Event: `tengu_session_memory_file_read`
Fired when the current memory file is read before extraction:
```javascript
{ content_length: number }
```

### Feature Flag: `tengu_session_memory`
- Type: boolean
- Default: `false`
- Controls: Whether auto-memory extraction is enabled at all

### Feature Flag: `tengu_sm_config`
- Type: object
- Default: `{}`
- Controls: Override threshold values (`minimumMessageTokensToInit`, `minimumTokensBetweenUpdate`, `toolCallsBetweenUpdates`)

---

## 10. Complete Data Flow

```
User sends message
    ↓
Main LLM sampling
    ↓
Response messages produced
    ↓
Zif() dispatches to all registered hooks
    ↓
g9_ (auto-memory) runs:
    │
    ├─ querySource === "repl_main_thread"?  (NO → skip, prevents recursion)
    ├─ tengu_session_memory flag on?         (NO → skip)
    ├─ Load config from tengu_sm_config
    ├─ B9_() threshold check:
    │   ├─ First time: tokenCount >= 10,000?
    │   ├─ Recurring: tokenCount - lastExtraction >= 5,000?
    │   └─ Recurring: toolCallsSinceLastExtraction >= 3?
    │   (NO → skip)
    │
    ├─ Lock (nnf: jR$ = Date.now())
    ├─ Read summary.md (create from template if missing)
    ├─ Build extraction prompt (fif + oversize warnings)
    │
    ├─ Fork sub-query via AT():
    │   ├─ Same model as main conversation
    │   ├─ Receives full conversation as context
    │   ├─ Tool access: ONLY Edit on summary.md
    │   ├─ querySource: "session_memory" (prevents recursive hook)
    │   └─ LLM extracts memories → Edit calls to update summary.md
    │
    ├─ Log tengu_session_memory_extraction
    ├─ Update token bookmark (cnf = current token count)
    ├─ Update UUID bookmark (lX8 = last message UUID)
    └─ Unlock (inf: jR$ = undefined)
```

---

## 11. Disabling Auto-Memory

Any of these will prevent the hook from running:

| Method | Effect |
|--------|--------|
| `tengu_session_memory = false` | Feature flag (server-side, default) |
| `DISABLE_COMPACT=true` | Prevents hook registration (`$h()` fails) |
| `DISABLE_AUTO_COMPACT=true` | Same effect |
| `CLAUDE_CODE_SIMPLE=true` | Headless mode, skips hook registration |
| Non-REPL querySource | Hook self-filters (only runs on `repl_main_thread`) |

---

## 12. Relationship to User-Facing "Auto Memory"

The auto-memory system visible to users (`/home/zack/.claude/projects/<hash>/memory/MEMORY.md`) is a **different system** from session memory. Session memory (`summary.md`) is:

- Per-session (lives in session directory, not project memory directory)
- Automatically extracted (no user control over content)
- Used for session continuity after compaction
- Gated by `tengu_session_memory` (currently off by default)

The user-facing auto-memory directory at `~/.claude/projects/<hash>/memory/` is managed by the model directly during conversation (via explicit Write/Edit tool calls in the main conversation), not by this post-sampling hook system.


---
## auto-mode-config-f0dacf5866.md

> ## Documentation Index
> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Configure auto mode

> Tell the auto mode classifier which repos, buckets, and domains your organization trusts. Set environment context, override the default block and allow rules, and inspect your effective config with the auto-mode CLI subcommands.

[Auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) lets Claude Code run without permission prompts by routing each tool call through a classifier that blocks anything irreversible, destructive, or aimed outside your environment. Use the `autoMode` settings block to tell that classifier which repos, buckets, and domains your organization trusts, so it stops blocking routine internal operations.

Out of the box, the classifier trusts only the working directory and the current repo's configured remotes. Actions like pushing to your company's source-control org or writing to a team cloud bucket are blocked until you add them to `autoMode.environment`.

For how to enable auto mode and what it blocks by default, see [Permission modes](/en/permission-modes#eliminate-prompts-with-auto-mode). This page is the configuration reference.

This page covers how to:

* [Choose where to set rules](#where-the-classifier-reads-configuration) across CLAUDE.md, user settings, and managed settings
* [Define trusted infrastructure](#define-trusted-infrastructure) with `autoMode.environment`
* [Override the block and allow rules](#override-the-block-and-allow-rules) when the defaults don't fit your pipeline
* [Inspect your effective config](#inspect-the-defaults-and-your-effective-config) with the `claude auto-mode` subcommands
* [Review denials](#review-denials) so you know what to add next

## Where the classifier reads configuration

The classifier reads the same [CLAUDE.md](how-claude-remembers-your-project-claude-code-docs-f1c064262d.md) 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:

| Scope                          | File                                            | Use for                                              |
| :----------------------------- | :---------------------------------------------- | :--------------------------------------------------- |
| One developer                  | `~/.claude/settings.json`                       | Personal trusted infrastructure                      |
| One project, one developer     | `.claude/settings.local.json`                   | Per-project trusted buckets or services, gitignored  |
| Organization-wide              | [Managed settings](../13-Enterprise-Admin/configure-server-managed-settings-claude-code-docs-d6a169b0bf.md) | Trusted infrastructure distributed to all developers |
| `--settings` flag or Agent SDK | Inline JSON                                     | Per-invocation overrides for automation              |

The classifier does not read `autoMode` from shared project settings in `.claude/settings.json`, so a checked-in repo cannot inject its own allow rules.

Entries from each scope are combined. A developer can extend `environment`, `allow`, and `soft_deny` with personal entries but cannot remove entries that managed settings provide. Because allow rules act as exceptions to block rules inside the classifier, a developer-added `allow` entry can override an organization `soft_deny` entry: the combination is additive, not a hard policy boundary.

<Note>
  The classifier is a second gate that runs after the [permissions system](configure-permissions-claude-code-docs-7b0e64d485.md). 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 cannot be overridden.
</Note>

## 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.

The default environment list trusts the working repo and its configured remotes. To add your own entries alongside that default, include the literal string `"$defaults"` in the array. The default entries are spliced in at that position, so your custom entries can go before or after them.

```json theme={null}
{
  "autoMode": {
    "environment": [
      "$defaults",
      "Source control: github.example.com/acme-corp and all repos under it",
      "Trusted cloud buckets: s3://acme-build-artifacts, gs://acme-ml-datasets",
      "Trusted internal domains: *.corp.example.com, api.internal.example.com",
      "Key internal services: Jenkins at ci.example.com, Artifactory at artifacts.example.com"
    ]
  }
}
```

Entries are prose, not regex or tool patterns. The classifier reads them as natural-language rules. Write them the way you would describe your infrastructure to a new engineer. A thorough environment section covers:

* **Organization**: your company name and what Claude Code is primarily used for, like software development, infrastructure automation, or data engineering
* **Source control**: every GitHub, GitLab, or Bitbucket org your developers push to
* **Cloud providers and trusted buckets**: bucket names or prefixes that Claude should be able to read from and write to
* **Trusted internal domains**: hostnames for APIs, dashboards, and services inside your network, like `*.internal.example.com`
* **Key internal services**: CI, artifact registries, internal package indexes, incident tooling
* **Additional context**: regulated-industry constraints, multi-tenant infrastructure, or compliance requirements that affect what the classifier should treat as risky

A useful starting template: fill in the bracketed fields and remove any lines that don't apply.

```json theme={null}
{
  "autoMode": {
    "environment": [
      "$defaults",
      "Organization: {COMPANY_NAME}. Primary use: {PRIMARY_USE_CASE, e.g. software development, infrastructure automation}",
      "Source control: {SOURCE_CONTROL, e.g. GitHub org github.example.com/acme-corp}",
      "Cloud provider(s): {CLOUD_PROVIDERS, e.g. AWS, GCP, Azure}",
      "Trusted cloud buckets: {TRUSTED_BUCKETS, e.g. s3://acme-builds, gs://acme-datasets}",
      "Trusted internal domains: {TRUSTED_DOMAINS, e.g. *.internal.example.com, api.example.com}",
      "Key internal services: {SERVICES, e.g. Jenkins at ci.example.com, Artifactory at artifacts.example.com}",
      "Additional context: {EXTRA, e.g. regulated industry, multi-tenant infrastructure, compliance requirements}"
    ]
  }
}
```

The more specific context you give, the better the classifier can distinguish routine internal operations from exfiltration attempts.

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.

## Override the block and allow rules

Two additional fields let you replace the classifier's built-in rule lists: `autoMode.soft_deny` controls what gets blocked, and `autoMode.allow` controls which exceptions apply. Each is an array of prose descriptions, read as natural-language rules. There is no `autoMode.deny` field; to hard-block an action regardless of intent, use [`permissions.deny`](configure-permissions-claude-code-docs-7b0e64d485.md), which runs before the classifier.

Inside the classifier, precedence works in three tiers:

* `soft_deny` rules block first
* `allow` rules then override matching blocks as exceptions
* Explicit user intent overrides both: if the user's message directly and specifically describes the exact action Claude is about to take, the classifier allows it even when a `soft_deny` rule matches

General requests don't count as explicit intent. Asking Claude to "clean up the repo" does not authorize force-pushing, but asking Claude to "force-push this branch" does.

To loosen, add to `allow` when the classifier repeatedly flags a routine pattern the default exceptions don't cover. To tighten, add to `soft_deny` for risks specific to your environment that the defaults miss. To keep the built-in rules while adding your own, include the literal string `"$defaults"` in the array. The default rules are spliced in at that position, so your custom rules can go before or after them, and you continue to inherit updates as the built-in list changes across releases.

```json theme={null}
{
  "autoMode": {
    "environment": [
      "$defaults",
      "Source control: github.example.com/acme-corp and all repos under it"
    ],
    "allow": [
      "$defaults",
      "Deploying to the staging namespace is allowed: staging is isolated from production and resets nightly",
      "Writing to s3://acme-scratch/ is allowed: ephemeral bucket with a 7-day lifecycle policy"
    ],
    "soft_deny": [
      "$defaults",
      "Never run database migrations outside the migrations CLI, even against dev databases",
      "Never modify files under infra/terraform/prod/: production infrastructure changes go through the review workflow"
    ]
  }
}
```

<Danger>
  Setting any of `environment`, `allow`, or `soft_deny` without `"$defaults"` replaces the entire default list for that section. If you set `soft_deny` with a single entry and omit `"$defaults"`, every built-in block rule is discarded: force push, data exfiltration, `curl | bash`, production deploys, and all other default block rules become allowed. Only omit `"$defaults"` when you intend to take full ownership of the list. In that case, 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.
</Danger>

Each section is evaluated independently, so setting `environment` alone leaves the default `allow` and `soft_deny` lists intact.

## Inspect the defaults and your effective config

Three CLI subcommands help you inspect and validate your configuration.

Print the built-in `environment`, `allow`, and `soft_deny` rules as JSON:

```bash theme={null}
claude auto-mode defaults
```

Print what the classifier actually uses as JSON, with your settings applied where set and defaults otherwise:

```bash theme={null}
claude auto-mode config
```

Get AI feedback on your custom `allow` and `soft_deny` rules:

```bash theme={null}
claude auto-mode critique
```

Run `claude auto-mode config` after saving your settings to confirm the effective rules are what you expect, with `"$defaults"` expanded in place. If you've written custom rules, `claude auto-mode critique` reviews them and flags entries that are ambiguous, redundant, or likely to cause false positives. If you need to remove or rewrite a built-in rule rather than add alongside it, save the output of `claude auto-mode defaults` to a file, edit the lists, and paste the result into your settings file in place of `"$defaults"`.

## Review denials

When auto mode denies a tool call, the denial is recorded in `/permissions` under the Recently denied tab. Press `r` on a denied action to mark it for retry: when you exit the dialog, Claude Code sends a message telling the model it may retry that tool call and resumes the conversation.

Repeated denials for the same destination usually mean the classifier is missing context. Add that destination to `autoMode.environment`, then run `claude auto-mode config` to confirm it took effect.

To react to denials programmatically, use the [`PermissionDenied` hook](/en/hooks#permissiondenied).

## See also

* [Permission modes](/en/permission-modes#eliminate-prompts-with-auto-mode): what auto mode is, what it blocks by default, and how to enable it
* [Managed settings](../13-Enterprise-Admin/configure-server-managed-settings-claude-code-docs-d6a169b0bf.md): deploy `autoMode` configuration across your organization
* [Permissions](configure-permissions-claude-code-docs-7b0e64d485.md): allow, ask, and deny rules that apply before the classifier runs
* [Settings](claude-code-settings-claude-code-docs-d4420b4b52.md): the full settings reference, including the `autoMode` key


---
## automate-work-with-routines-claude-code-docs-1c8313d077.md

# Automate work with routines


Put Claude Code on autopilot. Define routines that run on a schedule, trigger on API calls, or react to GitHub events from Anthropic-managed cloud infrastructure.


> ## Documentation Index
>
> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt>
>
> Use this file to discover all available pages before exploring further.

Routines are in research preview. Behavior, limits, and the API surface may change.

A routine is a saved Claude Code configuration: a prompt, one or more repositories, and a set of [connectors](/docs/en/mcp), packaged once and run automatically. Routines execute on Anthropic-managed cloud infrastructure, so they keep working when your laptop is closed. Each routine can have one or more triggers attached to it:

- **Scheduled**: run on a recurring cadence like hourly, nightly, or weekly, or once at a specific future time
- **API**: trigger on demand by sending an HTTP POST to a per-routine endpoint with a bearer token
- **GitHub**: run automatically in response to repository events such as pull requests or releases

A single routine can combine triggers. For example, a PR review routine can run nightly, trigger from a deploy script, and also react to every new PR. Routines are available on Pro, Max, Team, and Enterprise plans with [Claude Code on the web](/docs/en/claude-code-on-the-web) enabled. Create and manage them at [claude.ai/code/routines](https://claude.ai/code/routines), or from the CLI with `/schedule`. Team and Enterprise admins can disable routines for all members with the Routines toggle at [claude.ai/admin-settings/claude-code](https://claude.ai/admin-settings/claude-code). When disabled, existing routines stop running and members cannot create new ones. This page covers creating a routine, configuring each trigger type, managing runs, and how usage limits apply.


Example use cases

Each example pairs a trigger type with the kind of work routines are suited to: unattended, repeatable, and tied to a clear outcome. **Backlog maintenance.** A schedule trigger runs every weeknight against your issue tracker via a connector. The routine reads issues opened since the last run, applies labels, assigns owners based on the area of code referenced, and posts a summary to Slack so the team starts the day with a groomed queue. **Alert triage.** Your monitoring tool calls the routine’s API endpoint when an error threshold is crossed, passing the alert body as `text`. The routine pulls the stack trace, correlates it with recent commits in the repository, and opens a draft pull request with a proposed fix and a link back to the alert. On-call reviews the PR instead of starting from a blank terminal. **Bespoke code review.** A GitHub trigger runs on `pull_request.opened`. The routine applies your team’s own review checklist, leaves inline comments for security, performance, and style issues, and adds a summary comment so human reviewers can focus on design instead of mechanical checks. **Deploy verification.** Your CD pipeline calls the routine’s API endpoint after each production deploy. The routine runs smoke checks against the new build, scans error logs for regressions, and posts a go or no-go to the release channel before the deploy window closes. **Docs drift.** A schedule trigger runs weekly. The routine 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 routine 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. The sections below walk through creating a routine and configuring each of these trigger types.


Create a routine

Create a routine from the web at [claude.ai/code/routines](https://claude.ai/code/routines), from the Desktop app, or from the CLI. All three surfaces write to the same cloud account, so a routine you create in one shows up in the others immediately. In the Desktop app, click **Routines** in the sidebar, then **New routine**, and choose **Remote**; choosing **Local** instead creates a [Desktop scheduled task](/docs/en/desktop-scheduled-tasks), which runs on your machine rather than in the cloud. The creation form sets up the routine’s prompt, repositories, environment, connectors, and triggers. Routines run autonomously as full Claude Code cloud sessions: execution stays within the repositories, environment, and connectors you preconfigure for the run. The session can run shell commands, use [skills](/docs/en/skills) committed to the cloned repository, and call any connectors you include. What a routine can reach is determined by the repositories you select and their branch-push setting, the [environment’s](/docs/en/claude-code-on-the-web#the-cloud-environment) network access and variables, and the connectors you include. Scope each of those to what the routine actually needs. Routines belong to your individual claude.ai account. They are not shared with teammates, and they count against your account’s daily run allowance. Anything a routine does through your connected GitHub identity or connectors appears as you: commits and pull requests carry your GitHub user, and Slack messages, Linear tickets, or other connector actions use your linked accounts for those services.


Create from the web

1


Open the creation form

Visit [claude.ai/code/routines](https://claude.ai/code/routines) and click **New routine**.

2


Name the routine and write the prompt

Give the routine a descriptive name and write the prompt Claude runs each time. The prompt is the most important part: the routine runs autonomously, so the prompt must be self-contained and explicit about what to do and what success looks like.The prompt input includes a model selector. Claude uses the selected model on every run.

3


Select repositories

Add one or more GitHub repositories for Claude to work in. Each repository is cloned at the start of a run, starting from the default branch. Claude creates `claude/`-prefixed branches for its changes.

4


Select an environment

Pick a [cloud environment](/docs/en/claude-code-on-the-web#the-cloud-environment) for the routine. Environments control what the cloud session has access to:

- **Network access**: set the level of internet access available during each run
- **Environment variables**: provide API keys, tokens, or other secrets Claude can use
- **Setup script**: install dependencies and tools the routine needs. The result is [cached](/docs/en/claude-code-on-the-web#environment-caching), so the script doesn’t re-run on every session

A **Default** environment is provided with **Trusted** network access, which allows the [default set](/docs/en/claude-code-on-the-web#default-allowed-domains) of package registries, cloud provider APIs, container registries, and common development domains, but blocks everything else. If your routine needs to reach your own services or a domain outside that list, edit the environment’s [network access](/docs/en/claude-code-on-the-web#network-access) before running. To use a separate environment, [create one](/docs/en/claude-code-on-the-web#configure-your-environment) first.

5


Select a trigger

Under **Select a trigger**, choose how the routine starts. You can pick one trigger type or combine several.

- Schedule

- GitHub event

- API

Pick a preset frequency for a recurring run, or schedule a single one-off run at a specific timestamp. See [Add a schedule trigger](#add-a-schedule-trigger) for timezone handling, stagger, custom cron intervals, and one-off runs.

Select the repository, the event to react to, and optional filters. See [Add a GitHub trigger](#add-a-github-trigger) for the full list of supported events and filter fields.

Select **API** here, then save the routine. The URL and token are generated after the routine is saved, since they depend on the routine ID. See [Add an API trigger](#add-an-api-trigger) to copy the URL and generate a token.

6


Review connectors and permissions

The **Connectors** and **Permissions** tabs at the bottom of the form control what the routine can reach.Under Connectors, all of your connected [MCP connectors](/docs/en/mcp) are included by default. Remove any the routine doesn’t need. Claude can use every tool from an included connector, including writes, without asking for permission during a run.Under Permissions, enable **Allow unrestricted branch pushes** for any repository where Claude should be able to push to existing branches instead of only `claude/`-prefixed ones.

7


Create the routine

Click **Create**. The routine appears in the list and runs the next time one of its triggers matches. To start a run immediately, click **Run now** on the routine’s detail page.Each run creates a new session alongside your other sessions, where you can see what Claude did, review changes, and create a pull request.


Create from the CLI

Run `/schedule` in any session to create a scheduled routine conversationally. You can also pass a description directly, for a recurring routine like `/schedule daily PR review at 9am` or a one-off like `/schedule clean up feature flag in one week`. Claude walks through the same information the web form collects, then saves the routine to your account. `/schedule` in the CLI creates scheduled routines only. To add an API or GitHub trigger, edit the routine on the web at [claude.ai/code/routines](https://claude.ai/code/routines). The CLI also supports managing existing routines. Run `/schedule list` to see all routines, `/schedule update` to change one, or `/schedule run` to trigger it immediately.


Configure triggers

A routine starts when one of its triggers matches. You can attach any combination of schedule, API, and GitHub triggers to the same routine, and add or remove them at any time from the **Select a trigger** section of the routine’s edit form.


Add a schedule trigger

A schedule trigger runs the routine on a recurring cadence, or once at a specific future time. Pick a preset frequency in the **Select a trigger** section: hourly, daily, weekdays, or weekly. Times are entered in your local zone and converted automatically, so the routine runs at that wall-clock time regardless of where the cloud infrastructure is located. Runs may start a few minutes after the scheduled time due to stagger. The offset is consistent for each routine. For a custom interval such as every two hours or the first of each month, pick the closest preset in the form, then run `/schedule update` in the CLI to set a specific cron expression. The minimum interval is one hour; expressions that run more frequently are rejected.


Schedule a one-off run

A one-off schedule fires the routine a single time at a specific timestamp. Use it to remind yourself later in the week, to open a cleanup PR after a rollout finishes, or to kick off a follow-up task when an upstream change lands. After the routine fires, it auto-disables and the web UI marks it as **Ran**. To run it again, edit the routine and set a new one-off time. Create a one-off run from the CLI by describing the time in natural language. Claude resolves the phrase against the current time and confirms the absolute timestamp before saving.

```python
/schedule tomorrow at 9am, summarize yesterday's merged PRs
```

```python
/schedule in 2 weeks, open a cleanup PR that removes the feature flag
```

The same local-to-UTC conversion as recurring schedules applies to one-off timestamps. One-off runs do not count against the daily routine run cap. They consume your plan’s regular subscription usage like any other session. See [Usage and limits](#usage-and-limits) for details.


Add an API trigger

An API trigger gives a routine a dedicated HTTP endpoint. POSTing to the endpoint with the routine’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. API triggers are added to an existing routine from the web. The CLI cannot currently create or revoke tokens.

1


Open the routine for editing

Go to [claude.ai/code/routines](https://claude.ai/code/routines), click the routine you want to trigger via API, then click the pencil icon to open **Edit routine**.

2


Add an API trigger

Scroll to the **Select a trigger** section below the **Instructions** box, click **Add another trigger**, and choose **API**.

3


Copy the URL and generate a token

The modal shows the URL for this routine along with a sample curl command. Copy the URL, then click **Generate token** and copy the token immediately. The token is shown once and cannot be retrieved later, so store it somewhere secure such as your alerting tool’s secret store.

4


Call the endpoint

Send the token in the `Authorization: Bearer` header when you POST to the URL. The [Trigger a routine](#trigger-a-routine) section below shows a complete example.

Each routine has its own token, scoped to triggering that routine only. To rotate or revoke it, return to the same modal and click **Regenerate** or **Revoke**.


Trigger a routine

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 routine alongside its saved prompt. The value is freeform text and is not parsed: if you send JSON or another structured payload, the routine receives it as a literal string. The example below triggers a routine from a shell:

```python
curl -X POST https://api.anthropic.com/v1/claude_code/routines/trig_01ABCDEFGHJKLMNOPQRSTUVW/fire \
  -H "Authorization: Bearer sk-ant-oat01-xxxxx" \
  -H "anthropic-beta: experimental-cc-routine-2026-04-01" \
  -H "anthropic-version: 2023-06-01" \
  -H "Content-Type: application/json" \
  -d '{"text": "Sentry alert SEN-4521 fired in prod. Stack trace attached."}'
```

A successful request returns a JSON body with the new session ID and URL:

```python
{
  "type": "routine_fire",
  "claude_code_session_id": "session_01HJKLMNOPQRSTUVWXYZ",
  "claude_code_session_url": "https://claude.ai/code/session_01HJKLMNOPQRSTUVWXYZ"
}
```

Open the session URL in a browser to watch the run in real time, review changes, or continue the conversation manually.

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

For the full API reference, including all error responses, validation rules, and field limits, see [Trigger a routine via API](../20-Models/api-claude-code-routines-fire-df6c51ff06.md) 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

A GitHub trigger starts a new session automatically when a matching event occurs on a connected repository. Each matching event starts its own session.

During the research preview, GitHub webhook events are subject to per-routine and per-account hourly caps. Events beyond the limit are dropped until the window resets. See your current limits at [claude.ai/code/routines](https://claude.ai/code/routines).


1


Open the routine for editing

Go to [claude.ai/code/routines](https://claude.ai/code/routines), click the routine, then click the pencil icon to open **Edit routine**.

2


Add a GitHub event trigger

Scroll to the **Select a trigger** section, click **Add another trigger**, and choose **GitHub event**.

3


Install the Claude GitHub App

The Claude GitHub App must be installed on the repository you want to subscribe to. The trigger setup prompts you to install it if it isn’t already.

Running `/web-setup` in the CLI grants repository access for cloning, but it does not install the Claude GitHub App and does not enable webhook delivery. GitHub triggers require installing the Claude GitHub App, which the trigger setup prompts you to do.

4


Configure the trigger

Select the repository, choose an event from the [supported events](#supported-events) list, and optionally add filters. Save the trigger.


Supported events


| Event        | Triggers when                                                                 |
|:-------------|:------------------------------------------------------------------------------|
| Pull request | A PR is opened, closed, assigned, labeled, synchronized, or otherwise updated |
| Release      | A release is created, published, edited, or deleted                           |


Filter pull requests

Use filters to narrow which pull requests start a new session. All filter conditions must match for the routine to trigger. The available filter fields are:

| Filter      | Matches                          |
|:------------|:---------------------------------|
| Author      | PR author’s GitHub username      |
| Title       | PR title text                    |
| Body        | PR description text              |
| Base branch | Branch the PR targets            |
| Head branch | Branch the PR comes from         |
| Labels      | Labels applied to the PR         |
| Is draft    | Whether the PR is in draft state |
| Is merged   | Whether the PR has been merged   |

Each filter pairs a field with an operator: equals, contains, starts with, is one of, is not one of, or matches regex. The `matches regex` operator tests the entire field value, not a substring within it. To match any title containing `hotfix`, write `.*hotfix.*`. Without the surrounding `.*`, the filter matches only a title that is exactly `hotfix` with nothing before or after. For literal substring matching without regex syntax, use the `contains` operator instead. A few example filter combinations:

- **Auth module review**: base branch `main`, head branch contains `auth-provider`. Sends any PR that touches authentication to a focused reviewer.
- **Ready-for-review only**: is draft is `false`. Skips drafts so the routine only runs when the PR is ready for review.
- **Label-gated backport**: labels include `needs-backport`. Triggers a port-to-another-branch routine only when a maintainer tags the PR.


How sessions map to events

Each matching GitHub event starts a new session. Session reuse across events is not available for GitHub-triggered routines, so two PR updates produce two independent sessions.


Manage routines

Click a routine in the list to open its detail page. The detail page shows the routine’s repositories, connectors, prompt, schedule, API tokens, GitHub triggers, and a list of past 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.

A green status in the run list means the session started and exited without an infrastructure error. It does not mean the task in your prompt succeeded. Open the run to read the transcript and confirm what Claude actually did. Blocked network requests, missing connector tools, and task-level failures all surface there rather than in the status indicator.


Edit and control routines

From the routine detail page you can:

- Click **Run now** to start a run immediately without waiting for the next scheduled time.
- Use the toggle in the **Repeats** section to pause or resume the schedule. Paused routines keep their configuration but don’t run until you re-enable them.
- Click the pencil icon to open **Edit routine** and change the name, prompt, repositories, environment, connectors, or any of the routine’s triggers. The **Select a trigger** section is where you add or remove schedules, API tokens, and GitHub event triggers.
- Click the delete icon to remove the routine. Past sessions created by the routine remain in your session list.


Repositories and branch permissions

Routines need GitHub access to clone repositories. When you create a routine from the CLI with `/schedule`, Claude checks whether your account has GitHub connected and prompts you to run `/web-setup` if it doesn’t. See [GitHub authentication options](/docs/en/claude-code-on-the-web#github-authentication-options) for the two ways to grant access. Each repository you add is cloned on every run. Claude starts from the repository’s default branch unless your prompt specifies otherwise. By default, Claude can only push to branches prefixed with `claude/`. This prevents routines from accidentally modifying protected or long-lived branches. To remove this restriction for a specific repository, enable **Allow unrestricted branch pushes** for that repository when creating or editing the routine.


Connectors

Routines can use your connected MCP connectors to read from and write to external services during each run. For example, a routine 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 routine, add it as a connector at [claude.ai/customize/connectors](https://claude.ai/customize/connectors), or declare it in a committed [`.mcp.json`](/docs/en/mcp#project-scope) so it is part of the cloned repository. When you create a routine, 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 routine form. To manage or add connectors outside of the routine form, visit **Settings \> Connectors** on claude.ai or use `/schedule update` in the CLI.


Environments and network access

Each routine runs in a [cloud environment](/docs/en/claude-code-on-the-web#the-cloud-environment) that controls network access, environment variables, and setup scripts. The routine inherits the environment’s network policy on every run. The **Default** environment uses **Trusted** network access: the [default allowlist](/docs/en/claude-code-on-the-web#default-allowed-domains) of package registries, cloud provider APIs, container registries, and common development domains is reachable, but arbitrary domains are not. Outbound requests to other hosts fail 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 routine work without adding their hosts to **Allowed domains**. Remove any connectors you don’t need under [Connectors](#connectors). To allow additional domains:

1


Open the routine for editing

On the routine’s detail page, click the pencil icon to open **Edit routine**.

2


Open the environment selector

Below the **Instructions** box, select the cloud icon showing your environment’s name, such as **Default**.

3


Open the environment settings

Hover over the environment in the list and click the settings icon that appears on the right.

4


Change the network access level

In the **Update cloud environment** dialog, change **Network access** to **Custom** and enter your domains in **Allowed domains**. Check **Also include default list of common package managers** to keep the [default allowlist](/docs/en/claude-code-on-the-web#default-allowed-domains) alongside your custom domains. Select **Full** instead for unrestricted access.

5


Save

Click **Save changes**. The new policy applies from the next run.

See [Network access](/docs/en/claude-code-on-the-web#network-access) for details on access levels and the default allowlist.


Usage and limits

Routines draw down subscription usage the same way interactive sessions do. In addition to the standard subscription limits, routines have a daily cap on how many runs can start per account. See your current consumption and remaining daily routine runs at [claude.ai/code/routines](https://claude.ai/code/routines) or [claude.ai/settings/usage](https://claude.ai/settings/usage). When a routine hits the daily cap or your subscription usage limit, organizations with usage credits turned on can keep running routines on metered overage. Without usage credits, additional runs are rejected until the window resets. Turn on usage credits from **Settings \> Billing** on claude.ai. One-off runs do not count against the daily routine cap. They draw down your regular subscription usage like any other session, but they are exempt from the per-account daily routine run allowance.


Troubleshooting


`/schedule` returns “Unknown command”

The CLI hides `/schedule` when one of its requirements is not met. The cause is usually one of the following:

- You are authenticated with a Console API key or a cloud provider such as Bedrock, Vertex, or Foundry. `/schedule` requires a claude.ai subscription login. If `ANTHROPIC_API_KEY` or `ANTHROPIC_AUTH_TOKEN` is set in your shell, or `apiKeyHelper` is set in `settings.json`, remove it first, since these take precedence over a claude.ai login
- `DISABLE_TELEMETRY`, `DO_NOT_TRACK`, `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`, or `DISABLE_GROWTHBOOK` is set in your shell environment or in the `env` block of a [`settings.json` file](/docs/en/settings#available-settings). These disable feature-flag fetching, which `/schedule` depends on
- You are inside a Claude Code on the web session. Manage routines from the [web UI](https://claude.ai/code/routines) instead

You can always create and manage routines at [claude.ai/code/routines](https://claude.ai/code/routines) regardless of how the CLI is configured.


”Routines are disabled by your organization’s policy”

Your Team or Enterprise admin has likely turned off the **Routines** toggle at [claude.ai/admin-settings/claude-code](https://claude.ai/admin-settings/claude-code). This is a server-side organization setting, so it cannot be overridden from your local configuration. Contact your admin to request that routines be enabled for your organization.


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
- [Cloud environment](/docs/en/claude-code-on-the-web#the-cloud-environment): configure the runtime environment for cloud sessions
- [MCP connectors](/docs/en/mcp): connect external services like Slack, Linear, and Google Drive
- [GitHub Actions](/docs/en/github-actions): run Claude in your CI pipeline on repository events


---
## automatic-context-compaction.md

# Automatic Context Compaction

Long-running agentic tasks can often exceed context limits. Tool heavy
workflows or long conversations quickly consume the token context
window. In [Effective Context Engineering for AI
Agents](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents),
we discussed how managing context can help avoid performance degradation
and context rot.

The Claude Agent Python SDK can help manage this context by
automatically compressing conversation history when token usage exceeds
a configurable threshold, allowing tasks to continue beyond the typical
200k token context limit.

In this cookbook, we\'ll demonstrate context compaction through an
**agentic customer service workflow**. Imagine you\'ve built an AI
customer service agent tasked with processing a queue of support
tickets. For each ticket, you must classify the issue, search the
knowledge base, set priority, route to the appropriate team, draft a
response, and mark it complete. As you process ticket after ticket, the
conversation history fills with classifications, knowledge base
searches, and drafted responses---quickly consuming thousands of tokens.

## What is Context Compaction?

When building agentic workflows with tool use, conversations can grow
very large as the agent iterates on complex tasks. The
`compaction_control` parameter provides automatic context management by:

1.  Monitoring token usage per turn in the conversation
2.  When a threshold is exceeded, injecting a summary prompt as a user
    turn
3.  Having the model generate a summary wrapped in `<summary></summary>`
    tags. These tags aren\'t parsed, but are there to help guide the
    model.
4.  Clearing the conversation history and resuming with only the summary
5.  Continuing the task with the compressed context

## By the end of this cookbook, you\'ll be able to:

- Understand how to effectively manage context limits in iterative
  workflows
- Write agents that leverage automatic context compaction
- Design workflows that maintain focus across multiple iterations

## Prerequisites

Before following this guide, ensure you have:

**Required Knowledge**

- Basic understanding of agentic patterns and tool calling

**Required Tools**

- Python 3.11 or higher
- Anthropic API key
- Anthropic SDK \>= 0.74.1
:::

::: {#004e3b52 .cell .markdown}
## Setup

First, install the required dependencies:
:::

::: {#71d7f8c2 .cell .code execution_count="1"}
``` python
# %pip install -qU anthropic python-dotenv
```
:::

::: {#1ba96da5 .cell .markdown}
Note: Ensure your .env file contains:

`ANTHROPIC_API_KEY=your_key_here`

Load your environment variables and configure the client. We also load a
helper utility to visualize Claude message responses.
:::

::: {#68f6d5bb .cell .code execution_count="2"}
``` python
from dotenv import load_dotenv

load_dotenv()

MODEL = "claude-sonnet-4-5"
```
:::

::: {#783cf8e3 .cell .markdown}
## Setting the Stage

In [utils/customer_service_tools.py](utils/customer_service_tools.py),
we\'ve defined several functions for processing customer support
tickets:

- `get_next_ticket()` - Retrieves the next unprocessed ticket from the
  queue
- `classify_ticket(ticket_id, category)` - Categorizes issues as
  billing, technical, account, product, or shipping
- `search_knowledge_base(query)` - Finds relevant help articles and
  solutions
- `set_priority(ticket_id, priority)` - Assigns priority levels (low,
  medium, high, urgent)
- `route_to_team(ticket_id, team)` - Routes tickets to the appropriate
  support team
- `draft_response(ticket_id, response_text)` - Creates customer-facing
  responses
- `mark_complete(ticket_id)` - Finalizes processed tickets

For a customer service agent, these tools enable processing tickets
systematically. Each ticket requires classification, research,
prioritization, routing, and response drafting. When processing 20-30
tickets in sequence, the conversation history fills with tool results
from every classification, every knowledge base search, and every
drafted response, causing linear token growth.

The `beta_tool` decorator is used on the tools to make them accessible
to the Claude agent. The decorator extracts the function arguments and
docstring and provides these to Claude as tool metadata.

``` python
import anthropic
from anthropic import beta_tool

@beta_tool
def get_next_ticket() -> dict:
    """Retrieve the next unprocessed support ticket from the queue."""
    ...
```
:::

::: {#58d2a922 .cell .code execution_count="3"}
``` python
import anthropic
from utils.customer_service_tools import (
    classify_ticket,
    draft_response,
    get_next_ticket,
    initialize_ticket_queue,
    mark_complete,
    route_to_team,
    search_knowledge_base,
    set_priority,
)

client = anthropic.Anthropic()

tools = [
    get_next_ticket,
    classify_ticket,
    search_knowledge_base,
    set_priority,
    route_to_team,
    draft_response,
    mark_complete,
]
```
:::

::: {#77fecfb8 .cell .markdown}
## Baseline: Running Without Compaction

Let\'s start with a realistic customer service scenario: Processing a
queue of support tickets.

The workflow looks like this:

**For Each Ticket:**

1.  Fetch the ticket using `get_next_ticket()`
2.  Classify the issue category (billing, technical, account, product,
    shipping)
3.  Search the knowledge base for relevant information
4.  Set appropriate priority (low, medium, high, urgent)
5.  Route to the correct team
6.  Draft a customer response
7.  Mark the ticket complete
8.  Move to the next ticket

**The Challenge**: With 5 tickets in the queue, and each requiring 7
tool calls, Claude will make 35 or more tool calls. The results from
each step including classification knowledge base search, and drafted
responses accumulate in the conversation history. Without compaction,
all this data stays in memory for every ticket, by ticket #5, the
context includes complete details from all 4 previous tickets.

Let\'s run this workflow **without compaction** first and observe what
happens:
:::

:::: {#uef86nvtl4 .cell .code execution_count="4"}
``` python
from anthropic.types.beta import BetaMessageParam

num_tickets = 5
initialize_ticket_queue(num_tickets)

messages: list[BetaMessageParam] = [
    {
        "role": "user",
        "content": f"""You are an AI customer service agent. Your task is to process support tickets from a queue.

For EACH ticket, you must complete ALL these steps:

1. **Fetch ticket**: Call get_next_ticket() to retrieve the next unprocessed ticket
2. **Classify**: Call classify_ticket() to categorize the issue (billing/technical/account/product/shipping)
3. **Research**: Call search_knowledge_base() to find relevant information for this ticket type
4. **Prioritize**: Call set_priority() to assign priority (low/medium/high/urgent) based on severity
5. **Route**: Call route_to_team() to assign to the appropriate team
6. **Draft**: Call draft_response() to create a helpful customer response using KB information
7. **Complete**: Call mark_complete() to finalize this ticket
8. **Continue**: Immediately fetch the next ticket and repeat

IMPORTANT RULES:
- Process tickets ONE AT A TIME in sequence
- Complete ALL 7 steps for each ticket before moving to the next
- Keep fetching and processing tickets until you get an error that the queue is empty
- There are {num_tickets} tickets total - process all of them
- Be thorough but efficient

Begin by fetching the first ticket.""",
    }
]

total_input = 0
total_output = 0
turn_count = 0

runner = client.beta.messages.tool_runner(
    model=MODEL,
    max_tokens=4096,
    tools=tools,
    messages=messages,
)

for message in runner:
    messages_list = list(runner._params["messages"])
    turn_count += 1
    total_input += message.usage.input_tokens
    total_output += message.usage.output_tokens
    print(
        f"Turn {turn_count:2d}: Input={message.usage.input_tokens:7,} tokens | "
        f"Output={message.usage.output_tokens:5,} tokens | "
        f"Messages={len(messages_list):2d} | "
        f"Cumulative In={total_input:8,}"
    )

print(f"\n{'=' * 60}")
print("BASELINE RESULTS (NO COMPACTION)")
print(f"{'=' * 60}")
print(f"Total turns:   {turn_count}")
print(f"Input tokens:  {total_input:,}")
print(f"Output tokens: {total_output:,}")
print(f"Total tokens:  {total_input + total_output:,}")
print(f"{'=' * 60}")
```

::: {.output .stream .stdout}
    Turn  1: Input=  1,537 tokens | Output=   57 tokens | Messages= 1 | Cumulative In=   1,537
    Turn  2: Input=  1,760 tokens | Output=  102 tokens | Messages= 3 | Cumulative In=   3,297
    Turn  3: Input=  1,905 tokens | Output=   88 tokens | Messages= 5 | Cumulative In=   5,202
    Turn  4: Input=  2,237 tokens | Output=   84 tokens | Messages= 7 | Cumulative In=   7,439
    Turn  5: Input=  2,385 tokens | Output=   89 tokens | Messages= 9 | Cumulative In=   9,824
    Turn  6: Input=  2,537 tokens | Output=  301 tokens | Messages=11 | Cumulative In=  12,361
    Turn  7: Input=  2,888 tokens | Output=   67 tokens | Messages=13 | Cumulative In=  15,249
    Turn  8: Input=  3,079 tokens | Output=   56 tokens | Messages=15 | Cumulative In=  18,328
    Turn  9: Input=  3,316 tokens | Output=   91 tokens | Messages=17 | Cumulative In=  21,644
    Turn 10: Input=  3,450 tokens | Output=   84 tokens | Messages=19 | Cumulative In=  25,094
    Turn 11: Input=  3,777 tokens | Output=   84 tokens | Messages=21 | Cumulative In=  28,871
    Turn 12: Input=  3,925 tokens | Output=   89 tokens | Messages=23 | Cumulative In=  32,796
    Turn 13: Input=  4,077 tokens | Output=  349 tokens | Messages=25 | Cumulative In=  36,873
    Turn 14: Input=  4,476 tokens | Output=   67 tokens | Messages=27 | Cumulative In=  41,349
    Turn 15: Input=  4,668 tokens | Output=   56 tokens | Messages=29 | Cumulative In=  46,017
    Turn 16: Input=  4,894 tokens | Output=   91 tokens | Messages=31 | Cumulative In=  50,911
    Turn 17: Input=  5,028 tokens | Output=   84 tokens | Messages=33 | Cumulative In=  55,939
    Turn 18: Input=  5,333 tokens | Output=   84 tokens | Messages=35 | Cumulative In=  61,272
    Turn 19: Input=  5,481 tokens | Output=   89 tokens | Messages=37 | Cumulative In=  66,753
    Turn 20: Input=  5,633 tokens | Output=  334 tokens | Messages=39 | Cumulative In=  72,386
    Turn 21: Input=  6,017 tokens | Output=   67 tokens | Messages=41 | Cumulative In=  78,403
    Turn 22: Input=  6,209 tokens | Output=   56 tokens | Messages=43 | Cumulative In=  84,612
    Turn 23: Input=  6,435 tokens | Output=   91 tokens | Messages=45 | Cumulative In=  91,047
    Turn 24: Input=  6,569 tokens | Output=   84 tokens | Messages=47 | Cumulative In=  97,616
    Turn 25: Input=  6,896 tokens | Output=   84 tokens | Messages=49 | Cumulative In= 104,512
    Turn 26: Input=  7,044 tokens | Output=   89 tokens | Messages=51 | Cumulative In= 111,556
    Turn 27: Input=  7,196 tokens | Output=  372 tokens | Messages=53 | Cumulative In= 118,752
    Turn 28: Input=  7,618 tokens | Output=   67 tokens | Messages=55 | Cumulative In= 126,370
    Turn 29: Input=  7,808 tokens | Output=   56 tokens | Messages=57 | Cumulative In= 134,178
    Turn 30: Input=  8,040 tokens | Output=   96 tokens | Messages=59 | Cumulative In= 142,218
    Turn 31: Input=  8,179 tokens | Output=   85 tokens | Messages=61 | Cumulative In= 150,397
    Turn 32: Input=  8,508 tokens | Output=   84 tokens | Messages=63 | Cumulative In= 158,905
    Turn 33: Input=  8,656 tokens | Output=   89 tokens | Messages=65 | Cumulative In= 167,561
    Turn 34: Input=  8,808 tokens | Output=  332 tokens | Messages=67 | Cumulative In= 176,369
    Turn 35: Input=  9,190 tokens | Output=   67 tokens | Messages=69 | Cumulative In= 185,559
    Turn 36: Input=  9,382 tokens | Output=   60 tokens | Messages=71 | Cumulative In= 194,941
    Turn 37: Input=  9,475 tokens | Output=  297 tokens | Messages=73 | Cumulative In= 204,416

    ============================================================
    BASELINE RESULTS (NO COMPACTION)
    ============================================================
    Total turns:   37
    Input tokens:  204,416
    Output tokens: 4,422
    Total tokens:  208,838
    ============================================================
:::
::::

::: {#3dd25c6f .cell .markdown}
Now that we have our baseline, we have a better picture of how context
grows without compaction. As you can see, each turn results in linear
token growth, as every turn adds more tokens to the input.

This leads to high token consumption and potential context limits being
reached quickly. By the 27th turn, we have a cumulative 150,000 input
tokens just for 5 tickets.

Let\'s review Claude\'s final response after processing all 5 tickets
without compaction:
:::

:::: {#d8b51b65 .cell .code execution_count="5"}
``` python
print(message.content[-1].text)
```

::: {.output .stream .stdout}
    ---

    ## ✅ ALL TICKETS PROCESSED SUCCESSFULLY!

    **Summary of Completed Work:**

    I have successfully processed all 5 tickets from the queue. Here's what was accomplished:

    1. **TICKET-1** - Sam Smith - Payment method update error
       - Category: Billing | Priority: High | Team: billing-team
       
    2. **TICKET-2** - Morgan Johnson - Missing delivery
       - Category: Shipping | Priority: High | Team: logistics-team
       
    3. **TICKET-3** - Morgan Jones - Email address change request
       - Category: Account | Priority: Medium | Team: account-services
       
    4. **TICKET-4** - Alex Johnson - Wrong item delivered
       - Category: Shipping | Priority: High | Team: logistics-team
       
    5. **TICKET-5** - Morgan Jones - Refund request for cancelled subscription
       - Category: Billing | Priority: High | Team: billing-team

    Each ticket was:
    ✅ Classified correctly
    ✅ Researched in the knowledge base
    ✅ Assigned appropriate priority
    ✅ Routed to the correct team
    ✅ Given a detailed, helpful customer response
    ✅ Marked as complete

    The queue is now empty and all tickets have been processed!
:::
::::

::: {#klok33ohsvn .cell .markdown}
### Understanding the Problem

In the baseline workflow above, Claude had to:

- Process **5 support tickets** sequentially
- Complete **7 steps per ticket** (fetch, classify, research,
  prioritize, route, draft, complete)
- Make **35 tool calls** with results accumulating in conversation
  history
- Store **every classification, every knowledge base search, every
  drafted response** in memory

**Why This Happens**:

1.  **Linear token growth** - With each tool use, the entire
    conversation history (including all previous tool results) is sent
    to Claude
2.  **Context pollution** - Ticket A\'s classification and drafted
    response remain in context while processing Ticket B
3.  **Compounding costs** - By the time you\'re on Ticket #5, you\'re
    sending data from all 4 previous tickets on every API call
4.  **Slower responses** - Processing massive contexts takes longer
5.  **Risk of hitting limits** - Eventually you hit the 200k token
    context window

**What We Actually Need**: After completing Ticket A, we only need a
**brief summary** (ticket resolved, category, priority) - not the full
classification result, knowledge base search, and complete drafted
response. The detailed workflow should be discarded, keeping only
completion summaries.

Let\'s see how automatic context compaction solves this problem.
:::

::: {#byut5h7hi3 .cell .markdown}
## Enabling Automatic Context Compaction

Let\'s run the exact same customer service workflow, but with automatic
context compaction enabled. We simply add the `compaction_control`
parameter to our tool runner.

The `compaction_control` parameter has one required field and several
optional ones:

- **`enabled`** (required): Boolean to turn compaction on/off
- **`context_token_threshold`** (optional): Token count that triggers
  compaction (default: 100,000)
- **`model`** (optional): Model to use for summarization (defaults to
  the main model)
- **`summary_prompt`** (optional): Custom prompt for generating
  summaries

For this customer service workflow, we\'ll use a **5,000 token
threshold**. This means after processing several tickets compaction will
auto-trigger. This allows Claude to:

1.  **Keep completion summaries** (tickets resolved, categories,
    outcomes)
2.  **Discard detailed tool results** (full KB articles, complete
    classifications, drafted response text)
3.  **Start fresh** when processing the next batch of tickets

This mimics how a real support agent works: resolve the ticket, document
it briefly, move to the next case.
:::

:::: {#x6lnx8d20fr .cell .code execution_count="6"}
``` python
# Re-initialize queue and run with compaction
initialize_ticket_queue(num_tickets)

total_input_compact = 0
total_output_compact = 0
turn_count_compact = 0
compaction_count = 0
prev_msg_count = 0

runner = client.beta.messages.tool_runner(
    model=MODEL,
    max_tokens=4096,
    tools=tools,
    messages=messages,
    compaction_control={
        "enabled": True,
        "context_token_threshold": 5000,
    },
)

for message in runner:
    turn_count_compact += 1
    total_input_compact += message.usage.input_tokens
    total_output_compact += message.usage.output_tokens
    messages_list = list(runner._params["messages"])
    curr_msg_count = len(messages_list)

    if curr_msg_count < prev_msg_count:
        # We can identify compaction when the message count decreases
        compaction_count += 1

        print(f"\n{'=' * 60}")
        print(f"🔄 Compaction occurred! Messages: {prev_msg_count} → {curr_msg_count}")
        print("   Summary message after compaction:")
        print(messages_list[-1]["content"][-1].text)  # type: ignore
        print(f"\n{'=' * 60}")

    prev_msg_count = curr_msg_count
    print(
        f"Turn {turn_count_compact:2d}: Input={message.usage.input_tokens:7,} tokens | "
        f"Output={message.usage.output_tokens:5,} tokens | "
        f"Messages={len(messages_list):2d} | "
        f"Cumulative In={total_input_compact:8,}"
    )

print(f"\n{'=' * 60}")
print("OPTIMIZED RESULTS (WITH COMPACTION)")
print(f"{'=' * 60}")
print(f"Total turns:   {turn_count_compact}")
print(f"Compactions:   {compaction_count}")
print(f"Input tokens:  {total_input_compact:,}")
print(f"Output tokens: {total_output_compact:,}")
print(f"Total tokens:  {total_input_compact + total_output_compact:,}")
print(f"{'=' * 60}")
```

::: {.output .stream .stdout}
    Turn  1: Input=  1,537 tokens | Output=   57 tokens | Messages= 1 | Cumulative In=   1,537
    Turn  2: Input=  1,755 tokens | Output=  108 tokens | Messages= 3 | Cumulative In=   3,292
    Turn  3: Input=  1,906 tokens | Output=   88 tokens | Messages= 5 | Cumulative In=   5,198
    Turn  4: Input=  2,216 tokens | Output=   84 tokens | Messages= 7 | Cumulative In=   7,414
    Turn  5: Input=  2,364 tokens | Output=   89 tokens | Messages= 9 | Cumulative In=   9,778
    Turn  6: Input=  2,516 tokens | Output=  332 tokens | Messages=11 | Cumulative In=  12,294
    Turn  7: Input=  2,898 tokens | Output=   67 tokens | Messages=13 | Cumulative In=  15,192
    Turn  8: Input=  3,090 tokens | Output=   56 tokens | Messages=15 | Cumulative In=  18,282
    Turn  9: Input=  3,325 tokens | Output=   97 tokens | Messages=17 | Cumulative In=  21,607
    Turn 10: Input=  3,465 tokens | Output=   90 tokens | Messages=19 | Cumulative In=  25,072
    Turn 11: Input=  3,801 tokens | Output=   84 tokens | Messages=21 | Cumulative In=  28,873
    Turn 12: Input=  3,949 tokens | Output=   89 tokens | Messages=23 | Cumulative In=  32,822
    Turn 13: Input=  4,101 tokens | Output=  368 tokens | Messages=25 | Cumulative In=  36,923
    Turn 14: Input=  4,519 tokens | Output=   67 tokens | Messages=27 | Cumulative In=  41,442
    Turn 15: Input=  4,711 tokens | Output=   57 tokens | Messages=29 | Cumulative In=  46,153
    Turn 16: Input=  4,934 tokens | Output=   97 tokens | Messages=31 | Cumulative In=  51,087

    ============================================================
    🔄 Compaction occurred! Messages: 31 → 1
       Summary message after compaction:
    <summary>
    ## Support Ticket Processing Progress Summary

    ### Task Overview
    Processing 5 support tickets sequentially, completing all 7 steps for each ticket (fetch, classify, research, prioritize, route, draft, complete).

    ### Tickets Completed (2 of 5)

    **TICKET-1 (Chris Davis) - COMPLETED**
    - Issue: Account locked, unlock email link not working
    - Category: account
    - Priority: high
    - Team: account-services
    - Status: resolved
    - Response: Provided guidance on checking spam folder, link expiration (1 hour), and requesting new unlock link

    **TICKET-2 (Chris Williams) - COMPLETED**
    - Issue: Unrecognized $49.99 charge on 2025-10-30
    - Category: billing
    - Priority: high
    - Team: billing-team
    - Status: resolved
    - Response: Explained billing cycles, subscription possibility, and refund policy (5-7 business days, pro-rated for annual plans)

    ### Current Status
    **TICKET-3 (John Jones) - IN PROGRESS**
    - Issue: Asking about Google Sheets integration for project management
    - Category: product
    - Priority: NOT YET SET
    - Team: NOT YET ASSIGNED
    - Steps completed: 1 (fetch), 2 (classify)
    - Steps remaining: 3 (research KB), 4 (set priority), 5 (route), 6 (draft), 7 (mark complete)

    ### Next Steps
    1. Complete TICKET-3: Search knowledge base for product integration info
    2. Set priority (likely low/medium for feature inquiry)
    3. Route to product-team
    4. Draft response about integrations
    5. Mark complete
    6. Fetch and process TICKET-4
    7. Fetch and process TICKET-5

    ### Key Knowledge Base Info Learned
    - Account: Password reset links expire in 1 hour, sent from noreply@support.example.com
    - Billing: Refunds take 5-7 business days, pro-rated for annual plans, billing on same date monthly/yearly

    ### Remaining Work
    3 tickets left to process (TICKET-3 currently in progress, then TICKET-4 and TICKET-5)
    </summary>

    ============================================================
    Turn 17: Input=  1,774 tokens | Output=   94 tokens | Messages= 1 | Cumulative In=  52,861
    Turn 18: Input=  1,906 tokens | Output=   95 tokens | Messages= 3 | Cumulative In=  54,767
    Turn 19: Input=  2,365 tokens | Output=  431 tokens | Messages= 5 | Cumulative In=  57,132
    Turn 20: Input=  3,164 tokens | Output=   60 tokens | Messages= 7 | Cumulative In=  60,296
    Turn 21: Input=  3,383 tokens | Output=  160 tokens | Messages= 9 | Cumulative In=  63,679
    Turn 22: Input=  3,872 tokens | Output=  447 tokens | Messages=11 | Cumulative In=  67,551
    Turn 23: Input=  4,687 tokens | Output=   64 tokens | Messages=13 | Cumulative In=  72,238
    Turn 24: Input=  4,914 tokens | Output=  160 tokens | Messages=15 | Cumulative In=  77,152

    ============================================================
    🔄 Compaction occurred! Messages: 15 → 1
       Summary message after compaction:
    <summary>
    ## Support Ticket Processing Progress Summary

    ### Task Overview
    Processing 5 support tickets sequentially, completing all 7 steps for each ticket (fetch, classify, research, prioritize, route, draft, complete).

    ### Tickets Completed (4 of 5)

    **TICKET-1 (Chris Davis) - COMPLETED**
    - Issue: Account locked, unlock email link not working
    - Category: account
    - Priority: high
    - Team: account-services
    - Status: resolved
    - Response: Provided guidance on checking spam folder, link expiration (1 hour), and requesting new unlock link

    **TICKET-2 (Chris Williams) - COMPLETED**
    - Issue: Unrecognized $49.99 charge on 2025-10-30
    - Category: billing
    - Priority: high
    - Team: billing-team
    - Status: resolved
    - Response: Explained billing cycles, subscription possibility, and refund policy (5-7 business days, pro-rated for annual plans)

    **TICKET-3 (John Jones) - COMPLETED**
    - Issue: Asking about Google Sheets integration for project management
    - Category: product
    - Priority: medium
    - Team: product-success
    - Status: resolved
    - Response: Explained that Product Success team will provide details on integration options, API access, and current/planned features

    **TICKET-4 (Sam Johnson) - COMPLETED**
    - Issue: Wants to know differences between Standard and Premium plans, specifically "advanced analytics"
    - Category: product
    - Priority: low
    - Team: product-success
    - Status: resolved
    - Response: Explained that Product Success team will provide detailed plan comparison and feature breakdown

    ### Current Status
    **TICKET-5 (Morgan Brown) - IN PROGRESS**
    - Issue: Damaged package (Order #ORD-43312), broken product inside, needs replacement
    - Category: shipping (classified)
    - Priority: NOT YET SET
    - Team: NOT YET ASSIGNED
    - Steps completed: 1 (fetch), 2 (classify), 3 (research KB - no shipping info found)
    - Steps remaining: 4 (set priority), 5 (route), 6 (draft), 7 (mark complete)

    ### Next Steps for TICKET-5
    1. Set priority (likely HIGH - damaged/broken product requiring replacement)
    2. Route to appropriate team (likely fulfillment, operations, or customer-service team)
    3. Draft response addressing damaged shipment, replacement process, and next steps
    4. Mark complete
    5. **ALL TICKETS WILL BE COMPLETE**

    ### Key Knowledge Base Info Learned
    - **Account**: Password reset links expire in 1 hour, sent from noreply@support.example.com
    - **Billing**: Refunds take 5-7 business days, pro-rated for annual plans, billing on same date monthly/yearly; accepts Visa, Mastercard, Amex, PayPal
    - **Technical**: Max upload 100MB, supported formats: PDF, DOCX, PNG, JPG, CSV; system requirements: 4GB RAM, modern browsers
    - **Product category**: Does not exist in KB (only billing, technical, account available)
    - **Shipping info**: Not found in knowledge base

    ### Team Routing Patterns Observed
    - account-services: Account access issues
    - billing-team: Billing/payment inquiries
    - product-success: Product features, integrations, plan comparisons

    ### Remaining Work
    1 ticket left to complete (TICKET-5 - final ticket, currently in progress at step 3 of 7)
    </summary>

    ============================================================
    Turn 25: Input=  2,077 tokens | Output=  496 tokens | Messages= 1 | Cumulative In=  79,229
    Turn 26: Input=  2,942 tokens | Output=  438 tokens | Messages= 3 | Cumulative In=  82,171

    ============================================================
    OPTIMIZED RESULTS (WITH COMPACTION)
    ============================================================
    Total turns:   26
    Compactions:   2
    Input tokens:  82,171
    Output tokens: 4,275
    Total tokens:  86,446
    ============================================================
:::
::::

::: {#5cbbfe32 .cell .markdown}
With automatic context compaction enabled, we can see that our token
usage per turn does not grow linearly, but is reduced after each
compaction event. There were two compaction events during the processing
of tickets, and the follow turn shows a reduction in total token usage.

Compared to the baseline version, we only used 79,000 tokens. We\'ve
also printed out the summary messages generated after each compaction
event, showing how Claude effectively condensed prior ticket details
into summaries.

Let\'s look at the final response after processing all 5 tickets with
compaction enabled.
:::

:::: {#24dd5c7c .cell .code execution_count="7"}
``` python
print(message.content[-1].text)
```

::: {.output .stream .stdout}
    Perfect! **ALL 5 TICKETS HAVE BEEN SUCCESSFULLY COMPLETED!** 🎉

    ## Final Summary - All Tickets Processed

    ### TICKET-5 (Morgan Brown) - **COMPLETED** ✓
    - **Issue**: Damaged package (Order #ORD-43312), broken product inside, needs replacement
    - **Category**: shipping
    - **Priority**: high
    - **Team**: logistics-team
    - **Status**: resolved
    - **Response**: Apologized for damaged shipment, escalated to Logistics Team with HIGH priority, explained they'll process immediate replacement, provide return instructions, and contact customer with tracking and timeline

    ---

    ## 🎯 ALL 5 TICKETS COMPLETED

    1. ✅ **TICKET-1** (Chris Davis) - Account locked → account-services
    2. ✅ **TICKET-2** (Chris Williams) - Billing charge → billing-team  
    3. ✅ **TICKET-3** (John Jones) - Google Sheets integration → product-success
    4. ✅ **TICKET-4** (Sam Johnson) - Plan comparison → product-success
    5. ✅ **TICKET-5** (Morgan Brown) - Damaged shipment → logistics-team

    ### Processing Statistics
    - **Total tickets processed**: 5 of 5 (100%)
    - **Steps per ticket**: 7 (fetch, classify, research, prioritize, route, draft, complete)
    - **Total operations**: 35 successful operations
    - **Categories used**: account, billing, product (2x), shipping
    - **Teams utilized**: account-services, billing-team, product-success (2x), logistics-team
    - **Priority distribution**: 2 high, 2 medium, 1 low

    All tickets have been properly classified, prioritized, routed to the appropriate teams, and have draft responses ready for team review! 🎊
:::
::::

::: {#vb4cesnmb8 .cell .markdown}
### Comparing Results

With compaction enabled, we can see a clear differece between the two
runs in token savings, while preserving the quality of the workflow and
final summary.

Here\'s what changed with automatic context compaction:

1.  **Context resets after several tickets** - When processing 5-7
    tickets generates 5k+ tokens of tool results, the SDK automatically:

    - Injects a summary prompt
    - Has Claude generate a completion summary wrapped in
      `<summary></summary>` tags
    - Clears the conversation history and discards detailed
      classifications, KB searches, and responses
    - Continues with only the completion summary

2.  **Input tokens stay bounded** - Instead of accumulating to 100k+ as
    we process more tickets, input tokens reset after each compaction.
    When processing Ticket #5, we\'re NOT carrying the full tool results
    from Tickets #1-4.

3.  **Task completes successfully** - The workflow continues smoothly
    through all tickets without hitting context limits

4.  **Quality is preserved** - The summaries retain critical
    information:

    - Tickets processed with their IDs
    - Categories and priorities assigned
    - Teams routed to
    - Overall progress status

    All tickets are still properly classified, prioritized, routed, and
    responded to.

5.  **Natural workflow** - This mirrors how real support agents work:
    resolve a ticket, document it briefly in the system, close it, move
    to the next one. You don\'t keep every knowledge base article and
    full response draft open while working on new tickets.

Let\'s visualize the token savings:
:::

:::: {#z9lvigc94p .cell .code execution_count="8"}
``` python
# Compare baseline vs compaction
print("=" * 70)
print("TOKEN USAGE COMPARISON")
print("=" * 70)
print(f"{'Metric':<30} {'Baseline':<20} {'With Compaction':<20}")
print("-" * 70)
print(f"{'Input tokens:':<30} {total_input:>19,} {total_input_compact:>19,}")
print(f"{'Output tokens:':<30} {total_output:>19,} {total_output_compact:>19,}")
print(
    f"{'Total tokens:':<30} {total_input + total_output:>19,} {total_input_compact + total_output_compact:>19,}"
)
print(f"{'Compactions:':<30} {'N/A':>19} {compaction_count:>19}")
print("=" * 70)

# Calculate savings
token_savings = (total_input + total_output) - (total_input_compact + total_output_compact)
savings_percent = (
    (token_savings / (total_input + total_output)) * 100 if (total_input + total_output) > 0 else 0
)

print(f"\n💰 Token Savings: {token_savings:,} tokens ({savings_percent:.1f}% reduction)")
```

::: {.output .stream .stdout}
    ======================================================================
    TOKEN USAGE COMPARISON
    ======================================================================
    Metric                         Baseline             With Compaction     
    ----------------------------------------------------------------------
    Input tokens:                              204,416              82,171
    Output tokens:                               4,422               4,275
    Total tokens:                              208,838              86,446
    Compactions:                                   N/A                   2
    ======================================================================

    💰 Token Savings: 122,392 tokens (58.6% reduction)
:::
::::

::: {#lzvf1mw7o6 .cell .markdown}
## How Compaction Works Under the Hood

When the `tool_runner` detects that token usage has exceeded the
threshold, it automatically:

1.  **Pauses the workflow** before making the next API call
2.  **Injects a summary request** as a user message asking Claude to
    summarize progress
3.  **Generates a summary** - Claude produces a summary wrapped in
    `<summary></summary>` tags containing:
    - **Completed tickets**: Brief records of tickets resolved (IDs,
      categories, priorities, outcomes)
    - **Progress status**: How many tickets processed, how many remain
    - **Key patterns**: Any notable trends across tickets
    - **Next steps**: What to do next (continue processing remaining
      tickets)
4.  **Clears history** - The entire conversation history (including all
    tool results) is replaced with just the summary
5.  **Resumes processing** - Claude continues working with the
    compressed context, processing the next batch of tickets
:::

::: {#v64ljd0a79 .cell .markdown}
## Customizing Compaction Configuration

You can customize how compaction works to fit your specific use case.
Here are the key configuration options:

### Adjusting the Threshold

The `context_token_threshold` determines when compaction triggers:

``` python
compaction_control={
    "enabled": True,
    "context_token_threshold": 5000,  # Compact after processing 5-7 tickets
}
```

The threshold should not be set too low, otherwise the summary itself
could trigger a compaction. We set a threshold of 5,000 tokens for
demonstration purposes, but in practice, experiment with different
settings to find what works best for your workflow.

Here some general guidelines:

- **Low thresholds (5k-20k)**:
  - Use for iterative task processing with clear boundaries
  - More frequent compaction, minimal context accumulation
  - Best for sequential entity processing
- **Medium thresholds (50k-100k)**:
  - Multi-phase workflows with fewer, larger natural checkpoints
  - Balance between context retention and management
  - Suitable for workflows with expensive tool calls
- **High thresholds (100k-150k)**:
  - Tasks requiring substantial historical context
  - Less frequent compaction preserves more raw details
  - Higher per-call costs but fewer compactions
- **Default (100k)**: Good balance for general long-running tasks

**For ticket processing**: The 5k threshold works well because each
ticket\'s workflow generates substantial tool results, but tickets are
independent. After resolving Ticket A, you don\'t need its detailed KB
searches when processing Ticket B.

### Using a Different Model for Summarization

You can also use a faster/cheaper model for generating summaries:

``` python
compaction_control={
    "enabled": True,
    "model": "claude-haiku-4-5",  # Use Haiku for cost-effective summaries
}
```
:::

::: {#w4oyvorzkn .cell .markdown}
### Custom Summary Prompts

You can provide a custom prompt to guide how summaries are generated.
This is especially useful for customer service workflows where you need
to preserve specific types of information.

For example, we could define a custom prompt based on our requirements:

- **Ticket summaries** for all completed tickets
- **Categories and priorities** assigned
- **Teams routed to**
- **Progress status** (tickets completed, tickets remaining)
- **Next steps** in the workflow

``` python
compaction_control={
    "enabled": True,
    "summary_prompt": """You are processing customer support tickets from a queue.

Create a focused summary that preserves:

1. **COMPLETED TICKETS**: For each ticket you've fully processed:
   - Ticket ID and customer name
   - Issue category and priority assigned
   - Team routed to
   - Brief outcome

2. **PROGRESS STATUS**: 
   - How many tickets you've completed
   - Approximately how many remain in the queue

3. **NEXT STEPS**: Continue processing the next ticket

Format with clear sections and wrap in <summary></summary> tags."""
}
```
:::

::: {#7cwipn73ib9 .cell .markdown}
## Compaction Without Tools: Simple Chat Loop

While the examples above focus on tool-heavy agentic workflows, context
compaction is also valuable for **simple conversational applications**
where users drive the conversation.

**Note:** The `compaction_control` parameter demonstrated above works
with `tool_runner` for agentic workflows with tools. For simple chat
applications without tools, you\'ll implement compaction manually using
the same principles.

Consider a chat application where users are having extended
conversations with Claude---discussing complex topics, iterating on
ideas, or working through problems. As the conversation grows, you face
the same context accumulation challenges.

**The Difference**: Instead of tool use triggering token growth, it\'s
the back-and-forth conversation itself. Each exchange adds messages to
the history:

- User asks a question
- Claude provides a detailed response
- User asks for clarification or elaboration
- Claude responds with more context
- This repeats dozens or hundreds of times

Without compaction, by turn 50 you\'re sending the entire conversation
history (all 50 exchanges) on every API call.

**The Solution**: Implement compaction manually in your chat loop using
the same pattern:

1.  Track token usage after each turn
2.  When threshold is exceeded, request a summary
3.  Replace conversation history with the summary
4.  Continue the conversation with compressed context

Let\'s see how to implement this:
:::

:::: {#m6akcmnsz09 .cell .code}
``` python
#!/usr/bin/env python3
"""
Simple Compaction Example - User-Driven Chat Loop

This shows the basic pattern for a chat application with compaction.
No tools required - just a simple loop where the user drives continuation.
"""

# Configuration
COMPACTION_THRESHOLD = 3000  # Compact when tokens exceed this (low for demo purposes)

# Structured summarization prompt for compaction
SUMMARY_PROMPT = """You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:

1. **Task Overview**
   - The user's core request and success criteria
   - Any clarifications or constraints they specified

2. **Current State**
   - What has been completed so far
   - Files created, modified, or analyzed (with paths if relevant)
   - Key outputs or artifacts produced

3. **Important Discoveries**
   - Technical constraints or requirements uncovered
   - Decisions made and their rationale
   - Errors encountered and how they were resolved
   - What approaches were tried that didn't work (and why)

4. **Next Steps**
   - Specific actions needed to complete the task
   - Any blockers or open questions to resolve
   - Priority order if multiple steps remain

5. **Context to Preserve**
   - User preferences or style requirements
   - Domain-specific details that aren't obvious
   - Any promises made to the user

Be concise but complete—err on the side of including information that would prevent duplicate work or repeated mistakes.
 Write in a way that enables immediate resumption of the task.

Wrap your summary in <summary></summary> tags."""

# Message history
messages = []

print("Chat with Claude (type 'quit' to exit, or just hit Enter to continue)")
print("This is a demonstration - try having a conversation and watch compaction trigger")
print("=" * 60)

# Simulate a conversation for demo purposes
demo_messages = [
    "Help me understand how Python decorators work",
    "Can you show me an example with a timing decorator?",
    "How would I make a decorator that takes arguments?",
]

for user_input in demo_messages:
    print(f"\nYou: {user_input}")

    # Add user message
    messages.append({"role": "user", "content": user_input})

    # Get Claude's response
    response = client.messages.create(
        model=MODEL,
        max_tokens=2048,
        messages=messages,
    )

    messages.append(
        {
            "role": "assistant",
            "content": response.content,
        }
    )

    print("\nClaude: ", end="")
    for block in response.content:
        if block.type == "text":
            print(f"{block.text[:300]} ...")

    # Check if we should compact
    usage = response.usage

    # Calculate total tokens (includes cache tokens)
    total_input_tokens = (
        usage.input_tokens
        + (usage.cache_creation_input_tokens or 0)
        + (usage.cache_read_input_tokens or 0)
    )
    total_tokens = total_input_tokens + usage.output_tokens

    cache_info = ""
    if usage.cache_creation_input_tokens or usage.cache_read_input_tokens:
        cache_info = f" (cache: {usage.cache_creation_input_tokens or 0} write + {usage.cache_read_input_tokens or 0} read)"

    print(
        f"\n[Tokens: {total_input_tokens} in{cache_info} + {usage.output_tokens} out = {total_tokens} total]"
    )

    if total_tokens > COMPACTION_THRESHOLD:
        print(f"\n{'=' * 60}")
        print(f"🔄 Compacting conversation... {len(messages)} messages → ", end="", flush=True)

        # Get summary using structured prompt
        summary_response = client.messages.create(
            model=MODEL,
            max_tokens=4096,
            messages=messages + [{"role": "user", "content": SUMMARY_PROMPT}],
        )

        summary_text = "".join(
            block.text for block in summary_response.content if block.type == "text"
        )

        # Replace history with summary
        messages = [{"role": "user", "content": summary_text}]

        print("1 message")
        print(f"{'=' * 60}\n")

print(f"Final conversation messages: {messages[-1].get('content')}")

print("\nDemo complete! In a real application, this loop would continue with user input.")
```

::: {.output .stream .stdout}
    Chat with Claude (type 'quit' to exit, or just hit Enter to continue)
    This is a demonstration - try having a conversation and watch compaction trigger
    ============================================================

    You: Help me understand how Python decorators work
:::
::::

::: {#b229j75wdjm .cell .markdown}
### Understanding the Chat Loop Pattern

The example above demonstrates manual compaction in a conversational
context. Here\'s how it works:

**Key Components**:

1.  **Token Tracking**: After each response, calculate total tokens
    (input + output + cache tokens)
2.  **Threshold Check**: When total exceeds threshold, trigger
    compaction
3.  **Summary Request**: Send the same structured SUMMARY_PROMPT to
    Claude
4.  **History Replacement**: Replace entire message history with just
    the summary
5.  **Continue**: Next user message builds on the summary, not full
    history

**When to Use This Pattern**:

- **Extended brainstorming sessions**: Users exploring ideas with Claude
  over many turns
- **Learning conversations**: Tutorials or explanations that span dozens
  of exchanges
- **Iterative refinement**: Users providing feedback on drafts, designs,
  or solutions
- **Chat applications**: Any multi-turn conversation interface

**Key Differences from Tool Runner**:

  ---------------------------------------------------------------------------
  Aspect         Tool Runner (Automatic)           Chat Loop (Manual)
  -------------- --------------------------------- --------------------------
  **Trigger**    Automatic when threshold reached  You implement threshold
                                                   check

  **Summary**    SDK handles summary request       You make explicit API call

  **History      SDK replaces messages             You manually replace list
  Management**                                     

  **Use Case**   Agentic workflows with tools      User-driven conversations
  ---------------------------------------------------------------------------

**Production Considerations**:

1.  **Adjust threshold**: Use larger thresholds for real applications
2.  **Customize summary prompt**: Tailor to your conversation type
    (brainstorming vs. technical support vs. tutoring)
3.  **Show user indicators**: Display a message like \"Summarizing
    conversation\...\" so users understand the pause
4.  **Preserve key context**: Ensure the summary prompt captures
    domain-specific information your users care about

This pattern gives you full control over when and how compaction
happens, making it ideal for conversational applications where the
SDK\'s automatic tool-runner compaction isn\'t available.
:::

::: {#d71dwo1dayp .cell .markdown}
## Limitations and Considerations

While automatic context compaction is powerful, there are important
limitations to understand:

### Server-Side Sampling Loops

**Current Limitation**: Compaction does not work optimally with
server-side sampling loops, such as server-side web search tools.

**Why**: Cache tokens accumulate across sampling loops, which can
trigger compaction prematurely based on cached content rather than
actual conversation history.

This feature works best with:

- ✅ Client-side tools (like the customer service API in this cookbook)
- ✅ Standard agentic workflows with regular tool use
- ✅ File operations, database queries, API calls
- ❌ Server-side Extended Thinking
- ❌ Server-side web search tools

### Information Loss

**Trade-off**: Summaries inherently lose some information. While Claude
is good at identifying key points, some details will be compressed or
omitted.

**In ticket processing**:

- ✅ **Retained**: Ticket IDs, categories, priorities, teams, outcomes,
  progress status
- ❌ **Lost**: Full knowledge base article text, complete drafted
  response text, detailed classification reasoning

This is usually acceptable, you don\'t need every KB article and full
response text in perpetuity, just the completion records.

**Mitigation**:

- Use custom summary prompts to preserve critical information
- Set higher thresholds for tasks requiring extensive historical context
- Structure your tasks to be modular (each phase builds on summaries,
  not raw details)

### When NOT to Use Compaction

Avoid compaction for:

1.  **Short tasks**: If your task completes within 50k-100k tokens,
    compaction adds unnecessary overhead
2.  **Tasks requiring full audit trails**: Some tasks need access to ALL
    previous details
3.  **Server-side sampling workflows**: As mentioned above, wait for
    this limitation to be addressed
4.  **Highly iterative refinement**: Tasks where each step critically
    depends on exact details from all previous steps

### When TO Use Compaction

Compaction is ideal for:

1.  **Sequential processing**: Like our ticket workflow---process
    multiple items one after another
2.  **Multi-phase workflows**: Where each phase can summarize progress
    before moving on
3.  **Iterative data processing**: Processing large datasets in chunks
    or entities one at a time
4.  **Extended analysis sessions**: Analyzing data across many entities
5.  **Batch operations**: Processing hundreds of items where each is
    independent

**Ticket processing is a perfect use case** because:

- Each ticket workflow is largely independent
- You need completion summaries, not full tool results
- Natural compaction points exist (after completing several tickets)
- The workflow is iterative and sequential
:::

::: {#b4pz1jmdidi .cell .markdown}
## Summary

Automatic context compaction is a powerful feature that enables
long-running agentic workflows to exceed typical context limits. In this
cookbook, we\'ve explored compaction through a customer service ticket
processing workflow.

### Next Steps

Try implementing compaction in your own workflows:

1.  Identify natural compaction points (after processing each item,
    completing each phase, etc.)
2.  Start with an aggressive threshold (5k-10k) if you have clear
    per-item boundaries
3.  Use custom summary prompts to preserve critical information
4.  Monitor when compaction triggers and verify quality is maintained
5.  Adjust threshold based on your specific needs

For more on effective context management, see [Effective Context
Engineering for AI
Agents](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents).
:::


---
## best-practices-5fdbbed47a.md

> ## Documentation Index
> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Best Practices for Claude Code

> Tips and patterns for getting the most out of Claude Code, from configuring your environment to scaling across parallel sessions.

Claude Code is an agentic coding environment. Unlike a chatbot that answers questions and waits, Claude Code can read your files, run commands, make changes, and autonomously work through problems while you watch, redirect, or step away entirely.

This changes how you work. Instead of writing code yourself and asking Claude to review it, you describe what you want and Claude figures out how to build it. Claude explores, plans, and implements.

But this autonomy still comes with a learning curve. Claude works within certain constraints you need to understand.

This guide covers patterns that have proven effective across Anthropic's internal teams and for engineers using Claude Code across various codebases, languages, and environments. For how the agentic loop works under the hood, see [How Claude Code works](how-claude-code-works-0871be411d.md).

***

Most best practices are based on one constraint: Claude's context window fills up fast, and performance degrades as it fills.

Claude's context window holds your entire conversation, including every message, every file Claude reads, and every command output. However, this can fill up fast. A single debugging session or codebase exploration might generate and consume tens of thousands of tokens.

This matters since LLM performance degrades as context fills. When the context window is getting full, Claude may start "forgetting" earlier instructions or making more mistakes. The context window is the most important resource to manage. To see how a session fills up in practice, [watch an interactive walkthrough](context-window-d266068204.md) of what loads at startup and what each file read costs. Track context usage continuously with a [custom status line](customize-your-status-line-claude-code-docs-8a9fc80be1.md), and see [Reduce token usage](/en/costs#reduce-token-usage) for strategies on reducing token usage.

***

## Give Claude a way to verify its work

<Tip>
  Include tests, screenshots, or expected outputs so Claude can check itself. This is the single highest-leverage thing you can do.
</Tip>

Claude performs dramatically better when it can verify its own work, like run tests, compare screenshots, and validate outputs.

Without clear success criteria, it might produce something that looks right but actually doesn't work. You become the only feedback loop, and every mistake requires your attention.

| Strategy                              | Before                                                  | After                                                                                                                                                                                                   |
| ------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Provide verification criteria**     | *"implement a function that validates email addresses"* | *"write a validateEmail function. example test cases: [user@example.com](mailto:user@example.com) is true, invalid is false, [user@.com](mailto:user@.com) is false. run the tests after implementing"* |
| **Verify UI changes visually**        | *"make the dashboard look better"*                      | *"\[paste screenshot] implement this design. take a screenshot of the result and compare it to the original. list differences and fix them"*                                                            |
| **Address root causes, not symptoms** | *"the build is failing"*                                | *"the build fails with this error: \[paste error]. fix it and verify the build succeeds. address the root cause, don't suppress the error"*                                                             |

UI changes can be verified using the [Claude in Chrome extension](../03-IDE-Integrations/use-claude-code-with-chrome-beta-claude-code-docs-4f2f5a5a96.md). It opens new tabs in your browser, tests the UI, and iterates until the code works.

Your verification can also be a test suite, a linter, or a Bash command that checks output. Invest in making your verification rock-solid.

***

## Explore first, then plan, then code

<Tip>
  Separate research and planning from implementation to avoid solving the wrong problem.
</Tip>

Letting Claude jump straight to coding can produce code that solves the wrong problem. Use [Plan Mode](/en/common-workflows#use-plan-mode-for-safe-code-analysis) to separate exploration from execution.

The recommended workflow has four phases:

<Steps>
  <Step title="Explore">
    Enter Plan Mode. Claude reads files and answers questions without making changes.

    ```txt claude (Plan Mode) theme={null}
    read /src/auth and understand how we handle sessions and login.
    also look at how we manage environment variables for secrets.
    ```
  </Step>

  <Step title="Plan">
    Ask Claude to create a detailed implementation plan.

    ```txt claude (Plan Mode) theme={null}
    I want to add Google OAuth. What files need to change?
    What's the session flow? Create a plan.
    ```

    Press `Ctrl+G` to open the plan in your text editor for direct editing before Claude proceeds.
  </Step>

  <Step title="Implement">
    Switch back to Normal Mode and let Claude code, verifying against its plan.

    ```txt claude (Normal Mode) theme={null}
    implement the OAuth flow from your plan. write tests for the
    callback handler, run the test suite and fix any failures.
    ```
  </Step>

  <Step title="Commit">
    Ask Claude to commit with a descriptive message and create a PR.

    ```txt claude (Normal Mode) theme={null}
    commit with a descriptive message and open a PR
    ```
  </Step>
</Steps>

<Callout>
  Plan Mode is useful, but also adds overhead.

  For tasks where the scope is clear and the fix is small (like fixing a typo, adding a log line, or renaming a variable) ask Claude to do it directly.

  Planning is most useful when you're uncertain about the approach, when the change modifies multiple files, or when you're unfamiliar with the code being modified. If you could describe the diff in one sentence, skip the plan.
</Callout>

***

## Provide specific context in your prompts

<Tip>
  The more precise your instructions, the fewer corrections you'll need.
</Tip>

Claude can infer intent, but it can't read your mind. Reference specific files, mention constraints, and point to example patterns.

| Strategy                                                                                         | Before                                               | After                                                                                                                                                                                                                                                                                                                                                            |
| ------------------------------------------------------------------------------------------------ | ---------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Scope the task.** Specify which file, what scenario, and testing preferences.                  | *"add tests for foo.py"*                             | *"write a test for foo.py covering the edge case where the user is logged out. avoid mocks."*                                                                                                                                                                                                                                                                    |
| **Point to sources.** Direct Claude to the source that can answer a question.                    | *"why does ExecutionFactory have such a weird api?"* | *"look through ExecutionFactory's git history and summarize how its api came to be"*                                                                                                                                                                                                                                                                             |
| **Reference existing patterns.** Point Claude to patterns in your codebase.                      | *"add a calendar widget"*                            | *"look at how existing widgets are implemented on the home page to understand the patterns. HotDogWidget.php is a good example. follow the pattern to implement a new calendar widget that lets the user select a month and paginate forwards/backwards to pick a year. build from scratch without libraries other than the ones already used in the codebase."* |
| **Describe the symptom.** Provide the symptom, the likely location, and what "fixed" looks like. | *"fix the login bug"*                                | *"users report that login fails after session timeout. check the auth flow in src/auth/, especially token refresh. write a failing test that reproduces the issue, then fix it"*                                                                                                                                                                                 |

Vague prompts can be useful when you're exploring and can afford to course-correct. A prompt like `"what would you improve in this file?"` can surface things you wouldn't have thought to ask about.

### Provide rich content

<Tip>
  Use `@` to reference files, paste screenshots/images, or pipe data directly.
</Tip>

You can provide rich data to Claude in several ways:

* **Reference files with `@`** instead of describing where code lives. Claude reads the file before responding.
* **Paste images directly**. Copy/paste or drag and drop images into the prompt.
* **Give URLs** for documentation and API references. Use `/permissions` to allowlist frequently-used domains.
* **Pipe in data** by running `cat error.log | claude` to send file contents directly.
* **Let Claude fetch what it needs**. Tell Claude to pull context itself using Bash commands, MCP tools, or by reading files.

***

## Configure your environment

A few setup steps make Claude Code significantly more effective across all your sessions. For a full overview of extension features and when to use each one, see [Extend Claude Code](extend-claude-code-claude-code-docs-3b35aaf641.md).

### Write an effective CLAUDE.md

<Tip>
  Run `/init` to generate a starter CLAUDE.md file based on your current project structure, then refine over time.
</Tip>

CLAUDE.md is a special file that Claude reads at the start of every conversation. Include Bash commands, code style, and workflow rules. This gives Claude persistent context it can't infer from code alone.

The `/init` command analyzes your codebase to detect build systems, test frameworks, and code patterns, giving you a solid foundation to refine.

There's no required format for CLAUDE.md files, but keep it short and human-readable. For example:

```markdown CLAUDE.md theme={null}
# Code style
- Use ES modules (import/export) syntax, not CommonJS (require)
- Destructure imports when possible (eg. import { foo } from 'bar')

# Workflow
- Be sure to typecheck when you're done making a series of code changes
- Prefer running single tests, and not the whole test suite, for performance
```

CLAUDE.md is loaded every session, so only include things that apply broadly. For domain knowledge or workflows that are only relevant sometimes, use [skills](../08-Plugins-Skills/extend-claude-with-skills-claude-code-docs.md) instead. Claude loads them on demand without bloating every conversation.

Keep it concise. For each line, ask: *"Would removing this cause Claude to make mistakes?"* If not, cut it. Bloated CLAUDE.md files cause Claude to ignore your actual instructions!

| ✅ Include                                            | ❌ Exclude                                          |
| ---------------------------------------------------- | -------------------------------------------------- |
| Bash commands Claude can't guess                     | Anything Claude can figure out by reading code     |
| Code style rules that differ from defaults           | Standard language conventions Claude already knows |
| Testing instructions and preferred test runners      | Detailed API documentation (link to docs instead)  |
| Repository etiquette (branch naming, PR conventions) | Information that changes frequently                |
| Architectural decisions specific to your project     | Long explanations or tutorials                     |
| Developer environment quirks (required env vars)     | File-by-file descriptions of the codebase          |
| Common gotchas or non-obvious behaviors              | Self-evident practices like "write clean code"     |

If Claude keeps doing something you don't want despite having a rule against it, the file is probably too long and the rule is getting lost. If Claude asks you questions that are answered in CLAUDE.md, the phrasing might be ambiguous. Treat CLAUDE.md like code: review it when things go wrong, prune it regularly, and test changes by observing whether Claude's behavior actually shifts.

You can tune instructions by adding emphasis (e.g., "IMPORTANT" or "YOU MUST") to improve adherence. Check CLAUDE.md into git so your team can contribute. The file compounds in value over time.

CLAUDE.md files can import additional files using `@path/to/import` syntax:

```markdown CLAUDE.md theme={null}
See @README.md for project overview and @package.json for available npm commands.

# Additional Instructions
- Git workflow: @docs/git-instructions.md
- Personal overrides: @~/.claude/my-project-instructions.md
```

You can place CLAUDE.md files in several locations:

* **Home folder (`~/.claude/CLAUDE.md`)**: applies to all Claude sessions
* **Project root (`./CLAUDE.md`)**: check into git to share with your team
* **Project root (`./CLAUDE.local.md`)**: personal project-specific notes; add this file to your `.gitignore` so it isn't shared with your team
* **Parent directories**: useful for monorepos where both `root/CLAUDE.md` and `root/foo/CLAUDE.md` are pulled in automatically
* **Child directories**: Claude pulls in child CLAUDE.md files on demand when working with files in those directories

### Configure permissions

<Tip>
  Use [auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) to let a classifier handle approvals, `/permissions` to allowlist specific commands, or `/sandbox` for OS-level isolation. Each reduces interruptions while keeping you in control.
</Tip>

By default, Claude Code requests permission for actions that might modify your system: file writes, Bash commands, MCP tools, etc. This is safe but tedious. After the tenth approval you're not really reviewing anymore, you're just clicking through. There are three ways to reduce these interruptions:

* **Auto mode**: a separate classifier model reviews commands and blocks only what looks risky: scope escalation, unknown infrastructure, or hostile-content-driven actions. Best when you trust the general direction of a task but don't want to click through every step
* **Permission allowlists**: permit specific tools you know are safe, like `npm run lint` or `git commit`
* **Sandboxing**: enable OS-level isolation that restricts filesystem and network access, allowing Claude to work more freely within defined boundaries

Read more about [permission modes](permission-modes-c83d6eff7e.md), [permission rules](configure-permissions-claude-code-docs-7b0e64d485.md), and [sandboxing](../22-Safety-Policy/sandboxing-claude-code-docs-5f97cd27c4.md).

### Use CLI tools

<Tip>
  Tell Claude Code to use CLI tools like `gh`, `aws`, `gcloud`, and `sentry-cli` when interacting with external services.
</Tip>

CLI tools are the most context-efficient way to interact with external services. If you use GitHub, install the `gh` CLI. Claude knows how to use it for creating issues, opening pull requests, and reading comments. Without `gh`, Claude can still use the GitHub API, but unauthenticated requests often hit rate limits.

Claude is also effective at learning CLI tools it doesn't already know. Try prompts like `Use 'foo-cli-tool --help' to learn about foo tool, then use it to solve A, B, C.`

### Connect MCP servers

<Tip>
  Run `claude mcp add` to connect external tools like Notion, Figma, or your database.
</Tip>

With [MCP servers](../06-MCP-Tools/mcp-208e742686.md), you can ask Claude to implement features from issue trackers, query databases, analyze monitoring data, integrate designs from Figma, and automate workflows.

### Set up hooks

<Tip>
  Use hooks for actions that must happen every time with zero exceptions.
</Tip>

[Hooks](../07-Hooks/automate-workflows-with-hooks-claude-code-docs-e843f93261.md) run scripts automatically at specific points in Claude's workflow. Unlike CLAUDE.md instructions which are advisory, hooks are deterministic and guarantee the action happens.

Claude can write hooks for you. Try prompts like *"Write a hook that runs eslint after every file edit"* or *"Write a hook that blocks writes to the migrations folder."* Edit `.claude/settings.json` directly to configure hooks by hand, and run `/hooks` to browse what's configured.

### Create skills

<Tip>
  Create `SKILL.md` files in `.claude/skills/` to give Claude domain knowledge and reusable workflows.
</Tip>

[Skills](../08-Plugins-Skills/extend-claude-with-skills-claude-code-docs.md) extend Claude's knowledge with information specific to your project, team, or domain. Claude applies them automatically when relevant, or you can invoke them directly with `/skill-name`.

Create a skill by adding a directory with a `SKILL.md` to `.claude/skills/`:

```markdown .claude/skills/api-conventions/SKILL.md theme={null}
---
name: api-conventions
description: REST API design conventions for our services
---
# API Conventions
- Use kebab-case for URL paths
- Use camelCase for JSON properties
- Always include pagination for list endpoints
- Version APIs in the URL path (/v1/, /v2/)
```

Skills can also define repeatable workflows you invoke directly:

```markdown .claude/skills/fix-issue/SKILL.md theme={null}
---
name: fix-issue
description: Fix a GitHub issue
disable-model-invocation: true
---
Analyze and fix the GitHub issue: $ARGUMENTS.

1. Use `gh issue view` to get the issue details
2. Understand the problem described in the issue
3. Search the codebase for relevant files
4. Implement the necessary changes to fix the issue
5. Write and run tests to verify the fix
6. Ensure code passes linting and type checking
7. Create a descriptive commit message
8. Push and create a PR
```

Run `/fix-issue 1234` to invoke it. Use `disable-model-invocation: true` for workflows with side effects that you want to trigger manually.

### Create custom subagents

<Tip>
  Define specialized assistants in `.claude/agents/` that Claude can delegate to for isolated tasks.
</Tip>

[Subagents](../09-Agents-Patterns/create-custom-subagents-claude-code-docs-7dc93e85c0.md) run in their own context with their own set of allowed tools. They're useful for tasks that read many files or need specialized focus without cluttering your main conversation.

```markdown .claude/agents/security-reviewer.md theme={null}
---
name: security-reviewer
description: Reviews code for security vulnerabilities
tools: Read, Grep, Glob, Bash
model: opus
---
You are a senior security engineer. Review code for:
- Injection vulnerabilities (SQL, XSS, command injection)
- Authentication and authorization flaws
- Secrets or credentials in code
- Insecure data handling

Provide specific line references and suggested fixes.
```

Tell Claude to use subagents explicitly: *"Use a subagent to review this code for security issues."*

### Install plugins

<Tip>
  Run `/plugin` to browse the marketplace. Plugins add skills, tools, and integrations without configuration.
</Tip>

[Plugins](../08-Plugins-Skills/create-plugins-claude-code-docs.md) bundle skills, hooks, subagents, and MCP servers into a single installable unit from the community and Anthropic. If you work with a typed language, install a [code intelligence plugin](/en/discover-plugins#code-intelligence) to give Claude precise symbol navigation and automatic error detection after edits.

For guidance on choosing between skills, subagents, hooks, and MCP, see [Extend Claude Code](/en/features-overview#match-features-to-your-goal).

***

## Communicate effectively

The way you communicate with Claude Code significantly impacts the quality of results.

### Ask codebase questions

<Tip>
  Ask Claude questions you'd ask a senior engineer.
</Tip>

When onboarding to a new codebase, use Claude Code for learning and exploration. You can ask Claude the same sorts of questions you would ask another engineer:

* How does logging work?
* How do I make a new API endpoint?
* What does `async move { ... }` do on line 134 of `foo.rs`?
* What edge cases does `CustomerOnboardingFlowImpl` handle?
* Why does this code call `foo()` instead of `bar()` on line 333?

Using Claude Code this way is an effective onboarding workflow, improving ramp-up time and reducing load on other engineers. No special prompting required: ask questions directly.

### Let Claude interview you

<Tip>
  For larger features, have Claude interview you first. Start with a minimal prompt and ask Claude to interview you using the `AskUserQuestion` tool.
</Tip>

Claude asks about things you might not have considered yet, including technical implementation, UI/UX, edge cases, and tradeoffs.

```text theme={null}
I want to build [brief description]. Interview me in detail using the AskUserQuestion tool.

Ask about technical implementation, UI/UX, edge cases, concerns, and tradeoffs. Don't ask obvious questions, dig into the hard parts I might not have considered.

Keep interviewing until we've covered everything, then write a complete spec to SPEC.md.
```

Once the spec is complete, start a fresh session to execute it. The new session has clean context focused entirely on implementation, and you have a written spec to reference.

***

## Manage your session

Conversations are persistent and reversible. Use this to your advantage!

### Course-correct early and often

<Tip>
  Correct Claude as soon as you notice it going off track.
</Tip>

The best results come from tight feedback loops. Though Claude occasionally solves problems perfectly on the first attempt, correcting it quickly generally produces better solutions faster.

* **`Esc`**: stop Claude mid-action with the `Esc` key. Context is preserved, so you can redirect.
* **`Esc + Esc` or `/rewind`**: press `Esc` twice or run `/rewind` to open the rewind menu and restore previous conversation and code state, or summarize from a selected message.
* **`"Undo that"`**: have Claude revert its changes.
* **`/clear`**: reset context between unrelated tasks. Long sessions with irrelevant context can reduce performance.

If you've corrected Claude more than twice on the same issue in one session, the context is cluttered with failed approaches. Run `/clear` and start fresh with a more specific prompt that incorporates what you learned. A clean session with a better prompt almost always outperforms a long session with accumulated corrections.

### Manage context aggressively

<Tip>
  Run `/clear` between unrelated tasks to reset context.
</Tip>

Claude Code automatically compacts conversation history when you approach context limits, which preserves important code and decisions while freeing space.

During long sessions, Claude's context window can fill with irrelevant conversation, file contents, and commands. This can reduce performance and sometimes distract Claude.

* Use `/clear` frequently between tasks to reset the context window entirely
* When auto compaction triggers, Claude summarizes what matters most, including code patterns, file states, and key decisions
* For more control, run `/compact <instructions>`, like `/compact Focus on the API changes`
* To compact only part of the conversation, use `Esc + Esc` or `/rewind`, select a message checkpoint, and choose **Summarize from here**. This condenses messages from that point forward while keeping earlier context intact.
* Customize compaction behavior in CLAUDE.md with instructions like `"When compacting, always preserve the full list of modified files and any test commands"` to ensure critical context survives summarization
* For quick questions that don't need to stay in context, use [`/btw`](/en/interactive-mode#side-questions-with-%2Fbtw). The answer appears in a dismissible overlay and never enters conversation history, so you can check a detail without growing context.

### Use subagents for investigation

<Tip>
  Delegate research with `"use subagents to investigate X"`. They explore in a separate context, keeping your main conversation clean for implementation.
</Tip>

Since context is your fundamental constraint, subagents are one of the most powerful tools available. When Claude researches a codebase it reads lots of files, all of which consume your context. Subagents run in separate context windows and report back summaries:

```text theme={null}
Use subagents to investigate how our authentication system handles token
refresh, and whether we have any existing OAuth utilities I should reuse.
```

The subagent explores the codebase, reads relevant files, and reports back with findings, all without cluttering your main conversation.

You can also use subagents for verification after Claude implements something:

```text theme={null}
use a subagent to review this code for edge cases
```

### Rewind with checkpoints

<Tip>
  Every action Claude makes creates a checkpoint. You can restore conversation, code, or both to any previous checkpoint.
</Tip>

Claude automatically checkpoints before changes. Double-tap `Escape` or run `/rewind` to open the rewind menu. You can restore conversation only, restore code only, restore both, or summarize from a selected message. See [Checkpointing](checkpointing-94f7cd24eb.md) for details.

Instead of carefully planning every move, you can tell Claude to try something risky. If it doesn't work, rewind and try a different approach. Checkpoints persist across sessions, so you can close your terminal and still rewind later.

<Warning>
  Checkpoints only track changes made *by Claude*, not external processes. This isn't a replacement for git.
</Warning>

### Resume conversations

<Tip>
  Run `claude --continue` to pick up where you left off, or `--resume` to choose from recent sessions.
</Tip>

Claude Code saves conversations locally. When a task spans multiple sessions, you don't have to re-explain the context:

```bash theme={null}
claude --continue    # Resume the most recent conversation
claude --resume      # Select from recent conversations
```

Use `/rename` to give sessions descriptive names like `"oauth-migration"` or `"debugging-memory-leak"` so you can find them later. Treat sessions like branches: different workstreams can have separate, persistent contexts.

***

## Automate and scale

Once you're effective with one Claude, multiply your output with parallel sessions, non-interactive mode, and fan-out patterns.

Everything so far assumes one human, one Claude, and one conversation. But Claude Code scales horizontally. The techniques in this section show how you can get more done.

### Run non-interactive mode

<Tip>
  Use `claude -p "prompt"` in CI, pre-commit hooks, or scripts. Add `--output-format stream-json` for streaming JSON output.
</Tip>

With `claude -p "your prompt"`, you can run Claude non-interactively, without a session. Non-interactive mode is how you integrate Claude into CI pipelines, pre-commit hooks, or any automated workflow. The output formats let you parse results programmatically: plain text, JSON, or streaming JSON.

```bash theme={null}
# One-off queries
claude -p "Explain what this project does"

# Structured output for scripts
claude -p "List all API endpoints" --output-format json

# Streaming for real-time processing
claude -p "Analyze this log file" --output-format stream-json
```

### Run multiple Claude sessions

<Tip>
  Run multiple Claude sessions in parallel to speed up development, run isolated experiments, or start complex workflows.
</Tip>

There are three main ways to run parallel sessions:

* [Claude Code desktop app](/en/desktop#work-in-parallel-with-sessions): Manage multiple local sessions visually. Each session gets its own isolated worktree.
* [Claude Code on the web](claude-code-on-the-web-69d53821d4.md): Run on Anthropic's secure cloud infrastructure in isolated VMs.
* [Agent teams](../09-Agents-Patterns/agent-teams-e29da6ed1b.md): Automated coordination of multiple sessions with shared tasks, messaging, and a team lead.

Beyond parallelizing work, multiple sessions enable quality-focused workflows. A fresh context improves code review since Claude won't be biased toward code it just wrote.

For example, use a Writer/Reviewer pattern:

| Session A (Writer)                                                      | Session B (Reviewer)                                                                                                                                                     |
| ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `Implement a rate limiter for our API endpoints`                        |                                                                                                                                                                          |
|                                                                         | `Review the rate limiter implementation in @src/middleware/rateLimiter.ts. Look for edge cases, race conditions, and consistency with our existing middleware patterns.` |
| `Here's the review feedback: [Session B output]. Address these issues.` |                                                                                                                                                                          |

You can do something similar with tests: have one Claude write tests, then another write code to pass them.

### Fan out across files

<Tip>
  Loop through tasks calling `claude -p` for each. Use `--allowedTools` to scope permissions for batch operations.
</Tip>

For large migrations or analyses, you can distribute work across many parallel Claude invocations:

<Steps>
  <Step title="Generate a task list">
    Have Claude list all files that need migrating (e.g., `list all 2,000 Python files that need migrating`)
  </Step>

  <Step title="Write a script to loop through the list">
    ```bash theme={null}
    for file in $(cat files.txt); do
      claude -p "Migrate $file from React to Vue. Return OK or FAIL." \
        --allowedTools "Edit,Bash(git commit *)"
    done
    ```
  </Step>

  <Step title="Test on a few files, then run at scale">
    Refine your prompt based on what goes wrong with the first 2-3 files, then run on the full set. The `--allowedTools` flag restricts what Claude can do, which matters when you're running unattended.
  </Step>
</Steps>

You can also integrate Claude into existing data/processing pipelines:

```bash theme={null}
claude -p "<your prompt>" --output-format json | your_command
```

Use `--verbose` for debugging during development, and turn it off in production.

### Run autonomously with auto mode

For uninterrupted execution with background safety checks, use [auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode). A classifier model reviews commands before they run, blocking scope escalation, unknown infrastructure, and hostile-content-driven actions while letting routine work proceed without prompts.

```bash theme={null}
claude --permission-mode auto -p "fix all lint errors"
```

For non-interactive runs with the `-p` flag, auto mode aborts if the classifier repeatedly blocks actions, since there is no user to fall back to. See [when auto mode falls back](/en/permission-modes#when-auto-mode-falls-back) for thresholds.

***

## Avoid common failure patterns

These are common mistakes. Recognizing them early saves time:

* **The kitchen sink session.** You start with one task, then ask Claude something unrelated, then go back to the first task. Context is full of irrelevant information.
  > **Fix**: `/clear` between unrelated tasks.
* **Correcting over and over.** Claude does something wrong, you correct it, it's still wrong, you correct again. Context is polluted with failed approaches.
  > **Fix**: After two failed corrections, `/clear` and write a better initial prompt incorporating what you learned.
* **The over-specified CLAUDE.md.** If your CLAUDE.md is too long, Claude ignores half of it because important rules get lost in the noise.
  > **Fix**: Ruthlessly prune. If Claude already does something correctly without the instruction, delete it or convert it to a hook.
* **The trust-then-verify gap.** Claude produces a plausible-looking implementation that doesn't handle edge cases.
  > **Fix**: Always provide verification (tests, scripts, screenshots). If you can't verify it, don't ship it.
* **The infinite exploration.** You ask Claude to "investigate" something without scoping it. Claude reads hundreds of files, filling the context.
  > **Fix**: Scope investigations narrowly or use subagents so the exploration doesn't consume your main context.

***

## Develop your intuition

The patterns in this guide aren't set in stone. They're starting points that work well in general, but might not be optimal for every situation.

Sometimes you *should* let context accumulate because you're deep in one complex problem and the history is valuable. Sometimes you should skip planning and let Claude figure it out because the task is exploratory. Sometimes a vague prompt is exactly right because you want to see how Claude interprets the problem before constraining it.

Pay attention to what works. When Claude produces great output, notice what you did: the prompt structure, the context you provided, the mode you were in. When Claude struggles, ask why. Was the context too noisy? The prompt too vague? The task too big for one pass?

Over time, you'll develop intuition that no guide can capture. You'll know when to be specific and when to be open-ended, when to plan and when to explore, when to clear context and when to let it accumulate.

## Related resources

* [How Claude Code works](how-claude-code-works-0871be411d.md): the agentic loop, tools, and context management
* [Extend Claude Code](extend-claude-code-claude-code-docs-3b35aaf641.md): skills, hooks, MCP, subagents, and plugins
* [Common workflows](common-workflows-c909406123.md): step-by-step recipes for debugging, testing, PRs, and more
* [CLAUDE.md](how-claude-remembers-your-project-claude-code-docs-f1c064262d.md): store project conventions and persistent context


---
## best-practices.md

> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Best Practices for Claude Code

> Tips and patterns for getting the most out of Claude Code, from configuring your environment to scaling across parallel sessions.

Claude Code is an agentic coding environment. Unlike a chatbot that answers questions and waits, Claude Code can read your files, run commands, make changes, and autonomously work through problems while you watch, redirect, or step away entirely.

This changes how you work. Instead of writing code yourself and asking Claude to review it, you describe what you want and Claude figures out how to build it. Claude explores, plans, and implements.

But this autonomy still comes with a learning curve. Claude works within certain constraints you need to understand.

This guide covers patterns that have proven effective across Anthropic's internal teams and for engineers using Claude Code across various codebases, languages, and environments. For how the agentic loop works under the hood, see [How Claude Code works](how-claude-code-works-0871be411d.md).

***

Most best practices are based on one constraint: Claude's context window fills up fast, and performance degrades as it fills.

Claude's context window holds your entire conversation, including every message, every file Claude reads, and every command output. However, this can fill up fast. A single debugging session or codebase exploration might generate and consume tens of thousands of tokens.

This matters since LLM performance degrades as context fills. When the context window is getting full, Claude may start "forgetting" earlier instructions or making more mistakes. The context window is the most important resource to manage. For detailed strategies on reducing token usage, see [Reduce token usage](/en/costs#reduce-token-usage).

***

## Give Claude a way to verify its work

<Tip>
  Include tests, screenshots, or expected outputs so Claude can check itself. This is the single highest-leverage thing you can do.
</Tip>

Claude performs dramatically better when it can verify its own work, like run tests, compare screenshots, and validate outputs.

Without clear success criteria, it might produce something that looks right but actually doesn't work. You become the only feedback loop, and every mistake requires your attention.

| Strategy                              | Before                                                  | After                                                                                                                                                                                                   |
| ------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Provide verification criteria**     | *"implement a function that validates email addresses"* | *"write a validateEmail function. example test cases: [user@example.com](mailto:user@example.com) is true, invalid is false, [user@.com](mailto:user@.com) is false. run the tests after implementing"* |
| **Verify UI changes visually**        | *"make the dashboard look better"*                      | *"\[paste screenshot] implement this design. take a screenshot of the result and compare it to the original. list differences and fix them"*                                                            |
| **Address root causes, not symptoms** | *"the build is failing"*                                | *"the build fails with this error: \[paste error]. fix it and verify the build succeeds. address the root cause, don't suppress the error"*                                                             |

UI changes can be verified using the [Claude in Chrome extension](chrome.md). It opens a browser, tests the UI, and iterates until the code works.

Your verification can also be a test suite, a linter, or a Bash command that checks output. Invest in making your verification rock-solid.

***

## Explore first, then plan, then code

<Tip>
  Separate research and planning from implementation to avoid solving the wrong problem.
</Tip>

Letting Claude jump straight to coding can produce code that solves the wrong problem. Use [Plan Mode](/en/common-workflows#use-plan-mode-for-safe-code-analysis) to separate exploration from execution.

The recommended workflow has four phases:

<Steps>
  <Step title="Explore">
    Enter Plan Mode. Claude reads files and answers questions without making changes.

    ```txt claude (Plan Mode) theme={null}
    read /src/auth and understand how we handle sessions and login.
    also look at how we manage environment variables for secrets.
    ```
  </Step>

  <Step title="Plan">
    Ask Claude to create a detailed implementation plan.

    ```txt claude (Plan Mode) theme={null}
    I want to add Google OAuth. What files need to change?
    What's the session flow? Create a plan.
    ```

    Press `Ctrl+G` to open the plan in your text editor for direct editing before Claude proceeds.
  </Step>

  <Step title="Implement">
    Switch back to Normal Mode and let Claude code, verifying against its plan.

    ```txt claude (Normal Mode) theme={null}
    implement the OAuth flow from your plan. write tests for the
    callback handler, run the test suite and fix any failures.
    ```
  </Step>

  <Step title="Commit">
    Ask Claude to commit with a descriptive message and create a PR.

    ```txt claude (Normal Mode) theme={null}
    commit with a descriptive message and open a PR
    ```
  </Step>
</Steps>

<Callout>
  Plan Mode is useful, but also adds overhead.

  For tasks where the scope is clear and the fix is small (like fixing a typo, adding a log line, or renaming a variable) ask Claude to do it directly.

  Planning is most useful when you're uncertain about the approach, when the change modifies multiple files, or when you're unfamiliar with the code being modified. If you could describe the diff in one sentence, skip the plan.
</Callout>

***

## Provide specific context in your prompts

<Tip>
  The more precise your instructions, the fewer corrections you'll need.
</Tip>

Claude can infer intent, but it can't read your mind. Reference specific files, mention constraints, and point to example patterns.

| Strategy                                                                                         | Before                                               | After                                                                                                                                                                                                                                                                                                                                                            |
| ------------------------------------------------------------------------------------------------ | ---------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Scope the task.** Specify which file, what scenario, and testing preferences.                  | *"add tests for foo.py"*                             | *"write a test for foo.py covering the edge case where the user is logged out. avoid mocks."*                                                                                                                                                                                                                                                                    |
| **Point to sources.** Direct Claude to the source that can answer a question.                    | *"why does ExecutionFactory have such a weird api?"* | *"look through ExecutionFactory's git history and summarize how its api came to be"*                                                                                                                                                                                                                                                                             |
| **Reference existing patterns.** Point Claude to patterns in your codebase.                      | *"add a calendar widget"*                            | *"look at how existing widgets are implemented on the home page to understand the patterns. HotDogWidget.php is a good example. follow the pattern to implement a new calendar widget that lets the user select a month and paginate forwards/backwards to pick a year. build from scratch without libraries other than the ones already used in the codebase."* |
| **Describe the symptom.** Provide the symptom, the likely location, and what "fixed" looks like. | *"fix the login bug"*                                | *"users report that login fails after session timeout. check the auth flow in src/auth/, especially token refresh. write a failing test that reproduces the issue, then fix it"*                                                                                                                                                                                 |

Vague prompts can be useful when you're exploring and can afford to course-correct. A prompt like `"what would you improve in this file?"` can surface things you wouldn't have thought to ask about.

### Provide rich content

<Tip>
  Use `@` to reference files, paste screenshots/images, or pipe data directly.
</Tip>

You can provide rich data to Claude in several ways:

* **Reference files with `@`** instead of describing where code lives. Claude reads the file before responding.
* **Paste images directly**. Copy/paste or drag and drop images into the prompt.
* **Give URLs** for documentation and API references. Use `/permissions` to allowlist frequently-used domains.
* **Pipe in data** by running `cat error.log | claude` to send file contents directly.
* **Let Claude fetch what it needs**. Tell Claude to pull context itself using Bash commands, MCP tools, or by reading files.

***

## Configure your environment

A few setup steps make Claude Code significantly more effective across all your sessions. For a full overview of extension features and when to use each one, see [Extend Claude Code](extend-claude-code-claude-code-docs-3b35aaf641.md).

### Write an effective CLAUDE.md

<Tip>
  Run `/init` to generate a starter CLAUDE.md file based on your current project structure, then refine over time.
</Tip>

CLAUDE.md is a special file that Claude reads at the start of every conversation. Include Bash commands, code style, and workflow rules. This gives Claude persistent context **it can't infer from code alone**.

The `/init` command analyzes your codebase to detect build systems, test frameworks, and code patterns, giving you a solid foundation to refine.

There's no required format for CLAUDE.md files, but keep it short and human-readable. For example:

```markdown CLAUDE.md theme={null}
# Code style
- Use ES modules (import/export) syntax, not CommonJS (require)
- Destructure imports when possible (eg. import { foo } from 'bar')

# Workflow
- Be sure to typecheck when you're done making a series of code changes
- Prefer running single tests, and not the whole test suite, for performance
```

CLAUDE.md is loaded every session, so only include things that apply broadly. For domain knowledge or workflows that are only relevant sometimes, use [skills](../08-Plugins-Skills/extend-claude-with-skills-claude-code-docs.md) instead. Claude loads them on demand without bloating every conversation.

Keep it concise. For each line, ask: *"Would removing this cause Claude to make mistakes?"* If not, cut it. Bloated CLAUDE.md files cause Claude to ignore your actual instructions!

| ✅ Include                                            | ❌ Exclude                                          |
| ---------------------------------------------------- | -------------------------------------------------- |
| Bash commands Claude can't guess                     | Anything Claude can figure out by reading code     |
| Code style rules that differ from defaults           | Standard language conventions Claude already knows |
| Testing instructions and preferred test runners      | Detailed API documentation (link to docs instead)  |
| Repository etiquette (branch naming, PR conventions) | Information that changes frequently                |
| Architectural decisions specific to your project     | Long explanations or tutorials                     |
| Developer environment quirks (required env vars)     | File-by-file descriptions of the codebase          |
| Common gotchas or non-obvious behaviors              | Self-evident practices like "write clean code"     |

If Claude keeps doing something you don't want despite having a rule against it, the file is probably too long and the rule is getting lost. If Claude asks you questions that are answered in CLAUDE.md, the phrasing might be ambiguous. Treat CLAUDE.md like code: review it when things go wrong, prune it regularly, and test changes by observing whether Claude's behavior actually shifts.

You can tune instructions by adding emphasis (e.g., "IMPORTANT" or "YOU MUST") to improve adherence. Check CLAUDE.md into git so your team can contribute. The file compounds in value over time.

CLAUDE.md files can import additional files using `@path/to/import` syntax:

```markdown CLAUDE.md theme={null}
See @README.md for project overview and @package.json for available npm commands.

# Additional Instructions
- Git workflow: @docs/git-instructions.md
- Personal overrides: @~/.claude/my-project-instructions.md
```

You can place CLAUDE.md files in several locations:

* **Home folder (`~/.claude/CLAUDE.md`)**: Applies to all Claude sessions
* **Project root (`./CLAUDE.md`)**: Check into git to share with your team, or name it `CLAUDE.local.md` and `.gitignore` it
* **Parent directories**: Useful for monorepos where both `root/CLAUDE.md` and `root/foo/CLAUDE.md` are pulled in automatically
* **Child directories**: Claude pulls in child CLAUDE.md files on demand when working with files in those directories

### Configure permissions

<Tip>
  Use `/permissions` to allowlist safe commands or `/sandbox` for OS-level isolation. This reduces interruptions while keeping you in control.
</Tip>

By default, Claude Code requests permission for actions that might modify your system: file writes, Bash commands, MCP tools, etc. This is safe but tedious. After the tenth approval you're not really reviewing anymore, you're just clicking through. There are two ways to reduce these interruptions:

* **Permission allowlists**: Permit specific tools you know are safe (like `npm run lint` or `git commit`)
* **Sandboxing**: Enable OS-level isolation that restricts filesystem and network access, allowing Claude to work more freely within defined boundaries

Alternatively, use `--dangerously-skip-permissions` to bypass all permission checks for contained workflows like fixing lint errors or generating boilerplate.

<Warning>
  Letting Claude run arbitrary commands can result in data loss, system corruption, or data exfiltration via prompt injection. Only use `--dangerously-skip-permissions` in a sandbox without internet access.
</Warning>

Read more about [configuring permissions](claude-code-settings-claude-code-docs-d4420b4b52.md) and [enabling sandboxing](/en/sandboxing#sandboxing).

### Use CLI tools

<Tip>
  Tell Claude Code to use CLI tools like `gh`, `aws`, `gcloud`, and `sentry-cli` when interacting with external services.
</Tip>

CLI tools are the most context-efficient way to interact with external services. If you use GitHub, install the `gh` CLI. Claude knows how to use it for creating issues, opening pull requests, and reading comments. Without `gh`, Claude can still use the GitHub API, but unauthenticated requests often hit rate limits.

Claude is also effective at learning CLI tools it doesn't already know. Try prompts like `Use 'foo-cli-tool --help' to learn about foo tool, then use it to solve A, B, C.`

### Connect MCP servers

<Tip>
  Run `claude mcp add` to connect external tools like Notion, Figma, or your database.
</Tip>

With [MCP servers](../06-MCP-Tools/General/connect-claude-code-to-tools-via-mcp-claude-code-docs.md), you can ask Claude to implement features from issue trackers, query databases, analyze monitoring data, integrate designs from Figma, and automate workflows.

### Set up hooks

<Tip>
  Use hooks for actions that must happen every time with zero exceptions.
</Tip>

[Hooks](../07-Hooks/automate-workflows-with-hooks-claude-code-docs-e843f93261.md) run scripts automatically at specific points in Claude's workflow. Unlike CLAUDE.md instructions which are advisory, hooks are deterministic and guarantee the action happens.

Claude can write hooks for you. Try prompts like *"Write a hook that runs eslint after every file edit"* or *"Write a hook that blocks writes to the migrations folder."* Run `/hooks` for interactive configuration, or edit `.claude/settings.json` directly.

### Create skills

<Tip>
  Create `SKILL.md` files in `.claude/skills/` to give Claude domain knowledge and reusable workflows.
</Tip>

[Skills](../08-Plugins-Skills/extend-claude-with-skills-claude-code-docs.md) extend Claude's knowledge with information specific to your project, team, or domain. Claude applies them automatically when relevant, or you can invoke them directly with `/skill-name`.

Create a skill by adding a directory with a `SKILL.md` to `.claude/skills/`:

```markdown .claude/skills/api-conventions/SKILL.md theme={null}
---
name: api-conventions
description: REST API design conventions for our services
---
# API Conventions
- Use kebab-case for URL paths
- Use camelCase for JSON properties
- Always include pagination for list endpoints
- Version APIs in the URL path (/v1/, /v2/)
```

Skills can also define repeatable workflows you invoke directly:

```markdown .claude/skills/fix-issue/SKILL.md theme={null}
---
name: fix-issue
description: Fix a GitHub issue
disable-model-invocation: true
---
Analyze and fix the GitHub issue: $ARGUMENTS.

1. Use `gh issue view` to get the issue details
2. Understand the problem described in the issue
3. Search the codebase for relevant files
4. Implement the necessary changes to fix the issue
5. Write and run tests to verify the fix
6. Ensure code passes linting and type checking
7. Create a descriptive commit message
8. Push and create a PR
```

Run `/fix-issue 1234` to invoke it. Use `disable-model-invocation: true` for workflows with side effects that you want to trigger manually.

### Create custom subagents

<Tip>
  Define specialized assistants in `.claude/agents/` that Claude can delegate to for isolated tasks.
</Tip>

[Subagents](../09-Agents-Patterns/create-custom-subagents-claude-code-docs-7dc93e85c0.md) run in their own context with their own set of allowed tools. They're useful for tasks that read many files or need specialized focus without cluttering your main conversation.

```markdown .claude/agents/security-reviewer.md theme={null}
---
name: security-reviewer
description: Reviews code for security vulnerabilities
tools: Read, Grep, Glob, Bash
model: opus
---
You are a senior security engineer. Review code for:
- Injection vulnerabilities (SQL, XSS, command injection)
- Authentication and authorization flaws
- Secrets or credentials in code
- Insecure data handling

Provide specific line references and suggested fixes.
```

Tell Claude to use subagents explicitly: *"Use a subagent to review this code for security issues."*

### Install plugins

<Tip>
  Run `/plugin` to browse the marketplace. Plugins add skills, tools, and integrations without configuration.
</Tip>

[Plugins](../08-Plugins-Skills/create-plugins-claude-code-docs.md) bundle skills, hooks, subagents, and MCP servers into a single installable unit from the community and Anthropic. If you work with a typed language, install a [code intelligence plugin](/en/discover-plugins#code-intelligence) to give Claude precise symbol navigation and automatic error detection after edits.

For guidance on choosing between skills, subagents, hooks, and MCP, see [Extend Claude Code](/en/features-overview#match-features-to-your-goal).

***

## Communicate effectively

The way you communicate with Claude Code significantly impacts the quality of results.

### Ask codebase questions

<Tip>
  Ask Claude questions you'd ask a senior engineer.
</Tip>

When onboarding to a new codebase, use Claude Code for learning and exploration. You can ask Claude the same sorts of questions you would ask another engineer:

* How does logging work?
* How do I make a new API endpoint?
* What does `async move { ... }` do on line 134 of `foo.rs`?
* What edge cases does `CustomerOnboardingFlowImpl` handle?
* Why does this code call `foo()` instead of `bar()` on line 333?

Using Claude Code this way is an effective onboarding workflow, improving ramp-up time and reducing load on other engineers. No special prompting required: ask questions directly.

### Let Claude interview you

<Tip>
  For larger features, have Claude interview you first. Start with a minimal prompt and ask Claude to interview you using the `AskUserQuestion` tool.
</Tip>

Claude asks about things you might not have considered yet, including technical implementation, UI/UX, edge cases, and tradeoffs.

```
I want to build [brief description]. Interview me in detail using the AskUserQuestion tool.

Ask about technical implementation, UI/UX, edge cases, concerns, and tradeoffs. Don't ask obvious questions, dig into the hard parts I might not have considered.

Keep interviewing until we've covered everything, then write a complete spec to SPEC.md.
```

Once the spec is complete, start a fresh session to execute it. The new session has clean context focused entirely on implementation, and you have a written spec to reference.

***

## Manage your session

Conversations are persistent and reversible. Use this to your advantage!

### Course-correct early and often

<Tip>
  Correct Claude as soon as you notice it going off track.
</Tip>

The best results come from tight feedback loops. Though Claude occasionally solves problems perfectly on the first attempt, correcting it quickly generally produces better solutions faster.

* **`Esc`**: Stop Claude mid-action with the `Esc` key. Context is preserved, so you can redirect.
* **`Esc + Esc` or `/rewind`**: Press `Esc` twice or run `/rewind` to open the rewind menu and restore previous conversation and code state.
* **`"Undo that"`**: Have Claude revert its changes.
* **`/clear`**: Reset context between unrelated tasks. Long sessions with irrelevant context can reduce performance.

If you've corrected Claude more than twice on the same issue in one session, the context is cluttered with failed approaches. Run `/clear` and start fresh with a more specific prompt that incorporates what you learned. A clean session with a better prompt almost always outperforms a long session with accumulated corrections.

### Manage context aggressively

<Tip>
  Run `/clear` between unrelated tasks to reset context.
</Tip>

Claude Code automatically compacts conversation history when you approach context limits, which preserves important code and decisions while freeing space.

During long sessions, Claude's context window can fill with irrelevant conversation, file contents, and commands. This can reduce performance and sometimes distract Claude.

* Use `/clear` frequently between tasks to reset the context window entirely
* When auto compaction triggers, Claude summarizes what matters most, including code patterns, file states, and key decisions
* For more control, run `/compact <instructions>`, like `/compact Focus on the API changes`
* Customize compaction behavior in CLAUDE.md with instructions like `"When compacting, always preserve the full list of modified files and any test commands"` to ensure critical context survives summarization

### Use subagents for investigation

<Tip>
  Delegate research with `"use subagents to investigate X"`. They explore in a separate context, keeping your main conversation clean for implementation.
</Tip>

Since context is your fundamental constraint, subagents are one of the most powerful tools available. When Claude researches a codebase it reads lots of files, all of which consume your context. Subagents run in separate context windows and report back summaries:

```
Use subagents to investigate how our authentication system handles token
refresh, and whether we have any existing OAuth utilities I should reuse.
```

The subagent explores the codebase, reads relevant files, and reports back with findings, all without cluttering your main conversation.

You can also use subagents for verification after Claude implements something:

```
use a subagent to review this code for edge cases
```

### Rewind with checkpoints

<Tip>
  Every action Claude makes creates a checkpoint. You can restore conversation, code, or both to any previous checkpoint.
</Tip>

Claude automatically checkpoints before changes. Double-tap `Escape` or run `/rewind` to open the checkpoint menu. You can restore conversation only (keep code changes), restore code only (keep conversation), or restore both.

Instead of carefully planning every move, you can tell Claude to try something risky. If it doesn't work, rewind and try a different approach. Checkpoints persist across sessions, so you can close your terminal and still rewind later.

<Warning>
  Checkpoints only track changes made *by Claude*, not external processes. This isn't a replacement for git.
</Warning>

### Resume conversations

<Tip>
  Run `claude --continue` to pick up where you left off, or `--resume` to choose from recent sessions.
</Tip>

Claude Code saves conversations locally. When a task spans multiple sessions (you start a feature, get interrupted, come back the next day) you don't have to re-explain the context:

```bash  theme={null}
claude --continue    # Resume the most recent conversation
claude --resume      # Select from recent conversations
```

Use `/rename` to give sessions descriptive names (`"oauth-migration"`, `"debugging-memory-leak"`) so you can find them later. Treat sessions like branches. Different workstreams can have separate, persistent contexts.

***

## Automate and scale

Once you're effective with one Claude, multiply your output with parallel sessions, headless mode, and fan-out patterns.

Everything so far assumes one human, one Claude, and one conversation. But Claude Code scales horizontally. The techniques in this section show how you can get more done.

### Run headless mode

<Tip>
  Use `claude -p "prompt"` in CI, pre-commit hooks, or scripts. Add `--output-format stream-json` for streaming JSON output.
</Tip>

With `claude -p "your prompt"`, you can run Claude headlessly, without an interactive session. Headless mode is how you integrate Claude into CI pipelines, pre-commit hooks, or any automated workflow. The output formats (plain text, JSON, streaming JSON) let you parse results programmatically.

```bash  theme={null}
# One-off queries
claude -p "Explain what this project does"

# Structured output for scripts
claude -p "List all API endpoints" --output-format json

# Streaming for real-time processing
claude -p "Analyze this log file" --output-format stream-json
```

### Run multiple Claude sessions

<Tip>
  Run multiple Claude sessions in parallel to speed up development, run isolated experiments, or start complex workflows.
</Tip>

There are two main ways to run parallel sessions:

* [Claude Desktop](../16-Mobile-Desktop/desktop.md): Manage multiple local sessions visually. Each session gets its own isolated worktree.
* [Claude Code on the web](claude-code-on-the-web-69d53821d4.md): Run on Anthropic's secure cloud infrastructure in isolated VMs.

Beyond parallelizing work, multiple sessions enable quality-focused workflows. A fresh context improves code review since Claude won't be biased toward code it just wrote.

For example, use a Writer/Reviewer pattern:

| Session A (Writer)                                                      | Session B (Reviewer)                                                                                                                                                     |
| ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `Implement a rate limiter for our API endpoints`                        |                                                                                                                                                                          |
|                                                                         | `Review the rate limiter implementation in @src/middleware/rateLimiter.ts. Look for edge cases, race conditions, and consistency with our existing middleware patterns.` |
| `Here's the review feedback: [Session B output]. Address these issues.` |                                                                                                                                                                          |

You can do something similar with tests: have one Claude write tests, then another write code to pass them.

### Fan out across files

<Tip>
  Loop through tasks calling `claude -p` for each. Use `--allowedTools` to scope permissions for batch operations.
</Tip>

For large migrations or analyses, you can distribute work across many parallel Claude invocations:

<Steps>
  <Step title="Generate a task list">
    Have Claude list all files that need migrating (e.g., `list all 2,000 Python files that need migrating`)
  </Step>

  <Step title="Write a script to loop through the list">
    ```bash  theme={null}
    for file in $(cat files.txt); do
      claude -p "Migrate $file from React to Vue. Return OK or FAIL." \
        --allowedTools "Edit,Bash(git commit *)"
    done
    ```
  </Step>

  <Step title="Test on a few files, then run at scale">
    Refine your prompt based on what goes wrong with the first 2-3 files, then run on the full set. The `--allowedTools` flag restricts what Claude can do, which matters when you're running unattended.
  </Step>
</Steps>

You can also integrate Claude into existing data/processing pipelines:

```bash  theme={null}
claude -p "<your prompt>" --output-format json | your_command
```

Use `--verbose` for debugging during development, and turn it off in production.

### Safe Autonomous Mode

Use `claude --dangerously-skip-permissions` to bypass all permission checks and let Claude work uninterrupted. This works well for workflows like fixing lint errors or generating boilerplate code.

<Warning>
  Letting Claude run arbitrary commands is risky and can result in data loss, system corruption, or data exfiltration (e.g., via prompt injection attacks). To minimize these risks, use `--dangerously-skip-permissions` in a container without internet access.

  With sandboxing enabled (`/sandbox`), you get similar autonomy with better security. Sandbox defines upfront boundaries rather than bypassing all checks.
</Warning>

***

## Avoid common failure patterns

These are common mistakes. Recognizing them early saves time:

* **The kitchen sink session.** You start with one task, then ask Claude something unrelated, then go back to the first task. Context is full of irrelevant information.
  > **Fix**: `/clear` between unrelated tasks.
* **Correcting over and over.** Claude does something wrong, you correct it, it's still wrong, you correct again. Context is polluted with failed approaches.
  > **Fix**: After two failed corrections, `/clear` and write a better initial prompt incorporating what you learned.
* **The over-specified CLAUDE.md.** If your CLAUDE.md is too long, Claude ignores half of it because important rules get lost in the noise.
  > **Fix**: Ruthlessly prune. If Claude already does something correctly without the instruction, delete it or convert it to a hook.
* **The trust-then-verify gap.** Claude produces a plausible-looking implementation that doesn't handle edge cases.
  > **Fix**: Always provide verification (tests, scripts, screenshots). If you can't verify it, don't ship it.
* **The infinite exploration.** You ask Claude to "investigate" something without scoping it. Claude reads hundreds of files, filling the context.
  > **Fix**: Scope investigations narrowly or use subagents so the exploration doesn't consume your main context.

***

## Develop your intuition

The patterns in this guide aren't set in stone. They're starting points that work well in general, but might not be optimal for every situation.

Sometimes you *should* let context accumulate because you're deep in one complex problem and the history is valuable. Sometimes you should skip planning and let Claude figure it out because the task is exploratory. Sometimes a vague prompt is exactly right because you want to see how Claude interprets the problem before constraining it.

Pay attention to what works. When Claude produces great output, notice what you did: the prompt structure, the context you provided, the mode you were in. When Claude struggles, ask why. Was the context too noisy? The prompt too vague? The task too big for one pass?

Over time, you'll develop intuition that no guide can capture. You'll know when to be specific and when to be open-ended, when to plan and when to explore, when to clear context and when to let it accumulate.

## Related resources

<CardGroup cols={2}>
  <Card title="How Claude Code works" icon="gear" href="/en/how-claude-code-works">
    Understand the agentic loop, tools, and context management
  </Card>

  <Card title="Extend Claude Code" icon="puzzle-piece" href="/en/features-overview">
    Choose between skills, hooks, MCP, subagents, and plugins
  </Card>

  <Card title="Common workflows" icon="list-check" href="/en/common-workflows">
    Step-by-step recipes for debugging, testing, PRs, and more
  </Card>

  <Card title="CLAUDE.md" icon="file-lines" href="/en/memory">
    Store project conventions and persistent context
  </Card>
</CardGroup>


---
## built-in-commands-claude-code-docs.md

# Built-in commands


Complete reference for built-in commands available in Claude Code.


Type `/` in Claude Code to see all available commands, or type `/` followed by any letters to filter. Not all commands are visible to every user. Some depend on your platform, plan, or environment. For example, `/desktop` only appears on macOS and Windows, `/upgrade` and `/privacy-settings` are only available on Pro and Max plans, and `/terminal-setup` is hidden when your terminal natively supports its keybindings. Claude Code also includes [bundled skills](/docs/en/skills#bundled-skills) like `/simplify`, `/batch`, and `/debug` that appear alongside built-in commands when you type `/`. To create your own commands, see [skills](/docs/en/skills). In the table below, `<arg>` indicates a required argument and `[arg]` indicates an optional one.

| Command | Purpose |
|:---|:---|
| `/add-dir <path>` | Add a new working directory to the current session |
| `/agents` | Manage [agent](/docs/en/sub-agents) configurations |
| `/btw <question>` | Ask a quick [side question](/docs/en/interactive-mode#side-questions-with-btw) without adding to the conversation |
| `/chrome` | Configure [Claude in Chrome](/docs/en/chrome) settings |
| `/clear` | Clear conversation history and free up context. Aliases: `/reset`, `/new` |
| `/color [color|default]` | Set the prompt bar color for the current session. Available colors: `red`, `blue`, `green`, `yellow`, `purple`, `orange`, `pink`, `cyan`. Use `default` to reset |
| `/compact [instructions]` | Compact conversation with optional focus instructions |
| `/config` | Open the [Settings](/docs/en/settings) interface to adjust theme, model, [output style](/docs/en/output-styles), and other preferences. Alias: `/settings` |
| `/context` | Visualize current context usage as a colored grid. Shows optimization suggestions for context-heavy tools, memory bloat, and capacity warnings |
| `/copy` | Copy the last assistant response to clipboard. When code blocks are present, shows an interactive picker to select individual blocks or the full response |
| `/cost` | Show token usage statistics. See [cost tracking guide](/docs/en/costs#using-the-cost-command) for subscription-specific details |
| `/desktop` | Continue the current session in the Claude Code Desktop app. macOS and Windows only. Alias: `/app` |
| `/diff` | Open an interactive diff viewer showing uncommitted changes and per-turn diffs. Use left/right arrows to switch between the current git diff and individual Claude turns, and up/down to browse files |
| `/doctor` | Diagnose and verify your Claude Code installation and settings |
| `/effort [low|medium|high|max|auto]` | Set the model [effort level](/docs/en/model-config#adjust-effort-level). `low`, `medium`, and `high` persist across sessions. `max` applies to the current session only and requires Opus 4.6. `auto` resets to the model default. Without an argument, shows the current level. Takes effect immediately without waiting for the current response to finish |
| `/exit` | Exit the CLI. Alias: `/quit` |
| `/export [filename]` | Export the current conversation as plain text. With a filename, writes directly to that file. Without, opens a dialog to copy to clipboard or save to a file |
| `/extra-usage` | Configure extra usage to keep working when rate limits are hit |
| `/fast [on|off]` | Toggle [fast mode](/docs/en/fast-mode) on or off |
| `/feedback [report]` | Submit feedback about Claude Code. Alias: `/bug` |
| `/fork [name]` | Create a fork of the current conversation at this point |
| `/help` | Show help and available commands |
| `/hooks` | View [hook](/docs/en/hooks) configurations for tool events |
| `/ide` | Manage IDE integrations and show status |
| `/init` | Initialize project with `CLAUDE.md` guide |
| `/insights` | Generate a report analyzing your Claude Code sessions, including project areas, interaction patterns, and friction points |
| `/install-github-app` | Set up the [Claude GitHub Actions](/docs/en/github-actions) app for a repository. Walks you through selecting a repo and configuring the integration |
| `/install-slack-app` | Install the Claude Slack app. Opens a browser to complete the OAuth flow |
| `/keybindings` | Open or create your keybindings configuration file |
| `/login` | Sign in to your Anthropic account |
| `/logout` | Sign out from your Anthropic account |
| `/mcp` | Manage MCP server connections and OAuth authentication |
| `/memory` | Edit `CLAUDE.md` memory files, enable or disable [auto-memory](/docs/en/memory#auto-memory), and view auto-memory entries |
| `/mobile` | Show QR code to download the Claude mobile app. Aliases: `/ios`, `/android` |
| `/model [model]` | Select or change the AI model. For models that support it, use left/right arrows to [adjust effort level](/docs/en/model-config#adjust-effort-level). The change takes effect immediately without waiting for the current response to finish |
| `/passes` | Share a free week of Claude Code with friends. Only visible if your account is eligible |
| `/permissions` | View or update [permissions](/docs/en/permissions#manage-permissions). Alias: `/allowed-tools` |
| `/plan` | Enter plan mode directly from the prompt |
| `/plugin` | Manage Claude Code [plugins](/docs/en/plugins) |
| `/pr-comments [PR]` | Fetch and display comments from a GitHub pull request. Automatically detects the PR for the current branch, or pass a PR URL or number. Requires the `gh` CLI |
| `/privacy-settings` | View and update your privacy settings. Only available for Pro and Max plan subscribers |
| `/release-notes` | View the full changelog, with the most recent version closest to your prompt |
| `/reload-plugins` | Reload all active [plugins](/docs/en/plugins) to apply pending changes without restarting. Reports what was loaded and notes any changes that require a restart |
| `/remote-control` | Make this session available for [remote control](/docs/en/remote-control) from claude.ai. Alias: `/rc` |
| `/remote-env` | Configure the default remote environment for [web sessions started with `--remote`](/docs/en/claude-code-on-the-web#environment-configuration) |
| `/rename [name]` | Rename the current session and show the name on the prompt bar. Without a name, auto-generates one from conversation history |
| `/resume [session]` | Resume a conversation by ID or name, or open the session picker. Alias: `/continue` |
| `/review` | Deprecated. Install the [`code-review` plugin](https://github.com/anthropics/claude-code-marketplace/blob/main/code-review/README.md) instead: `claude plugin install code-review@claude-code-marketplace` |
| `/rewind` | Rewind the conversation and/or code to a previous point, or summarize from a selected message. See [checkpointing](/docs/en/checkpointing). Alias: `/checkpoint` |
| `/sandbox` | Toggle [sandbox mode](/docs/en/sandboxing). Available on supported platforms only |
| `/security-review` | Analyze pending changes on the current branch for security vulnerabilities. Reviews the git diff and identifies risks like injection, auth issues, and data exposure |
| `/skills` | List available [skills](/docs/en/skills) |
| `/stats` | Visualize daily usage, session history, streaks, and model preferences |
| `/status` | Open the Settings interface (Status tab) showing version, model, account, and connectivity |
| `/statusline` | Configure Claude Code’s [status line](/docs/en/statusline). Describe what you want, or run without arguments to auto-configure from your shell prompt |
| `/stickers` | Order Claude Code stickers |
| `/tasks` | List and manage background tasks |
| `/terminal-setup` | Configure terminal keybindings for Shift+Enter and other shortcuts. Only visible in terminals that need it, like VS Code, Alacritty, or Warp |
| `/theme` | Change the color theme. Includes light and dark variants, colorblind-accessible (daltonized) themes, and ANSI themes that use your terminal’s color palette |
| `/upgrade` | Open the upgrade page to switch to a higher plan tier |
| `/usage` | Show plan usage limits and rate limit status |
| `/vim` | Toggle between Vim and Normal editing modes |

## 

MCP prompts

MCP servers can expose prompts that appear as commands. These use the format `/mcp__<server>__<prompt>` and are dynamically discovered from connected servers. See [MCP prompts](/docs/en/mcp#use-mcp-prompts-as-commands) for details.

## 

See also

- [Skills](/docs/en/skills): create your own commands
- [Interactive mode](/docs/en/interactive-mode): keyboard shortcuts, Vim mode, and command history
- [CLI reference](/docs/en/cli-reference): launch-time flags


---
## changelog-67fadc96e4.md

> ## Documentation Index
> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Changelog

> Release notes for Claude Code, including new features, improvements, and bug fixes by version.

This page is generated from the [CHANGELOG.md on GitHub](https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md).

Run `claude --version` to check your installed version.

<Update label="2.1.119" description="April 23, 2026">
  * `/config` settings (theme, editor mode, verbose, etc.) now persist to `~/.claude/settings.json` and participate in project/local/policy override precedence
  * Added `prUrlTemplate` setting to point the footer PR badge at a custom code-review URL instead of github.com
  * Added `CLAUDE_CODE_HIDE_CWD` environment variable to hide the working directory in the startup logo
  * `--from-pr` now accepts GitLab merge-request, Bitbucket pull-request, and GitHub Enterprise PR URLs
  * `--print` mode now honors the agent's `tools:` and `disallowedTools:` frontmatter, matching interactive-mode behavior
  * `--agent <name>` now honors the agent definition's `permissionMode` for built-in agents
  * PowerShell tool commands can now be auto-approved in permission mode, matching Bash behavior
  * Hooks: `PostToolUse` and `PostToolUseFailure` hook inputs now include `duration_ms` (tool execution time, excluding permission prompts and PreToolUse hooks)
  * Subagent and SDK MCP server reconfiguration now connects servers in parallel instead of serially
  * Plugins pinned by another plugin's version constraint now auto-update to the highest satisfying git tag
  * Vim mode: Esc in INSERT no longer pulls a queued message back into the input; press Esc again to interrupt
  * Slash command suggestions now highlight the characters that matched your query
  * Slash command picker now wraps long descriptions onto a second line instead of truncating
  * `owner/repo#N` shorthand links in output now use your git remote's host instead of always pointing at github.com
  * Security: `blockedMarketplaces` now correctly enforces `hostPattern` and `pathPattern` entries
  * OpenTelemetry: `tool_result` and `tool_decision` events now include `tool_use_id`; `tool_result` also includes `tool_input_size_bytes`
  * Status line: stdin JSON now includes `effort.level` and `thinking.enabled`
  * Fixed pasting CRLF content (Windows clipboards, Xcode console) inserting an extra blank line between every line
  * Fixed multi-line paste losing newlines in terminals using kitty keyboard protocol sequences inside bracketed paste
  * Fixed Glob and Grep tools disappearing on native macOS/Linux builds when the Bash tool is denied via permissions
  * Fixed scrolling up in fullscreen mode snapping back to the bottom every time a tool finishes
  * Fixed MCP HTTP connections failing with "Invalid OAuth error response" when servers returned non-JSON bodies for OAuth discovery requests
  * Fixed Rewind overlay showing "(no prompt)" for messages with image attachments
  * Fixed auto mode overriding plan mode with conflicting "Execute immediately" instructions
  * Fixed async `PostToolUse` hooks that emit no response payload writing empty entries to the session transcript
  * Fixed spinner staying on when a subagent task notification is orphaned in the queue
  * Tool search is now disabled by default on Vertex AI to avoid an unsupported beta header error (opt in with `ENABLE_TOOL_SEARCH`)
  * Fixed `@`-file Tab completion replacing the entire prompt when used inside a slash command with an absolute path
  * Fixed a stray `p` character appearing at the prompt on startup in macOS Terminal.app via Docker or SSH
  * Fixed `${ENV_VAR}` placeholders in `headers` for HTTP/SSE/WebSocket MCP servers not being substituted before requests
  * Fixed MCP OAuth client secret stored via `--client-secret` not being sent during token exchange for servers requiring `client_secret_post`
  * Fixed `/skills` Enter key closing the dialog instead of pre-filling `/<skill-name>` in the prompt
  * Fixed `/agents` detail view mislabeling built-in tools unavailable to subagents as "Unrecognized"
  * Fixed MCP servers from plugins not spawning on Windows when the plugin cache was incomplete
  * Fixed `/export` showing the current default model instead of the model the conversation actually used
  * Fixed verbose output setting not persisting after restart
  * Fixed `/usage` progress bars overlapping with their "Resets …" labels
  * Fixed plugin MCP servers failing when `${user_config.*}` references an optional field left blank
  * Fixed list items containing a sentence-final number wrapping the number onto its own line
  * Fixed `/plan` and `/plan open` not acting on the existing plan when entering plan mode
  * Fixed skills invoked before auto-compaction being re-executed against the next user message
  * Fixed `/reload-plugins` and `/doctor` reporting load errors for disabled plugins
  * Fixed Agent tool with `isolation: "worktree"` reusing stale worktrees from prior sessions
  * Fixed disabled MCP servers appearing as "failed" in `/status`
  * Fixed `TaskList` returning tasks in arbitrary filesystem order instead of sorted by ID
  * Fixed spurious "GitHub API rate limit exceeded" hints when `gh` output contained PR titles mentioning "rate limit"
  * Fixed SDK/bridge `read_file` not correctly enforcing size cap on growing files
  * Fixed PR not linked to session when working in a git worktree
  * Fixed `/doctor` warning about MCP server entries overridden by a higher-precedence scope
  * Windows: removed false-positive "Windows requires 'cmd /c' wrapper" MCP config warning
  * \[VSCode] Fixed voice dictation's first recording producing nothing on macOS while the microphone permission prompt is showing
</Update>

<Update label="2.1.118" description="April 23, 2026">
  * Added vim visual mode (`v`) and visual-line mode (`V`) with selection, operators, and visual feedback
  * Merged `/cost` and `/stats` into `/usage` — both remain as typing shortcuts that open the relevant tab
  * Create and switch between named custom themes from `/theme`, or hand-edit JSON files in `~/.claude/themes/`; plugins can also ship themes via a `themes/` directory
  * Hooks can now invoke MCP tools directly via `type: "mcp_tool"`
  * Added `DISABLE_UPDATES` env var to completely block all update paths including manual `claude update` — stricter than `DISABLE_AUTOUPDATER`
  * WSL on Windows can now inherit Windows-side managed settings via the `wslInheritsWindowsSettings` policy key
  * Auto mode: include `"$defaults"` in `autoMode.allow`, `autoMode.soft_deny`, or `autoMode.environment` to add custom rules alongside the built-in list instead of replacing it
  * Added a "Don't ask again" option to the auto mode opt-in prompt
  * Added `claude plugin tag` to create release git tags for plugins with version validation
  * `--continue`/`--resume` now find sessions that added the current directory via `/add-dir`
  * `/color` now syncs the session accent color to claude.ai/code when Remote Control is connected
  * The `/model` picker now honors `ANTHROPIC_DEFAULT_*_MODEL_NAME`/`_DESCRIPTION` overrides when using a custom `ANTHROPIC_BASE_URL` gateway
  * When auto-update skips a plugin due to another plugin's version constraint, the skip now appears in `/doctor` and the `/plugin` Errors tab
  * Fixed `/mcp` menu hiding OAuth Authenticate/Re-authenticate actions for servers configured with `headersHelper`, and HTTP/SSE MCP servers with custom headers being stuck in "needs authentication" after a transient 401
  * Fixed MCP servers whose OAuth token response omits `expires_in` requiring re-authentication every hour
  * Fixed MCP step-up authorization silently refreshing instead of prompting for re-consent when the server's `insufficient_scope` 403 names a scope the current token already has
  * Fixed an unhandled promise rejection when an MCP server's OAuth flow times out or is cancelled
  * Fixed MCP OAuth refresh proceeding without its cross-process lock under contention
  * Fixed macOS keychain race where a concurrent MCP token refresh could overwrite a freshly-refreshed OAuth token, causing unexpected "Please run /login" prompts
  * Fixed OAuth token refresh failing when the server revokes a token before its local expiry time
  * Fixed credential save crash on Linux/Windows corrupting `~/.claude/.credentials.json`
  * Fixed `/login` having no effect in a session launched with `CLAUDE_CODE_OAUTH_TOKEN` — the env token is now cleared so disk credentials take effect
  * Fixed unreadable text in the "new messages" scroll pill and `/plugin` badges
  * Fixed plan acceptance dialog offering "auto mode" instead of "bypass permissions" when running with `--dangerously-skip-permissions`
  * Fixed agent-type hooks failing with "Messages are required for agent hooks" when configured for events other than `Stop` or `SubagentStop`
  * Fixed `prompt` hooks re-firing on tool calls made by an agent-hook verifier subagent
  * Fixed `/fork` writing the full parent conversation to disk per fork — now writes a pointer and hydrates on read
  * Fixed Alt+K / Alt+X / Alt+^ / Alt+\_ freezing keyboard input
  * Fixed connecting to a remote session overwriting your local `model` setting in `~/.claude/settings.json`
  * Fixed typeahead showing "No commands match" error when pasting file paths that start with `/`
  * Fixed `plugin install` on an already-installed plugin not re-resolving a dependency installed at the wrong version
  * Fixed unhandled errors from file watcher on invalid paths or fd exhaustion
  * 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
</Update>

<Update label="2.1.117" description="April 22, 2026">
  * Forked subagents can now be enabled on external builds by setting `CLAUDE_CODE_FORK_SUBAGENT=1`
  * Agent frontmatter `mcpServers` are now loaded for main-thread agent sessions via `--agent`
  * Improved `/model`: selections now persist across restarts even when the project pins a different model, and the startup header shows when the active model comes from a project or managed-settings pin
  * The `/resume` command now offers to summarize stale, large sessions before re-reading them, matching the existing `--resume` behavior
  * Faster startup when both local and claude.ai MCP servers are configured (concurrent connect now default)
  * `plugin install` on an already-installed plugin now installs any missing dependencies instead of stopping at "already installed"
  * Plugin dependency errors now say "not installed" with an install hint, and `claude plugin marketplace add` now auto-resolves missing dependencies from configured marketplaces
  * Managed-settings `blockedMarketplaces` and `strictKnownMarketplaces` are now enforced on plugin install, update, refresh, and autoupdate
  * Advisor Tool (experimental): dialog now carries an "experimental" label, learn-more link, and startup notification when enabled; sessions no longer get stuck with "Advisor tool result content could not be processed" errors on every prompt and `/compact`
  * The `cleanupPeriodDays` retention sweep now also covers `~/.claude/tasks/`, `~/.claude/shell-snapshots/`, and `~/.claude/backups/`
  * OpenTelemetry: `user_prompt` events now include `command_name` and `command_source` for slash commands; `cost.usage`, `token.usage`, `api_request`, and `api_error` now include an `effort` attribute when the model supports effort levels. Custom/MCP command names are redacted unless `OTEL_LOG_TOOL_DETAILS=1` is set
  * Native builds on macOS and Linux: the `Glob` and `Grep` tools are replaced by embedded `bfs` and `ugrep` available through the Bash tool — faster searches without a separate tool round-trip (Windows and npm-installed builds unchanged)
  * Windows: cached `where.exe` executable lookups per process for faster subprocess launches
  * Default effort for Pro/Max subscribers on Opus 4.6 and Sonnet 4.6 is now `high` (was `medium`)
  * Fixed Plain-CLI OAuth sessions dying with "Please run /login" when the access token expires mid-session — the token is now refreshed reactively on 401
  * Fixed `WebFetch` hanging on very large HTML pages by truncating input before HTML-to-markdown conversion
  * Fixed a crash when a proxy returns HTTP 204 No Content — now surfaces a clear error instead of a `TypeError`
  * Fixed `/login` having no effect when launched with `CLAUDE_CODE_OAUTH_TOKEN` env var and that token expires
  * Fixed prompt-input undo (`Ctrl+_`) doing nothing immediately after typing, and skipping a state on each undo step
  * Fixed `NO_PROXY` not being respected for remote API requests when running under Bun
  * Fixed rare spurious escape/return triggers when key names arrive as coalesced text over slow connections
  * Fixed SDK `reload_plugins` reconnecting all user MCP servers serially
  * Fixed Bedrock application-inference-profile requests failing with 400 when backed by Opus 4.7 with thinking disabled
  * Fixed MCP `elicitation/create` requests auto-cancelling in print/SDK mode when the server finishes connecting mid-turn
  * Fixed subagents running a different model than the main agent incorrectly flagging file reads with a malware warning
  * Fixed idle re-render loop when background tasks are present, reducing memory growth on Linux
  * \[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
</Update>

<Update label="2.1.116" description="April 20, 2026">
  * `/resume` on large sessions is significantly faster (up to 67% on 40MB+ sessions) and handles sessions with many dead-fork entries more efficiently
  * Faster MCP startup when multiple stdio servers are configured; `resources/templates/list` is now deferred to first `@`-mention
  * Smoother fullscreen scrolling in VS Code, Cursor, and Windsurf terminals — `/terminal-setup` now configures the editor's scroll sensitivity
  * Thinking spinner now shows progress inline ("still thinking", "thinking more", "almost done thinking"), replacing the separate hint row
  * `/config` search now matches option values (e.g. searching "vim" finds the Editor mode setting)
  * `/doctor` can now be opened while Claude is responding, without waiting for the current turn to finish
  * `/reload-plugins` and background plugin auto-update now auto-install missing plugin dependencies from marketplaces you've already added
  * Bash tool now surfaces a hint when `gh` commands hit GitHub's API rate limit, so agents can back off instead of retrying
  * The Usage tab in Settings now shows your 5-hour and weekly usage immediately and no longer fails when the usage endpoint is rate-limited
  * Agent frontmatter `hooks:` now fire when running as a main-thread agent via `--agent`
  * Slash command menu now shows "No commands match" when your filter has zero results, instead of disappearing
  * Security: sandbox auto-allow no longer bypasses the dangerous-path safety check for `rm`/`rmdir` targeting `/`, `$HOME`, or other critical system directories
  * Claude Code and installer now use `https://downloads.claude.ai/claude-code-releases` instead of `https://storage.googleapis.com/claude-code-dist-86c565f3-f756-42ad-8dfa-d59b1c096819/claude-code-releases`
  * Fixed Devanagari and other Indic scripts rendering with broken column alignment in the terminal UI
  * Fixed Ctrl+- not triggering undo in terminals using the Kitty keyboard protocol (iTerm2, Ghostty, kitty, WezTerm, Windows Terminal)
  * Fixed Cmd+Left/Right not jumping to line start/end in terminals that use the Kitty keyboard protocol (Warp fullscreen, kitty, Ghostty, WezTerm)
  * Fixed Ctrl+Z hanging the terminal when Claude Code is launched via a wrapper process (e.g. `npx`, `bun run`)
  * Fixed scrollback duplication in inline mode where resizing the terminal or large output bursts would repeat earlier conversation history
  * Fixed modal search dialogs overflowing the screen at short terminal heights, hiding the search box and keyboard hints
  * Fixed scattered blank cells and disappearing composer chrome in the VS Code integrated terminal during scrolling
  * Fixed an intermittent API 400 error related to cache control TTL ordering that could occur when a parallel request completed during request setup
  * Fixed `/branch` rejecting conversations with transcripts larger than 50MB
  * Fixed `/resume` silently showing an empty conversation on large session files instead of reporting the load error
  * 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
</Update>

<Update label="2.1.114" description="April 18, 2026">
  * Fixed a crash in the permission dialog when an agent teams teammate requested tool permission
</Update>

<Update label="2.1.113" description="April 17, 2026">
  * Changed the CLI to spawn a native Claude Code binary (via a per-platform optional dependency) instead of bundled JavaScript
  * Added `sandbox.network.deniedDomains` setting to block specific domains even when a broader `allowedDomains` wildcard would otherwise permit them
  * Fullscreen mode: Shift+↑/↓ now scrolls the viewport when extending a selection past the visible edge
  * `Ctrl+A` and `Ctrl+E` now move to the start/end of the current logical line in multiline input, matching readline behavior
  * Windows: `Ctrl+Backspace` now deletes the previous word
  * Long URLs in responses and bash output stay clickable when they wrap across lines (in terminals with OSC 8 hyperlinks)
  * Improved `/loop`: pressing Esc now cancels pending wakeups, and wakeups display as "Claude resuming /loop wakeup" for clarity
  * `/extra-usage` now works from Remote Control (mobile/web) clients
  * Remote Control clients can now query `@`-file autocomplete suggestions
  * Improved `/ultrareview`: faster launch with parallelized checks, diffstat in the launch dialog, and animated launching state
  * Subagents that stall mid-stream now fail with a clear error after 10 minutes instead of hanging silently
  * Bash tool: multi-line commands whose first line is a comment now show the full command in the transcript, closing a UI-spoofing vector
  * Running `cd <current-directory> && git …` no longer triggers a permission prompt when the `cd` is a no-op
  * Security: on macOS, `/private/{etc,var,tmp,home}` paths are now treated as dangerous removal targets under `Bash(rm:*)` allow rules
  * Security: Bash deny rules now match commands wrapped in `env`/`sudo`/`watch`/`ionice`/`setsid` and similar exec wrappers
  * Security: `Bash(find:*)` allow rules no longer auto-approve `find -exec`/`-delete`
  * Fixed MCP concurrent-call timeout handling where a message for one tool call could silently disarm another call's watchdog
  * Fixed Cmd-backspace / `Ctrl+U` to once again delete from the cursor to the start of the line
  * Fixed markdown tables breaking when a cell contains an inline code span with a pipe character
  * Fixed session recap auto-firing while composing unsent text in the prompt
  * Fixed `/copy` "Full response" not aligning markdown table columns for pasting into GitHub, Notion, or Slack
  * Fixed messages typed while viewing a running subagent being hidden from its transcript and misattributed to the parent AI
  * Fixed Bash `dangerouslyDisableSandbox` running commands outside the sandbox without a permission prompt
  * Fixed `/effort auto` confirmation — now says "Effort level set to max" to match the status bar label
  * Fixed the "copied N chars" toast overcounting emoji and other multi-code-unit characters
  * Fixed `/insights` crashing with `EBUSY` on Windows
  * Fixed exit confirmation dialog mislabeling one-shot scheduled tasks as recurring — now shows a countdown
  * Fixed slash/@ completion menu not sitting flush against the prompt border in fullscreen mode
  * Fixed `CLAUDE_CODE_EXTRA_BODY` `output_config.effort` causing 400 errors on subagent calls to models that don't support effort and on Vertex AI
  * Fixed prompt cursor disappearing when `NO_COLOR` is set
  * Fixed `ToolSearch` ranking so pasted MCP tool names surface the actual tool instead of description-matching siblings
  * Fixed compacting a resumed long-context session failing with "Extra usage is required for long context requests"
  * Fixed `plugin install` succeeding when a dependency version conflicts with an already-installed plugin — now reports `range-conflict`
  * Fixed "Refine with Ultraplan" not showing the remote session URL in the transcript
  * Fixed SDK image content blocks that fail to process crashing the session — now degrade to a text placeholder
  * Fixed Remote Control sessions not streaming subagent transcripts
  * 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
</Update>

<Update label="2.1.112" description="April 16, 2026">
  * Fixed "claude-opus-4-7 is temporarily unavailable" for auto mode
</Update>

<Update label="2.1.111" description="April 16, 2026">
  * Claude Opus 4.7 xhigh is now available! Use /effort to tune speed vs. intelligence
  * Auto mode is now available for Max subscribers when using Opus 4.7
  * Added `xhigh` effort level for Opus 4.7, sitting between `high` and `max`. Available via `/effort`, `--effort`, and the model picker; other models fall back to `high`
  * `/effort` now opens an interactive slider when called without arguments, with arrow-key navigation between levels and Enter to confirm
  * Added "Auto (match terminal)" theme option that matches your terminal's dark/light mode — select it from `/theme`
  * Added `/less-permission-prompts` skill — scans transcripts for common read-only Bash and MCP tool calls and proposes a prioritized allowlist for `.claude/settings.json`
  * Added `/ultrareview` for running comprehensive code review in the cloud using parallel multi-agent analysis and critique — invoke with no arguments to review your current branch, or `/ultrareview <PR#>` to fetch and review a specific GitHub PR
  * Auto mode no longer requires `--enable-auto-mode`
  * Windows: PowerShell tool is progressively rolling out. Opt in or out with `CLAUDE_CODE_USE_POWERSHELL_TOOL`. On Linux and macOS, enable with `CLAUDE_CODE_USE_POWERSHELL_TOOL=1` (requires `pwsh` on PATH)
  * Read-only bash commands with glob patterns (e.g. `ls *.ts`) and commands starting with `cd <project-dir> &&` no longer trigger a permission prompt
  * Suggest the closest matching subcommand when `claude <word>` is invoked with a near-miss typo (e.g. `claude udpate` → "Did you mean `claude update`?")
  * Plan files are now named after your prompt (e.g. `fix-auth-race-snug-otter.md`) instead of purely random words
  * Improved `/setup-vertex` and `/setup-bedrock` to show the actual `settings.json` path when `CLAUDE_CONFIG_DIR` is set, seed model candidates from existing pins on re-run, and offer a "with 1M context" option for supported models
  * `/skills` menu now supports sorting by estimated token count — press `t` to toggle
  * `Ctrl+U` now clears the entire input buffer (previously: delete to start of line); press `Ctrl+Y` to restore
  * `Ctrl+L` now forces a full screen redraw in addition to clearing the prompt input
  * Transcript view footer now shows `[` (dump to scrollback) and `v` (open in editor) shortcuts
  * The "+N lines" marker for truncated long pastes is now a full-width rule for easier scanning
  * Headless `--output-format stream-json` now includes `plugin_errors` on the init event when plugins are demoted for unsatisfied dependencies
  * Added `OTEL_LOG_RAW_API_BODIES` environment variable to emit full API request and response bodies as OpenTelemetry log events for debugging
  * Suppressed spurious decompression, network, and transient error messages that could appear in the TUI during normal operation
  * Reverted the v2.1.110 cap on non-streaming fallback retries — it traded long waits for more outright failures during API overload
  * Fixed terminal display tearing (random characters, drifting input) in iTerm2 + tmux setups when terminal notifications are sent
  * Fixed `@` file suggestions re-scanning the entire project on every turn in non-git working directories, and showing only config files in freshly-initialized git repos with no tracked files
  * Fixed LSP diagnostics from before an edit appearing after it, causing the model to re-read files it just edited
  * Fixed tab-completing `/resume` immediately resuming an arbitrary titled session instead of showing the session picker
  * Fixed `/context` grid rendering with extra blank lines between rows
  * Fixed `/clear` dropping the session name set by `/rename`, causing statusline output to lose `session_name`
  * Improved plugin error handling: dependency errors now distinguish conflicting, invalid, and overly complex version requirements; fixed stale resolved versions after `plugin update`; `plugin install` now recovers from interrupted prior installs
  * Fixed Claude calling a non-existent `commit` skill and showing "Unknown skill: commit" for users without a custom `/commit` command
  * 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
  * Windows: `CLAUDE_ENV_FILE` and SessionStart hook environment files now apply (previously a no-op)
  * Windows: permission rules with drive-letter paths are now correctly root-anchored, and paths differing only by drive-letter case are recognized as the same path
</Update>

<Update label="2.1.110" description="April 15, 2026">
  * Added `/tui` command and `tui` setting — run `/tui fullscreen` to switch to flicker-free rendering in the same conversation
  * Added push notification tool — Claude can send mobile push notifications when Remote Control and "Push when Claude decides" config are enabled
  * Changed `Ctrl+O` to toggle between normal and verbose transcript only; focus view is now toggled separately with the new `/focus` command
  * Added `autoScrollEnabled` config to disable conversation auto-scroll in fullscreen mode
  * Added option to show Claude's last response as commented context in the `Ctrl+G` external editor (enable via `/config`)
  * Improved `/plugin` Installed tab — items needing attention and favorites appear at the top, disabled items are hidden behind a fold, and `f` favorites the selected item
  * Improved `/doctor` to warn when an MCP server is defined in multiple config scopes with different endpoints
  * `--resume`/`--continue` now resurrects unexpired scheduled tasks
  * `/context`, `/exit`, and `/reload-plugins` now work from Remote Control (mobile/web) clients
  * Write tool now informs the model when you edit the proposed content in the IDE diff before accepting
  * Bash tool now enforces the documented maximum timeout instead of accepting arbitrarily large values
  * SDK/headless sessions now read `TRACEPARENT`/`TRACESTATE` from the environment for distributed trace linking
  * Session recap is now enabled for users with telemetry disabled (Bedrock, Vertex, Foundry, `DISABLE_TELEMETRY`). Opt out via `/config` or `CLAUDE_CODE_ENABLE_AWAY_SUMMARY=0`.
  * Fixed MCP tool calls hanging indefinitely when the server connection drops mid-response on SSE/HTTP transports
  * Fixed non-streaming fallback retries causing multi-minute hangs when the API is unreachable
  * Fixed session recap, local slash-command output, and other system status lines not appearing in focus mode
  * Fixed high CPU usage in fullscreen when text is selected while a tool is running
  * Fixed plugin install not honoring dependencies declared in `plugin.json` when the marketplace entry omits them; `/plugin` install now lists auto-installed dependencies
  * Fixed skills with `disable-model-invocation: true` failing when invoked via `/<skill>` mid-message
  * Fixed `--resume` sometimes showing the first prompt instead of the `/rename` name for sessions still running or exited uncleanly
  * Fixed queued messages briefly appearing twice during multi-tool-call turns
  * Fixed session cleanup not removing the full session directory including subagent transcripts
  * Fixed dropped keystrokes after the CLI relaunches (e.g. `/tui`, provider setup wizards)
  * Fixed garbled startup rendering in macOS Terminal.app and other terminals that don't support synchronized output
  * Hardened "Open in editor" actions against command injection from untrusted filenames
  * Fixed `PermissionRequest` hooks returning `updatedInput` not being re-checked against `permissions.deny` rules; `setMode:'bypassPermissions'` updates now respect `disableBypassPermissionsMode`
  * Fixed `PreToolUse` hook `additionalContext` being dropped when the tool call fails
  * Fixed stdio MCP servers that print stray non-JSON lines to stdout being disconnected on the first stray line (regression in 2.1.105)
  * Fixed headless/SDK session auto-title firing an extra Haiku request when `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` or `CLAUDE_CODE_DISABLE_TERMINAL_TITLE` is set
  * Fixed potential excessive memory allocation when piped (non-TTY) Ink output contains a single very wide line
  * Fixed `/skills` menu not scrolling when the list overflows the modal in fullscreen mode
  * 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
</Update>

<Update label="2.1.109" description="April 15, 2026">
  * Improved the extended-thinking indicator with a rotating progress hint
</Update>

<Update label="2.1.108" description="April 14, 2026">
  * Added `ENABLE_PROMPT_CACHING_1H` env var to opt into 1-hour prompt cache TTL on API key, Bedrock, Vertex, and Foundry (`ENABLE_PROMPT_CACHING_1H_BEDROCK` is deprecated but still honored), and `FORCE_PROMPT_CACHING_5M` to force 5-minute TTL
  * Added recap feature to provide context when returning to a session, configurable in `/config` and manually invocable with `/recap`; force with `CLAUDE_CODE_ENABLE_AWAY_SUMMARY` if telemetry disabled.
  * The model can now discover and invoke built-in slash commands like `/init`, `/review`, and `/security-review` via the Skill tool
  * `/undo` is now an alias for `/rewind`
  * Improved `/model` to warn before switching models mid-conversation, since the next response re-reads the full history uncached
  * Improved `/resume` picker to default to sessions from the current directory; press `Ctrl+A` to show all projects
  * Improved error messages: server rate limits are now distinguished from plan usage limits; 5xx/529 errors show a link to status.claude.com; unknown slash commands suggest the closest match
  * Reduced memory footprint for file reads, edits, and syntax highlighting by loading language grammars on demand
  * Added "verbose" indicator when viewing the detailed transcript (`Ctrl+O`)
  * Added a warning at startup when prompt caching is disabled via `DISABLE_PROMPT_CACHING*` environment variables
  * Fixed paste not working in the `/login` code prompt (regression in 2.1.105)
  * Fixed subscribers who set `DISABLE_TELEMETRY` falling back to 5-minute prompt cache TTL instead of 1 hour
  * Fixed Agent tool prompting for permission in auto mode when the safety classifier's transcript exceeded its context window
  * Fixed Bash tool producing no output when `CLAUDE_ENV_FILE` (e.g. `~/.zprofile`) ends with a `#` comment line
  * Fixed `claude --resume <session-id>` losing the session's custom name and color set via `/rename`
  * Fixed session titles showing placeholder example text when the first message is a short greeting
  * Fixed terminal escape codes appearing as garbage text in the prompt input after `--teleport`
  * Fixed `/feedback` retry: pressing Enter to resubmit after a failure now works without first editing the description
  * Fixed `--teleport` and `--resume <id>` precondition errors (e.g. dirty git tree, session not found) exiting silently instead of showing the error message
  * Fixed Remote Control session titles set in the web UI being overwritten by auto-generated titles after the third message
  * Fixed `--resume` truncating sessions when the transcript contained a self-referencing message
  * Fixed transcript write failures (e.g., disk full) being silently dropped instead of being logged
  * 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
</Update>

<Update label="2.1.107" description="April 14, 2026">
  * Show thinking hints sooner during long operations
</Update>

<Update label="2.1.105" description="April 13, 2026">
  * Added `path` parameter to the `EnterWorktree` tool to switch into an existing worktree of the current repository
  * Added PreCompact hook support: hooks can now block compaction by exiting with code 2 or returning `{"decision":"block"}`
  * Added background monitor support for plugins via a top-level `monitors` manifest key that auto-arms at session start or on skill invoke
  * `/proactive` is now an alias for `/loop`
  * Improved stalled API stream handling: streams now abort after 5 minutes of no data and retry non-streaming instead of hanging indefinitely
  * Improved network error messages: connection errors now show a retry message immediately instead of a silent spinner
  * Improved file write display: long single-line writes (e.g. minified JSON) are now truncated in the UI instead of paginating across many screens
  * Improved `/doctor` layout with status icons; press `f` to have Claude fix reported issues
  * Improved `/config` labels and descriptions for clarity
  * Improved skill description handling: raised the listing cap from 250 to 1,536 characters and added a startup warning when descriptions are truncated
  * Improved `WebFetch` to strip `<style>` and `<script>` contents from fetched pages so CSS-heavy pages no longer exhaust the content budget before reaching actual text
  * Improved stale agent worktree cleanup to remove worktrees whose PR was squash-merged instead of keeping them indefinitely
  * Improved MCP large-output truncation prompt to give format-specific recipes (e.g. `jq` for JSON, computed Read chunk sizes for text)
  * Fixed images attached to queued messages (sent while Claude is working) being dropped
  * Fixed screen going blank when the prompt input wraps to a second line in long conversations
  * Fixed leading whitespace getting copied when selecting multi-line assistant responses in fullscreen mode
  * Fixed leading whitespace being trimmed from assistant messages, breaking ASCII art and indented diagrams
  * Fixed garbled bash output when commands print clickable file links (e.g. Python `rich`/`loguru` logging)
  * Fixed alt+enter not inserting a newline in terminals using ESC-prefix alt encoding, and Ctrl+J not inserting a newline (regression in 2.1.100)
  * Fixed duplicate "Creating worktree" text in EnterWorktree/ExitWorktree tool display
  * Fixed queued user prompts disappearing from focus mode
  * Fixed one-shot scheduled tasks re-firing repeatedly when the file watcher missed the post-fire cleanup
  * Fixed inbound channel notifications being silently dropped after the first message for Team/Enterprise users
  * Fixed marketplace plugins with `package.json` and lockfile not having dependencies installed automatically after install/update
  * Fixed marketplace auto-update leaving the official marketplace in a broken state when a plugin process holds files open during the update
  * Fixed "Resume this session with..." hint not printing on exit after `/resume`, `--worktree`, or `/branch`
  * Fixed feedback survey shortcut keys firing when typed at the end of a longer prompt
  * Fixed stdio MCP server emitting malformed (non-JSON) output hanging the session instead of failing fast with "Connection closed"
  * Fixed MCP tools missing on the first turn of headless/remote-trigger sessions when MCP servers connect asynchronously
  * Fixed `/model` picker on AWS Bedrock in non-US regions persisting invalid `us.*` model IDs to `settings.json` when inference profile discovery is still in-flight
  * Fixed 429 rate-limit errors showing a raw JSON dump instead of a clean message for API-key, Bedrock, and Vertex users
  * Fixed crash on resume when session contains malformed text blocks
  * Fixed `/help` dropping the tab bar, Shortcuts heading, and footer at short terminal heights
  * Fixed malformed keybinding entry values in `keybindings.json` being silently loaded instead of rejected with a clear error
  * 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
</Update>

<Update label="2.1.101" description="April 10, 2026">
  * Added `/team-onboarding` command to generate a teammate ramp-up guide from your local Claude Code usage
  * Added OS CA certificate store trust by default, so enterprise TLS proxies work without extra setup (set `CLAUDE_CODE_CERT_STORE=bundled` to use only bundled CAs)
  * `/ultraplan` and other remote-session features now auto-create a default cloud environment instead of requiring web setup first
  * Improved brief mode to retry once when Claude responds with plain text instead of a structured message
  * Improved focus mode: Claude now writes more self-contained summaries since it knows you only see its final message
  * Improved tool-not-available errors to explain why and how to proceed when the model calls a tool that exists but isn't available in the current context
  * Improved rate-limit retry messages to show which limit was hit and when it resets instead of an opaque seconds countdown
  * Improved refusal error messages to include the API-provided explanation when available
  * Improved `claude -p --resume <name>` to accept session titles set via `/rename` or `--name`
  * Improved settings resilience: an unrecognized hook event name in `settings.json` no longer causes the entire file to be ignored
  * Improved plugin hooks from plugins force-enabled by managed settings to run when `allowManagedHooksOnly` is set
  * Improved `/plugin` and `claude plugin update` to show a warning when the marketplace could not be refreshed, instead of silently reporting a stale version
  * Improved plan mode to hide the "Refine with Ultraplan" option when the user's org or auth setup can't reach Claude Code on the web
  * Improved beta tracing to honor `OTEL_LOG_USER_PROMPTS`, `OTEL_LOG_TOOL_DETAILS`, and `OTEL_LOG_TOOL_CONTENT`; sensitive span attributes are no longer emitted unless opted in
  * Improved SDK `query()` to clean up subprocess and temp files when consumers `break` from `for await` or use `await using`
  * Fixed a command injection vulnerability in the POSIX `which` fallback used by LSP binary detection
  * Fixed a memory leak where long sessions retained dozens of historical copies of the message list in the virtual scroller
  * Fixed `--resume`/`--continue` losing conversation context on large sessions when the loader anchored on a dead-end branch instead of the live conversation
  * Fixed `--resume` chain recovery bridging into an unrelated subagent conversation when a subagent message landed near a main-chain write gap
  * Fixed a crash on `--resume` when a persisted Edit/Write tool result was missing its `file_path`
  * Fixed a hardcoded 5-minute request timeout that aborted slow backends (local LLMs, extended thinking, slow gateways) regardless of `API_TIMEOUT_MS`
  * Fixed `permissions.deny` rules not overriding a PreToolUse hook's `permissionDecision: "ask"` — previously the hook could downgrade a deny into a prompt
  * Fixed `--setting-sources` without `user` causing background cleanup to ignore `cleanupPeriodDays` and delete conversation history older than 30 days
  * Fixed Bedrock SigV4 authentication failing with 403 when `ANTHROPIC_AUTH_TOKEN`, `apiKeyHelper`, or `ANTHROPIC_CUSTOM_HEADERS` set an Authorization header
  * Fixed `claude -w <name>` failing with "already exists" after a previous session's worktree cleanup left a stale directory
  * Fixed subagents not inheriting MCP tools from dynamically-injected servers
  * Fixed sub-agents running in isolated worktrees being denied Read/Edit access to files inside their own worktree
  * Fixed sandboxed Bash commands failing with `mktemp: No such file or directory` after a fresh boot
  * Fixed `claude mcp serve` tool calls failing with "Tool execution failed" in MCP clients that validate `outputSchema`
  * Fixed `RemoteTrigger` tool's `run` action sending an empty body and being rejected by the server
  * Fixed several `/resume` picker issues: narrow default view hiding sessions from other projects, unreachable preview on Windows Terminal, incorrect cwd in worktrees, session-not-found errors not surfacing in stderr, terminal title not being set, and resume hint overlapping the prompt input
  * Fixed Grep tool ENOENT when the embedded ripgrep binary path becomes stale (VS Code extension auto-update, macOS App Translocation); now falls back to system `rg` and self-heals mid-session
  * Fixed `/btw` writing a copy of the entire conversation to disk on every use
  * Fixed `/context` Free space and Messages breakdown disagreeing with the header percentage
  * Fixed several plugin issues: slash commands resolving to the wrong plugin with duplicate `name:` frontmatter, `/plugin update` failing with `ENAMETOOLONG`, Discover showing already-installed plugins, directory-source plugins loading from a stale version cache, and skills not honoring `context: fork` and `agent` frontmatter fields
  * Fixed the `/mcp` menu offering OAuth-specific actions for MCP servers configured with `headersHelper`; Reconnect is now offered instead to re-invoke the helper script
  * Fixed `ctrl+]`, `ctrl+\`, and `ctrl+^` keybindings not firing in terminals that send raw C0 control bytes (Terminal.app, default iTerm2, xterm)
  * Fixed `/login` OAuth URL rendering with padding that prevented clean mouse selection
  * Fixed rendering issues: flicker in non-fullscreen mode when content above the visible area changed, terminal scrollback being wiped during long sessions in non-fullscreen mode, and mouse-scroll escape sequences occasionally leaking into the prompt as text
  * Fixed crash when `settings.json` env values are numbers instead of strings
  * Fixed in-app settings writes (e.g. `/add-dir --remember`, `/config`) not refreshing the in-memory snapshot, preventing removed directories from being revoked mid-session
  * Fixed custom keybindings (`~/.claude/keybindings.json`) not loading on Bedrock, Vertex, and other third-party providers
  * Fixed `claude --continue -p` not correctly continuing sessions created by `-p` or the SDK
  * 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
</Update>

<Update label="2.1.98" description="April 9, 2026">
  * Added interactive Google Vertex AI setup wizard accessible from the login screen when selecting "3rd-party platform", guiding you through GCP authentication, project and region configuration, credential verification, and model pinning
  * Added `CLAUDE_CODE_PERFORCE_MODE` env var: when set, Edit/Write/NotebookEdit fail on read-only files with a `p4 edit` hint instead of silently overwriting them
  * Added Monitor tool for streaming events from background scripts
  * Added subprocess sandboxing with PID namespace isolation on Linux when `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB` is set, and `CLAUDE_CODE_SCRIPT_CAPS` env var to limit per-session script invocations
  * Added `--exclude-dynamic-system-prompt-sections` flag to print mode for improved cross-user prompt caching
  * Added `workspace.git_worktree` to the status line JSON input, set whenever the current directory is inside a linked git worktree
  * Added W3C `TRACEPARENT` env var to Bash tool subprocesses when OTEL tracing is enabled, so child-process spans correctly parent to Claude Code's trace tree
  * LSP: Claude Code now identifies itself to language servers via `clientInfo` in the initialize request
  * Fixed a Bash tool permission bypass where a backslash-escaped flag could be auto-allowed as read-only and lead to arbitrary code execution
  * Fixed compound Bash commands bypassing forced permission prompts for safety checks and explicit ask rules in auto and bypass-permissions modes
  * Fixed read-only commands with env-var prefixes not prompting unless the var is known-safe (`LANG`, `TZ`, `NO_COLOR`, etc.)
  * Fixed redirects to `/dev/tcp/...` or `/dev/udp/...` not prompting instead of auto-allowing
  * Fixed stalled streaming responses timing out instead of falling back to non-streaming mode
  * Fixed 429 retries burning all attempts in \~13s when the server returns a small `Retry-After` — exponential backoff now applies as a minimum
  * Fixed MCP OAuth `oauth.authServerMetadataUrl` config override not being honored on token refresh after restart, affecting ADFS and similar IdPs
  * Fixed capital letters being dropped to lowercase on xterm and VS Code integrated terminal when the kitty keyboard protocol is active
  * Fixed macOS text replacements deleting the trigger word instead of inserting the substitution
  * Fixed `--dangerously-skip-permissions` being silently downgraded to accept-edits mode after approving a write to a protected path via Bash
  * Fixed managed-settings allow rules remaining active after an admin removed them, until process restart
  * Fixed `permissions.additionalDirectories` changes not applying mid-session — removed directories lose access immediately and added ones work without restart
  * Fixed removing a directory from `additionalDirectories` revoking access to the same directory passed via `--add-dir`
  * Fixed `Bash(cmd:*)` and `Bash(git commit *)` wildcard permission rules failing to match commands with extra spaces or tabs
  * Fixed `Bash(...)` deny rules being downgraded to a prompt for piped commands that mix `cd` with other segments
  * Fixed false Bash permission prompts for `cut -d /`, `paste -d /`, `column -s /`, `awk '{print $1}' file`, and filenames containing `%`
  * Fixed permission rules with names matching JavaScript prototype properties (e.g. `toString`) causing `settings.json` to be silently ignored
  * Fixed agent team members not inheriting the leader's permission mode when using `--dangerously-skip-permissions`
  * Fixed a crash in fullscreen mode when hovering over MCP tool results
  * Fixed copying wrapped URLs in fullscreen mode inserting spaces at line breaks
  * Fixed file-edit diffs disappearing from the UI on `--resume` when the edited file was larger than 10KB
  * Fixed several `/resume` picker issues: `--resume <name>` opening uneditable, filter reload wiping search state, empty list swallowing arrow keys, cross-project staleness, and transient task-status text replacing conversation summaries
  * Fixed `/export` not honoring absolute paths and `~`, and silently rewriting user-supplied extensions to `.txt`
  * Fixed `/effort max` being denied for unknown or future model IDs
  * Fixed slash command picker breaking when a plugin's frontmatter `name` is a YAML boolean keyword
  * Fixed rate-limit upsell text being hidden after message remounts
  * Fixed MCP tools with `_meta["anthropic/maxResultSizeChars"]` not bypassing the token-based persist layer
  * Fixed voice mode leaking dozens of space characters into the input when re-holding the push-to-talk key while the previous transcript is still processing
  * Fixed `DISABLE_AUTOUPDATER` not fully suppressing the npm registry version check and symlink modification on npm-based installs
  * Fixed a memory leak where Remote Control permission handler entries were retained for the lifetime of the session
  * Fixed background subagents that fail with an error not reporting partial progress to the parent agent
  * Fixed prompt-type Stop/SubagentStop hooks failing on long sessions, and hook evaluator API errors showing "JSON validation failed" instead of the real message
  * Fixed feedback survey rendering when dismissed
  * Fixed Bash `grep -f FILE` / `rg -f FILE` not prompting when reading a pattern file outside the working directory
  * Fixed stale subagent worktree cleanup removing worktrees that contain untracked files
  * Fixed `sandbox.network.allowMachLookup` not taking effect on macOS
  * Improved `/resume` filter hint labels and added project/worktree/branch names in the filter indicator
  * Improved footer indicators (Focus, notifications) to stay on the mode-indicator row instead of wrapping at narrow terminal widths
  * Improved `/agents` with a tabbed layout: a Running tab shows live subagents, and the Library tab adds Run agent and View running instance actions
  * Improved `/reload-plugins` to pick up plugin-provided skills without requiring a restart
  * Improved Accept Edits mode to auto-approve filesystem commands prefixed with safe env vars or process wrappers
  * Improved Vim mode: `j`/`k` in NORMAL mode now navigate history and select the footer pill at the input boundary
  * Improved hook errors in the transcript to include the first line of stderr for self-diagnosis without `--debug`
  * Improved OTEL tracing: interaction spans now correctly wrap full turns under concurrent SDK calls, and headless turns end spans per-turn
  * Improved transcript entries to carry final token usage instead of streaming placeholders
  * Updated the `/claude-api` skill to cover Managed Agents alongside Claude API
  * \[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.
  * Dropped `/compact` hints when `DISABLE_COMPACT` is set.
</Update>

<Update label="2.1.97" description="April 8, 2026">
  * Added focus view toggle (`Ctrl+O`) in `NO_FLICKER` mode showing prompt, one-line tool summary with edit diffstats, and final response
  * Added `refreshInterval` status line setting to re-run the status line command every N seconds
  * Added `workspace.git_worktree` to the status line JSON input, set when the current directory is inside a linked git worktree
  * Added `● N running` indicator in `/agents` next to agent types with live subagent instances
  * Added syntax highlighting for Cedar policy files (`.cedar`, `.cedarpolicy`)
  * Fixed `--dangerously-skip-permissions` being silently downgraded to accept-edits mode after approving a write to a protected path
  * Fixed and hardened Bash tool permissions, tightening checks around env-var prefixes and network redirects, and reducing false prompts on common commands
  * Fixed permission rules with names matching JavaScript prototype properties (e.g. `toString`) causing `settings.json` to be silently ignored
  * Fixed managed-settings allow rules remaining active after an admin removed them until process restart
  * Fixed `permissions.additionalDirectories` changes in settings not applying mid-session
  * Fixed removing a directory from `settings.permissions.additionalDirectories` revoking access to the same directory passed via `--add-dir`
  * Fixed MCP HTTP/SSE connections accumulating \~50 MB/hr of unreleased buffers when servers reconnect
  * Fixed MCP OAuth `oauth.authServerMetadataUrl` not being honored on token refresh after restart, fixing ADFS and similar IdPs
  * Fixed 429 retries burning all attempts in \~13 seconds when the server returns a small `Retry-After` — exponential backoff now applies as a minimum
  * Fixed rate-limit upgrade options disappearing after context compaction
  * Fixed several `/resume` picker issues: `--resume <name>` opening uneditable, Ctrl+A reload wiping search, empty list swallowing navigation, task-status text replacing conversation summary, and cross-project staleness
  * Fixed file-edit diffs disappearing on `--resume` when the edited file was larger than 10KB
  * Fixed `--resume` cache misses and lost mid-turn input from attachment messages not being saved to the transcript
  * Fixed messages typed while Claude is working not being persisted to the transcript
  * Fixed prompt-type `Stop`/`SubagentStop` hooks failing on long sessions, and hook evaluator API errors displaying "JSON validation failed" instead of the actual message
  * Fixed subagents with worktree isolation or `cwd:` override leaking their working directory back to the parent session's Bash tool
  * Fixed compaction writing duplicate multi-MB subagent transcript files on prompt-too-long retries
  * Fixed `claude plugin update` reporting "already at the latest version" for git-based marketplace plugins when the remote had newer commits
  * Fixed slash command picker breaking when a plugin's frontmatter `name` is a YAML boolean keyword
  * Fixed copying wrapped URLs in `NO_FLICKER` mode inserting spaces at line breaks
  * Fixed scroll rendering artifacts in `NO_FLICKER` mode when running inside zellij
  * Fixed a crash in `NO_FLICKER` mode when hovering over MCP tool results
  * Fixed a `NO_FLICKER` mode memory leak where API retries left stale streaming state
  * Fixed slow mouse-wheel scrolling in `NO_FLICKER` mode on Windows Terminal
  * Fixed custom status line not displaying in `NO_FLICKER` mode on terminals shorter than 24 rows
  * Fixed Shift+Enter and Alt/Cmd+arrow shortcuts not working in Warp with `NO_FLICKER` mode
  * 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)
  * Improved Accept Edits mode to auto-approve filesystem commands prefixed with safe env vars or process wrappers (e.g. `LANG=C rm foo`, `timeout 5 mkdir out`)
  * Improved auto mode and bypass-permissions mode to auto-approve sandbox network access prompts
  * Improved sandbox: `sandbox.network.allowMachLookup` now takes effect on macOS
  * Improved image handling: pasted and attached images are now compressed to the same token budget as images read via the Read tool
  * Improved slash command and `@`-mention completion to trigger after CJK sentence punctuation, so Japanese/Chinese input no longer requires a space before `/` or `@`
  * Improved Bridge sessions to show the local git repo, branch, and working directory on the claude.ai session card
  * Improved footer layout: indicators (Focus, notifications) now stay on the mode-indicator row instead of wrapping below
  * Improved context-low warning to show as a transient footer notification instead of a persistent row
  * Improved markdown blockquotes to show a continuous left bar across wrapped lines
  * Improved session transcript size by skipping empty hook entries and capping stored pre-edit file copies
  * Improved transcript accuracy: per-block entries now carry the final token usage instead of the streaming placeholder
  * Improved Bash tool OTEL tracing: subprocesses now inherit a W3C `TRACEPARENT` env var when tracing is enabled
  * Updated `/claude-api` skill to cover Managed Agents alongside the Claude API
</Update>

<Update label="2.1.96" description="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)
</Update>

<Update label="2.1.94" description="April 7, 2026">
  * Added support for Amazon Bedrock powered by Mantle, set `CLAUDE_CODE_USE_MANTLE=1`
  * Changed default effort level from medium to high for API-key, Bedrock/Vertex/Foundry, Team, and Enterprise users (control this with `/effort`)
  * Added compact `Slacked #channel` header with a clickable channel link for Slack MCP send-message tool calls
  * Added `keep-coding-instructions` frontmatter field support for plugin output styles
  * Added `hookSpecificOutput.sessionTitle` to `UserPromptSubmit` hooks for setting the session title
  * Plugin skills declared via `"skills": ["./"]` now use the skill's frontmatter `name` for the invocation name instead of the directory basename, giving a stable name across install methods
  * Fixed agents appearing stuck after a 429 rate-limit response with a long Retry-After header — the error now surfaces immediately instead of silently waiting
  * Fixed Console login on macOS silently failing with "Not logged in" when the login keychain is locked or its password is out of sync — the error is now surfaced and `claude doctor` diagnoses the fix
  * Fixed plugin skill hooks defined in YAML frontmatter being silently ignored
  * Fixed plugin hooks failing with "No such file or directory" when `CLAUDE_PLUGIN_ROOT` was not set
  * Fixed `${CLAUDE_PLUGIN_ROOT}` resolving to the marketplace source directory instead of the installed cache for local-marketplace plugins on startup
  * Fixed scrollback showing the same diff repeated and blank pages in long-running sessions
  * Fixed multiline user prompts in the transcript indenting wrapped lines under the `❯` caret instead of under the text
  * Fixed Shift+Space inserting the literal word "space" instead of a space character in search inputs
  * Fixed hyperlinks opening two browser tabs when clicked inside tmux running in an xterm.js-based terminal (VS Code, Hyper, Tabby)
  * Fixed an alt-screen rendering bug where content height changes mid-scroll could leave compounding ghost lines
  * Fixed `FORCE_HYPERLINK` environment variable being ignored when set via `settings.json` `env`
  * Fixed native terminal cursor not tracking the selected tab in dialogs, so screen readers and magnifiers can follow tab navigation
  * Fixed Bedrock invocation of Sonnet 3.5 v2 by using the `us.` inference profile ID
  * Fixed SDK/print mode not preserving the partial assistant response in conversation history when interrupted mid-stream
  * Improved `--resume` to resume sessions from other worktrees of the same repo directly instead of printing a `cd` command
  * 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] Reduced cold-open subprocess work on starting a session
  * \[VSCode] Fixed dropdown menus selecting the wrong item when the mouse was over the list while typing or using arrow keys
  * \[VSCode] Added a warning banner when `settings.json` files fail to parse, so users know their permission rules are not being applied
</Update>

<Update label="2.1.92" description="April 4, 2026">
  * Added `forceRemoteSettingsRefresh` policy setting: when set, the CLI blocks startup until remote managed settings are freshly fetched, and exits if the fetch fails (fail-closed)
  * Added interactive Bedrock setup wizard accessible from the login screen when selecting "3rd-party platform" — guides you through AWS authentication, region configuration, credential verification, and model pinning
  * Added per-model and cache-hit breakdown to `/cost` for subscription users
  * `/release-notes` is now an interactive version picker
  * Remote Control session names now use your hostname as the default prefix (e.g. `myhost-graceful-unicorn`), overridable with `--remote-control-session-name-prefix`
  * Pro users now see a footer hint when returning to a session after the prompt cache has expired, showing roughly how many tokens the next turn will send uncached
  * Fixed subagent spawning permanently failing with "Could not determine pane count" after tmux windows are killed or renumbered during a long-running session
  * Fixed prompt-type Stop hooks incorrectly failing when the small fast model returns `ok:false`, and restored `preventContinuation:true` semantics for non-Stop prompt-type hooks
  * Fixed tool input validation failures when streaming emits array/object fields as JSON-encoded strings
  * Fixed an API 400 error that could occur when extended thinking produced a whitespace-only text block alongside real content
  * Fixed accidental feedback survey submissions from auto-pilot keypresses and consecutive-prompt digit collisions
  * Fixed misleading "esc to interrupt" hint appearing alongside "esc to clear" when a text selection exists in fullscreen mode during processing
  * Fixed Homebrew install update prompts to use the cask's release channel (`claude-code` → stable, `claude-code@latest` → latest)
  * Fixed `ctrl+e` jumping to the end of the next line when already at end of line in multiline prompts
  * Fixed an issue where the same message could appear at two positions when scrolling up in fullscreen mode (iTerm2, Ghostty, and other terminals with DEC 2026 support)
  * 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
  * Improved Write tool diff computation speed for large files (60% faster on files with tabs/`&`/`$`)
  * Removed `/tag` command
  * Removed `/vim` command (toggle vim mode via `/config` → Editor mode)
  * Linux sandbox now ships the `apply-seccomp` helper in both npm and native builds, restoring unix-socket blocking for sandboxed commands
</Update>

<Update label="2.1.91" description="April 2, 2026">
  * Added MCP tool result persistence override via `_meta["anthropic/maxResultSizeChars"]` annotation (up to 500K), allowing larger results like DB schemas to pass through without truncation
  * Added `disableSkillShellExecution` setting to disable inline shell execution in skills, custom slash commands, and plugin commands
  * Added support for multi-line prompts in `claude-cli://open?q=` deep links (encoded newlines `%0A` no longer rejected)
  * Plugins can now ship executables under `bin/` and invoke them as bare commands from the Bash tool
  * Fixed transcript chain breaks on `--resume` that could lose conversation history when async transcript writes fail silently
  * Fixed `cmd+delete` not deleting to start of line on iTerm2, kitty, WezTerm, Ghostty, and Windows Terminal
  * 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
  * `/feedback` now explains why it's unavailable instead of disappearing from the slash menu
  * Improved `/claude-api` skill guidance for agent design patterns including tool surface decisions, context management, and caching strategy
  * Improved performance: faster `stripAnsi` on Bun by routing through `Bun.stripANSI`
  * Edit tool now uses shorter `old_string` anchors, reducing output tokens
</Update>

<Update label="2.1.90" description="April 1, 2026">
  * Added `/powerup` — interactive lessons teaching Claude Code features with animated demos
  * Added `CLAUDE_CODE_PLUGIN_KEEP_MARKETPLACE_ON_FAILURE` env var to keep the existing marketplace cache when `git pull` fails, useful in offline environments
  * Added `.husky` to protected directories (acceptEdits mode)
  * Fixed an infinite loop where the rate-limit options dialog would repeatedly auto-open after hitting your usage limit, eventually crashing the session
  * Fixed `--resume` causing a full prompt-cache miss on the first request for users with deferred tools, MCP servers, or custom agents (regression since v2.1.69)
  * Fixed `Edit`/`Write` failing with "File content has changed" when a PostToolUse format-on-save hook rewrites the file between consecutive edits
  * Fixed `PreToolUse` hooks that emit JSON to stdout and exit with code 2 not correctly blocking the tool call
  * Fixed collapsed search/read summary badge appearing multiple times in fullscreen scrollback when a CLAUDE.md file auto-loads during a tool call
  * Fixed auto mode not respecting explicit user boundaries ("don't push", "wait for X before Y") even when the action would otherwise be allowed
  * 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
  * Hardened PowerShell tool permission checks: fixed trailing `&` background job bypass, `-ErrorAction Break` debugger hang, archive-extraction TOCTOU, and parse-fail fallback deny-rule degradation
  * Improved performance: eliminated per-turn JSON.stringify of MCP tool schemas on cache-key lookup
  * Improved performance: SSE transport now handles large streamed frames in linear time (was quadratic)
  * Improved performance: SDK sessions with long conversations no longer slow down quadratically on transcript writes
  * Improved `/resume` all-projects view to load project sessions in parallel, improving load times for users with many projects
  * Changed `--resume` picker to no longer show sessions created by `claude -p` or SDK invocations
  * Removed `Get-DnsClientCache` and `ipconfig /displaydns` from auto-allow (DNS cache privacy)
</Update>

<Update label="2.1.89" description="April 1, 2026">
  * Added `"defer"` permission decision to `PreToolUse` hooks — headless sessions can pause at a tool call and resume with `-p --resume` to have the hook re-evaluate
  * Added `CLAUDE_CODE_NO_FLICKER=1` environment variable to opt into flicker-free alt-screen rendering with virtualized scrollback
  * Added `PermissionDenied` hook that fires after auto mode classifier denials — return `{retry: true}` to tell the model it can retry
  * Added named subagents to `@` mention typeahead suggestions
  * Added `MCP_CONNECTION_NONBLOCKING=true` for `-p` mode to skip the MCP connection wait entirely, and bounded `--mcp-config` server connections at 5s instead of blocking on the slowest server
  * Auto mode: denied commands now show a notification and appear in `/permissions` → Recent tab where you can retry with `r`
  * Fixed `Edit(//path/**)` and `Read(//path/**)` allow rules to check the resolved symlink target, not just the requested path
  * Fixed voice push-to-talk not activating for some modifier-combo bindings, and voice mode on Windows failing with "WebSocket upgrade rejected with HTTP 101"
  * Fixed Edit/Write tools doubling CRLF on Windows and stripping Markdown hard line breaks (two trailing spaces)
  * Fixed `StructuredOutput` schema cache bug causing \~50% failure rate when using multiple schemas
  * Fixed memory leak where large JSON inputs were retained as LRU cache keys in long-running sessions
  * Fixed a crash when removing a message from very large session files (over 50MB)
  * Fixed LSP server zombie state after crash — server now restarts on next request instead of failing until session restart
  * Fixed prompt history entries containing CJK or emoji being silently dropped when they fall on a 4KB boundary in `~/.claude/history.jsonl`
  * Fixed `/stats` undercounting tokens by excluding subagent usage, and losing historical data beyond 30 days when the stats cache format changes
  * Fixed `-p --resume` hangs when the deferred tool input exceeds 64KB or no deferred marker exists, and `-p --continue` not resuming deferred tools
  * Fixed `claude-cli://` deep links not opening on macOS
  * Fixed MCP tool errors truncating to only the first content block when the server returns multi-element error content
  * Fixed skill reminders and other system context being dropped when sending messages with images via the SDK
  * Fixed PreToolUse/PostToolUse hooks to receive `file_path` as an absolute path for Write/Edit/Read tools, matching the documented behavior
  * Fixed autocompact thrash loop — now detects when context refills to the limit immediately after compacting three times in a row and stops with an actionable error instead of burning API calls
  * Fixed prompt cache misses in long sessions caused by tool schema bytes changing mid-session
  * Fixed nested CLAUDE.md files being re-injected dozens of times in long sessions that read many files
  * Fixed `--resume` crash when transcript contains a tool result from an older CLI version or interrupted write
  * Fixed misleading "Rate limit reached" message when the API returned an entitlement error — now shows the actual error with actionable hints
  * Fixed hooks `if` condition filtering not matching compound commands (`ls && git push`) or commands with env-var prefixes (`FOO=bar git push`)
  * Fixed collapsed search/read group badges duplicating in terminal scrollback during heavy parallel tool use
  * Fixed notification `invalidates` not clearing the currently-displayed notification immediately
  * Fixed prompt briefly disappearing after submit when background messages arrived during processing
  * Fixed Devanagari and other combining-mark text being truncated in assistant output
  * Fixed rendering artifacts on main-screen terminals after layout shifts
  * Fixed voice mode failing to request microphone permission on macOS Apple Silicon
  * Fixed Shift+Enter submitting instead of inserting a newline on Windows Terminal Preview 1.25
  * Fixed periodic UI jitter during streaming in iTerm2 when running inside tmux
  * 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)
  * Improved collapsed tool summary to show "Listed N directories" for `ls`/`tree`/`du` instead of "Read N files"
  * Improved Bash tool to warn when a formatter/linter command modifies files you have previously read, preventing stale-edit errors
  * Improved `@`-mention typeahead to rank source files above MCP resources with similar names
  * Improved PowerShell tool prompt with version-appropriate syntax guidance (5.1 vs 7+)
  * Changed `Edit` to work on files viewed via `Bash` with `sed -n` or `cat`, without requiring a separate `Read` call first
  * Changed hook output over 50K characters to be saved to disk with a file path + preview instead of being injected directly into context
  * Changed `cleanupPeriodDays: 0` in settings.json to be rejected with a validation error — it previously silently disabled transcript persistence
  * Changed thinking summaries to no longer be generated by default in interactive sessions — set `showThinkingSummaries: true` in settings.json to restore
  * Documented `TaskCreated` hook event and its blocking behavior
  * Preserved task notifications when backgrounding a running command with Ctrl+B
  * PowerShell tool on Windows: external-command arguments containing both a double-quote and whitespace now prompt instead of auto-allowing (PS 5.1 argument-splitting hardening)
  * `/env` now applies to PowerShell tool commands (previously only affected Bash)
  * `/usage` now hides redundant "Current week (Sonnet only)" bar for Pro and Enterprise plans
  * Image paste no longer inserts a trailing space
  * Pasting `!command` into an empty prompt now enters bash mode, matching typed `!` behavior
  * `/buddy` is here for April 1st — hatch a small creature that watches you code
</Update>

<Update label="2.1.87" description="March 29, 2026">
  * Fixed messages in Cowork Dispatch not getting delivered
</Update>

<Update label="2.1.86" description="March 27, 2026">
  * Added `X-Claude-Code-Session-Id` header to API requests so proxies can aggregate requests by session without parsing the body
  * Added `.jj` and `.sl` to VCS directory exclusion lists so Grep and file autocomplete don't descend into Jujutsu or Sapling metadata
  * Fixed `--resume` failing with "tool\_use ids were found without tool\_result blocks" on sessions created before v2.1.85
  * Fixed Write/Edit/Read failing on files outside the project root (e.g., `~/.claude/CLAUDE.md`) when conditional skills or rules are configured
  * Fixed unnecessary config disk writes on every skill invocation that could cause performance issues and config corruption on Windows
  * Fixed potential out-of-memory crash when using `/feedback` on very long sessions with large transcript files
  * Fixed `--bare` mode dropping MCP tools in interactive sessions and silently discarding messages enqueued mid-turn
  * Fixed the `c` shortcut copying only \~20 characters of the OAuth login URL instead of the full URL
  * Fixed masked input (e.g., OAuth code paste) leaking the start of the token when wrapping across multiple lines on narrow terminals
  * Fixed official marketplace plugin scripts failing with "Permission denied" on macOS/Linux since v2.1.83
  * Fixed statusline showing another session's model when running multiple Claude Code instances and using `/model` in one of them
  * Fixed scroll not following new messages after wheel scroll or click-to-select at the bottom of a long conversation
  * Fixed `/plugin` uninstall dialog: pressing `n` now correctly uninstalls the plugin while preserving its data directory
  * Fixed a regression where pressing Enter after clicking could leave the transcript blank until the response arrived
  * Fixed `ultrathink` hint lingering after deleting the keyword
  * Fixed memory growth in long sessions from markdown/highlight render caches retaining full content strings
  * Reduced startup event-loop stalls when many claude.ai MCP connectors are configured (macOS keychain cache extended from 5s to 30s)
  * Reduced token overhead when mentioning files with `@` — raw string content no longer JSON-escaped
  * Improved prompt cache hit rate for Bedrock, Vertex, and Foundry users by removing dynamic content from tool descriptions
  * Memory filenames in the "Saved N memories" notice now highlight on hover and open on click
  * Skill descriptions in the `/skills` listing are now capped at 250 characters to reduce context usage
  * Changed `/skills` menu to sort alphabetically for easier scanning
  * Auto mode now shows "unavailable for your plan" when disabled by plan restrictions (was "temporarily unavailable")
  * \[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)
  * Read tool now uses compact line-number format and deduplicates unchanged re-reads, reducing token usage
</Update>

<Update label="2.1.85" description="March 26, 2026">
  * Added `CLAUDE_CODE_MCP_SERVER_NAME` and `CLAUDE_CODE_MCP_SERVER_URL` environment variables to MCP `headersHelper` scripts, allowing one helper to serve multiple servers
  * Added conditional `if` field for hooks using permission rule syntax (e.g., `Bash(git *)`) to filter when they run, reducing process spawning overhead
  * Added timestamp markers in transcripts when scheduled tasks (`/loop`, `CronCreate`) fire
  * Added trailing space after `[Image #N]` placeholder when pasting images
  * Deep link queries (`claude-cli://open?q=…`) now support up to 5,000 characters, with a "scroll to review" warning for long pre-filled prompts
  * MCP OAuth now follows RFC 9728 Protected Resource Metadata discovery to find the authorization server
  * Plugins blocked by organization policy (`managed-settings.json`) can no longer be installed or enabled, and are hidden from marketplace views
  * PreToolUse hooks can now satisfy `AskUserQuestion` by returning `updatedInput` alongside `permissionDecision: "allow"`, enabling headless integrations that collect answers via their own UI
  * `tool_parameters` in OpenTelemetry tool\_result events are now gated behind `OTEL_LOG_TOOL_DETAILS=1`
  * Fixed `/compact` failing with "context exceeded" when the conversation has grown too large for the compact request itself to fit
  * Fixed `/plugin enable` and `/plugin disable` failing when a plugin's install location differs from where it's declared in settings
  * Fixed `--worktree` exiting with an error in non-git repositories before the `WorktreeCreate` hook could run
  * Fixed `deniedMcpServers` setting not blocking claude.ai MCP servers
  * Fixed `switch_display` in the computer-use tool returning "not available in this session" on multi-monitor setups
  * Fixed crash when `OTEL_LOGS_EXPORTER`, `OTEL_METRICS_EXPORTER`, or `OTEL_TRACES_EXPORTER` is set to `none`
  * Fixed diff syntax highlighting not working in non-native builds
  * Fixed MCP step-up authorization failing when a refresh token exists — servers requesting elevated scopes via `403 insufficient_scope` now correctly trigger the re-authorization flow
  * Fixed memory leak in remote sessions when a streaming response is interrupted
  * Fixed persistent ECONNRESET errors during edge connection churn by using a fresh TCP connection on retry
  * Fixed prompts getting stuck in the queue after running certain slash commands, with up-arrow unable to retrieve them
  * Fixed Python Agent SDK: `type:'sdk'` MCP servers passed via `--mcp-config` are no longer dropped during startup
  * Fixed raw key sequences appearing in the prompt when running over SSH or in the VS Code integrated terminal
  * Fixed Remote Control session status staying stuck on "Requires Action" after a permission is resolved
  * Fixed shift+enter and meta+enter being intercepted by typeahead suggestions instead of inserting newlines
  * 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
  * Improved @-mention file autocomplete performance on large repositories
  * Improved PowerShell dangerous command detection
  * Improved scroll performance with large transcripts by replacing WASM yoga-layout with a pure TypeScript implementation
  * Reduced UI stutter when compaction triggers on large sessions
</Update>

<Update label="2.1.84" description="March 26, 2026">
  * Added PowerShell tool for Windows as an opt-in preview. Learn more at [https://code.claude.com/docs/en/tools-reference#powershell-tool](../04-API-Reference/tools-reference-claude-code-docs-d21fdcb4c5.md#powershell-tool)
  * Added `ANTHROPIC_DEFAULT_{OPUS,SONNET,HAIKU}_MODEL_SUPPORTS` env vars to override effort/thinking capability detection for pinned default models for 3p (Bedrock, Vertex, Foundry), and `_MODEL_NAME`/`_DESCRIPTION` to customize the `/model` picker label
  * Added `CLAUDE_STREAM_IDLE_TIMEOUT_MS` env var to configure the streaming idle watchdog threshold (default 90s)
  * Added `TaskCreated` hook that fires when a task is created via `TaskCreate`
  * Added `WorktreeCreate` hook support for `type: "http"` — return the created worktree path via `hookSpecificOutput.worktreePath` in the response JSON
  * Added `allowedChannelPlugins` managed setting for team/enterprise admins to define a channel plugin allowlist
  * Added `x-client-request-id` header to API requests for debugging timeouts
  * Added idle-return prompt that nudges users returning after 75+ minutes to `/clear`, reducing unnecessary token re-caching on stale sessions
  * Deep links (`claude-cli://`) now open in your preferred terminal instead of whichever terminal happens to be first in the detection list
  * Rules and skills `paths:` frontmatter now accepts a YAML list of globs
  * MCP tool descriptions and server instructions are now capped at 2KB to prevent OpenAPI-generated servers from bloating context
  * MCP servers configured both locally and via claude.ai connectors are now deduplicated — the local config wins
  * Background bash tasks that appear stuck on an interactive prompt now surface a notification after \~45 seconds
  * Token counts ≥1M now display as "1.5m" instead of "1512.6k"
  * Global system-prompt caching now works when `ToolSearch` is enabled, including for users with MCP tools configured
  * Fixed voice push-to-talk: holding the voice key no longer leaks characters into the text input, and transcripts now insert at the correct position
  * Fixed up/down arrow keys being unresponsive when a footer item is focused
  * Fixed `Ctrl+U` (kill-to-line-start) being a no-op at line boundaries in multiline input, so repeated `Ctrl+U` now clears across lines
  * Fixed null-unbinding a default chord binding (e.g. `"ctrl+x ctrl+k": null`) still entering chord-wait mode instead of freeing the prefix key
  * Fixed mouse events inserting literal "mouse" text into transcript search input
  * Fixed workflow subagents failing with API 400 when the outer session uses `--json-schema` and the subagent also specifies a schema
  * Fixed missing background color behind certain emoji in user message bubbles on some terminals
  * Fixed the "allow Claude to edit its own settings for this session" permission option not sticking for users with `Edit(.claude)` allow rules
  * Fixed a hang when generating attachment snippets for large edited files
  * Fixed MCP tool/resource cache leak on server reconnect
  * Fixed a startup performance issue where partial clone repositories (Scalar/GVFS) triggered mass blob downloads
  * 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
  * Improved detection for dangerous removals of Windows drive roots (`C:\`, `C:\Windows`, etc.)
  * Improved interactive startup by \~30ms by running `setup()` in parallel with slash command and agent loading
  * Improved startup for `claude "prompt"` with MCP servers — the REPL now renders immediately instead of blocking until all servers connect
  * Improved Remote Control to show a specific reason when blocked instead of a generic "not yet enabled" message
  * Improved p90 prompt cache rate
  * Reduced scroll-to-top resets in long sessions by making the message window immune to compaction and grouping changes
  * Reduced terminal flickering when animated tool progress scrolls above the viewport
  * Changed issue/PR references to only become clickable links when written as `owner/repo#123` — bare `#123` is no longer auto-linked
  * Slash commands unavailable for the current auth setup (`/voice`, `/mobile`, `/chrome`, `/upgrade`, etc.) are now hidden instead of shown
  * \[VSCode] Added rate limit warning banner with usage percentage and reset time
  * Stats screenshot (Ctrl+S in /stats) now works in all builds and is 16× faster
</Update>

<Update label="2.1.83" description="March 25, 2026">
  * Added `managed-settings.d/` drop-in directory alongside `managed-settings.json`, letting separate teams deploy independent policy fragments that merge alphabetically
  * Added `CwdChanged` and `FileChanged` hook events for reactive environment management (e.g., direnv)
  * Added `sandbox.failIfUnavailable` setting to exit with an error when sandbox is enabled but cannot start, instead of running unsandboxed
  * Added `disableDeepLinkRegistration` setting to prevent `claude-cli://` protocol handler registration
  * Added `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=1` to strip Anthropic and cloud provider credentials from subprocess environments (Bash tool, hooks, MCP stdio servers)
  * Added transcript search — press `/` in transcript mode (`Ctrl+O`) to search, `n`/`N` to step through matches
  * Added `Ctrl+X Ctrl+E` as an alias for opening the external editor (readline-native binding; `Ctrl+G` still works)
  * Pasted images now insert an `[Image #N]` chip at the cursor so you can reference them positionally in your prompt
  * Agents can now declare `initialPrompt` in frontmatter to auto-submit a first turn
  * `chat:killAgents` and `chat:fastMode` are now rebindable via `~/.claude/keybindings.json`
  * Fixed mouse tracking escape sequences leaking to shell prompt after exit
  * Fixed Claude Code hanging on exit on macOS
  * Fixed screen flashing blank after being idle for a few seconds
  * Fixed a hang when diffing very large files with few common lines — diffs now time out after 5 seconds and fall back gracefully
  * Fixed a 1–8 second UI freeze on startup when voice input was enabled, caused by eagerly loading the native audio module
  * Fixed a startup regression where Claude Code would wait \~3s for claude.ai MCP config fetch before proceeding
  * Fixed `--mcp-config` CLI flag bypassing `allowedMcpServers`/`deniedMcpServers` managed policy enforcement
  * Fixed claude.ai MCP connectors (Slack, Gmail, etc.) not being available in single-turn `--print` mode
  * Fixed `caffeinate` process not properly terminating when Claude Code exits, preventing Mac from sleeping
  * Fixed bash mode not activating when tab-accepting `!`-prefixed command suggestions
  * Fixed stale slash command selection showing wrong highlighted command after navigating suggestions
  * Fixed `/config` menu showing both the search cursor and list selection at the same time
  * Fixed background subagents becoming invisible after context compaction, which could cause duplicate agents to be spawned
  * Fixed background agent tasks staying stuck in "running" state when git or API calls hang during cleanup
  * Fixed `--channels` showing "Channels are not currently available" on first launch after upgrade
  * Fixed uninstalled plugin hooks continuing to fire until the next session
  * Fixed queued commands flickering during streaming responses
  * Fixed slash commands being sent to the model as text when submitted while a message is processing
  * Fixed scrollback jumping when collapsed read/search groups finish after scrolling offscreen
  * Fixed scrollback jumping to top when the model starts or stops thinking
  * Fixed SDK session history loss on resume caused by hook progress/attachment messages forking the parentUuid chain
  * Fixed copy-on-select not firing when you release the mouse outside the terminal window
  * Fixed ghost characters appearing in height-constrained lists when items overflow
  * Fixed `Ctrl+B` interfering with readline backward-char at an idle prompt — it now only fires when a foreground task can be backgrounded
  * Fixed tool result files never being cleaned up, ignoring the `cleanupPeriodDays` setting
  * Fixed space key being swallowed for up to 3 seconds after releasing voice hold-to-talk
  * Fixed ALSA library errors corrupting the terminal UI when using voice mode on Linux without audio hardware (Docker, headless, WSL1)
  * Fixed voice mode SoX detection on Termux/Android where spawning `which` is kernel-restricted
  * Fixed Remote Control sessions showing as Idle in the web session list while actively running
  * Fixed footer navigation selecting an invisible Remote Control pill in config-driven mode
  * Fixed memory leak in remote sessions where tool use IDs accumulate indefinitely
  * Improved Bedrock SDK cold-start latency by overlapping profile fetch with other boot work
  * Improved `--resume` memory usage and startup latency on large sessions
  * Improved plugin startup — commands, skills, and agents now load from disk cache without re-fetching
  * Improved Remote Control session titles: AI-generated titles now appear within seconds of the first message
  * Improved `WebFetch` to identify as `Claude-User` so site operators can recognize and allowlist Claude Code traffic via `robots.txt`
  * Reduced `WebFetch` peak memory usage for large pages
  * Reduced scrollback resets in long sessions from once per turn to once per \~50 messages
  * Faster `claude -p` startup with unauthenticated HTTP/SSE MCP servers (\~600ms saved)
  * Bash ghost-text suggestions now include just-submitted commands immediately
  * Increased non-streaming fallback token cap (21k → 64k) and timeout (120s → 300s local) so fallback requests are less likely to be truncated
  * Interrupting a prompt before any response now automatically restores your input so you can edit and resubmit
  * `/status` now works while Claude is responding, instead of being queued until the turn finishes
  * Plugin MCP servers that duplicate an org-managed connector are now suppressed instead of running a second connection
  * Linux: respect `XDG_DATA_HOME` when registering the `claude-cli://` protocol handler
  * Changed "stop all background agents" keybinding from `Ctrl+F` to `Ctrl+X Ctrl+K` to stop shadowing readline forward-char
  * Deprecated `TaskOutput` tool in favor of using `Read` on the background task's output file path
  * Added `CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK` env var to disable the non-streaming fallback when streaming fails
  * Plugin options (`manifest.userConfig`) now available externally — plugins can prompt for configuration at enable time, with `sensitive: true` values stored in keychain (macOS) or protected credentials file (other platforms)
  * Claude can now reference the on-disk path of clipboard-pasted images for file operations
  * `Ctrl+L` now clears the screen and forces a full redraw — use this to recover when Cmd+K leaves the UI partially blank. Use `Ctrl+U` or double-Esc to clear prompt input.
  * `--bare -p` (SDK pattern) is \~14% faster to the API request
  * Memory: `MEMORY.md` index now truncates at 25KB as well as 200 lines
  * Disabled `AskUserQuestion` and plan-mode tools when `--channels` is active
  * Fixed API 400 error when a pasted image was queued during a failing tool call
  * Fixed MCP tool calls hanging indefinitely when an SSE connection drops mid-call and exhausts its reconnection attempts
  * Fixed Remote Control session titles showing raw XML when a background agent completed before the first user message
  * Fixed remote sessions forgetting conversation history after a container restart due to progress-message gaps in the resumed transcript chain
  * Fixed remote sessions requiring re-login on transient auth errors instead of retrying automatically
  * Fixed `rg ... | wc -l` and similar piped commands hanging and returning `0` in sandbox mode on Linux
  * Fixed voice input hold-to-talk not activating when a CJK IME inserts a full-width space
  * Fixed `--worktree` hanging silently when the worktree name contained a forward slash
  * \[VSCode] Spinner now turns red with "Not responding" when the backend hasn't responded for 60 seconds
  * \[VSCode] Fixed session history not loading correctly when reopening a session via URL or after restart
  * \[VSCode] Added Esc-twice (or `/rewind`) to open a keyboard-navigable rewind picker
  * \[VSCode] Fixed "Fork conversation from here" and rewind actions failing silently after the session cache goes stale
</Update>

<Update label="2.1.81" description="March 20, 2026">
  * Added `--bare` flag for scripted `-p` calls — skips hooks, LSP, plugin sync, and skill directory walks; requires `ANTHROPIC_API_KEY` or an `apiKeyHelper` via `--settings` (OAuth and keychain auth disabled); auto-memory fully disabled
  * Added `--channels` permission relay — channel servers that declare the permission capability can forward tool approval prompts to your phone
  * Fixed multiple concurrent Claude Code sessions requiring repeated re-authentication when one session refreshes its OAuth token
  * Fixed voice mode silently swallowing retry failures and showing a misleading "check your network" message instead of the actual error
  * Fixed voice mode audio not recovering when the server silently drops the WebSocket connection
  * Fixed `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` not suppressing the structured-outputs beta header, causing 400 errors on proxy gateways forwarding to Vertex/Bedrock
  * Fixed `--channels` bypass for Team/Enterprise orgs with no other managed settings configured
  * Fixed a crash on Node.js 18
  * Fixed unnecessary permission prompts for Bash commands containing dashes in strings
  * Fixed plugin hooks blocking prompt submission when the plugin directory is deleted mid-session
  * Fixed a race condition where background agent task output could hang indefinitely when the task completed between polling intervals
  * Resuming a session that was in a worktree now switches back to that worktree
  * Fixed `/btw` not including pasted text when used during an active response
  * Fixed a race where fast Cmd+Tab followed by paste could beat the clipboard copy under tmux
  * Fixed terminal tab title not updating with an auto-generated session description
  * Fixed invisible hook attachments inflating the message count in transcript mode
  * Fixed Remote Control sessions showing a generic title instead of deriving from the first prompt
  * Fixed `/rename` not syncing the title for Remote Control sessions
  * Fixed Remote Control `/exit` not reliably archiving the session
  * Improved MCP read/search tool calls to collapse into a single "Queried `{server}`" line (expand with Ctrl+O)
  * Improved `!` bash mode discoverability — Claude now suggests it when you need to run an interactive command
  * Improved plugin freshness — ref-tracked plugins now re-clone on every load to pick up upstream changes
  * Improved Remote Control session titles to refresh after your third message
  * Updated MCP OAuth to support Client ID Metadata Document (CIMD / SEP-991) for servers without Dynamic Client Registration
  * Changed plan mode to hide the "clear context" option by default (restore with `"showClearContextOnPlanAccept": true`)
  * Disabled line-by-line response streaming on Windows (including WSL in Windows Terminal) due to rendering issues
  * \[VSCode] Fixed Windows PATH inheritance for Bash tool when using Git Bash (regression in v2.1.78)
</Update>

<Update label="2.1.80" description="March 19, 2026">
  * Added `rate_limits` field to statusline scripts for displaying Claude.ai rate limit usage (5-hour and 7-day windows with `used_percentage` and `resets_at`)
  * Added `source: 'settings'` plugin marketplace source — declare plugin entries inline in settings.json
  * Added CLI tool usage detection to plugin tips, in addition to file pattern matching
  * Added `effort` frontmatter support for skills and slash commands to override the model effort level when invoked
  * Added `--channels` (research preview) — allow MCP servers to push messages into your session
  * Fixed `--resume` dropping parallel tool results — sessions with parallel tool calls now restore all tool\_use/tool\_result pairs instead of showing `[Tool result missing]` placeholders
  * Fixed voice mode WebSocket failures caused by Cloudflare bot detection on non-browser TLS fingerprints
  * Fixed 400 errors when using fine-grained tool streaming through API proxies, Bedrock, or Vertex
  * 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
  * Improved responsiveness of `@` file autocomplete in large git repositories
  * Improved `/effort` to show what auto currently resolves to, matching the status bar indicator
  * Improved `/permissions` — Tab and arrow keys now switch tabs from within a list
  * Improved background tasks panel — left arrow now closes from the list view
  * Simplified plugin install tips to use a single `/plugin install` command instead of a two-step flow
  * Reduced memory usage on startup in large repositories (\~80 MB saved on 250k-file repos)
  * 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
</Update>

<Update label="2.1.79" description="March 18, 2026">
  * Added `--console` flag to `claude auth login` for Anthropic Console (API billing) authentication
  * Added "Show turn duration" toggle to the `/config` menu
  * Fixed `claude -p` hanging when spawned as a subprocess without explicit stdin (e.g. Python `subprocess.run`)
  * Fixed Ctrl+C not working in `-p` (print) mode
  * Fixed `/btw` returning the main agent's output instead of answering the side question when triggered during streaming
  * Fixed voice mode not activating correctly on startup when `voiceEnabled: true` is set
  * Fixed left/right arrow tab navigation in `/permissions`
  * Fixed `CLAUDE_CODE_DISABLE_TERMINAL_TITLE` not preventing terminal title from being set on startup
  * Fixed custom status line showing nothing when workspace trust is blocking it
  * Fixed enterprise users being unable to retry on rate limit (429) errors
  * Fixed `SessionEnd` hooks not firing when using interactive `/resume` to switch sessions
  * Improved startup memory usage by \~18MB across all scenarios
  * Improved non-streaming API fallback with a 2-minute per-attempt timeout, preventing sessions from hanging indefinitely
  * `CLAUDE_CODE_PLUGIN_SEED_DIR` now supports multiple seed directories separated by the platform path delimiter (`:` on Unix, `;` on Windows)
  * \[VSCode] Added `/remote-control` — bridge your session to claude.ai/code to continue from a browser or phone
  * \[VSCode] Session tabs now get AI-generated titles based on your first message
  * \[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
</Update>

<Update label="2.1.78" description="March 17, 2026">
  * Added `StopFailure` hook event that fires when the turn ends due to an API error (rate limit, auth failure, etc.)
  * Added `${CLAUDE_PLUGIN_DATA}` variable for plugin persistent state that survives plugin updates; `/plugin uninstall` prompts before deleting it
  * Added `effort`, `maxTurns`, and `disallowedTools` frontmatter support for plugin-shipped agents
  * Terminal notifications (iTerm2/Kitty/Ghostty popups, progress bar) now reach the outer terminal when running inside tmux with `set -g allow-passthrough on`
  * Response text now streams line-by-line as it's generated
  * Fixed `git log HEAD` failing with "ambiguous argument" inside sandboxed Bash on Linux, and stub files polluting `git status` in the working directory
  * Fixed `cc log` and `--resume` silently truncating conversation history on large sessions (>5 MB) that used subagents
  * Fixed infinite loop when API errors triggered stop hooks that re-fed blocking errors to the model
  * Fixed `deny: ["mcp__servername"]` permission rules not removing MCP server tools before sending to the model, allowing it to see and attempt blocked tools
  * Fixed `sandbox.filesystem.allowWrite` not working with absolute paths (previously required `//` prefix)
  * Fixed `/sandbox` Dependencies tab showing Linux prerequisites on macOS instead of macOS-specific info
  * **Security:** Fixed silent sandbox disable when `sandbox.enabled: true` is set but dependencies are missing — now shows a visible startup warning
  * Fixed `.git`, `.claude`, and other protected directories being writable without a prompt in `bypassPermissions` mode
  * Fixed ctrl+u in normal mode scrolling instead of readline kill-line (ctrl+u/ctrl+d half-page scroll moved to transcript mode only)
  * Fixed voice mode modifier-combo push-to-talk keybindings (e.g. ctrl+k) requiring a hold instead of activating immediately
  * Fixed voice mode not working on WSL2 with WSLg (Windows 11); WSL1/Win10 users now get a clear error
  * Fixed `--worktree` flag not loading skills and hooks from the worktree directory
  * Fixed `CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS` and `includeGitInstructions` setting not suppressing the git status section in the system prompt
  * Fixed Bash tool not finding Homebrew and other PATH-dependent binaries when VS Code is launched from Dock/Spotlight
  * Fixed washed-out Claude orange color in VS Code/Cursor/code-server terminals that don't advertise truecolor support
  * Added `ANTHROPIC_CUSTOM_MODEL_OPTION` env var to add a custom entry to the `/model` picker, with optional `_NAME` and `_DESCRIPTION` suffixed vars for display
  * Fixed `ANTHROPIC_BETAS` environment variable being silently ignored when using Haiku models
  * Fixed queued prompts being concatenated without a newline separator
  * Improved memory usage and startup time when resuming large sessions
  * \[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
</Update>

<Update label="2.1.77" description="March 17, 2026">
  * Increased default maximum output token limits for Claude Opus 4.6 to 64k tokens, and the upper bound for Opus 4.6 and Sonnet 4.6 models to 128k tokens
  * Added `allowRead` sandbox filesystem setting to re-allow read access within `denyRead` regions
  * `/copy` now accepts an optional index: `/copy N` copies the Nth-latest assistant response
  * Fixed "Always Allow" on compound bash commands (e.g. `cd src && npm test`) saving a single rule for the full string instead of per-subcommand, leading to dead rules and repeated permission prompts
  * Fixed auto-updater starting overlapping binary downloads when the slash-command overlay repeatedly opened and closed, accumulating tens of gigabytes of memory
  * Fixed `--resume` silently truncating recent conversation history due to a race between memory-extraction writes and the main transcript
  * Fixed PreToolUse hooks returning `"allow"` bypassing `deny` permission rules, including enterprise managed settings
  * Fixed Write tool silently converting line endings when overwriting CRLF files or creating files in CRLF directories
  * Fixed memory growth in long-running sessions from progress messages surviving compaction
  * Fixed cost and token usage not being tracked when the API falls back to non-streaming mode
  * Fixed `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` not stripping beta tool-schema fields, causing proxy gateways to reject requests
  * Fixed Bash tool reporting errors for successful commands when the system temp directory path contains spaces
  * Fixed paste being lost when typing immediately after pasting
  * Fixed Ctrl+D in `/feedback` text input deleting forward instead of the second press exiting the session
  * Fixed API error when dragging a 0-byte image file into the prompt
  * Fixed Claude Desktop sessions incorrectly using the terminal CLI's configured API key instead of OAuth
  * Fixed `git-subdir` plugins at different subdirectories of the same monorepo commit colliding in the plugin cache
  * Fixed ordered list numbers not rendering in terminal UI
  * Fixed a race condition where stale-worktree cleanup could delete an agent worktree just resumed from a previous crash
  * Fixed input deadlock when opening `/mcp` or similar dialogs while the agent is running
  * Fixed Backspace and Delete keys not working in vim NORMAL mode
  * Fixed status line not updating when vim mode is toggled on or off
  * Fixed hyperlinks opening twice on Cmd+click in VS Code, Cursor, and other xterm.js-based terminals
  * Fixed background colors rendering as terminal-default inside tmux with default configuration
  * Fixed iTerm2 session crash when selecting text inside tmux over SSH
  * Fixed clipboard copy silently failing in tmux sessions; copy toast now indicates whether to paste with `⌘V` or tmux `prefix+]`
  * Fixed `←`/`→` accidentally switching tabs in settings, permissions, and sandbox dialogs while navigating lists
  * Fixed IDE integration not auto-connecting when Claude Code is launched inside tmux or screen
  * Fixed CJK characters visually bleeding into adjacent UI elements when clipped at the right edge
  * Fixed teammate panes not closing when the leader exits
  * Fixed iTerm2 auto mode not detecting iTerm2 for native split-pane teammates
  * Faster startup on macOS (\~60ms) by reading keychain credentials in parallel with module loading
  * Faster `--resume` on fork-heavy and very large sessions — up to 45% faster loading and \~100-150MB less peak memory
  * Improved Esc to abort in-flight non-streaming API requests
  * Improved `claude plugin validate` to check skill, agent, and command frontmatter plus `hooks/hooks.json`, catching YAML parse errors and schema violations
  * Background bash tasks are now killed if output exceeds 5GB, preventing runaway processes from filling disk
  * Sessions are now auto-named from plan content when you accept a plan
  * Improved headless mode plugin installation to compose correctly with `CLAUDE_CODE_PLUGIN_SEED_DIR`
  * Show a notice when `apiKeyHelper` takes longer than 10s, preventing it from blocking the main loop
  * The Agent tool no longer accepts a `resume` parameter — use `SendMessage({to: agentId})` to continue a previously spawned agent
  * `SendMessage` now auto-resumes stopped agents in the background instead of returning an error
  * Renamed `/fork` to `/branch` (`/fork` still works as an alias)
  * \[VSCode] Improved plan preview tab titles to use the plan's heading instead of "Claude's Plan"
  * \[VSCode] When option+click doesn't trigger native selection on macOS, the footer now points to the `macOptionClickForcesSelection` setting
</Update>

<Update label="2.1.76" description="March 14, 2026">
  * Added MCP elicitation support — MCP servers can now request structured input mid-task via an interactive dialog (form fields or browser URL)
  * Added new `Elicitation` and `ElicitationResult` hooks to intercept and override responses before they're sent back
  * Added `-n` / `--name <name>` CLI flag to set a display name for the session at startup
  * Added `worktree.sparsePaths` setting for `claude --worktree` in large monorepos to check out only the directories you need via git sparse-checkout
  * Added `PostCompact` hook that fires after compaction completes
  * Added `/effort` slash command to set model effort level
  * Added session quality survey — enterprise admins can configure the sample rate via the `feedbackSurveyRate` setting
  * Fixed deferred tools (loaded via `ToolSearch`) losing their input schemas after conversation compaction, causing array and number parameters to be rejected with type errors
  * Fixed slash commands showing "Unknown skill"
  * Fixed plan mode asking for re-approval after the plan was already accepted
  * Fixed voice mode swallowing keypresses while a permission dialog or plan editor was open
  * Fixed `/voice` not working on Windows when installed via npm
  * Fixed spurious "Context limit reached" when invoking a skill with `model:` frontmatter on a 1M-context session
  * Fixed "adaptive thinking is not supported on this model" error when using non-standard model strings
  * Fixed `Bash(cmd:*)` permission rules not matching when a quoted argument contains `#`
  * Fixed "don't ask again" in the Bash permission dialog showing the full raw command for pipes and compound commands
  * Fixed auto-compaction retrying indefinitely after consecutive failures — a circuit breaker now stops after 3 attempts
  * Fixed MCP reconnect spinner persisting after successful reconnection
  * Fixed LSP plugins not registering servers when the LSP Manager initialized before marketplaces were reconciled
  * Fixed clipboard copying in tmux over SSH — now attempts both direct terminal write and tmux clipboard integration
  * Fixed `/export` showing only the filename instead of the full file path in the success message
  * Fixed transcript not auto-scrolling to new messages after selecting text
  * Fixed Escape key not working to exit the login method selection screen
  * Fixed several Remote Control issues: sessions silently dying when the server reaps an idle environment, rapid messages being queued one-at-a-time instead of batched, and stale work items causing redelivery after JWT refresh
  * Fixed bridge sessions failing to recover after extended WebSocket disconnects
  * Fixed slash commands not found when typing the exact name of a soft-hidden command
  * Improved `--worktree` startup performance by reading git refs directly and skipping redundant `git fetch` when the remote branch is already available locally
  * Improved background agent behavior — killing a background agent now preserves its partial results in the conversation context
  * Improved model fallback notifications — now always visible instead of hidden behind verbose mode, with human-friendly model names
  * Improved blockquote readability on dark terminal themes — text is now italic with a left bar instead of dim
  * Improved stale worktree cleanup — worktrees left behind after an interrupted parallel run are now automatically cleaned up
  * Improved Remote Control session titles — now derived from your first prompt instead of showing "Interactive session"
  * Improved `/voice` to show your dictation language on enable and warn when your `language` setting isn't supported for voice input
  * Updated `--plugin-dir` to only accept one path to support subcommands — use repeated `--plugin-dir` for multiple directories
  * \[VSCode] Fixed gitignore patterns containing commas silently excluding entire filetypes from the @-mention file picker
</Update>

<Update label="2.1.75" description="March 13, 2026">
  * Added 1M context window for Opus 4.6 by default for Max, Team, and Enterprise plans (previously required extra usage)
  * Added `/color` command for all users to set a prompt-bar color for your session
  * Added session name display on the prompt bar when using `/rename`
  * Added last-modified timestamps to memory files, helping Claude reason about which memories are fresh vs. stale
  * Added hook source display (settings/plugin/skill) in permission prompts when a hook requires confirmation
  * Fixed voice mode not activating correctly on fresh installs without toggling `/voice` twice
  * Fixed the Claude Code header not updating the displayed model name after switching models with `/model` or Option+P
  * Fixed session crash when an attachment message computation returns undefined values
  * Fixed Bash tool mangling `!` in piped commands (e.g., `jq 'select(.x != .y)'` now works correctly)
  * Fixed managed-disabled plugins showing up in the `/plugin` Installed tab — plugins force-disabled by your organization are now hidden
  * Fixed token estimation over-counting for thinking and `tool_use` blocks, preventing premature context compaction
  * Fixed corrupted marketplace config path handling
  * Fixed `/resume` losing session names after resuming a forked or continued session
  * 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"
  * Improved startup performance on macOS non-MDM machines by skipping unnecessary subprocess spawns
  * Suppressed async hook completion messages by default (visible with `--verbose` or transcript mode)
  * Breaking change: Removed deprecated Windows managed settings fallback at `C:\ProgramData\ClaudeCode\managed-settings.json` — use `C:\Program Files\ClaudeCode\managed-settings.json`
</Update>

<Update label="2.1.74" description="March 12, 2026">
  * Added actionable suggestions to `/context` command — identifies context-heavy tools, memory bloat, and capacity warnings with specific optimization tips
  * Added `autoMemoryDirectory` setting to configure a custom directory for auto-memory storage
  * Fixed memory leak where streaming API response buffers were not released when the generator was terminated early, causing unbounded RSS growth on the Node.js/npm code path
  * Fixed managed policy `ask` rules being bypassed by user `allow` rules or skill `allowed-tools`
  * Fixed full model IDs (e.g., `claude-opus-4-5`) being silently ignored in agent frontmatter `model:` field and `--agents` JSON config — agents now accept the same model values as `--model`
  * Fixed MCP OAuth authentication hanging when the callback port is already in use
  * Fixed MCP OAuth refresh never prompting for re-auth after the refresh token expires, for OAuth servers that return errors with HTTP 200 (e.g. Slack)
  * Fixed voice mode silently failing on the macOS native binary for users whose terminal had never been granted microphone permission — the binary now includes the `audio-input` entitlement so macOS prompts correctly
  * Fixed `SessionEnd` hooks being killed after 1.5 s on exit regardless of `hook.timeout` — now configurable via `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS`
  * Fixed `/plugin install` failing inside the REPL for marketplace plugins with local sources
  * Fixed marketplace update not syncing git submodules — plugin sources in submodules no longer break after update
  * Fixed unknown slash commands with arguments silently dropping input — now shows your input as a warning
  * 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
  * Changed `--plugin-dir` so local dev copies now override installed marketplace plugins with the same name (unless that plugin is force-enabled by managed settings)
  * \[VSCode] Fixed delete button not working for Untitled sessions
  * \[VSCode] Improved scroll wheel responsiveness in the integrated terminal with terminal-aware acceleration
</Update>

<Update label="2.1.73" description="March 11, 2026">
  * Added `modelOverrides` setting to map model picker entries to custom provider model IDs (e.g. Bedrock inference profile ARNs)
  * Added actionable guidance when OAuth login or connectivity checks fail due to SSL certificate errors (corporate proxies, `NODE_EXTRA_CA_CERTS`)
  * Fixed freezes and 100% CPU loops triggered by permission prompts for complex bash commands
  * Fixed a deadlock that could freeze Claude Code when many skill files changed at once (e.g. during `git pull` in a repo with a large `.claude/skills/` directory)
  * Fixed Bash tool output being lost when running multiple Claude Code sessions in the same project directory
  * Fixed subagents with `model: opus`/`sonnet`/`haiku` being silently downgraded to older model versions on Bedrock, Vertex, and Microsoft Foundry
  * Fixed background bash processes spawned by subagents not being cleaned up when the agent exits
  * Fixed `/resume` showing the current session in the picker
  * Fixed `/ide` crashing with `onInstall is not defined` when auto-installing the extension
  * Fixed `/loop` not being available on Bedrock/Vertex/Foundry and when telemetry was disabled
  * Fixed SessionStart hooks firing twice when resuming a session via `--resume` or `--continue`
  * Fixed JSON-output hooks injecting no-op system-reminder messages into the model's context on every turn
  * Fixed voice mode session corruption when a slow connection overlaps a new recording
  * Fixed Linux sandbox failing to start with "ripgrep (rg) not found" on native builds
  * Fixed Linux native modules not loading on Amazon Linux 2 and other glibc 2.26 systems
  * 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
  * Improved Up arrow after interrupting Claude — now restores the interrupted prompt and rewinds the conversation in one step
  * Improved IDE detection speed at startup
  * Improved clipboard image pasting performance on macOS
  * Improved `/effort` to work while Claude is responding, matching `/model` behavior
  * Improved voice mode to automatically retry transient connection failures during rapid push-to-talk re-press
  * Improved the Remote Control spawn mode selection prompt with better context
  * Changed default Opus model on Bedrock, Vertex, and Microsoft Foundry to Opus 4.6 (was Opus 4.1)
  * Deprecated `/output-style` command — use `/config` instead. Output style is now fixed at session start for better prompt caching
  * VSCode: Fixed HTTP 400 errors for users behind proxies or on Bedrock/Vertex with Claude 4.5 models
</Update>

<Update label="2.1.72" description="March 10, 2026">
  * Fixed tool search to activate even with `ANTHROPIC_BASE_URL` as long as `ENABLE_TOOL_SEARCH` is set.
  * Added `w` key in `/copy` to write the focused selection directly to a file, bypassing the clipboard (useful over SSH)
  * Added optional description argument to `/plan` (e.g., `/plan fix the auth bug`) that enters plan mode and immediately starts
  * Added `ExitWorktree` tool to leave an `EnterWorktree` session
  * Added `CLAUDE_CODE_DISABLE_CRON` environment variable to immediately stop scheduled cron jobs mid-session
  * Added `lsof`, `pgrep`, `tput`, `ss`, `fd`, and `fdfind` to the bash auto-approval allowlist, reducing permission prompts for common read-only operations
  * Restored the `model` parameter on the Agent tool for per-invocation model overrides
  * Simplified effort levels to low/medium/high (removed max) with new symbols (○ ◐ ●) and a brief notification instead of a persistent icon. Use `/effort auto` to reset to default
  * Improved `/config` — Escape now cancels changes, Enter saves and closes, Space toggles settings
  * Improved up-arrow history to show current session's messages first when running multiple concurrent sessions
  * Improved voice input transcription accuracy for repo names and common dev terms (regex, OAuth, JSON)
  * Improved bash command parsing by switching to a native module — faster initialization and no memory leak
  * Reduced bundle size by \~510 KB
  * Changed CLAUDE.md HTML comments (`<!-- ... -->`) to be hidden from Claude when auto-injected. Comments remain visible when read with the Read tool
  * Fixed slow exits when background tasks or hooks were slow to respond
  * Fixed agent task progress stuck on "Initializing…"
  * Fixed skill hooks firing twice per event when a hooks-enabled skill is invoked by the model
  * Fixed several voice mode issues: occasional input lag, false "No speech detected" errors after releasing push-to-talk, and stale transcripts re-filling the prompt after submission
  * Fixed `--continue` not resuming from the most recent point after `--compact`
  * Fixed bash security parsing edge cases
  * Added support for marketplace git URLs without `.git` suffix (Azure DevOps, AWS CodeCommit)
  * Improved marketplace clone failure messages to show diagnostic info even when git produces no stderr
  * Fixed several plugin issues: installation failing on Windows with `EEXIST` error in OneDrive folders, marketplace blocking user-scope installs when a project-scope install exists, `CLAUDE_CODE_PLUGIN_CACHE_DIR` creating literal `~` directories, and `plugin.json` with marketplace-only fields failing to load
  * Fixed feedback survey appearing too frequently in long sessions
  * Fixed `--effort` CLI flag being reset by unrelated settings writes on startup
  * Fixed backgrounded Ctrl+B queries losing their transcript or corrupting the new conversation after `/clear`
  * Fixed `/clear` killing background agent/bash tasks — only foreground tasks are now cleared
  * Fixed worktree isolation issues: Task tool resume not restoring cwd, and background task notifications missing `worktreePath` and `worktreeBranch`
  * Fixed `/model` not displaying results when run while Claude is working
  * Fixed digit keys selecting menu options instead of typing in plan mode permission prompt's text input
  * Fixed sandbox permission issues: certain file write operations incorrectly allowed without prompting, and output redirections to allowlisted directories (like `/tmp/claude/`) prompting unnecessarily
  * Improved CPU utilization in long sessions
  * Fixed prompt cache invalidation in SDK `query()` calls, reducing input token costs up to 12x
  * Fixed Escape key becoming unresponsive after cancelling a query
  * Fixed double Ctrl+C not exiting when background agents or tasks are running
  * Fixed team agents to inherit the leader's model
  * Fixed "Always Allow" saving permission rules that never match again
  * Fixed several hooks issues: `transcript_path` pointing to the wrong directory for resumed/forked sessions, agent `prompt` being silently deleted from settings.json on every settings write, PostToolUse block reason displaying twice, async hooks not receiving stdin with bash `read -r`, and validation error message showing an example that fails validation
  * Fixed session crashes in Desktop/SDK when Read returned files containing U+2028/U+2029 characters
  * Fixed terminal title being cleared on exit even when `CLAUDE_CODE_DISABLE_TERMINAL_TITLE` was set
  * Fixed several permission rule matching issues: wildcard rules not matching commands with heredocs, embedded newlines, or no arguments; `sandbox.excludedCommands` failing with env var prefixes; "always allow" suggesting overly broad prefixes for nested CLI tools; and deny rules not applying to all command forms
  * Fixed oversized and truncated images from Bash data-URL output
  * Fixed a crash when resuming sessions that contained Bedrock API errors
  * Fixed intermittent "expected boolean, received string" validation errors on Edit, Bash, and Grep tool inputs
  * Fixed multi-line session titles when forking from a conversation whose first message contained newlines
  * Fixed queued messages not showing attached images, and images being lost when pressing ↑ to edit a queued message
  * Fixed parallel tool calls where a failed Read/WebFetch/Glob would cancel its siblings — only Bash errors now cascade
  * 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
  * VSCode: Added effort level indicator on the input border
  * VSCode: Added `vscode://anthropic.claude-code/open` URI handler to open a new Claude Code tab programmatically, with optional `prompt` and `session` query parameters
</Update>

<Update label="2.1.71" description="March 7, 2026">
  * Added `/loop` command to run a prompt or slash command on a recurring interval (e.g. `/loop 5m check the deploy`)
  * Added cron scheduling tools for recurring prompts within a session
  * Added `voice:pushToTalk` keybinding to make the voice activation key rebindable in `keybindings.json` (default: space) — modifier+letter combos like `meta+k` have zero typing interference
  * Added `fmt`, `comm`, `cmp`, `numfmt`, `expr`, `test`, `printf`, `getconf`, `seq`, `tsort`, and `pr` to the bash auto-approval allowlist
  * Fixed stdin freeze in long-running sessions where keystrokes stop being processed but the process stays alive
  * Fixed a 5–8 second startup freeze for users with voice mode enabled, caused by CoreAudio initialization blocking the main thread after system wake
  * Fixed startup UI freeze when many claude.ai proxy connectors refresh an expired OAuth token simultaneously
  * Fixed forked conversations (`/fork`) sharing the same plan file, which caused plan edits in one fork to overwrite the other
  * Fixed the Read tool putting oversized images into context when image processing failed, breaking subsequent turns in long image-heavy sessions
  * Fixed false-positive permission prompts for compound bash commands containing heredoc commit messages
  * Fixed plugin installations being lost when running multiple Claude Code instances
  * Fixed claude.ai connectors failing to reconnect after OAuth token refresh
  * Fixed claude.ai MCP connector startup notifications appearing for every org-configured connector instead of only previously connected ones
  * Fixed background agent completion notifications missing the output file path, which made it difficult for parent agents to recover agent results after context compaction
  * Fixed duplicate output in Bash tool error messages when commands exit with non-zero status
  * Fixed Chrome extension auto-detection getting permanently stuck on "not installed" after running on a machine without local Chrome
  * Fixed `/plugin marketplace update` failing with merge conflicts when the marketplace is pinned to a branch/tag ref
  * Fixed `/plugin marketplace add owner/repo@ref` incorrectly parsing `@` — previously only `#` worked as a ref separator, causing undiagnosable errors with `strictKnownMarketplaces`
  * Fixed duplicate entries in `/permissions` Workspace tab when the same directory is added with and without a trailing slash
  * 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
  * Improved startup time by deferring native image processor loading to first use
  * Improved bridge session reconnection to complete within seconds after laptop wake from sleep, instead of waiting up to 10 minutes
  * Improved `/plugin uninstall` to disable project-scoped plugins in `.claude/settings.local.json` instead of modifying `.claude/settings.json`, so changes don't affect teammates
  * Improved plugin-provided MCP server deduplication — servers that duplicate a manually-configured server (same command/URL) are now skipped, preventing duplicate connections and tool sets. Suppressions are shown in the `/plugin` menu.
  * Updated `/debug` to toggle debug logging on mid-session, since debug logs are no longer written by default
  * Removed startup notification noise for unauthenticated org-registered claude.ai connectors
</Update>

<Update label="2.1.70" description="March 6, 2026">
  * Fixed API 400 errors when using `ANTHROPIC_BASE_URL` with a third-party gateway — tool search now correctly detects proxy endpoints and disables `tool_reference` blocks
  * Fixed `API Error: 400 This model does not support the effort parameter` when using custom Bedrock inference profiles or other model identifiers not matching standard Claude naming patterns
  * Fixed empty model responses immediately after `ToolSearch` — the server renders tool schemas with system-prompt-style tags at the prompt tail, which could confuse models into stopping early
  * Fixed prompt-cache bust when an MCP server with `instructions` connects after the first turn
  * Fixed Enter inserting a newline instead of submitting when typing over a slow SSH connection
  * Fixed clipboard corrupting non-ASCII text (CJK, emoji) on Windows/WSL by using PowerShell `Set-Clipboard`
  * Fixed extra VS Code windows opening at startup on Windows when running from the VS Code integrated terminal
  * Fixed voice mode failing on Windows native binary with "native audio module could not be loaded"
  * Fixed push-to-talk not activating on session start when `voiceEnabled: true` was set in settings
  * Fixed markdown links containing `#NNN` references incorrectly pointing to the current repository instead of the linked URL
  * Fixed repeated "Model updated to Opus 4.6" notification when a project's `.claude/settings.json` has a legacy Opus model string pinned
  * Fixed plugins showing as inaccurately installed in `/plugin`
  * Fixed plugins showing "not found in marketplace" errors on fresh startup by auto-refreshing after marketplace installation
  * Fixed `/security-review` command failing with `unknown option merge-base` on older git versions
  * Fixed `/color` command having no way to reset back to the default color — `/color default`, `/color gray`, `/color reset`, and `/color none` now restore the default
  * Fixed a performance regression in the `AskUserQuestion` preview dialog that re-ran markdown rendering on every keystroke in the notes input
  * Fixed feature flags read during early startup never refreshing their disk cache, causing stale values to persist across sessions
  * 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
  * Improved error message when microphone captures silence to distinguish from "no speech detected"
  * Improved compaction to preserve images in the summarizer request, allowing prompt cache reuse for faster and cheaper compaction
  * Improved `/rename` to work while Claude is processing, instead of being silently queued
  * Reduced prompt input re-renders during turns by \~74%
  * Reduced startup memory by \~426KB for users without custom CA certificates
  * Reduced Remote Control `/poll` rate to once per 10 minutes while connected (was 1–2s), cutting server load \~300×. Reconnection is unaffected — transport loss immediately wakes fast polling.
  * \[VSCode] Added spark icon in VS Code activity bar that lists all Claude Code sessions, with sessions opening as full editors
  * \[VSCode] Added full markdown document view for plans in VS Code, with support for adding comments to provide feedback
  * \[VSCode] Added native MCP server management dialog — use `/mcp` in the chat panel to enable/disable servers, reconnect, and manage OAuth authentication without switching to the terminal
</Update>

<Update label="2.1.69" description="March 5, 2026">
  * Added the `/claude-api` skill for building applications with the Claude API and Anthropic SDK
  * Added Ctrl+U on an empty bash prompt (`!`) to exit bash mode, matching `escape` and `backspace`
  * Added numeric keypad support for selecting options in Claude's interview questions (previously only the number row above QWERTY worked)
  * Added optional name argument to `/remote-control` and `claude remote-control` (`/remote-control My Project` or `--name "My Project"`) to set a custom session title visible in claude.ai/code
  * Added Voice STT support for 10 new languages (20 total) — Russian, Polish, Turkish, Dutch, Ukrainian, Greek, Czech, Danish, Swedish, Norwegian
  * Added effort level display (e.g., "with low effort") to the logo and spinner, making it easier to see which effort setting is active
  * Added agent name display in terminal title when using `claude --agent`
  * Added `sandbox.enableWeakerNetworkIsolation` setting (macOS only) to allow Go programs like `gh`, `gcloud`, and `terraform` to verify TLS certificates when using a custom MITM proxy with `httpProxyPort`
  * Added `includeGitInstructions` setting (and `CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS` env var) to remove built-in commit and PR workflow instructions from Claude's system prompt
  * Added `/reload-plugins` command to activate pending plugin changes without restarting
  * Added a one-time startup prompt suggesting Claude Code Desktop on macOS and Windows (max 3 showings, dismissible)
  * Added `${CLAUDE_SKILL_DIR}` variable for skills to reference their own directory in SKILL.md content
  * Added `InstructionsLoaded` hook event that fires when CLAUDE.md or `.claude/rules/*.md` files are loaded into context
  * Added `agent_id` (for subagents) and `agent_type` (for subagents and `--agent`) to hook events
  * Added `worktree` field to status line hook commands with name, path, branch, and original repo directory when running in a `--worktree` session
  * Added `pluginTrustMessage` in managed settings to append organization-specific context to the plugin trust warning shown before installation
  * Added policy limit fetching (e.g., remote control restrictions) for Team plan OAuth users, not just Enterprise
  * Added `pathPattern` to `strictKnownMarketplaces` for regex-matching file/directory marketplace sources alongside `hostPattern` restrictions
  * Added plugin source type `git-subdir` to point to a subdirectory within a git repo
  * Added `oauth.authServerMetadataUrl` config option for MCP servers to specify a custom OAuth metadata discovery URL when standard discovery fails
  * Fixed a security issue where nested skill discovery could load skills from gitignored directories like `node_modules`
  * Fixed trust dialog silently enabling all `.mcp.json` servers on first run. You'll now see the per-server approval dialog as expected
  * Fixed `claude remote-control` crashing immediately on npm installs with "bad option: --sdk-url" (anthropics/claude-code#28334)
  * Fixed `--model claude-opus-4-0` and `--model claude-opus-4-1` resolving to deprecated Opus versions instead of current
  * Fixed macOS keychain corruption when using multiple OAuth MCP servers. Large OAuth metadata blobs could overflow the `security -i` stdin buffer, silently leaving stale credentials behind and causing repeated `/login` prompts.
  * Fixed `.credentials.json` losing `subscriptionType` (showing "Claude API" instead of "Claude Pro"/"Claude Max") when the profile endpoint transiently fails during token refresh (anthropics/claude-code#30185)
  * Fixed ghost dotfiles (`.bashrc`, `HEAD`, etc.) appearing as untracked files in the working directory after sandboxed Bash commands on Linux
  * Fixed Shift+Enter printing `[27;2;13~` instead of inserting a newline in Ghostty over SSH
  * Fixed stash (Ctrl+S) being cleared when submitting a message while Claude is working
  * Fixed ctrl+o (transcript toggle) freezing for many seconds in long sessions with lots of file edits
  * Fixed plan mode feedback input not supporting multi-line text entry (backslash+Enter and Shift+Enter now insert newlines)
  * Fixed cursor not moving down into blank lines at the top of the input box
  * Fixed `/stats` crash when transcript files contain entries with missing or malformed timestamps
  * Fixed a brief hang after a streaming error on long sessions (the transcript was being fully rewritten to drop one line; it is now truncated in place)
  * Fixed `--setting-sources user` not blocking dynamically discovered project skills
  * Fixed duplicate CLAUDE.md, slash commands, agents, and rules when running from a worktree nested inside its main repo (e.g. `claude -w`)
  * Fixed plugin Stop/SessionEnd/etc hooks not firing after any `/plugin` operation
  * Fixed plugin hooks being silently dropped when two plugins use the same `${CLAUDE_PLUGIN_ROOT}/...` command template
  * Fixed memory leak in long-running SDK/CCR sessions where conversation messages were retained unnecessarily
  * Fixed API 400 errors in forked agents (autocompact, summarization) when resuming sessions that were interrupted mid-tool-batch
  * Fixed "unexpected tool\_use\_id found in tool\_result blocks" error when resuming conversations that start with an orphaned tool result
  * 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 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
  * Fixed sandbox prompting users to approve non-allowed domains when `allowManagedDomainsOnly` is enabled in managed settings — non-allowed domains are now blocked automatically with no bypass
  * Fixed interactive tools (e.g., `AskUserQuestion`) being silently auto-allowed when listed in a skill's allowed-tools, bypassing the permission prompt and running with empty answers
  * Fixed multi-GB memory spike when committing with large untracked binary files in the working tree
  * Fixed Escape not interrupting a running turn when the input box has draft text. Use Up arrow to pull queued messages back for editing, or Ctrl+U to clear the input line.
  * Fixed Android app crash when running local slash commands (`/voice`, `/cost`) in Remote Control sessions
  * Fixed a memory leak where old message array versions accumulated in React Compiler `memoCache` over long sessions
  * Fixed a memory leak where REPL render scopes accumulated over long sessions (\~35MB over 1000 turns)
  * Fixed memory retention in in-process teammates where the parent's full conversation history was pinned for the teammate's lifetime, preventing GC after `/clear` or auto-compact
  * Fixed a memory leak in interactive mode where hook events could accumulate unboundedly during long sessions
  * Fixed hang when `--mcp-config` points to a corrupted file
  * Fixed slow startup when many skills/plugins are installed
  * Fixed `cd <outside-dir> && <cmd>` permission prompt to surface the chained command instead of only showing "Yes, allow reading from `<dir>`/"
  * Fixed conditional `.claude/rules/*.md` files (with `paths:` frontmatter) and nested CLAUDE.md files not loading in print mode (`claude -p`)
  * Fixed `/clear` not fully clearing all session caches, reducing memory retention in long sessions
  * Fixed terminal flicker caused by animated elements at the scrollback boundary
  * Fixed UI frame drops on macOS when using MCP servers with OAuth (regression from 2.1.x)
  * Fixed occasional frame stalls during typing caused by synchronous debug log flushes
  * Fixed `TeammateIdle` and `TaskCompleted` hooks to support `{"continue": false, "stopReason": "..."}` to stop the teammate, matching `Stop` hook behavior
  * Fixed `WorktreeCreate` and `WorktreeRemove` plugin hooks being silently ignored
  * Fixed skill descriptions with colons (e.g., "Triggers include: X, Y, Z") failing to load from SKILL.md frontmatter
  * Fixed project skills without a `description:` frontmatter field not appearing in Claude's available skills list
  * Fixed `/context` showing identical token counts for all MCP tools from a server
  * Fixed literal `nul` file creation on Windows when the model uses CMD-style `2>nul` redirection in Git Bash
  * Fixed extra blank lines appearing below each tool call in the expanded subagent transcript view (Ctrl+O)
  * Fixed Tab/arrow keys not cycling Settings tabs when `/config` search box is focused but empty
  * Fixed service key OAuth sessions (CCR containers) spamming `[ERROR]` logs with 403s from profile-scoped endpoints
  * Fixed inconsistent color for "Remote Control active" status indicator
  * Fixed Voice waveform cursor covering the first suffix letter when dictating mid-input
  * Fixed Voice input showing all 5 spaces during warmup instead of capping at \~2 (aligning with the "keep holding…" hint)
  * Improved spinner performance by isolating the 50ms animation loop from the surrounding shell, reducing render and CPU overhead during turns
  * Improved UI rendering performance in native binaries with React Compiler
  * Improved `--worktree` startup by eliminating a git subprocess on the startup path
  * Improved macOS startup by eliminating redundant settings-file reloads when managed settings resolve
  * Improved macOS startup for Claude.ai enterprise/team users by skipping an unnecessary keychain lookup
  * Improved MCP `-p` startup by pipelining claude.ai config fetch with local connections and using a concurrency pool instead of sequential batching
  * Improved voice startup by removing imperceptible warmup pulse animations that were causing re-render stutter
  * Improved MCP binary content handling: tools returning PDFs, Office documents, or audio now save decoded bytes to disk with the correct file extension instead of dumping raw base64 into the conversation context. WebFetch also saves binary responses alongside its summary.
  * Improved memory usage in long sessions by stabilizing `onSubmit` across message updates
  * Improved LSP tool rendering and memory context building to no longer read entire files
  * Improved session upload and memory sync to avoid reading large files into memory before size/binary checks
  * Improved file operation performance by avoiding reading file contents for existence checks (6 sites)
  * Improved documentation to clarify that `--append-system-prompt-file` and `--system-prompt-file` work in interactive mode (the docs previously said print mode only)
  * Reduced baseline memory by \~16MB by deferring Yoga WASM preloading
  * Reduced memory footprint for SDK and CCR sessions using stream-json output
  * Reduced memory usage when resuming large sessions (including compacted history)
  * Reduced token usage on multi-agent tasks with more concise subagent final reports
  * Changed Sonnet 4.5 users on Pro/Max/Team Premium to be automatically migrated to Sonnet 4.6
  * Changed the `/resume` picker to show your most recent prompt instead of the first one. This also resolves some titles appearing as `(session)`.
  * Changed claude.ai MCP connector failures to show a notification instead of silently disappearing from the tool list
  * Changed example command suggestions to be generated deterministically instead of calling Haiku
  * Changed resuming after compaction to no longer produce a preamble recap before continuing
  * \[SDK] Changed task creation to no longer require the `activeForm` field — the spinner falls back to the task subject
  * \[VSCode] Added compaction display as a collapsible "Compacted chat" card with the summary inside
  * \[VSCode] The permission mode picker now respects `permissions.disableBypassPermissionsMode` from your effective Claude Code settings (including managed/policy settings) — when set to `disable`, bypass permissions mode is hidden from the picker
  * \[VSCode] Fixed RTL text (Arabic, Hebrew, Persian) rendering reversed in the chat panel (regression in v2.1.63)
</Update>

<Update label="2.1.68" description="March 4, 2026">
  * Opus 4.6 now defaults to medium effort for Max and Team subscribers. Medium effort works well for most tasks — it's the sweet spot between speed and thoroughness. You can change this anytime with `/model`
  * 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
</Update>

<Update label="2.1.66" description="March 4, 2026">
  * Reduced spurious error logging
</Update>

<Update label="2.1.63" description="February 28, 2026">
  * Added `/simplify` and `/batch` bundled slash commands
  * Fixed local slash command output like /cost appearing as user-sent messages instead of system messages in the UI
  * Project configs & auto memory now shared across git worktrees of the same repository
  * Added `ENABLE_CLAUDEAI_MCP_SERVERS=false` env var to opt out from making claude.ai MCP servers available
  * Improved `/model` command to show the currently active model in the slash command menu
  * Added HTTP hooks, which can POST JSON to a URL and receive JSON instead of running a shell command
  * Fixed listener leak in bridge polling loop
  * Fixed listener leak in MCP OAuth flow cleanup
  * Added manual URL paste fallback during MCP OAuth authentication. If the automatic localhost redirect doesn't work, you can paste the callback URL to complete authentication.
  * Fixed memory leak when navigating hooks configuration menu
  * Fixed listener leak in interactive permission handler during auto-approvals
  * Fixed file count cache ignoring glob ignore patterns
  * Fixed memory leak in bash command prefix cache
  * Fixed MCP tool/resource cache leak on server reconnect
  * Fixed IDE host IP detection cache incorrectly sharing results across ports
  * Fixed WebSocket listener leak on transport reconnect
  * Fixed memory leak in git root detection cache that could cause unbounded growth in long-running sessions
  * Fixed memory leak in JSON parsing cache that grew unbounded over long sessions
  * VSCode: Fixed remote sessions not appearing in conversation history
  * Fixed a race condition in the REPL bridge where new messages could arrive at the server interleaved with historical messages during the initial connection flush, causing message ordering issues.
  * Fixed memory leak where long-running teammates retained all messages in AppState even after conversation compaction
  * Fixed a memory leak where MCP server fetch caches were not cleared on disconnect, causing growing memory usage with servers that reconnect frequently
  * Improved memory usage in long sessions with subagents by stripping heavy progress message payloads during context compaction
  * Added "Always copy full response" option to the `/copy` picker. When selected, future `/copy` commands will skip the code block picker and copy the full response directly.
  * VSCode: Added session rename and remove actions to the sessions list
  * Fixed `/clear` not resetting cached skills, which could cause stale skill content to persist in the new conversation
</Update>

<Update label="2.1.62" description="February 27, 2026">
  * Fixed prompt suggestion cache regression that reduced cache hit rates
</Update>

<Update label="2.1.61" description="February 26, 2026">
  * Fixed concurrent writes corrupting config file on Windows
</Update>

<Update label="2.1.59" description="February 26, 2026">
  * Claude automatically saves useful context to auto-memory. Manage with /memory
  * Added `/copy` command to show an interactive picker when code blocks are present, allowing selection of individual code blocks or the full response.
  * Improved "always allow" prefix suggestions for compound bash commands (e.g. `cd /tmp && git fetch && git push`) to compute smarter per-subcommand prefixes instead of treating the whole command as one
  * Improved ordering of short task lists
  * Improved memory usage in multi-agent sessions by releasing completed subagent task state
  * Fixed MCP OAuth token refresh race condition when running multiple Claude Code instances simultaneously
  * 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
</Update>

<Update label="2.1.58" description="February 25, 2026">
  * Expand Remote Control to more users
</Update>

<Update label="2.1.56" description="February 25, 2026">
  * VS Code: Fixed another cause of "command 'claude-vscode.editor.openLast' not found" crashes
</Update>

<Update label="2.1.55" description="February 25, 2026">
  * Fixed BashTool failing on Windows with EINVAL error
</Update>

<Update label="2.1.53" description="February 25, 2026">
  * Fixed a UI flicker where user input would briefly disappear after submission before the message rendered
  * Fixed bulk agent kill (ctrl+f) to send a single aggregate notification instead of one per agent, and to properly clear the command queue
  * Fixed graceful shutdown sometimes leaving stale sessions when using Remote Control by parallelizing teardown network calls
  * Fixed `--worktree` sometimes being ignored on first launch
  * Fixed a panic ("switch on corrupted value") on Windows
  * Fixed a crash that could occur when spawning many processes on Windows
  * Fixed a crash in the WebAssembly interpreter on Linux x64 & Windows x64
  * Fixed a crash that sometimes occurred after 2 minutes on Windows ARM64
</Update>

<Update label="2.1.52" description="February 24, 2026">
  * VS Code: Fixed extension crash on Windows ("command 'claude-vscode.editor.openLast' not found")
</Update>

<Update label="2.1.51" description="February 24, 2026">
  * Added `claude remote-control` subcommand for external builds, enabling local environment serving for all users.
  * Updated plugin marketplace default git timeout from 30s to 120s and added `CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS` to configure.
  * Added support for custom npm registries and specific version pinning when installing plugins from npm sources
  * BashTool now skips login shell (`-l` flag) by default when a shell snapshot is available, improving command execution performance. Previously this required setting `CLAUDE_BASH_NO_LOGIN=true`.
  * Fixed a security issue where `statusLine` and `fileSuggestion` hook commands could execute without workspace trust acceptance in interactive mode.
  * Tool results larger than 50K characters are now persisted to disk (previously 100K). This reduces context window usage and improves conversation longevity.
  * 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.
  * Added `CLAUDE_CODE_ACCOUNT_UUID`, `CLAUDE_CODE_USER_EMAIL`, and `CLAUDE_CODE_ORGANIZATION_UUID` environment variables for SDK callers to provide account info synchronously, eliminating a race condition where early telemetry events lacked account metadata.
  * Fixed slash command autocomplete crashing when a plugin's SKILL.md description is a YAML array or other non-string type
  * The `/model` picker now shows human-readable labels (e.g., "Sonnet 4.5") instead of raw model IDs for pinned model versions, with an upgrade hint when a newer version is available.
  * Managed settings can now be set via macOS plist or Windows Registry. Learn more at [https://code.claude.com/docs/en/settings#settings-files](claude-code-settings-claude-code-docs-d4420b4b52.md#settings-files)
</Update>

<Update label="2.1.50" description="February 20, 2026">
  * Added support for `startupTimeout` configuration for LSP servers
  * Added `WorktreeCreate` and `WorktreeRemove` hook events, enabling custom VCS setup and teardown when agent worktree isolation creates or removes worktrees.
  * Fixed a bug where resumed sessions could be invisible when the working directory involved symlinks, because the session storage path was resolved at different times during startup. Also fixed session data loss on SSH disconnect by flushing session data before hooks and analytics in the graceful shutdown sequence.
  * Linux: Fixed native modules not loading on systems with glibc older than 2.30 (e.g., RHEL 8)
  * Fixed memory leak in agent teams where completed teammate tasks were never garbage collected from session state
  * Fixed `CLAUDE_CODE_SIMPLE` to fully strip down skills, session memory, custom agents, and CLAUDE.md token counting
  * Fixed `/mcp reconnect` freezing the CLI when given a server name that doesn't exist
  * Fixed memory leak where completed task state objects were never removed from AppState
  * Added support for `isolation: worktree` in agent definitions, allowing agents to declaratively run in isolated git worktrees.
  * `CLAUDE_CODE_SIMPLE` mode now also disables MCP tools, attachments, hooks, and CLAUDE.md file loading for a fully minimal experience.
  * Fixed bug where MCP tools were not discovered when tool search is enabled and a prompt is passed in as a launch argument
  * Improved memory usage during long sessions by clearing internal caches after compaction
  * Added `claude agents` CLI command to list all configured agents
  * Improved memory usage during long sessions by clearing large tool results after they have been processed
  * Fixed a memory leak where LSP diagnostic data was never cleaned up after delivery, causing unbounded memory growth in long sessions
  * Fixed a memory leak where completed task output was not freed from memory, reducing memory usage in long sessions with many tasks
  * Improved startup performance for headless mode (`-p` flag) by deferring Yoga WASM and UI component imports
  * Fixed prompt suggestion cache regression that reduced cache hit rates
  * Fixed unbounded memory growth in long sessions by capping file history snapshots
  * Added `CLAUDE_CODE_DISABLE_1M_CONTEXT` environment variable to disable 1M context window support
  * Opus 4.6 (fast mode) now includes the full 1M context window
  * VSCode: Added `/extra-usage` command support in VS Code sessions
  * Fixed memory leak where TaskOutput retained recent lines after cleanup
  * 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
</Update>

<Update label="2.1.49" description="February 19, 2026">
  * Improved MCP OAuth authentication with step-up auth support and discovery caching, reducing redundant network requests during server connections
  * Added `--worktree` (`-w`) flag to start Claude in an isolated git worktree
  * Subagents support `isolation: "worktree"` for working in a temporary git worktree
  * Added Ctrl+F keybinding to kill background agents (two-press confirmation)
  * Agent definitions support `background: true` to always run as a background task
  * Plugins can ship `settings.json` for default configuration
  * Fixed file-not-found errors to suggest corrected paths when the model drops the repo folder
  * Fixed Ctrl+C and ESC being silently ignored when background agents are running and the main thread is idle. Pressing twice within 3 seconds now kills all background agents.
  * Fixed prompt suggestion cache regression that reduced cache hit rates.
  * Fixed `plugin enable` and `plugin disable` to auto-detect the correct scope when `--scope` is not specified, instead of always defaulting to user scope
  * Simple mode (`CLAUDE_CODE_SIMPLE`) now includes the file edit tool in addition to the Bash tool, allowing direct file editing in simple mode.
  * Permission suggestions are now populated when safety checks trigger an ask response, enabling SDK consumers to display permission options
  * Sonnet 4.5 with 1M context is being removed from the Max plan in favor of our frontier Sonnet 4.6 model, which now has 1M context. Please switch in /model.
  * Fixed verbose mode not updating thinking block display when toggled via `/config` — memo comparators now correctly detect verbose changes
  * Fixed unbounded WASM memory growth during long sessions by periodically resetting the tree-sitter parser
  * Fixed potential rendering issues caused by stale yoga layout references
  * Improved performance in non-interactive mode (`-p`) by skipping unnecessary API calls during startup
  * Improved performance by caching authentication failures for HTTP and SSE MCP servers, avoiding repeated connection attempts to servers requiring auth
  * Fixed unbounded memory growth during long-running sessions caused by Yoga WASM linear memory never shrinking
  * SDK model info now includes `supportsEffort`, `supportedEffortLevels`, and `supportsAdaptiveThinking` fields so consumers can discover model capabilities.
  * Added `ConfigChange` hook event that fires when configuration files change during a session, enabling enterprise security auditing and optional blocking of settings changes.
  * Improved startup performance by caching MCP auth failures to avoid redundant connection attempts
  * Improved startup performance by reducing HTTP calls for analytics token counting
  * Improved startup performance by batching MCP tool token counting into a single API call
  * 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.
  * Improved permission prompts for path safety and working directory blocks to show the reason for the restriction instead of a bare prompt with no context
</Update>

<Update label="2.1.47" description="February 18, 2026">
  * Fixed FileWriteTool line counting to preserve intentional trailing blank lines instead of stripping them with `trimEnd()`.
  * Fixed Windows terminal rendering bugs caused by `os.EOL` (`\r\n`) in display code — line counts now show correct values instead of always showing 1 on Windows.
  * Improved VS Code plan preview: auto-updates as Claude iterates, enables commenting only when the plan is ready for review, and keeps the preview open when rejecting so Claude can revise.
  * Fixed a bug where bold and colored text in markdown output could shift to the wrong characters on Windows due to `\r\n` line endings.
  * Fixed compaction failing when conversation contains many PDF documents by stripping document blocks alongside images before sending to the compaction API (anthropics/claude-code#26188)
  * Improved memory usage in long-running sessions by releasing API stream buffers, agent context, and skill state after use
  * Improved startup performance by deferring SessionStart hook execution, reducing time-to-interactive by \~500ms.
  * Fixed an issue where bash tool output was silently discarded on Windows when using MSYS2 or Cygwin shells.
  * Improved performance of `@` file mentions - file suggestions now appear faster by pre-warming the index on startup and using session-based caching with background refresh.
  * Improved memory usage by trimming agent task message history after tasks complete
  * Improved memory usage during long agent sessions by eliminating O(n²) message accumulation in progress updates
  * Fixed the bash permission classifier to validate that returned match descriptions correspond to actual input rules, preventing hallucinated descriptions from incorrectly granting permissions
  * Fixed user-defined agents only loading one file on NFS/FUSE filesystems that report zero inodes (anthropics/claude-code#26044)
  * Fixed plugin agent skills silently failing to load when referenced by bare name instead of fully-qualified plugin name (anthropics/claude-code#25834)
  * Search patterns in collapsed tool results are now displayed in quotes for clarity
  * Windows: Fixed CWD tracking temp files never being cleaned up, causing them to accumulate indefinitely (anthropics/claude-code#17600)
  * Use `ctrl+f` to kill all background agents instead of double-pressing ESC. Background agents now continue running when you press ESC to cancel the main thread, giving you more control over agent lifecycle.
  * Fixed API 400 errors ("thinking blocks cannot be modified") that occurred in sessions with concurrent agents, caused by interleaved streaming content blocks preventing proper message merging.
  * Simplified teammate navigation to use only Shift+Down (with wrapping) instead of both Shift+Up and Shift+Down.
  * Fixed an issue where a single file write/edit error would abort all other parallel file write/edit operations. Independent file mutations now complete even when a sibling fails.
  * Added `last_assistant_message` field to Stop and SubagentStop hook inputs, providing the final assistant response text so hooks can access it without parsing transcript files.
  * Fixed custom session titles set via `/rename` being lost after resuming a conversation (anthropics/claude-code#23610)
  * Fixed collapsed read/search hint text overflowing on narrow terminals by truncating from the start.
  * Fixed an issue where bash commands with backslash-newline continuation lines (e.g., long commands split across multiple lines with `\`) would produce spurious empty arguments, potentially breaking command execution.
  * Fixed built-in slash commands (`/help`, `/model`, `/compact`, etc.) being hidden from the autocomplete dropdown when many user skills are installed (anthropics/claude-code#22020)
  * Fixed MCP servers not appearing in the MCP Management Dialog after deferred loading
  * Fixed session name persisting in status bar after `/clear` command (anthropics/claude-code#26082)
  * Fixed crash when a skill's `name` or `description` in SKILL.md frontmatter is a bare number (e.g., `name: 3000`) — the value is now properly coerced to a string (anthropics/claude-code#25837)
  * Fixed /resume silently dropping sessions when the first message exceeds 16KB or uses array-format content (anthropics/claude-code#25721)
  * Added `chat:newline` keybinding action for configurable multi-line input (anthropics/claude-code#26075)
  * Added `added_dirs` to the statusline JSON `workspace` section, exposing directories added via `/add-dir` to external scripts (anthropics/claude-code#26096)
  * Fixed `claude doctor` misclassifying mise and asdf-managed installations as native installs (anthropics/claude-code#26033)
  * Fixed zsh heredoc failing with "read-only file system" error in sandboxed commands (anthropics/claude-code#25990)
  * Fixed agent progress indicator showing inflated tool use count (anthropics/claude-code#26023)
  * Fixed image pasting not working on WSL2 systems where Windows copies images as BMP format (anthropics/claude-code#25935)
  * Fixed background agent results returning raw transcript data instead of the agent's final answer (anthropics/claude-code#26012)
  * Fixed Warp terminal incorrectly prompting for Shift+Enter setup when it supports it natively (anthropics/claude-code#25957)
  * Fixed CJK wide characters causing misaligned timestamps and layout elements in the TUI (anthropics/claude-code#26084)
  * Fixed custom agent `model` field in `.claude/agents/*.md` being ignored when spawning team teammates (anthropics/claude-code#26064)
  * Fixed plan mode being lost after context compaction, causing the model to switch from planning to implementation mode (anthropics/claude-code#26061)
  * Fixed `alwaysThinkingEnabled: true` in settings.json not enabling thinking mode on Bedrock and Vertex providers (anthropics/claude-code#26074)
  * Fixed `tool_decision` OTel telemetry event not being emitted in headless/SDK mode (anthropics/claude-code#26059)
  * Fixed session name being lost after context compaction — renamed sessions now preserve their custom title through compaction (anthropics/claude-code#26121)
  * Increased initial session count in resume picker from 10 to 50 for faster session discovery (anthropics/claude-code#26123)
  * Windows: fixed worktree session matching when drive letter casing differs (anthropics/claude-code#26123)
  * Fixed `/resume <session-id>` failing to find sessions whose first message exceeds 16KB (anthropics/claude-code#25920)
  * Fixed "Always allow" on multiline bash commands creating invalid permission patterns that corrupt settings (anthropics/claude-code#25909)
  * Fixed React crash (error #31) when a skill's `argument-hint` in SKILL.md frontmatter uses YAML sequence syntax (e.g., `[topic: foo | bar]`) — the value is now properly coerced to a string (anthropics/claude-code#25826)
  * Fixed crash when using `/fork` on sessions that used web search — null entries in search results from transcript deserialization are now handled gracefully (anthropics/claude-code#25811)
  * Fixed read-only git commands triggering FSEvents file watcher loops on macOS by adding --no-optional-locks flag (anthropics/claude-code#25750)
  * Fixed custom agents and skills not being discovered when running from a git worktree — project-level `.claude/agents/` and `.claude/skills/` from the main repository are now included (anthropics/claude-code#25816)
  * Fixed non-interactive subcommands like `claude doctor` and `claude plugin validate` being blocked inside nested Claude sessions (anthropics/claude-code#25803)
  * Windows: Fixed the same CLAUDE.md file being loaded twice when drive letter casing differs between paths (anthropics/claude-code#25756)
  * Fixed inline code spans in markdown being incorrectly parsed as bash commands (anthropics/claude-code#25792)
  * Fixed teammate spinners not respecting custom spinnerVerbs from settings (anthropics/claude-code#25748)
  * Fixed shell commands permanently failing after a command deletes its own working directory (anthropics/claude-code#26136)
  * Fixed hooks (PreToolUse, PostToolUse) silently failing to execute on Windows by using Git Bash instead of cmd.exe (anthropics/claude-code#25981)
  * Fixed LSP `findReferences` and other location-based operations returning results from gitignored files (e.g., `node_modules/`, `venv/`) (anthropics/claude-code#26051)
  * Moved config backup files from home directory root to `~/.claude/backups/` to reduce home directory clutter (anthropics/claude-code#26130)
  * Fixed sessions with large first prompts (>16KB) disappearing from the /resume list (anthropics/claude-code#26140)
  * Fixed shell functions with double-underscore prefixes (e.g., `__git_ps1`) not being preserved across shell sessions (anthropics/claude-code#25824)
  * Fixed spinner showing "0 tokens" counter before any tokens have been received (anthropics/claude-code#26105)
  * VSCode: Fixed conversation messages appearing dimmed while the AskUserQuestion dialog is open (anthropics/claude-code#26078)
  * Fixed background tasks failing in git worktrees due to remote URL resolution reading from worktree-specific gitdir instead of the main repository config (anthropics/claude-code#26065)
  * Fixed Right Alt key leaving visible `[25~` escape sequence residue in the input field on Windows/Git Bash terminals (anthropics/claude-code#25943)
  * The `/rename` command now updates the terminal tab title by default (anthropics/claude-code#25789)
  * 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.
</Update>

<Update label="2.1.46" description="February 18, 2026">
  * Fixed orphaned CC processes after terminal disconnect on macOS
  * Added support for using claude.ai MCP connectors in Claude Code
</Update>

<Update label="2.1.45" description="February 17, 2026">
  * Added support for Claude Sonnet 4.6
  * Added support for reading `enabledPlugins` and `extraKnownMarketplaces` from `--add-dir` directories
  * Added `spinnerTipsOverride` setting to customize spinner tips — configure `tips` with an array of custom tip strings, and optionally set `excludeDefault: true` to show only your custom tips instead of the built-in ones
  * Added `SDKRateLimitInfo` and `SDKRateLimitEvent` types to the SDK, enabling consumers to receive rate limit status updates including utilization, reset times, and overage information
  * Fixed Agent Teams teammates failing on Bedrock, Vertex, and Foundry by propagating API provider environment variables to tmux-spawned processes (anthropics/claude-code#23561)
  * Fixed sandbox "operation not permitted" errors when writing temporary files on macOS by using the correct per-user temp directory (anthropics/claude-code#21654)
  * Fixed Task tool (backgrounded agents) crashing with a `ReferenceError` on completion (anthropics/claude-code#22087)
  * Fixed autocomplete suggestions not being accepted on Enter when images are pasted in the input
  * Fixed skills invoked by subagents incorrectly appearing in main session context after compaction
  * 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
  * Improved startup performance by removing eager loading of session history for stats caching
  * Improved memory usage for shell commands that produce large output — RSS no longer grows unboundedly with command output size
  * Improved collapsed read/search groups to show the current file or search pattern being processed beneath the summary line while active
  * \[VSCode] Improved permission destination choice (project/user/session) to persist across sessions
</Update>

<Update label="2.1.44" description="February 16, 2026">
  * Fixed ENAMETOOLONG errors for deeply-nested directory paths
  * Fixed auth refresh errors
</Update>

<Update label="2.1.43" description="February 16, 2026">
  * 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
</Update>

<Update label="2.1.42" description="February 13, 2026">
  * Improved startup performance by deferring Zod schema construction
  * Improved prompt cache hit rates by moving date out of system prompt
  * 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
</Update>

<Update label="2.1.41" description="February 13, 2026">
  * Added guard against launching Claude Code inside another Claude Code session
  * Fixed Agent Teams using wrong model identifier for Bedrock, Vertex, and Foundry customers
  * Fixed a crash when MCP tools return image content during streaming
  * Fixed /resume session previews showing raw XML tags instead of readable command names
  * Improved model error messages for Bedrock/Vertex/Foundry users with fallback suggestions
  * Fixed plugin browse showing misleading "Space to Toggle" hint for already-installed plugins
  * Fixed hook blocking errors (exit code 2) not showing stderr to the user
  * Added `speed` attribute to OTel events and trace spans for fast mode visibility
  * Added `claude auth login`, `claude auth status`, and `claude auth logout` CLI subcommands
  * Added Windows ARM64 (win32-arm64) native binary support
  * Improved `/rename` to auto-generate session name from conversation context when called without arguments
  * Improved narrow terminal layout for prompt footer
  * Fixed file resolution failing for @-mentions with anchor fragments (e.g., `@README.md#installation`)
  * Fixed FileReadTool blocking the process on FIFOs, `/dev/stdin`, and large files
  * Fixed background task notifications not being delivered in streaming Agent SDK mode
  * Fixed cursor jumping to end on each keystroke in classifier rule input
  * Fixed markdown link display text being dropped for raw URL
  * Fixed auto-compact failure error notifications being shown to users
  * Fixed permission wait time being included in subagent elapsed time display
  * Fixed proactive ticks firing while in plan mode
  * Fixed clear stale permission rules when settings change on disk
  * Fixed hook blocking errors showing stderr content in UI
</Update>

<Update label="2.1.39" description="February 10, 2026">
  * Improved terminal rendering performance
  * Fixed fatal errors being swallowed instead of displayed
  * Fixed process hanging after session close
  * Fixed character loss at terminal screen boundary
  * Fixed blank lines in verbose transcript view
</Update>

<Update label="2.1.38" description="February 10, 2026">
  * Fixed VS Code terminal scroll-to-top regression introduced in 2.1.37
  * Fixed Tab key queueing slash commands instead of autocompleting
  * Fixed bash permission matching for commands using environment variable wrappers
  * Fixed text between tool uses disappearing when not using streaming
  * Fixed duplicate sessions when resuming in VS Code extension
  * Improved heredoc delimiter parsing to prevent command smuggling
  * Blocked writes to `.claude/skills` directory in sandbox mode
</Update>

<Update label="2.1.37" description="February 7, 2026">
  * Fixed an issue where /fast was not immediately available after enabling /extra-usage
</Update>

<Update label="2.1.36" description="February 7, 2026">
  * Fast mode is now available for Opus 4.6. Learn more at [https://code.claude.com/docs/en/fast-mode](fast-mode-847ef2d690.md)
</Update>

<Update label="2.1.34" description="February 6, 2026">
  * 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
</Update>

<Update label="2.1.33" description="February 6, 2026">
  * Fixed agent teammate sessions in tmux to send and receive messages
  * Fixed warnings about agent teams not being available on your current plan
  * Added `TeammateIdle` and `TaskCompleted` hook events for multi-agent workflows
  * Added support for restricting which sub-agents can be spawned via `Task(agent_type)` syntax in agent "tools" frontmatter
  * Added `memory` frontmatter field support for agents, enabling persistent memory with `user`, `project`, or `local` scope
  * Added plugin name to skill descriptions and `/skills` menu for better discoverability
  * Fixed an issue where submitting a new message while the model was in extended thinking would interrupt the thinking phase
  * Fixed an API error that could occur when aborting mid-stream, where whitespace text combined with a thinking block would bypass normalization and produce an invalid request
  * Fixed API proxy compatibility issue where 404 errors on streaming endpoints no longer triggered non-streaming fallback
  * Fixed an issue where proxy settings configured via `settings.json` environment variables were not applied to WebFetch and other HTTP requests on the Node.js build
  * Fixed `/resume` session picker showing raw XML markup instead of clean titles for sessions started with slash commands
  * Improved error messages for API connection failures — now shows specific cause (e.g., ECONNREFUSED, SSL errors) instead of generic "Connection error"
  * Errors from invalid managed settings are now surfaced
  * VSCode: Added support for remote sessions, allowing OAuth users to browse and resume sessions from claude.ai
  * VSCode: Added git branch and message count to the session picker, with support for searching by branch name
  * VSCode: Fixed scroll-to-bottom under-scrolling on initial session load and session switch
</Update>

<Update label="2.1.32" description="February 5, 2026">
  * Claude Opus 4.6 is now available!
  * Added research preview agent teams feature for multi-agent collaboration (token-intensive feature, requires setting CLAUDE\_CODE\_EXPERIMENTAL\_AGENT\_TEAMS=1)
  * Claude now automatically records and recalls memories as it works
  * Added "Summarize from here" to the message selector, allowing partial conversation summarization.
  * Skills defined in `.claude/skills/` within additional directories (`--add-dir`) are now loaded automatically.
  * Fixed `@` file completion showing incorrect relative paths when running from a subdirectory
  * Updated --resume to re-use --agent value specified in previous conversation by default.
  * Fixed: Bash tool no longer throws "Bad substitution" errors when heredocs contain JavaScript template literals like `${index + 1}`, which previously interrupted tool execution
  * Skill character budget now scales with context window (2% of context), so users with larger context windows can see more skill descriptions without truncation
  * 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
  * VSCode: Added spinner when loading past conversations list
</Update>

<Update label="2.1.31" description="February 4, 2026">
  * Added session resume hint on exit, showing how to continue your conversation later
  * Added support for full-width (zenkaku) space input from Japanese IME in checkbox selection
  * Fixed PDF too large errors permanently locking up sessions, requiring users to start a new conversation
  * Fixed bash commands incorrectly reporting failure with "Read-only file system" errors when sandbox mode was enabled
  * 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
  * Improved system prompts to more clearly guide the model toward using dedicated tools (Read, Edit, Glob, Grep) instead of bash equivalents (`cat`, `sed`, `grep`, `find`), reducing unnecessary bash command usage
  * Improved PDF and request size error messages to show actual limits (100 pages, 20MB)
  * Reduced layout jitter in the terminal when the spinner appears and disappears during streaming
  * Removed misleading Anthropic API pricing from model selector for third-party provider (Bedrock, Vertex, Foundry) users
</Update>

<Update label="2.1.30" description="February 3, 2026">
  * Added `pages` parameter to the Read tool for PDFs, allowing specific page ranges to be read (e.g., `pages: "1-5"`). Large PDFs (>10 pages) now return a lightweight reference when `@` mentioned instead of being inlined into context.
  * Added pre-configured OAuth client credentials for MCP servers that don't support Dynamic Client Registration (e.g., Slack). Use `--client-id` and `--client-secret` with `claude mcp add`.
  * Added `/debug` for Claude to help troubleshoot the current session
  * Added support for additional `git log` and `git show` flags in read-only mode (e.g., `--topo-order`, `--cherry-pick`, `--format`, `--raw`)
  * Added token count, tool uses, and duration metrics to Task tool results
  * Added reduced motion mode to the config
  * Fixed phantom "(no content)" text blocks appearing in API conversation history, reducing token waste and potential model confusion
  * Fixed prompt cache not correctly invalidating when tool descriptions or input schemas changed, only when tool names changed
  * Fixed 400 errors that could occur after running `/login` when the conversation contained thinking blocks
  * Fixed a hang when resuming sessions with corrupted transcript files containing `parentUuid` cycles
  * Fixed rate limit message showing incorrect "/upgrade" suggestion for Max 20x users when extra-usage is unavailable
  * Fixed permission dialogs stealing focus while actively typing
  * Fixed subagents not being able to access SDK-provided MCP tools because they were not synced to the shared application state
  * Fixed a regression where Windows users with a `.bashrc` file could not run bash commands
  * Improved memory usage for `--resume` (68% reduction for users with many sessions) by replacing the session index with lightweight stat-based loading and progressive enrichment
  * Improved `TaskStop` tool to display the stopped command/task description in the result line instead of a generic "Task stopped" message
  * Changed `/model` to execute immediately instead of being queued
  * \[VSCode] Added multiline input support to the "Other" text input in question dialogs (use Shift+Enter for new lines)
  * \[VSCode] Fixed duplicate sessions appearing in the session list when starting a new conversation
</Update>

<Update label="2.1.29" description="January 31, 2026">
  * Fixed startup performance issues when resuming sessions that have `saved_hook_context`
</Update>

<Update label="2.1.27" description="January 30, 2026">
  * Added tool call failures and denials to debug logs
  * Fixed context management validation error for gateway users, ensuring `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1` avoids the error
  * Added `--from-pr` flag to resume sessions linked to a specific GitHub PR number or URL
  * Sessions are now automatically linked to PRs when created via `gh pr create`
  * Fixed /context command not displaying colored output
  * Fixed status bar duplicating background task indicator when PR status was shown
  * Windows: Fixed bash command execution failing for users with `.bashrc` files
  * Windows: Fixed console windows flashing when spawning child processes
  * VSCode: Fixed OAuth token expiration causing 401 errors after extended sessions
</Update>

<Update label="2.1.25" description="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
</Update>

<Update label="2.1.23" description="January 29, 2026">
  * Added customizable spinner verbs setting (`spinnerVerbs`)
  * Fixed mTLS and proxy connectivity for users behind corporate proxies or using client certificates
  * Fixed per-user temp directory isolation to prevent permission conflicts on shared systems
  * Fixed a race condition that could cause 400 errors when prompt caching scope was enabled
  * Fixed pending async hooks not being cancelled when headless streaming sessions ended
  * Fixed tab completion not updating the input field when accepting a suggestion
  * Fixed ripgrep search timeouts silently returning empty results instead of reporting errors
  * Improved terminal rendering performance with optimized screen data layout
  * Changed Bash commands to show timeout duration alongside elapsed time
  * Changed merged pull requests to show a purple status indicator in the prompt footer
  * \[IDE] Fixed model options displaying incorrect region strings for Bedrock users in headless mode
</Update>

<Update label="2.1.22" description="January 28, 2026">
  * Fixed structured outputs for non-interactive (-p) mode
</Update>

<Update label="2.1.21" description="January 28, 2026">
  * Added support for full-width (zenkaku) number input from Japanese IME in option selection prompts
  * Fixed shell completion cache files being truncated on exit
  * Fixed API errors when resuming sessions that were interrupted during tool execution
  * Fixed auto-compact triggering too early on models with large output token limits
  * Fixed task IDs potentially being reused after deletion
  * Fixed file search not working in VS Code extension on Windows
  * Improved read/search progress indicators to show "Reading…" while in progress and "Read" when complete
  * Improved Claude to prefer file operation tools (Read, Edit, Write) over bash equivalents (cat, sed, awk)
  * \[VSCode] Added automatic Python virtual environment activation, ensuring `python` and `pip` commands use the correct interpreter (configurable via `claudeCode.usePythonEnvironment` setting)
  * \[VSCode] Fixed message action buttons having incorrect background colors
</Update>

<Update label="2.1.20" description="January 27, 2026">
  * Added arrow key history navigation in vim normal mode when cursor cannot move further
  * Added external editor shortcut (Ctrl+G) to the help menu for better discoverability
  * Added PR review status indicator to the prompt footer, showing the current branch's PR state (approved, changes requested, pending, or draft) as a colored dot with a clickable link
  * Added support for loading `CLAUDE.md` files from additional directories specified via `--add-dir` flag (requires setting `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1`)
  * Added ability to delete tasks via the `TaskUpdate` tool
  * Fixed session compaction issues that could cause resume to load full history instead of the compact summary
  * Fixed agents sometimes ignoring user messages sent while actively working on a task
  * Fixed wide character (emoji, CJK) rendering artifacts where trailing columns were not cleared when replaced by narrower characters
  * Fixed JSON parsing errors when MCP tool responses contain special Unicode characters
  * Fixed up/down arrow keys in multi-line and wrapped text input to prioritize cursor movement over history navigation
  * Fixed draft prompt being lost when pressing UP arrow to navigate command history
  * Fixed ghost text flickering when typing slash commands mid-input
  * Fixed marketplace source removal not properly deleting settings
  * Fixed duplicate output in some commands like `/context`
  * Fixed task list sometimes showing outside the main conversation view
  * Fixed syntax highlighting for diffs occurring within multiline constructs like Python docstrings
  * Fixed crashes when cancelling tool use
  * Improved `/sandbox` command UI to show dependency status with installation instructions when dependencies are missing
  * Improved thinking status text with a subtle shimmer animation
  * Improved task list to dynamically adjust visible items based on terminal height
  * Improved fork conversation hint to show how to resume the original session
  * Changed collapsed read/search groups to show present tense ("Reading", "Searching for") while in progress, and past tense ("Read", "Searched for") when complete
  * Changed `ToolSearch` results to appear as a brief notification instead of inline in the conversation
  * Changed the `/commit-push-pr` skill to automatically post PR URLs to Slack channels when configured via MCP tools
  * Changed the `/copy` command to be available to all users
  * Changed background agents to prompt for tool permissions before launching
  * Changed permission rules like `Bash(*)` to be accepted and treated as equivalent to `Bash`
  * Changed config backups to be timestamped and rotated (keeping 5 most recent) to prevent data loss
</Update>

<Update label="2.1.19" description="January 23, 2026">
  * Added env var `CLAUDE_CODE_ENABLE_TASKS`, set to `false` to keep the old system temporarily
  * Added shorthand `$0`, `$1`, etc. for accessing individual arguments in custom commands
  * Fixed crashes on processors without AVX instruction support
  * Fixed dangling Claude Code processes when terminal is closed by catching EIO errors from `process.exit()` and using SIGKILL as fallback
  * Fixed `/rename` and `/tag` not updating the correct session when resuming from a different directory (e.g., git worktrees)
  * Fixed resuming sessions by custom title not working when run from a different directory
  * Fixed pasted text content being lost when using prompt stash (Ctrl+S) and restore
  * Fixed agent list displaying "Sonnet (default)" instead of "Inherit (default)" for agents without an explicit model setting
  * 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
  * Changed skills without additional permissions or hooks to be allowed without requiring approval
  * Changed indexed argument syntax from `$ARGUMENTS.0` to `$ARGUMENTS[0]` (bracket syntax)
  * \[SDK] Added replay of `queued_command` attachment messages as `SDKUserMessageReplay` events when `replayUserMessages` is enabled
  * \[VSCode] Enabled session forking and rewind functionality for all users
</Update>

<Update label="2.1.18" description="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](customize-keyboard-shortcuts-claude-code-docs-f23eb8cfd3.md)
</Update>

<Update label="2.1.17" description="January 22, 2026">
  * Fixed crashes on processors without AVX instruction support
</Update>

<Update label="2.1.16" description="January 22, 2026">
  * Added new task management system, including new capabilities like dependency tracking
  * \[VSCode] Added native plugin management support
  * \[VSCode] Added ability for OAuth users to browse and resume remote Claude sessions from the Sessions dialog
  * Fixed out-of-memory crashes when resuming sessions with heavy subagent usage
  * Fixed an issue where the "context remaining" warning was not hidden after running `/compact`
  * 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
</Update>

<Update label="2.1.15" description="January 21, 2026">
  * Added deprecation notification for npm installations - run `claude install` or see [https://docs.anthropic.com/en/docs/claude-code/getting-started](https://docs.anthropic.com/en/docs/claude-code/getting-started) for more options
  * 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
</Update>

<Update label="2.1.14" description="January 20, 2026">
  * Added history-based autocomplete in bash mode (`!`) - type a partial command and press Tab to complete from your bash command history
  * Added search to installed plugins list - type to filter by name or description
  * Added support for pinning plugins to specific git commit SHAs, allowing marketplace entries to install exact versions
  * Fixed a regression where the context window blocking limit was calculated too aggressively, blocking users at \~65% context usage instead of the intended \~98%
  * Fixed memory issues that could cause crashes when running parallel subagents
  * Fixed memory leak in long-running sessions where stream resources were not cleaned up after shell commands completed
  * Fixed `@` symbol incorrectly triggering file autocomplete suggestions in bash mode
  * Fixed `@`-mention menu folder click behavior to navigate into directories instead of selecting them
  * Fixed `/feedback` command generating invalid GitHub issue URLs when description is very long
  * Fixed `/context` command to show the same token count and percentage as the status line in verbose mode
  * Fixed an issue where `/config`, `/context`, `/model`, and `/todos` command overlays could close unexpectedly
  * Fixed slash command autocomplete selecting wrong command when typing similar commands (e.g., `/context` vs `/compact`)
  * 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
  * Improved backspace to delete pasted text as a single token instead of one character at a time
  * \[VSCode] Added `/usage` command to display current plan usage
</Update>

<Update label="2.1.12" description="January 17, 2026">
  * Fixed message rendering bug
</Update>

<Update label="2.1.11" description="January 17, 2026">
  * Fixed excessive MCP connection requests for HTTP/SSE transports
</Update>

<Update label="2.1.10" description="January 17, 2026">
  * Added new `Setup` hook event that can be triggered via `--init`, `--init-only`, or `--maintenance` CLI flags for repository setup and maintenance operations
  * Added keyboard shortcut 'c' to copy OAuth URL when browser doesn't open automatically during login
  * Fixed a crash when running bash commands containing heredocs with JavaScript template literals like `${index + 1}`
  * Improved startup to capture keystrokes typed before the REPL is fully ready
  * 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
</Update>

<Update label="2.1.9" description="January 16, 2026">
  * Added `auto:N` syntax for configuring the MCP tool search auto-enable threshold, where N is the context window percentage (0-100)
  * Added `plansDirectory` setting to customize where plan files are stored
  * Added external editor support (Ctrl+G) in AskUserQuestion "Other" input field
  * Added session URL attribution to commits and PRs created from web sessions
  * Added support for `PreToolUse` hooks to return `additionalContext` to the model
  * Added `${CLAUDE_SESSION_ID}` string substitution for skills to access the current session ID
  * Fixed long sessions with parallel tool calls failing with an API error about orphan tool\_result blocks
  * 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)
</Update>

<Update label="2.1.7" description="January 14, 2026">
  * Added `showTurnDuration` setting to hide turn duration messages (e.g., "Cooked for 1m 6s")
  * Added ability to provide feedback when accepting permission prompts
  * Added inline display of agent's final response in task notifications, making it easier to see results without reading the full transcript file
  * Fixed security vulnerability where wildcard permission rules could match compound commands containing shell operators
  * Fixed false "file modified" errors on Windows when cloud sync tools, antivirus scanners, or Git touch file timestamps without changing content
  * Fixed orphaned tool\_result errors when sibling tools fail during streaming execution
  * Fixed context window blocking limit being calculated using the full context window instead of the effective context window (which reserves space for max output tokens)
  * Fixed spinner briefly flashing when running local slash commands like `/model` or `/theme`
  * Fixed terminal title animation jitter by using fixed-width braille characters
  * 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
  * Improved typing responsiveness by reducing memory allocation overhead in terminal rendering
  * Enabled MCP tool search auto mode by default for all users. When MCP tool descriptions exceed 10% of the context window, they are automatically deferred and discovered via the MCPSearch tool instead of being loaded upfront. This reduces context usage for users with many MCP tools configured. Users can disable this by adding `MCPSearch` to `disallowedTools` in their settings.
  * Changed OAuth and API Console URLs from console.anthropic.com to platform.claude.com
  * \[VSCode] Fixed `claudeProcessWrapper` setting passing the wrapper path instead of the Claude binary path
</Update>

<Update label="2.1.6" description="January 13, 2026">
  * Added search functionality to `/config` command for quickly filtering settings
  * Added Updates section to `/doctor` showing auto-update channel and available npm versions (stable/latest)
  * Added date range filtering to `/stats` command - press `r` to cycle between Last 7 days, Last 30 days, and All time
  * Added automatic discovery of skills from nested `.claude/skills` directories when working with files in subdirectories
  * Added `context_window.used_percentage` and `context_window.remaining_percentage` fields to status line input for easier context window display
  * Added an error display when the editor fails during Ctrl+G
  * Fixed permission bypass via shell line continuation that could allow blocked commands to execute
  * Fixed false "File has been unexpectedly modified" errors when file watchers touch files without changing content
  * Fixed text styling (bold, colors) getting progressively misaligned in multi-line responses
  * Fixed the feedback panel closing unexpectedly when typing 'n' in the description field
  * Fixed rate limit warning appearing at low usage after weekly reset (now requires 70% usage)
  * Fixed rate limit options menu incorrectly auto-opening when resuming a previous session
  * Fixed numpad keys outputting escape sequences instead of characters in Kitty keyboard protocol terminals
  * Fixed Option+Return not inserting newlines in Kitty keyboard protocol terminals
  * Fixed corrupted config backup files accumulating in the home directory (now only one backup is created per config file)
  * Fixed `mcp list` and `mcp get` commands leaving orphaned MCP server processes
  * Fixed visual artifacts in ink2 mode when nodes become hidden via `display:none`
  * Improved the external CLAUDE.md imports approval dialog to show which files are being imported and from where
  * Improved the `/tasks` dialog to go directly to task details when there's only one background task running
  * Improved @ autocomplete with icons for different suggestion types and single-line formatting
  * Updated "Help improve Claude" setting fetch to refresh OAuth and retry when it fails due to a stale OAuth token
  * Changed task notification display to cap at 3 lines with overflow summary when multiple background tasks complete simultaneously
  * Changed terminal title to "Claude Code" on startup for better window identification
  * Removed ability to @-mention MCP servers to enable/disable - use `/mcp enable <name>` instead
  * \[VSCode] Fixed usage indicator not updating after manual compact
</Update>

<Update label="2.1.5" description="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
</Update>

<Update label="2.1.4" description="January 11, 2026">
  * 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
</Update>

<Update label="2.1.3" description="January 9, 2026">
  * Merged slash commands and skills, simplifying the mental model with no change in behavior
  * Added release channel (`stable` or `latest`) toggle to `/config`
  * Added detection and warnings for unreachable permission rules, with warnings in `/doctor` and after saving rules that include the source of each rule and actionable fix guidance
  * Fixed plan files persisting across `/clear` commands, now ensuring a fresh plan file is used after clearing a conversation
  * Fixed false skill duplicate detection on filesystems with large inodes (e.g., ExFAT) by using 64-bit precision for inode values
  * Fixed mismatch between background task count in status bar and items shown in tasks dialog
  * 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
  * Improved terminal rendering stability by preventing uncontrolled writes from corrupting cursor state
  * Improved slash command suggestion readability by truncating long descriptions to 2 lines
  * Changed tool hook execution timeout from 60 seconds to 10 minutes
  * \[VSCode] Added clickable destination selector for permission requests, allowing you to choose where settings are saved (this project, all projects, shared with team, or session only)
</Update>

<Update label="2.1.2" description="January 9, 2026">
  * Added source path metadata to images dragged onto the terminal, helping Claude understand where images originated
  * Added clickable hyperlinks for file paths in tool output in terminals that support OSC 8 (like iTerm)
  * Added support for Windows Package Manager (winget) installations with automatic detection and update instructions
  * Added Shift+Tab keyboard shortcut in plan mode to quickly select "auto-accept edits" option
  * Added `FORCE_AUTOUPDATE_PLUGINS` environment variable to allow plugin autoupdate even when the main auto-updater is disabled
  * Added `agent_type` to SessionStart hook input, populated if `--agent` is specified
  * Fixed a command injection vulnerability in bash command processing where malformed input could execute arbitrary commands
  * Fixed a memory leak where tree-sitter parse trees were not being freed, causing WASM memory to grow unbounded over long sessions
  * Fixed binary files (images, PDFs, etc.) being accidentally included in memory when using `@include` directives in CLAUDE.md files
  * Fixed updates incorrectly claiming another installation is in progress
  * Fixed crash when socket files exist in watched directories (defense-in-depth for EOPNOTSUPP errors)
  * 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
  * Improved Option-as-Meta hint on macOS to show terminal-specific instructions for native CSIu terminals like iTerm2, Kitty, and WezTerm
  * Improved error message when pasting images over SSH to suggest using `scp` instead of the unhelpful clipboard shortcut hint
  * Improved permission explainer to not flag routine dev workflows (git fetch/rebase, npm install, tests, PRs) as medium risk
  * Changed large bash command outputs to be saved to disk instead of truncated, allowing Claude to read the full content
  * Changed large tool outputs to be persisted to disk instead of truncated, providing full output access via file references
  * Changed `/plugins` installed tab to unify plugins and MCPs with scope-based grouping
  * Deprecated Windows managed settings path `C:\ProgramData\ClaudeCode\managed-settings.json` - administrators should migrate to `C:\Program Files\ClaudeCode\managed-settings.json`
  * \[SDK] Changed minimum zod peer dependency to ^4.0.0
  * \[VSCode] Fixed usage display not updating after manual compact
</Update>

<Update label="2.1.0" description="January 7, 2026">
  * Added automatic skill hot-reload - skills created or modified in `~/.claude/skills` or `.claude/skills` are now immediately available without restarting the session
  * Added support for running skills and slash commands in a forked sub-agent context using `context: fork` in skill frontmatter
  * Added support for `agent` field in skills to specify agent type for execution
  * Added `language` setting to configure Claude's response language (e.g., language: "japanese")
  * Changed Shift+Enter to work out of the box in iTerm2, WezTerm, Ghostty, and Kitty without modifying terminal configs
  * Added `respectGitignore` support in `settings.json` for per-project control over @-mention file picker behavior
  * Added `IS_DEMO` environment variable to hide email and organization from the UI, useful for streaming or recording sessions
  * Fixed security issue where sensitive data (OAuth tokens, API keys, passwords) could be exposed in debug logs
  * Fixed files and skills not being properly discovered when resuming sessions with `-c` or `--resume`
  * Fixed pasted content being lost when replaying prompts from history using up arrow or Ctrl+R search
  * Fixed Esc key with queued prompts to only move them to input without canceling the running task
  * Reduced permission prompts for complex bash commands
  * Fixed command search to prioritize exact and prefix matches on command names over fuzzy matches in descriptions
  * Fixed PreToolUse hooks to allow `updatedInput` when returning `ask` permission decision, enabling hooks to act as middleware while still requesting user consent
  * Fixed plugin path resolution for file-based marketplace sources
  * Fixed LSP tool being incorrectly enabled when no LSP servers were configured
  * Fixed background tasks failing with "git repository not found" error for repositories with dots in their names
  * Fixed Claude in Chrome support for WSL environments
  * Fixed Windows native installer silently failing when executable creation fails
  * Improved CLI help output to display options and subcommands in alphabetical order for easier navigation
  * Added wildcard pattern matching for Bash tool permissions using `*` at any position in rules (e.g., `Bash(npm *)`, `Bash(* install)`, `Bash(git * main)`)
  * Added unified Ctrl+B backgrounding for both bash commands and agents - pressing Ctrl+B now backgrounds all running foreground tasks simultaneously
  * Added support for MCP `list_changed` notifications, allowing MCP servers to dynamically update their available tools, prompts, and resources without requiring reconnection
  * Added `/teleport` and `/remote-env` slash commands for claude.ai subscribers, allowing them to resume and configure remote sessions
  * Added support for disabling specific agents using `Task(AgentName)` syntax in settings.json permissions or the `--disallowedTools` CLI flag
  * Added hooks support to agent frontmatter, allowing agents to define PreToolUse, PostToolUse, and Stop hooks scoped to the agent's lifecycle
  * Added hooks support for skill and slash command frontmatter
  * Added new Vim motions: `;` and `,` to repeat f/F/t/T motions, `y` operator for yank with `yy`/`Y`, `p`/`P` for paste, text objects (`iw`, `aw`, `iW`, `aW`, `i"`, `a"`, `i'`, `a'`, `i(`, `a(`, `i[`, `a[`, `i{`, `a{`), `>>` and `<<` for indent/dedent, and `J` to join lines
  * Added `/plan` command shortcut to enable plan mode directly from the prompt
  * Added slash command autocomplete support when `/` appears anywhere in input, not just at the beginning
  * Added `--tools` flag support in interactive mode to restrict which built-in tools Claude can use during interactive sessions
  * Added `CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS` environment variable to override the default file read token limit
  * Added support for `once: true` config for hooks
  * Added support for YAML-style lists in frontmatter `allowed-tools` field for cleaner skill declarations
  * Added support for prompt and agent hook types from plugins (previously only command hooks were supported)
  * Added Cmd+V support for image paste in iTerm2 (maps to Ctrl+V)
  * Added left/right arrow key navigation for cycling through tabs in dialogs
  * Added real-time thinking block display in Ctrl+O transcript mode
  * Added filepath to full output in background bash task details dialog
  * Added Skills as a separate category in the context visualization
  * Fixed OAuth token refresh not triggering when server reports token expired but local expiration check disagrees
  * Fixed session persistence getting stuck after transient server errors by recovering from 409 conflicts when the entry was actually stored
  * Fixed session resume failures caused by orphaned tool results during concurrent tool execution
  * Fixed a race condition where stale OAuth tokens could be read from the keychain cache during concurrent token refresh attempts
  * Fixed AWS Bedrock subagents not inheriting EU/APAC cross-region inference model configuration, causing 403 errors when IAM permissions are scoped to specific regions
  * Fixed API context overflow when background tasks produce large output by truncating to 30K chars with file path reference
  * Fixed a hang when reading FIFO files by skipping symlink resolution for special file types
  * Fixed terminal keyboard mode not being reset on exit in Ghostty, iTerm2, Kitty, and WezTerm
  * Fixed Alt+B and Alt+F (word navigation) not working in iTerm2, Ghostty, Kitty, and WezTerm
  * Fixed `${CLAUDE_PLUGIN_ROOT}` not being substituted in plugin `allowed-tools` frontmatter, which caused tools to incorrectly require approval
  * Fixed files created by the Write tool using hardcoded 0o600 permissions instead of respecting the system umask
  * Fixed commands with `$()` command substitution failing with parse errors
  * Fixed multi-line bash commands with backslash continuations being incorrectly split and flagged for permissions
  * Fixed bash command prefix extraction to correctly identify subcommands after global options (e.g., `git -C /path log` now correctly matches `Bash(git log:*)` rules)
  * Fixed slash commands passed as CLI arguments (e.g., `claude /context`) not being executed properly
  * Fixed pressing Enter after Tab-completing a slash command selecting a different command instead of submitting the completed one
  * Fixed slash command argument hint flickering and inconsistent display when typing commands with arguments
  * Fixed Claude sometimes redundantly invoking the Skill tool when running slash commands directly
  * Fixed skill token estimates in `/context` to accurately reflect frontmatter-only loading
  * Fixed subagents sometimes not inheriting the parent's model by default
  * Fixed model picker showing incorrect selection for Bedrock/Vertex users using `--model haiku`
  * Fixed duplicate Bash commands appearing in permission request option labels
  * Fixed noisy output when background tasks complete - now shows clean completion message instead of raw output
  * Fixed background task completion notifications to appear proactively with bullet point
  * Fixed forked slash commands showing "AbortError" instead of "Interrupted" message when cancelled
  * Fixed cursor disappearing after dismissing permission dialogs
  * Fixed `/hooks` menu selecting wrong hook type when scrolling to a different option
  * Fixed images in queued prompts showing as "\[object Object]" when pressing Esc to cancel
  * Fixed images being silently dropped when queueing messages while backgrounding a task
  * Fixed large pasted images failing with "Image was too large" error
  * Fixed extra blank lines in multiline prompts containing CJK characters (Japanese, Chinese, Korean)
  * Fixed ultrathink keyword highlighting being applied to wrong characters when user prompt text wraps to multiple lines
  * Fixed collapsed "Reading X files…" indicator incorrectly switching to past tense when thinking blocks appear mid-stream
  * Fixed Bash read commands (like `ls` and `cat`) not being counted in collapsed read/search groups, causing groups to incorrectly show "Read 0 files"
  * Fixed spinner token counter to properly accumulate tokens from subagents during execution
  * Fixed memory leak in git diff parsing where sliced strings retained large parent strings
  * Fixed race condition where LSP tool could return "no server available" during startup
  * Fixed feedback submission hanging indefinitely when network requests timeout
  * Fixed search mode in plugin discovery and log selector views exiting when pressing up arrow
  * Fixed hook success message showing trailing colon when hook has no output
  * Multiple optimizations to improve startup performance
  * Improved terminal rendering performance when using native installer or Bun, especially for text with emoji, ANSI codes, and Unicode characters
  * Improved performance when reading Jupyter notebooks with many cells
  * Improved reliability for piped input like `cat refactor.md | claude`
  * Improved reliability for AskQuestion tool
  * Improved sed in-place edit commands to render as file edits with diff preview
  * Improved Claude to automatically continue when response is cut off due to output token limit, instead of showing an error message
  * Improved compaction reliability
  * Improved subagents (Task tool) to continue working after permission denial, allowing them to try alternative approaches
  * Improved skills to show progress while executing, displaying tool uses as they happen
  * Improved skills from `/skills/` directories to be visible in the slash command menu by default (opt-out with `user-invocable: false` in frontmatter)
  * Improved skill suggestions to prioritize recently and frequently used skills
  * Improved spinner feedback when waiting for the first response token
  * Improved token count display in spinner to include tokens from background agents
  * Improved incremental output for async agents to give the main thread more control and visibility
  * Improved permission prompt UX with Tab hint moved to footer, cleaner Yes/No input labels with contextual placeholders
  * Improved the Claude in Chrome notification with shortened help text and persistent display until dismissed
  * Improved macOS screenshot paste reliability with TIFF format support
  * Improved `/stats` output
  * Updated Atlassian MCP integration to use a more reliable default configuration (streamable HTTP)
  * Changed "Interrupted" message color from red to grey for a less alarming appearance
  * Removed permission prompt when entering plan mode - users can now enter plan mode without approval
  * Removed underline styling from image reference links
  * \[SDK] Changed minimum zod peer dependency to ^4.0.0
  * \[VSCode] Added currently selected model name to the context menu
  * \[VSCode] Added descriptive labels on auto-accept permission button (e.g., "Yes, allow npm for this project" instead of "Yes, and don't ask again")
  * \[VSCode] Fixed paragraph breaks not rendering in markdown content
  * \[VSCode] Fixed scrolling in the extension inadvertently scrolling the parent iframe
  * \[Windows] Fixed issue with improper rendering
</Update>

<Update label="2.0.76" description="January 7, 2026">
  * Fixed issue with macOS code-sign warning when using Claude in Chrome integration
</Update>

<Update label="2.0.75" description="January 7, 2026">
  * Minor bugfixes
</Update>

<Update label="2.0.74" description="December 19, 2025">
  * Added LSP (Language Server Protocol) tool for code intelligence features like go-to-definition, find references, and hover documentation
  * Added `/terminal-setup` support for Kitty, Alacritty, Zed, and Warp terminals
  * Added ctrl+t shortcut in `/theme` to toggle syntax highlighting on/off
  * Added syntax highlighting info to theme picker
  * Added guidance for macOS users when Alt shortcuts fail due to terminal configuration
  * Fixed skill `allowed-tools` not being applied to tools invoked by the skill
  * Fixed Opus 4.5 tip incorrectly showing when user was already using Opus
  * Fixed a potential crash when syntax highlighting isn't initialized correctly
  * 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'
  * Improved `/context` command visualization with grouped skills and agents by source, slash commands, and sorted token count
  * \[Windows] Fixed issue with improper rendering
  * \[VSCode] Added gift tag pictogram for year-end promotion message
</Update>

<Update label="2.0.73" description="December 19, 2025">
  * Added clickable `[Image #N]` links that open attached images in the default viewer
  * Added alt-y yank-pop to cycle through kill ring history after ctrl-y yank
  * Added search filtering to the plugin discover screen (type to filter by name, description, or marketplace)
  * Added support for custom session IDs when forking sessions with `--session-id` combined with `--resume` or `--continue` and `--fork-session`
  * Fixed slow input history cycling and race condition that could overwrite text after message submission
  * Improved `/theme` command to open theme picker directly
  * Improved theme picker UI
  * 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)
</Update>

<Update label="2.0.72" description="December 17, 2025">
  * Added Claude in Chrome (Beta) feature that works with the Chrome extension ([https://claude.ai/chrome](https://claude.ai/chrome)) to let you control your browser directly from Claude Code
  * Reduced terminal flickering
  * Added scannable QR code to mobile app tip for quick app downloads
  * Added loading indicator when resuming conversations for better feedback
  * Fixed `/context` command not respecting custom system prompts in non-interactive mode
  * Fixed order of consecutive Ctrl+K lines when pasting with Ctrl+Y
  * Improved @ mention file suggestion speed (\~3× faster in git repositories)
  * Improved file suggestion performance in repos with `.ignore` or `.rgignore` files
  * Improved settings validation errors to be more prominent
  * Changed thinking toggle from Tab to Alt+T to avoid accidental triggers
</Update>

<Update label="2.0.71" description="December 16, 2025">
  * Added /config toggle to enable/disable prompt suggestions
  * Added `/settings` as an alias for the `/config` command
  * Fixed @ file reference suggestions incorrectly triggering when cursor is in the middle of a path
  * Fixed MCP servers from `.mcp.json` not loading when using `--dangerously-skip-permissions`
  * Fixed permission rules incorrectly rejecting valid bash commands containing shell glob patterns (e.g., `ls *.txt`, `for f in *.png`)
  * Bedrock: Environment variable `ANTHROPIC_BEDROCK_BASE_URL` is now respected for token counting and inference profile listing
  * New syntax highlighting engine for native build
</Update>

<Update label="2.0.70" description="December 15, 2025">
  * Added Enter key to accept and submit prompt suggestions immediately (tab still accepts for editing)
  * Added wildcard syntax `mcp__server__*` for MCP tool permissions to allow or deny all tools from a server
  * Added auto-update toggle for plugin marketplaces, allowing per-marketplace control over automatic updates
  * Added `current_usage` field to status line input, enabling accurate context window percentage calculations
  * Fixed input being cleared when processing queued commands while the user was typing
  * Fixed prompt suggestions replacing typed input when pressing Tab
  * Fixed diff view not updating when terminal is resized
  * Improved memory usage by 3x for large conversations
  * Improved resolution of stats screenshots copied to clipboard (Ctrl+S) for crisper images
  * Removed # shortcut for quick memory entry (tell Claude to edit your CLAUDE.md instead)
  * Fix thinking mode toggle in /config not persisting correctly
  * Improve UI for file creation permission dialog
</Update>

<Update label="2.0.69" description="December 13, 2025">
  * Minor bugfixes
</Update>

<Update label="2.0.68" description="December 12, 2025">
  * Fixed IME (Input Method Editor) support for languages like Chinese, Japanese, and Korean by correctly positioning the composition window at the cursor
  * Fixed a bug where disallowed MCP tools were visible to the model
  * Fixed an issue where steering messages could be lost while a subagent is working
  * 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.
</Update>

<Update label="2.0.67" description="December 12, 2025">
  * Thinking mode is now enabled by default for Opus 4.5
  * Thinking mode configuration has moved to /config
  * Added search functionality to `/permissions` command with `/` keyboard shortcut for filtering rules by tool name
  * Show reason why autoupdater is disabled in `/doctor`
  * Fixed false "Another process is currently updating Claude" error when running `claude update` while another instance is already on the latest version
  * Fixed MCP servers from `.mcp.json` being stuck in pending state when running in non-interactive mode (`-p` flag or piped input)
  * Fixed scroll position resetting after deleting a permission rule in `/permissions`
  * Fixed word deletion (opt+delete) and word navigation (opt+arrow) not working correctly with non-Latin text such as Cyrillic, Greek, Arabic, Hebrew, Thai, and Chinese
  * Fixed `claude install --force` not bypassing stale lock files
  * 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
</Update>

<Update label="2.0.65" description="December 11, 2025">
  * Added ability to switch models while writing a prompt using alt+p (linux, windows), option+p (macos).
  * Added context window information to status line input
  * Added `fileSuggestion` setting for custom `@` file search commands
  * Added `CLAUDE_CODE_SHELL` environment variable to override automatic shell detection (useful when login shell differs from actual working shell)
  * 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
</Update>

<Update label="2.0.64" description="December 10, 2025">
  * Made auto-compacting instant
  * Agents and bash commands can run asynchronously and send messages to wake up the main agent
  * /stats now provides users with interesting CC stats, such as favorite model, usage graph, usage streak
  * Added named session support: use `/rename` to name sessions, `/resume <name>` in REPL or `claude --resume <name>` from the terminal to resume them
  * Added support for .claude/rules/\`.  See [https://code.claude.com/docs/en/memory](how-claude-remembers-your-project-claude-code-docs-f1c064262d.md) for details.
  * Added image dimension metadata when images are resized, enabling accurate coordinate mappings for large images
  * Fixed auto-loading .env when using native installer
  * Fixed `--system-prompt` being ignored when using `--continue` or `--resume` flags
  * Improved `/resume` screen with grouped forked sessions and keyboard shortcuts for preview (P) and rename (R)
  * VSCode: Added copy-to-clipboard button on code blocks and bash tool inputs
  * VSCode: Fixed extension not working on Windows ARM64 by falling back to x64 binary via emulation
  * Bedrock: Improve efficiency of token counting
  * Bedrock: Add support for `aws login` AWS Management Console credentials
  * Unshipped AgentOutputTool and BashOutputTool, in favor of a new unified TaskOutputTool
</Update>

<Update label="2.0.62" description="December 9, 2025">
  * Added "(Recommended)" indicator for multiple-choice questions, with the recommended option moved to the top of the list
  * Added `attribution` setting to customize commit and PR bylines (deprecates `includeCoAuthoredBy`)
  * Fixed duplicate slash commands appearing when \~/.claude is symlinked to a project directory
  * Fixed slash command selection not working when multiple commands share the same name
  * Fixed an issue where skill files inside symlinked skill directories could become circular symlinks
  * Fixed running versions getting removed because lock file incorrectly going stale
  * Fixed IDE diff tab not closing when rejecting file changes
</Update>

<Update label="2.0.61" description="December 7, 2025">
  * Reverted VSCode support for multiple terminal clients due to responsiveness issues.
</Update>

<Update label="2.0.60" description="December 6, 2025">
  * Added background agent support. Agents run in the background while you work
  * Added --disable-slash-commands CLI flag to disable all slash commands
  * Added model name to "Co-Authored-By" commit messages
  * Enabled "/mcp enable \[server-name]" or "/mcp disable \[server-name]" to quickly toggle all servers
  * Updated Fetch to skip summarization for pre-approved websites
  * VSCode: Added support for multiple terminal clients connecting to the IDE server simultaneously
</Update>

<Update label="2.0.59" description="December 4, 2025">
  * Added --agent CLI flag to override the agent setting for the current session
  * 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
</Update>

<Update label="2.0.58" description="December 3, 2025">
  * Pro users now have access to Opus 4.5 as part of their subscription!
  * 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.
</Update>

<Update label="2.0.57" description="December 3, 2025">
  * Added feedback input when rejecting plans, allowing users to tell Claude what to change
  * VSCode: Added streaming message support for real-time response display
</Update>

<Update label="2.0.56" description="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.
</Update>

<Update label="2.0.55" description="November 26, 2025">
  * Fixed proxy DNS resolution being forced on by default. Now opt-in via `CLAUDE_CODE_PROXY_RESOLVES_HOSTS=true` environment variable
  * Fixed keyboard navigation becoming unresponsive when holding down arrow keys in memory location selector
  * 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
</Update>

<Update label="2.0.54" description="November 26, 2025">
  * Hooks: Enable PermissionRequest hooks to process 'always allow' suggestions and apply permission updates
  * Fix issue with excessive iTerm notifications
</Update>

<Update label="2.0.52" description="November 24, 2025">
  * Fixed duplicate message display when starting Claude with a command line argument
  * 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
</Update>

<Update label="2.0.51" description="November 24, 2025">
  * Added Opus 4.5! [https://www.anthropic.com/news/claude-opus-4-5](https://www.anthropic.com/news/claude-opus-4-5)
  * Introducing Claude Code for Desktop: [https://claude.com/download](https://claude.com/download)
  * To give you room to try out our new model, we've updated usage limits for Claude Code users. See the Claude Opus 4.5 blog for full details
  * Pro users can now purchase extra usage for access to Opus 4.5 in Claude Code
  * Plan Mode now builds more precise plans and executes more thoroughly
  * Usage limit notifications now easier to understand
  * Switched `/usage` back to "% used"
  * Fixed handling of thinking errors
  * Fixed performance regression
</Update>

<Update label="2.0.50" description="November 21, 2025">
  * Fixed bug preventing calling MCP tools that have nested references in their input schemas
  * Silenced a noisy but harmless error during upgrades
  * Improved ultrathink text display
  * Improved clarity of 5-hour session limit warning message
</Update>

<Update label="2.0.49" description="November 21, 2025">
  * Added readline-style ctrl-y for pasting deleted text
  * Improved clarity of usage limit warning message
  * Fixed handling of subagent permissions
</Update>

<Update label="2.0.47" description="November 19, 2025">
  * Improved error messages and validation for `claude --teleport`
  * Improved error handling in `/usage`
  * Fixed race condition with history entry not getting logged at exit
  * Fixed Vertex AI configuration not being applied from `settings.json`
</Update>

<Update label="2.0.46" description="November 19, 2025">
  * Fixed image files being reported with incorrect media type when format cannot be detected from metadata
</Update>

<Update label="2.0.45" description="November 18, 2025">
  * Added support for Microsoft Foundry! See [https://code.claude.com/docs/en/azure-ai-foundry](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 `&`
</Update>

<Update label="2.0.43" description="November 18, 2025">
  * Added `permissionMode` field for custom agents
  * Added `tool_use_id` field to `PreToolUseHookInput` and `PostToolUseHookInput` types
  * Added skills frontmatter field to declare skills to auto-load for subagents
  * Added the `SubagentStart` hook event
  * Fixed nested `CLAUDE.md` files not loading when @-mentioning files
  * Fixed duplicate rendering of some messages in the UI
  * Fixed some visual flickers
  * Fixed NotebookEdit tool inserting cells at incorrect positions when cell IDs matched the pattern `cell-N`
</Update>

<Update label="2.0.42" description="November 15, 2025">
  * Added `agent_id` and `agent_transcript_path` fields to `SubagentStop` hooks.
</Update>

<Update label="2.0.41" description="November 14, 2025">
  * Added `model` parameter to prompt-based stop hooks, allowing users to specify a custom model for hook evaluation
  * Fixed slash commands from user settings being loaded twice, which could cause rendering issues
  * Fixed incorrect labeling of user settings vs project settings in command descriptions
  * Fixed crash when plugin command hooks timeout during execution
  * Fixed: Bedrock users no longer see duplicate Opus entries in the /model picker when using `--model haiku`
  * 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
  * ctrl-r history search landing on a slash command no longer cancels the search
  * SDK: Support custom timeouts for hooks
  * Allow more safe git commands to run without approval
  * Plugins: Added support for sharing and installing output styles
  * Teleporting a session from web will automatically set the upstream branch
</Update>

<Update label="2.0.37" description="November 11, 2025">
  * Fixed how idleness is computed for notifications
  * Hooks: Added matcher values for Notification hook events
  * Output Styles: Added `keep-coding-instructions` option to frontmatter
</Update>

<Update label="2.0.36" description="November 7, 2025">
  * 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
</Update>

<Update label="2.0.35" description="November 6, 2025">
  * Improve fuzzy search results when searching commands
  * Improved VS Code extension to respect `chat.fontSize` and `chat.fontFamily` settings throughout the entire UI, and apply font changes immediately without requiring reload
  * Added `CLAUDE_CODE_EXIT_AFTER_STOP_DELAY` environment variable to automatically exit SDK mode after a specified idle duration, useful for automated workflows and scripts
  * 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)
</Update>

<Update label="2.0.34" description="November 5, 2025">
  * VSCode Extension: Added setting to configure the initial permission mode for new conversations
  * Improved file path suggestion performance with native Rust-based fuzzy finder
  * 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)
</Update>

<Update label="2.0.33" description="November 4, 2025">
  * Native binary installs now launch quicker.
  * Fixed `claude doctor` incorrectly detecting Homebrew vs npm-global installations by properly resolving symlinks
  * Fixed `claude mcp serve` exposing tools with incompatible outputSchemas
</Update>

<Update label="2.0.32" description="November 4, 2025">
  * 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
</Update>

<Update label="2.0.31" description="October 31, 2025">
  * Windows: native installation uses shift+tab as shortcut for mode switching, instead of alt+m
  * Vertex: add support for Web Search on supported models
  * VSCode: Adding the respectGitIgnore configuration to include .gitignored files in file searches (defaults to true)
  * 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
</Update>

<Update label="2.0.30" description="October 30, 2025">
  * Added helpful hint to run `security unlock-keychain` when encountering API key errors on macOS with locked keychain
  * Added `allowUnsandboxedCommands` sandbox setting to disable the dangerouslyDisableSandbox escape hatch at policy level
  * Added `disallowedTools` field to custom agent definitions for explicit tool blocking
  * Added prompt-based stop hooks
  * VSCode: Added respectGitIgnore configuration to include .gitignored files in file searches (defaults to true)
  * Enabled SSE MCP servers on native build
  * Deprecated output styles. Review options in `/output-style` and use --system-prompt-file, --system-prompt, --append-system-prompt, CLAUDE.md, or plugins instead
  * Removed support for custom ripgrep configuration, resolving an issue where Search returns no results and config discovery fails
  * Fixed Explore agent creating unwanted .md investigation files during codebase exploration
  * Fixed a bug where `/context` would sometimes fail with "max\_tokens must be greater than thinking.budget\_tokens" error message
  * Fixed `--mcp-config` flag to correctly override file-based MCP configurations
  * Fixed bug that saved session permissions to local settings
  * 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
  * VSCode: Restored selection indicator in input footer showing current file or code selection status
</Update>

<Update label="2.0.28" description="October 27, 2025">
  * Plan mode: introduced new Plan subagent
  * Subagents: claude can now choose to resume subagents
  * Subagents: claude can dynamically choose the model used by its subagents
  * SDK: added --max-budget-usd flag
  * Discovery of custom slash commands, subagents, and output styles no longer respects .gitignore
  * Stop `/terminal-setup` from adding backslash to `Shift + Enter` in VS Code
  * Add branch and tag support for git-based plugins and marketplaces using fragment syntax (e.g., `owner/repo#branch`)
  * Fixed a bug where macOS permission prompts would show up upon initial launch when launching from home directory
  * Various other bug fixes
</Update>

<Update label="2.0.27" description="October 24, 2025">
  * New UI for permission prompts
  * Added current branch filtering and search to session resume screen for easier navigation
  * Fixed directory @-mention causing "No assistant message found" error
  * 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
</Update>

<Update label="2.0.25" description="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](../05-Agent-SDK/agent-sdk-migration-guide.md)
</Update>

<Update label="2.0.24" description="October 20, 2025">
  * Fixed a bug where project-level skills were not loading when --setting-sources 'project' was specified
  * Claude Code Web: Support for Web -> CLI teleport
  * Sandbox: Releasing a sandbox mode for the BashTool on Linux & Mac
  * Bedrock: Display awsAuthRefresh output when auth is required
</Update>

<Update label="2.0.22" description="October 17, 2025">
  * Fixed content layout shift when scrolling through slash commands
  * 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
</Update>

<Update label="2.0.21" description="October 18, 2025">
  * Support MCP `structuredContent` field in tool responses
  * Added an interactive question tool
  * Claude will now ask you questions more often in plan mode
  * 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
</Update>

<Update label="2.0.20" description="October 16, 2025">
  * Added support for Claude Skills
</Update>

<Update label="2.0.19" description="October 15, 2025">
  * 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
</Update>

<Update label="2.0.17" description="October 15, 2025">
  * Added Haiku 4.5 to model selector!
  * Haiku 4.5 automatically uses Sonnet in plan mode, and Haiku for execution (i.e. SonnetPlan by default)
  * 3P (Bedrock and Vertex) are not automatically upgraded yet. Manual upgrading can be done through setting `ANTHROPIC_DEFAULT_HAIKU_MODEL`
  * Introducing the Explore subagent. Powered by Haiku it'll search through your codebase efficiently to save context!
  * OTEL: support HTTP\_PROXY and HTTPS\_PROXY
  * `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` now disables release notes fetching
</Update>

<Update label="2.0.15" description="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
</Update>

<Update label="2.0.14" description="October 10, 2025">
  * Fix @-mentioning MCP servers to toggle them on/off
  * Improve permission checks for bash with inline env vars
  * Fix ultrathink + thinking toggle
  * Reduce unnecessary logins
  * Document --system-prompt
  * Several improvements to rendering
  * Plugins UI polish
</Update>

<Update label="2.0.13" description="October 9, 2025">
  * Fixed `/plugin` not working on native build
</Update>

<Update label="2.0.12" description="October 9, 2025">
  * **Plugin System Released**: Extend Claude Code with custom commands, agents, hooks, and MCP servers from marketplaces
  * `/plugin install`, `/plugin enable/disable`, `/plugin marketplace` commands for plugin management
  * Repository-level plugin configuration via `extraKnownMarketplaces` for team collaboration
  * `/plugin validate` command for validating plugin structure and configuration
  * Plugin announcement blog post at [https://www.anthropic.com/news/claude-code-plugins](https://www.anthropic.com/news/claude-code-plugins)
  * Plugin documentation available at [https://code.claude.com/docs/en/plugins](../08-Plugins-Skills/create-plugins-claude-code-docs.md)
  * Comprehensive error messages and diagnostics via `/doctor` command
  * Avoid flickering in `/model` selector
  * Improvements to `/help`
  * Avoid mentioning hooks in `/resume` summaries
  * Changes to the "verbose" setting in `/config` now persist across sessions
</Update>

<Update label="2.0.11" description="October 8, 2025">
  * Reduced system prompt size by 1.4k tokens
  * 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
</Update>

<Update label="2.0.10" description="October 8, 2025">
  * Rewrote terminal renderer for buttery smooth UI
  * Enable/disable MCP servers by @mentioning, or in /mcp
  * Added tab completion for shell commands in bash mode
  * PreToolUse hooks can now modify tool inputs
  * 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
</Update>

<Update label="2.0.9" description="October 6, 2025">
  * Fix regression where bash backgrounding stopped working
</Update>

<Update label="2.0.8" description="October 4, 2025">
  * Update Bedrock default Sonnet model to `global.anthropic.claude-sonnet-4-5-20250929-v1:0`
  * IDE: Add drag-and-drop support for files and folders in chat
  * /context: Fix counting for thinking blocks
  * 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)
</Update>

<Update label="2.0.5" description="October 4, 2025">
  * IDE: Fix IME unintended message submission with Enter and Tab
  * IDE: Add "Open in Terminal" link in login screen
  * Fix unhandled OAuth expiration 401 API errors
  * SDK: Added SDKUserMessageReplay.isReplay to prevent duplicate messages
</Update>

<Update label="2.0.1" description="September 30, 2025">
  * Skip Sonnet 4.5 default model setting change for Bedrock and Vertex
  * Various bug fixes and presentation improvements
</Update>

<Update label="2.0.0" description="September 29, 2025">
  * New native VS Code extension
  * Fresh coat of paint throughout the whole app
  * /rewind a conversation to undo code changes
  * /usage command to see plan limits
  * Tab to toggle thinking (sticky across sessions)
  * Ctrl-R to search history
  * Unshipped claude config command
  * Hooks: Reduced PostToolUse 'tool\_use' ids were found without 'tool\_result' blocks errors
  * SDK: The Claude Code SDK is now the Claude Agent SDK
  * Add subagents dynamically with `--agents` flag
</Update>

<Update label="1.0.126" description="September 26, 2025">
  * Enable /context command for Bedrock and Vertex
  * Add mTLS support for HTTP-based OpenTelemetry exporters
</Update>

<Update label="1.0.124" description="September 25, 2025">
  * Set `CLAUDE_BASH_NO_LOGIN` environment variable to 1 or true to to skip login shell for BashTool
  * Fix Bedrock and Vertex environment variables evaluating all strings as truthy
  * 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
</Update>

<Update label="1.0.123" description="September 23, 2025">
  * Bash permission rules now support output redirections when matching (e.g., `Bash(python:*)` matches `python script.py > output.txt`)
  * Fixed thinking mode triggering on negation phrases like "don't think"
  * Fixed rendering performance degradation during token streaming
  * Added SlashCommand tool, which enables Claude to invoke your slash commands. [https://code.claude.com/docs/en/slash-commands#SlashCommand-tool](https://code.claude.com/docs/en/slash-commands#SlashCommand-tool)
  * Enhanced BashTool environment snapshot logging
  * 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
</Update>

<Update label="1.0.120" description="September 19, 2025">
  * Fix input lag during typing, especially noticeable with large prompts
  * Improved VSCode extension command registry and sessions dialog user experience
  * Enhanced sessions dialog responsiveness and visual feedback
  * Fixed IDE compatibility issue by removing worktree support check
  * Fixed security vulnerability where Bash tool permission checks could be bypassed using prefix matching
</Update>

<Update label="1.0.119" description="September 19, 2025">
  * Fix Windows issue where process visually freezes on entering interactive mode
  * 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
</Update>

<Update label="1.0.117" description="September 19, 2025">
  * Add Ctrl-R history search to recall previous commands like bash/zsh
  * Fix input lag while typing, especially on Windows
  * 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
</Update>

<Update label="1.0.115" description="September 16, 2025">
  * Improve thinking mode display with enhanced visual effects
  * Type /t to temporarily disable thinking mode in your prompt
  * Improve path validation for glob and grep tools
  * Show condensed output for post-tool hooks to reduce visual clutter
  * Fix visual feedback when loading state completes
  * Improve UI consistency for permission request dialogs
</Update>

<Update label="1.0.113" description="September 13, 2025">
  * Deprecated piped input in interactive mode
  * Move Ctrl+R keybinding for toggling transcript to Ctrl+O
</Update>

<Update label="1.0.112" description="September 12, 2025">
  * Transcript mode (Ctrl+R): Added the model used to generate each assistant message
  * Addressed issue where some Claude Max users were incorrectly recognized as Claude Pro users
  * Hooks: Added systemMessage support for SessionEnd hooks
  * Added `spinnerTipsEnabled` setting to disable spinner tips
  * IDE: Various improvements and bug fixes
</Update>

<Update label="1.0.111" description="September 10, 2025">
  * /model now validates provided model names
  * Fixed Bash tool crashes caused by malformed shell syntax parsing
</Update>

<Update label="1.0.110" description="September 10, 2025">
  * /terminal-setup command now supports WezTerm
  * MCP: OAuth tokens now proactively refresh before expiration
  * Fixed reliability issues with background Bash processes
</Update>

<Update label="1.0.109" description="September 9, 2025">
  * SDK: Added partial message streaming support via `--include-partial-messages` CLI flag
</Update>

<Update label="1.0.106" description="September 5, 2025">
  * Windows: Fixed path permission matching to consistently use POSIX format (e.g., `Read(//c/Users/...)`)
</Update>

<Update label="1.0.97" description="August 29, 2025">
  * Settings: /doctor now validates permission rule syntax and suggests corrections
</Update>

<Update label="1.0.94" description="August 27, 2025">
  * Vertex: add support for global endpoints for supported models
  * /memory command now allows direct editing of all imported memory files
  * SDK: Add custom tools as callbacks
  * Added /todos command to list current todo items
</Update>

<Update label="1.0.93" description="August 26, 2025">
  * Windows: Add alt + v shortcut for pasting images from clipboard
  * Support NO\_PROXY environment variable to bypass proxy for specified hostnames and IPs
</Update>

<Update label="1.0.90" description="August 25, 2025">
  * Settings file changes take effect immediately - no restart required
</Update>

<Update label="1.0.88" description="August 22, 2025">
  * Fixed issue causing "OAuth authentication is currently not supported"
  * Status line input now includes `exceeds_200k_tokens`
  * Fixed incorrect usage tracking in /cost.
  * 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
</Update>

<Update label="1.0.86" description="August 22, 2025">
  * Added /context to help users self-serve debug context issues
  * SDK: Added UUID support for all SDK messages
  * SDK: Added `--replay-user-messages` to replay user messages back to stdout
</Update>

<Update label="1.0.85" description="August 19, 2025">
  * Status line input now includes session cost info
  * Hooks: Introduced SessionEnd hook
</Update>

<Update label="1.0.84" description="August 18, 2025">
  * Fix tool\_use/tool\_result id mismatch error when network is unstable
  * Fix Claude sometimes ignoring real-time steering when wrapping up a task
  * @-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
</Update>

<Update label="1.0.83" description="August 18, 2025">
  * @-mention: Support files with spaces in path
  * New shimmering spinner
</Update>

<Update label="1.0.82" description="August 16, 2025">
  * SDK: Add request cancellation support
  * SDK: New additionalDirectories option to search custom paths, improved slash command processing
  * Settings: Validation prevents invalid fields in .claude/settings.json files
  * MCP: Improve tool name consistency
  * Bash: Fix crash when Claude tries to automatically read large files
</Update>

<Update label="1.0.81" description="August 14, 2025">
  * Released output styles, including new built-in educational output styles "Explanatory" and "Learning". Docs: [https://code.claude.com/docs/en/output-styles](output-styles-claude-code-docs-c315eeed32.md)
  * Agents: Fix custom agent loading when agent files are unparsable
</Update>

<Update label="1.0.80" description="August 14, 2025">
  * UI improvements: Fix text contrast for custom subagent colors and spinner rendering issues
</Update>

<Update label="1.0.77" description="August 14, 2025">
  * Bash tool: Fix heredoc and multiline string escaping, improve stderr redirection handling
  * 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
</Update>

<Update label="1.0.73" description="August 11, 2025">
  * MCP: Support multiple config files with `--mcp-config file1.json file2.json`
  * MCP: Press Esc to cancel OAuth authentication flows
  * Bash: Improved command validation and reduced false security warnings
  * UI: Enhanced spinner animations and status line visual hierarchy
  * Linux: Added support for Alpine and musl-based distributions (requires separate ripgrep installation)
</Update>

<Update label="1.0.72" description="August 11, 2025">
  * Ask permissions: have Claude Code always ask for confirmation to use specific tools with /permissions
</Update>

<Update label="1.0.71" description="August 7, 2025">
  * 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
</Update>

<Update label="1.0.70" description="August 7, 2025">
  * Performance: Optimized message rendering for better performance with large contexts
  * Windows: Fixed native file search, ripgrep, and subagent functionality
  * Added support for @-mentions in slash command arguments
</Update>

<Update label="1.0.69" description="August 5, 2025">
  * Upgraded Opus to version 4.1
</Update>

<Update label="1.0.68" description="August 4, 2025">
  * Fix incorrect model names being used for certain commands like `/pr-comments`
  * Windows: improve permissions checks for allow / deny tools and project trust. This may create a new project entry in `.claude.json` - manually merge the history field if desired.
  * Windows: improve sub-process spawning to eliminate "No such file or directory" when running commands like pnpm
  * Enhanced /doctor command with CLAUDE.md and MCP tool context for self-serve debugging
  * SDK: Added canUseTool callback support for tool confirmation
  * Added `disableAllHooks` setting
  * Improved file suggestions performance in large repos
</Update>

<Update label="1.0.65" description="July 31, 2025">
  * IDE: Fixed connection stability issues and error handling for diagnostics
  * Windows: Fixed shell environment setup for users without .bashrc files
</Update>

<Update label="1.0.64" description="July 30, 2025">
  * Agents: Added model customization support - you can now specify which model an agent should use
  * Agents: Fixed unintended access to the recursive agent tool
  * Hooks: Added systemMessage field to hook JSON output for displaying warnings and context
  * SDK: Fixed user input tracking across multi-turn conversations
  * Added hidden files to file search and @-mention suggestions
</Update>

<Update label="1.0.63" description="July 29, 2025">
  * Windows: Fixed file search, @agent mentions, and custom slash commands functionality
</Update>

<Update label="1.0.62" description="July 28, 2025">
  * Added @-mention support with typeahead for custom agents. @`<your-custom-agent>` to invoke it
  * Hooks: Added SessionStart hook for new session initialization
  * /add-dir command now supports typeahead for directory paths
  * Improved network connectivity check reliability
</Update>

<Update label="1.0.61" description="July 25, 2025">
  * Transcript mode (Ctrl+R): Changed Esc to exit transcript mode rather than interrupt
  * Settings: Added `--settings` flag to load settings from a JSON file
  * Settings: Fixed resolution of settings files paths that are symlinks
  * OTEL: Fixed reporting of wrong organization after authentication changes
  * Slash commands: Fixed permissions checking for allowed-tools with Bash
  * IDE: Added support for pasting images in VSCode MacOS using ⌘+V
  * 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
</Update>

<Update label="1.0.60" description="July 24, 2025">
  * You can now create custom subagents for specialized tasks! Run /agents to get started
</Update>

<Update label="1.0.59" description="July 23, 2025">
  * SDK: Added tool confirmation support with canUseTool callback
  * SDK: Allow specifying env for spawned process
  * Hooks: Exposed PermissionDecision to hooks (including "ask")
  * Hooks: UserPromptSubmit now supports additionalContext in advanced JSON output
  * Fixed issue where some Max users that specified Opus would still see fallback to Sonnet
</Update>

<Update label="1.0.58" description="July 23, 2025">
  * Added support for reading PDFs
  * MCP: Improved server health status display in 'claude mcp list'
  * Hooks: Added CLAUDE\_PROJECT\_DIR env var for hook commands
</Update>

<Update label="1.0.57" description="July 23, 2025">
  * Added support for specifying a model in slash commands
  * Improved permission messages to help Claude understand allowed tools
  * Fix: Remove trailing newlines from bash output in terminal wrapping
</Update>

<Update label="1.0.56" description="July 23, 2025">
  * 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
</Update>

<Update label="1.0.55" description="July 23, 2025">
  * Clarified knowledge cutoff for Opus 4 and Sonnet 4 models
  * Windows: fixed Ctrl+Z crash
  * SDK: Added ability to capture error logging
  * Add --system-prompt-file option to override system prompt in print mode
</Update>

<Update label="1.0.54" description="July 19, 2025">
  * Hooks: Added UserPromptSubmit hook and the current working directory to hook inputs
  * Custom slash commands: Added argument-hint to frontmatter
  * Windows: OAuth uses port 45454 and properly constructs browser URL
  * Windows: mode switching now uses alt + m, and plan mode renders properly
  * Shell: Switch to in-memory shell snapshot to fix file-related errors
</Update>

<Update label="1.0.53" description="July 18, 2025">
  * 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).
</Update>

<Update label="1.0.52" description="July 18, 2025">
  * Added support for MCP server instructions
</Update>

<Update label="1.0.51" description="July 11, 2025">
  * Added support for native Windows (requires Git for Windows)
  * Added support for Bedrock API keys through environment variable AWS\_BEARER\_TOKEN\_BEDROCK
  * Settings: /doctor can now help you identify and fix invalid setting files
  * `--append-system-prompt` can now be used in interactive mode, not just --print/-p.
  * Increased auto-compact warning threshold from 60% to 80%
  * Fixed an issue with handling user directories with spaces for shell snapshots
  * OTEL resource now includes os.type, os.version, host.arch, and wsl.version (if running on Windows Subsystem for Linux)
  * Custom slash commands: Fixed user-level commands in subdirectories
  * Plan mode: Fixed issue where rejected plan from sub-task would get discarded
</Update>

<Update label="1.0.48" description="July 10, 2025">
  * Fixed a bug in v1.0.45 where the app would sometimes freeze on launch
  * Added progress messages to Bash tool based on the last 5 lines of command output
  * Added expanding variables support for MCP server configuration
  * Moved shell snapshots from /tmp to \~/.claude for more reliable Bash tool calls
  * Improved IDE extension path handling when Claude Code runs in WSL
  * Hooks: Added a PreCompact hook
  * Vim mode: Added c, f/F, t/T
</Update>

<Update label="1.0.45" description="July 10, 2025">
  * Redesigned Search (Grep) tool with new tool input parameters and features
  * Disabled IDE diffs for notebook files, fixing "Timeout waiting after 1000ms" error
  * Fixed config file corruption issue by enforcing atomic writes
  * Updated prompt input undo to Ctrl+\_ to avoid breaking existing Ctrl+U behavior, matching zsh's undo shortcut
  * 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.
</Update>

<Update label="1.0.44" description="July 7, 2025">
  * New /export command lets you quickly export a conversation for sharing
  * MCP: resource\_link tool results are now supported
  * 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.
</Update>

<Update label="1.0.43" description="July 3, 2025">
  * Fixed a bug where the theme selector was saving excessively
  * Hooks: Added EPIPE system error handling
</Update>

<Update label="1.0.42" description="July 3, 2025">
  * Added tilde (`~`) expansion support to `/add-dir` command
</Update>

<Update label="1.0.41" description="July 3, 2025">
  * Hooks: Split Stop hook triggering into Stop and SubagentStop
  * Hooks: Enabled optional timeout configuration for each command
  * Hooks: Added "hook\_event\_name" to hook input
  * Fixed a bug where MCP tools would display twice in tool list
  * New tool parameters JSON for Bash tool in `tool_decision` event
</Update>

<Update label="1.0.40" description="July 3, 2025">
  * Fixed a bug causing API connection errors with UNABLE\_TO\_GET\_ISSUER\_CERT\_LOCALLY if `NODE_EXTRA_CA_CERTS` was set
</Update>

<Update label="1.0.39" description="July 3, 2025">
  * New Active Time metric in OpenTelemetry logging
</Update>

<Update label="1.0.38" description="June 30, 2025">
  * Released hooks. Special thanks to community input in [https://github.com/anthropics/claude-code/issues/712](https://github.com/anthropics/claude-code/issues/712). Docs: [https://code.claude.com/docs/en/hooks](../07-Hooks/hooks-9168ed62a4.md)
</Update>

<Update label="1.0.37" description="June 30, 2025">
  * Remove ability to set `Proxy-Authorization` header via ANTHROPIC\_AUTH\_TOKEN or apiKeyHelper
</Update>

<Update label="1.0.36" description="June 30, 2025">
  * Web search now takes today's date into context
  * Fixed a bug where stdio MCP servers were not terminating properly on exit
</Update>

<Update label="1.0.35" description="June 25, 2025">
  * Added support for MCP OAuth Authorization Server discovery
</Update>

<Update label="1.0.34" description="June 24, 2025">
  * Fixed a memory leak causing a MaxListenersExceededWarning message to appear
</Update>

<Update label="1.0.33" description="June 24, 2025">
  * Improved logging functionality with session ID support
  * Added prompt input undo functionality (Ctrl+Z and vim 'u' command)
  * Improvements to plan mode
</Update>

<Update label="1.0.32" description="June 24, 2025">
  * Updated loopback config for litellm
  * Added forceLoginMethod setting to bypass login selection screen
</Update>

<Update label="1.0.31" description="June 24, 2025">
  * Fixed a bug where \~/.claude.json would get reset when file contained invalid JSON
</Update>

<Update label="1.0.30" description="June 24, 2025">
  * Custom slash commands: Run bash output, @-mention files, enable thinking with thinking keywords
  * Improved file path autocomplete with filename matching
  * Added timestamps in Ctrl-r mode and fixed Ctrl-c handling
  * Enhanced jq regex support for complex filters with pipes and select
</Update>

<Update label="1.0.29" description="June 24, 2025">
  * Improved CJK character support in cursor navigation and rendering
</Update>

<Update label="1.0.28" description="June 24, 2025">
  * Slash commands: Fix selector display during history navigation
  * Resizes images before upload to prevent API size limit errors
  * Added XDG\_CONFIG\_HOME support to configuration directory
  * Performance optimizations for memory usage
  * New attributes (terminal.type, language) in OpenTelemetry logging
</Update>

<Update label="1.0.27" description="June 18, 2025">
  * Streamable HTTP MCP servers are now supported
  * Remote MCP servers (SSE and HTTP) now support OAuth
  * MCP resources can now be @-mentioned
  * /resume slash command to switch conversations within Claude Code
</Update>

<Update label="1.0.25" description="June 16, 2025">
  * Slash commands: moved "project" and "user" prefixes to descriptions
  * Slash commands: improved reliability for command discovery
  * Improved support for Ghostty
  * Improved web search reliability
</Update>

<Update label="1.0.24" description="June 16, 2025">
  * Improved /mcp output
  * Fixed a bug where settings arrays got overwritten instead of merged
</Update>

<Update label="1.0.23" description="June 16, 2025">
  * Released TypeScript SDK: import @anthropic-ai/claude-code to get started
  * Released Python SDK: pip install claude-code-sdk to get started
</Update>

<Update label="1.0.22" description="June 12, 2025">
  * SDK: Renamed `total_cost` to `total_cost_usd`
</Update>

<Update label="1.0.21" description="June 12, 2025">
  * 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
</Update>

<Update label="1.0.18" description="June 9, 2025">
  * Added --add-dir CLI argument for specifying additional working directories
  * Added streaming input support without require -p flag
  * Improved startup performance and session storage performance
  * Added CLAUDE\_BASH\_MAINTAIN\_PROJECT\_WORKING\_DIR environment variable to freeze working directory for bash commands
  * Added detailed MCP server tools display (/mcp)
  * MCP authentication and permission improvements
  * Added auto-reconnection for MCP SSE connections on disconnect
  * Fixed issue where pasted content was lost when dialogs appeared
</Update>

<Update label="1.0.17" description="June 9, 2025">
  * We now emit messages from sub-tasks in -p mode (look for the parent\_tool\_use\_id property)
  * 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"
</Update>

<Update label="1.0.11" description="June 4, 2025">
  * Claude Code can now also be used with a Claude Pro subscription
  * Added /upgrade for smoother switching to Claude Max plans
  * Improved UI for authentication from API keys and Bedrock/Vertex/external auth tokens
  * Improved shell configuration error handling
  * Improved todo list handling during compaction
</Update>

<Update label="1.0.10" description="June 4, 2025">
  * Added markdown table support
  * Improved streaming performance
</Update>

<Update label="1.0.8" description="June 2, 2025">
  * Fixed Vertex AI region fallback when using CLOUD\_ML\_REGION
  * Increased default otel interval from 1s -> 5s
  * Fixed edge cases where MCP\_TIMEOUT and MCP\_TOOL\_TIMEOUT weren't being respected
  * Fixed a regression where search tools unnecessarily asked for permissions
  * Added support for triggering thinking non-English languages
  * Improved compacting UI
</Update>

<Update label="1.0.7" description="June 2, 2025">
  * Renamed /allowed-tools -> /permissions
  * Migrated allowedTools and ignorePatterns from .claude.json -> settings.json
  * Deprecated claude config commands in favor of editing settings.json
  * Fixed a bug where --dangerously-skip-permissions sometimes didn't work in --print mode
  * Improved error handling for /install-github-app
  * Bugfixes, UI polish, and tool reliability improvements
</Update>

<Update label="1.0.6" description="June 2, 2025">
  * Improved edit reliability for tab-indented files
  * Respect CLAUDE\_CONFIG\_DIR everywhere
  * Reduced unnecessary tool permission prompts
  * Added support for symlinks in @file typeahead
  * Bugfixes, UI polish, and tool reliability improvements
</Update>

<Update label="1.0.4" description="May 28, 2025">
  * Fixed a bug where MCP tool errors weren't being parsed correctly
</Update>

<Update label="1.0.1" description="May 22, 2025">
  * Added `DISABLE_INTERLEAVED_THINKING` to give users the option to opt out of interleaved thinking.
  * Improved model references to show provider-specific names (Sonnet 3.7 for Bedrock, Sonnet 4 for Console)
  * Updated documentation links and OAuth process descriptions
</Update>

<Update label="1.0.0" description="May 22, 2025">
  * Claude Code is now generally available
  * Introducing Sonnet 4 and Opus 4 models
</Update>

<Update label="0.2.125" description="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
</Update>

<Update label="0.2.117" description="May 17, 2025">
  * Breaking change: --print JSON output now returns nested message objects, for forwards-compatibility as we introduce new metadata fields
  * Introduced settings.cleanupPeriodDays
  * Introduced CLAUDE\_CODE\_API\_KEY\_HELPER\_TTL\_MS env var
  * Introduced --debug mode
</Update>

<Update label="0.2.108" description="May 13, 2025">
  * You can now send messages to Claude while it works to steer Claude in real-time
  * Introduced BASH\_DEFAULT\_TIMEOUT\_MS and BASH\_MAX\_TIMEOUT\_MS env vars
  * Fixed a bug where thinking was not working in -p mode
  * Fixed a regression in /cost reporting
  * Deprecated MCP wizard interface in favor of other MCP commands
  * Lots of other bugfixes and improvements
</Update>

<Update label="0.2.107" description="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
</Update>

<Update label="0.2.106" description="May 9, 2025">
  * MCP SSE server configs can now specify custom headers
  * Fixed a bug where MCP permission prompt didn't always show correctly
</Update>

<Update label="0.2.105" description="May 8, 2025">
  * Claude can now search the web
  * Moved system & account status to /status
  * Added word movement keybindings for Vim
  * Improved latency for startup, todo tool, and file edits
</Update>

<Update label="0.2.102" description="May 5, 2025">
  * Improved thinking triggering reliability
  * Improved @mention reliability for images and folders
  * You can now paste multiple large chunks into one prompt
</Update>

<Update label="0.2.100" description="May 2, 2025">
  * Fixed a crash caused by a stack overflow error
  * Made db storage optional; missing db support disables --continue and --resume
</Update>

<Update label="0.2.98" description="May 1, 2025">
  * Fixed an issue where auto-compact was running twice
</Update>

<Update label="0.2.96" description="May 1, 2025">
  * Claude Code can now also be used with a Claude Max subscription ([https://claude.ai/upgrade](https://claude.ai/upgrade))
</Update>

<Update label="0.2.93" description="April 30, 2025">
  * 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
</Update>

<Update label="0.2.82" description="April 25, 2025">
  * Added support for --disallowedTools
  * Renamed tools for consistency: LSTool -> LS, View -> Read, etc.
</Update>

<Update label="0.2.75" description="April 21, 2025">
  * Hit Enter to queue up additional messages while Claude is working
  * Drag in or copy/paste image files directly into the prompt
  * @-mention files to directly add them to context
  * Run one-off MCP servers with `claude --mcp-config <path-to-file>`
  * Improved performance for filename auto-complete
</Update>

<Update label="0.2.74" description="April 18, 2025">
  * 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
</Update>

<Update label="0.2.72" description="April 18, 2025">
  * Updated spinner to indicate tokens loaded and tool usage
</Update>

<Update label="0.2.70" description="April 17, 2025">
  * Network commands like curl are now available for Claude to use
  * Claude can now run multiple web queries in parallel
  * Pressing ESC once immediately interrupts Claude in Auto-accept mode
</Update>

<Update label="0.2.69" description="April 17, 2025">
  * Fixed UI glitches with improved Select component behavior
  * Enhanced terminal output display with better text truncation logic
</Update>

<Update label="0.2.67" description="April 17, 2025">
  * Shared project permission rules can be saved in .claude/settings.json
</Update>

<Update label="0.2.66" description="April 17, 2025">
  * Print mode (-p) now supports streaming output via --output-format=stream-json
  * Fixed issue where pasting could trigger memory or bash mode unexpectedly
</Update>

<Update label="0.2.63" description="April 17, 2025">
  * Fixed an issue where MCP tools were loaded twice, which caused tool call errors
</Update>

<Update label="0.2.61" description="April 2, 2025">
  * Navigate menus with vim-style keys (j/k) or bash/emacs shortcuts (Ctrl+n/p) for faster interaction
  * Enhanced image detection for more reliable clipboard paste functionality
  * Fixed an issue where ESC key could crash the conversation history selector
</Update>

<Update label="0.2.59" description="April 2, 2025">
  * Copy+paste images directly into your prompt
  * Improved progress indicators for bash and fetch tools
  * Bugfixes for non-interactive mode (-p)
</Update>

<Update label="0.2.54" description="April 2, 2025">
  * Quickly add to Memory by starting your message with '#'
  * Press ctrl+r to see full output for long tool results
  * Added support for MCP SSE transport
</Update>

<Update label="0.2.53" description="April 2, 2025">
  * New web fetch tool lets Claude view URLs that you paste in
  * Fixed a bug with JPEG detection
</Update>

<Update label="0.2.50" description="April 2, 2025">
  * New MCP "project" scope now allows you to add MCP servers to .mcp.json files and commit them to your repository
</Update>

<Update label="0.2.49" description="April 2, 2025">
  * Previous MCP server scopes have been renamed: previous "project" scope is now "local" and "global" scope is now "user"
</Update>

<Update label="0.2.47" description="April 2, 2025">
  * Press Tab to auto-complete file and folder names
  * Press Shift + Tab to toggle auto-accept for file edits
  * Automatic conversation compaction for infinite conversation length (toggle with /config)
</Update>

<Update label="0.2.44" description="April 2, 2025">
  * Ask Claude to make a plan with thinking mode: just say 'think' or 'think harder' or even 'ultrathink'
</Update>

<Update label="0.2.41" description="April 2, 2025">
  * MCP server startup timeout can now be configured via MCP\_TIMEOUT environment variable
  * MCP server startup no longer blocks the app from starting up
</Update>

<Update label="0.2.37" description="April 2, 2025">
  * 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
</Update>

<Update label="0.2.36" description="April 2, 2025">
  * 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>`
</Update>

<Update label="0.2.34" description="April 2, 2025">
  * Vim bindings for text input - enable with /vim or /config
</Update>

<Update label="0.2.32" description="April 2, 2025">
  * Interactive MCP setup wizard: Run "claude mcp add" to add MCP servers with a step-by-step interface
  * Fix for some PersistentShell issues
</Update>

<Update label="0.2.31" description="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
</Update>

<Update label="0.2.30" description="April 2, 2025">
  * Added ANSI color theme for better terminal compatibility
  * Fixed issue where slash command arguments weren't being sent properly
  * (Mac-only) API keys are now stored in macOS Keychain
</Update>

<Update label="0.2.26" description="April 2, 2025">
  * New /approved-tools command for managing tool permissions
  * Word-level diff display for improved code readability
  * Fuzzy matching for slash commands
</Update>

<Update label="0.2.21" description="April 2, 2025">
  * Fuzzy matching for /commands
</Update>


---
## channels-00374ea787.md

> ## Documentation Index
> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Push events into a running session with channels

> Use channels to push messages, alerts, and webhooks into your Claude Code session from an MCP server. Forward CI results, chat messages, and monitoring events so Claude can react while you're away.

<Note>
  Channels are in [research preview](#research-preview) and require Claude Code v2.1.80 or later. They require claude.ai login. Console and API key authentication is not supported. Team and Enterprise organizations must [explicitly enable them](#enterprise-controls).
</Note>

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](#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.

This page covers:

* [Supported channels](#supported-channels): Telegram, Discord, and iMessage setup
* [Install and run a channel](#quickstart) with fakechat, a localhost demo
* [Who can push messages](#security): sender allowlists and how you pair
* [Enable channels for your organization](#enterprise-controls) on Team and Enterprise
* [How channels compare](#how-channels-compare) to web sessions, Slack, MCP, and Remote Control

To build your own channel, see the [Channels reference](channels-reference-claude-code-docs-67a0bbe41f.md).

## 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](#quickstart).

<Tabs>
  <Tab title="Telegram">
    View the full [Telegram plugin source](https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/telegram).

    <Steps>
      <Step title="Create a Telegram bot">
        Open [BotFather](https://t.me/BotFather) in Telegram and send `/newbot`. Give it a display name and a unique username ending in `bot`. Copy the token BotFather returns.
      </Step>

      <Step title="Install the plugin">
        In Claude Code, run:

        ```
        /plugin install telegram@claude-plugins-official
        ```

        If Claude Code reports that the plugin is not found in any marketplace, your marketplace is either missing or outdated. Run `/plugin marketplace update claude-plugins-official` to refresh it, or `/plugin marketplace add anthropics/claude-plugins-official` if you haven't added it before. Then retry the install.

        After installing, run `/reload-plugins` to activate the plugin's configure command.
      </Step>

      <Step title="Configure your token">
        Run the configure command with the token from BotFather:

        ```
        /telegram:configure <token>
        ```

        This saves it to `~/.claude/channels/telegram/.env`. You can also set `TELEGRAM_BOT_TOKEN` in your shell environment before launching Claude Code.
      </Step>

      <Step title="Restart with channels enabled">
        Exit Claude Code and restart with the channel flag. This starts the Telegram plugin, which begins polling for messages from your bot:

        ```bash theme={null}
        claude --channels plugin:telegram@claude-plugins-official
        ```
      </Step>

      <Step title="Pair your account">
        Open Telegram and send any message to your bot. The bot replies with a pairing code.

        <Note>If your bot doesn't respond, make sure Claude Code is running with `--channels` from the previous step. The bot can only reply while the channel is active.</Note>

        Back in Claude Code, run:

        ```
        /telegram:access pair <code>
        ```

        Then lock down access so only your account can send messages:

        ```
        /telegram:access policy allowlist
        ```
      </Step>
    </Steps>
  </Tab>

  <Tab title="Discord">
    View the full [Discord plugin source](https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/discord).

    <Steps>
      <Step title="Create a Discord bot">
        Go to the [Discord Developer Portal](https://discord.com/developers/applications), click **New Application**, and name it. In the **Bot** section, create a username, then click **Reset Token** and copy the token.
      </Step>

      <Step title="Enable Message Content Intent">
        In your bot's settings, scroll to **Privileged Gateway Intents** and enable **Message Content Intent**.
      </Step>

      <Step title="Invite the bot to your server">
        Go to **OAuth2 > URL Generator**. Select the `bot` scope and enable these permissions:

        * View Channels
        * Send Messages
        * Send Messages in Threads
        * Read Message History
        * Attach Files
        * Add Reactions

        Open the generated URL to add the bot to your server.
      </Step>

      <Step title="Install the plugin">
        In Claude Code, run:

        ```
        /plugin install discord@claude-plugins-official
        ```

        If Claude Code reports that the plugin is not found in any marketplace, your marketplace is either missing or outdated. Run `/plugin marketplace update claude-plugins-official` to refresh it, or `/plugin marketplace add anthropics/claude-plugins-official` if you haven't added it before. Then retry the install.

        After installing, run `/reload-plugins` to activate the plugin's configure command.
      </Step>

      <Step title="Configure your token">
        Run the configure command with the bot token you copied:

        ```
        /discord:configure <token>
        ```

        This saves it to `~/.claude/channels/discord/.env`. You can also set `DISCORD_BOT_TOKEN` in your shell environment before launching Claude Code.
      </Step>

      <Step title="Restart with channels enabled">
        Exit Claude Code and restart with the channel flag. This connects the Discord plugin so your bot can receive and respond to messages:

        ```bash theme={null}
        claude --channels plugin:discord@claude-plugins-official
        ```
      </Step>

      <Step title="Pair your account">
        DM your bot on Discord. The bot replies with a pairing code.

        <Note>If your bot doesn't respond, make sure Claude Code is running with `--channels` from the previous step. The bot can only reply while the channel is active.</Note>

        Back in Claude Code, run:

        ```
        /discord:access pair <code>
        ```

        Then lock down access so only your account can send messages:

        ```
        /discord:access policy allowlist
        ```
      </Step>
    </Steps>
  </Tab>

  <Tab title="iMessage">
    View the full [iMessage plugin source](https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/imessage).

    The iMessage channel reads your Messages database directly and sends replies through AppleScript. It requires macOS and needs no bot token or external service.

    <Steps>
      <Step title="Grant Full Disk Access">
        The Messages database at `~/Library/Messages/chat.db` is protected by macOS. The first time the server reads it, macOS prompts for access: click **Allow**. The prompt names whichever app launched Bun, such as Terminal, iTerm, or your IDE.

        If the prompt doesn't appear or you clicked Don't Allow, grant access manually under **System Settings > Privacy & Security > Full Disk Access** and add your terminal. Without this, the server exits immediately with `authorization denied`.
      </Step>

      <Step title="Install the plugin">
        In Claude Code, run:

        ```
        /plugin install imessage@claude-plugins-official
        ```

        If Claude Code reports that the plugin is not found in any marketplace, your marketplace is either missing or outdated. Run `/plugin marketplace update claude-plugins-official` to refresh it, or `/plugin marketplace add anthropics/claude-plugins-official` if you haven't added it before. Then retry the install.
      </Step>

      <Step title="Restart with channels enabled">
        Exit Claude Code and restart with the channel flag:

        ```bash theme={null}
        claude --channels plugin:imessage@claude-plugins-official
        ```
      </Step>

      <Step title="Text yourself">
        Open Messages on any device signed into your Apple ID and send a message to yourself. It reaches Claude immediately: self-chat bypasses access control with no setup.

        <Note>The first reply Claude sends triggers a macOS Automation prompt asking if your terminal can control Messages. Click **OK**.</Note>
      </Step>

      <Step title="Allow other senders">
        By default, only your own messages pass through. To let another contact reach Claude, add their handle:

        ```
        /imessage:access allow +15551234567
        ```

        Handles are phone numbers in `+country` format or Apple ID emails like `user@example.com`.
      </Step>
    </Steps>
  </Tab>
</Tabs>

You can also [build your own channel](channels-reference-claude-code-docs-67a0bbe41f.md) for systems that don't have a plugin yet.

## 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:

* Claude Code [installed and authenticated](/en/quickstart#step-1-install-claude-code) with a claude.ai account
* [Bun](https://bun.sh) installed. The pre-built channel plugins are Bun scripts. Check with `bun --version`; if that fails, [install Bun](https://bun.sh/docs/installation).
* **Team/Enterprise users**: your organization admin must [enable channels](#enterprise-controls) in managed settings

<Steps>
  <Step title="Install the fakechat channel plugin">
    Start a Claude Code session and run the install command:

    ```text theme={null}
    /plugin install fakechat@claude-plugins-official
    ```

    If Claude Code reports that the plugin is not found in any marketplace, your marketplace is either missing or outdated. Run `/plugin marketplace update claude-plugins-official` to refresh it, or `/plugin marketplace add anthropics/claude-plugins-official` if you haven't added it before. Then retry the install.
  </Step>

  <Step title="Restart with the channel enabled">
    Exit Claude Code, then restart with `--channels` and pass the fakechat plugin you installed:

    ```bash theme={null}
    claude --channels plugin:fakechat@claude-plugins-official
    ```

    The fakechat server starts automatically.

    <Tip>
      You can pass several plugins to `--channels`, space-separated.
    </Tip>
  </Step>

  <Step title="Push a message in">
    Open the fakechat UI at [http://localhost:8787](http://localhost:8787) and type a message:

    ```text theme={null}
    hey, what's in my working directory?
    ```

    The message arrives in your Claude Code session as a `<channel source="fakechat">` event. Claude reads it, does the work, and calls fakechat's `reply` tool. The answer shows up in the chat UI.
  </Step>
</Steps>

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](/en/channels-reference#relay-permission-prompts) can forward these prompts to you so you can approve or deny remotely. For unattended use, the admin-gated unattended-mode option bypasses prompts entirely; only enable it in environments you trust.

## 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:

1. Find your bot in Telegram or Discord and send it any message
2. The bot replies with a pairing code
3. In your Claude Code session, approve the code when prompted
4. Your sender ID is added to the allowlist

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 on Team and Enterprise plans your organization controls availability with [`channelsEnabled`](#enterprise-controls).

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](/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

On Team and Enterprise plans, channels are off by default. Admins control availability through two [managed settings](claude-code-settings-claude-code-docs-d4420b4b52.md) that users cannot override:

| Setting                 | Purpose                                                                                                                                                                                                                                                     | When not configured            |
| :---------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------- |
| `channelsEnabled`       | Master switch. Must be `true` for any channel to deliver messages. Set via the [claude.ai Admin console](https://claude.ai/admin-settings/claude-code) toggle or directly in managed settings. Blocks all channels including the development flag when off. | Channels blocked               |
| `allowedChannelPlugins` | Which plugins can register once channels are enabled. Replaces the Anthropic-maintained list when set. Only applies when `channelsEnabled` is `true`.                                                                                                       | Anthropic default list applies |

Pro and Max users without an organization skip these checks entirely: channels are available and users opt in per session with `--channels`.

### Enable channels for your organization

Admins can enable channels from [**claude.ai → Admin settings → Claude Code → Channels**](https://claude.ai/admin-settings/claude-code), 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

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:

```json theme={null}
{
  "channelsEnabled": true,
  "allowedChannelPlugins": [
    { "marketplace": "claude-plugins-official", "plugin": "telegram" },
    { "marketplace": "claude-plugins-official", "plugin": "discord" },
    { "marketplace": "acme-corp-plugins", "plugin": "internal-alerts" }
  ]
}
```

When `allowedChannelPlugins` is set, it replaces the Anthropic allowlist entirely: only the listed plugins can register. Leave it unset to fall back to the default Anthropic allowlist. An empty array blocks all channel plugins from the allowlist, but `--dangerously-load-development-channels` can still bypass it 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.

## 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.

During the preview, `--channels` only accepts plugins from an Anthropic-maintained allowlist, or from your organization's allowlist if an admin has set [`allowedChannelPlugins`](#restrict-which-channel-plugins-can-run). 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, use `--dangerously-load-development-channels`. See [Test during the research preview](/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

Several Claude Code features connect to systems outside the terminal, each suited to a different kind of work:

| Feature                                              | What it does                                                          | Good for                                                  |
| ---------------------------------------------------- | --------------------------------------------------------------------- | --------------------------------------------------------- |
| [Claude Code on the web](claude-code-on-the-web-69d53821d4.md) | Runs tasks in a fresh cloud sandbox, cloned from GitHub               | Delegating self-contained async work you check on later   |
| [Claude in Slack](../14-Connectors/claude-code-in-slack-claude-code-docs-c62a093e92.md)                         | Spawns a web session from an `@Claude` mention in a channel or thread | Starting tasks directly from team conversation context    |
| Standard [MCP server](../06-MCP-Tools/mcp-208e742686.md)                       | Claude queries it during a task; nothing is pushed to the session     | Giving Claude on-demand access to read or query a system  |
| [Remote Control](continue-local-sessions-from-any-device-with-remote-control-claude-code-docs-c1c03fd914.md)                 | You drive your local session from claude.ai or the Claude mobile app  | Steering an in-progress session while away from your desk |

Channels fill the gap in that list by pushing events from non-Claude sources into your already-running local session.

* **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](/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

Once you have a channel running, explore these related features:

* [Build your own channel](channels-reference-claude-code-docs-67a0bbe41f.md) for systems that don't have plugins yet
* [Remote Control](continue-local-sessions-from-any-device-with-remote-control-claude-code-docs-c1c03fd914.md) to drive a local session from your phone instead of forwarding events into it
* [Scheduled tasks](run-prompts-on-a-schedule-claude-code-docs.md) to poll on a timer instead of reacting to pushed events


---
## channels-reference-claude-code-docs-67a0bbe41f.md

# Channels reference


Build an MCP server that pushes webhooks, alerts, and chat messages into a Claude Code session. Reference for the channel contract: capability declaration, notification events, reply tools, sender gating, and permission relay.


> ## Documentation Index
>
> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt>
>
> Use this file to discover all available pages before exploring further.

Channels are in [research preview](/docs/en/channels#research-preview) and require Claude Code v2.1.80 or later. Team and Enterprise organizations must [explicitly enable them](/docs/en/channels#enterprise-controls).

A channel is an MCP server that pushes events into a Claude Code session so Claude can react to things happening outside the terminal. You can build a one-way or two-way channel. One-way channels forward alerts, webhooks, or monitoring events for Claude to act on. Two-way channels like chat bridges also [expose a reply tool](#expose-a-reply-tool) so Claude can send messages back. A channel with a trusted sender path can also opt in to [relay permission prompts](#relay-permission-prompts) so you can approve or deny tool use remotely. This page covers:

- [Overview](#overview): how channels work
- [What you need](#what-you-need): requirements and general steps
- [Example: build a webhook receiver](#example-build-a-webhook-receiver): a minimal one-way walkthrough
- [Server options](#server-options): the constructor fields
- [Notification format](#notification-format): the event payload and delivery behavior
- [Expose a reply tool](#expose-a-reply-tool): let Claude send messages back
- [Gate inbound messages](#gate-inbound-messages): sender checks to prevent prompt injection
- [Relay permission prompts](#relay-permission-prompts): forward tool approval prompts to remote channels

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

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

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:

1.  Declare the `claude/channel` capability so Claude Code registers a notification listener
2.  Emit `notifications/claude/channel` events when something happens
3.  Connect over [stdio transport](https://modelcontextprotocol.io/docs/concepts/transports#standard-io) (Claude Code spawns your server as a subprocess)

The [Server options](#server-options) and [Notification format](#notification-format) sections cover each of these in detail. See [Example: build a webhook receiver](#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](#test-during-the-research-preview) for details.


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).

1


Create the project

Create a new directory and install the MCP SDK:

```python
mkdir webhook-channel && cd webhook-channel
bun add @modelcontextprotocol/sdk
```

2


Write the channel server

Create a file called `webhook.ts`. This is your entire channel server: it connects to Claude Code over stdio, and it listens for HTTP POSTs on port 8788. When a request arrives, it pushes the body to Claude as a channel event.

webhook.ts

```python
#!/usr/bin/env bun
import { Server } from '@modelcontextprotocol/sdk/server/index.js'
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'

// Create the MCP server and declare it as a channel
const mcp = new Server(
  { name: 'webhook', version: '0.0.1' },
  {
    // this key is what makes it a channel — Claude Code registers a listener for it
    capabilities: { experimental: { 'claude/channel': {} } },
    // added to Claude's system prompt so it knows how to handle these events
    instructions: 'Events from the webhook channel arrive as <channel source="webhook" ...>. They are one-way: read them and act, no reply expected.',
  },
)

// Connect to Claude Code over stdio (Claude Code spawns this process)
await mcp.connect(new StdioServerTransport())

// Start an HTTP server that forwards every POST to Claude
Bun.serve({
  port: 8788,  // any open port works
  // localhost-only: nothing outside this machine can POST
  hostname: '127.0.0.1',
  async fetch(req) {
    const body = await req.text()
    await mcp.notification({
      method: 'notifications/claude/channel',
      params: {
        content: body,  // becomes the body of the <channel> tag
        // each key becomes a tag attribute, e.g. <channel path="/" method="POST">
        meta: { path: new URL(req.url).pathname, method: req.method },
      },
    })
    return new Response('ok')
  },
})
```

The file does three things in order:

- **Server configuration**: creates the MCP server with `claude/channel` in its capabilities, which is what tells Claude Code this is a channel. The [`instructions`](#server-options) string goes into Claude’s system prompt: tell Claude what events to expect, whether to reply, and how to route replies if it should.
- **Stdio connection**: connects to Claude Code over stdin/stdout. This is standard for any [MCP server](https://modelcontextprotocol.io/docs/concepts/transports#standard-io): Claude Code spawns it as a subprocess.
- **HTTP listener**: starts a local web server on port 8788. Every POST body gets forwarded to Claude as a channel event via `mcp.notification()`. The `content` becomes the event body, and each `meta` entry becomes an attribute on the `<channel>` tag. The listener needs access to the `mcp` instance, so it runs in the same process. You could split it into separate modules for a larger project.

3


Register your server with Claude Code

Add the server to your MCP config so Claude Code knows how to start it. For a project-level `.mcp.json` in the same directory, use a relative path. For user-level config in `~/.claude.json`, use the full absolute path so the server can be found from any project:

.mcp.json

```python
{
  "mcpServers": {
    "webhook": { "command": "bun", "args": ["./webhook.ts"] }
  }
}
```

Claude Code reads your MCP config at startup and spawns each server as a subprocess.

4


Test it

During the research preview, custom channels aren’t on the allowlist, so start Claude Code with the development flag:

```python
claude --dangerously-load-development-channels server:webhook
```

When Claude Code starts, it reads your MCP config, spawns your `webhook.ts` as a subprocess, and the HTTP listener starts automatically on the port you configured (8788 in this example). You don’t need to run the server yourself.If you see “blocked by org policy,” your organization admin needs to [enable channels](/docs/en/channels#enterprise-controls) first.In a separate terminal, simulate a webhook by sending an HTTP POST with a message to your server. This example sends a CI failure alert to port 8788 (or whichever port you configured):

```python
curl -X POST localhost:8788 -d "build failed on main: https://ci.example.com/run/1234"
```

The payload arrives in your Claude Code session as a `<channel>` tag:

```python
<channel source="webhook" path="/" method="POST">build failed on main: https://ci.example.com/run/1234</channel>
```

In your Claude Code terminal, you’ll see Claude receive the message and start responding: reading files, running commands, or whatever the message calls for. This is a one-way channel, so Claude acts in your session but doesn’t send anything back through the webhook. To add replies, see [Expose a reply tool](#expose-a-reply-tool).If the event doesn’t arrive, the diagnosis depends on what `curl` returned:

- **`curl` succeeds but nothing reaches Claude**: run `/mcp` in your session to check the server’s status. “Failed to connect” usually means a dependency or import error in your server file; check the debug log at `~/.claude/debug/<session-id>.txt` for the stderr trace.
- **`curl` fails with “connection refused”**: the port is either not bound yet or a stale process from an earlier run is holding it. `lsof -i :<port>` shows what’s listening; `kill` the stale process before restarting your session.

The [fakechat server](https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/fakechat) extends this pattern with a web UI, file attachments, and a reply tool for two-way chat.


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:

```python
# Testing a plugin you're developing
claude --dangerously-load-development-channels plugin:yourplugin@yourmarketplace

# Testing a bare .mcp.json server (no plugin wrapper yet)
claude --dangerously-load-development-channels server:webhook
```

The bypass is per-entry. Combining this flag with `--channels` doesn’t extend the bypass to the `--channels` entries. During the research preview, the approved allowlist is Anthropic-curated, so your channel stays on the development flag while you build and test.

This flag skips the allowlist only. The `channelsEnabled` organization policy still applies. Don’t use it to run channels from untrusted sources.


Server options

A channel sets these options in the [`Server`](https://modelcontextprotocol.io/docs/concepts/servers) constructor. The `instructions` and `capabilities.tools` fields are [standard MCP](https://modelcontextprotocol.io/docs/concepts/servers); `capabilities.experimental['claude/channel']` and `capabilities.experimental['claude/channel/permission']` are the channel-specific additions:

| Field                                                    | Type     | Description                                                                                                                                                                                                                                                             |
|:---------------------------------------------------------|:---------|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `capabilities.experimental['claude/channel']`            | `object` | Required. Always `{}`. Presence registers the notification listener.                                                                                                                                                                                                    |
| `capabilities.experimental['claude/channel/permission']` | `object` | Optional. Always `{}`. Declares that this channel can receive permission relay requests. When declared, Claude Code forwards tool approval prompts to your channel so you can approve or deny them remotely. See [Relay permission prompts](#relay-permission-prompts). |
| `capabilities.tools`                                     | `object` | Two-way only. Always `{}`. Standard MCP tool capability. See [Expose a reply tool](#expose-a-reply-tool).                                                                                                                                                               |
| `instructions`                                           | `string` | Recommended. Added to Claude’s system prompt. Tell Claude what events to expect, what the `<channel>` tag attributes mean, whether to reply, and if so which tool to use and which attribute to pass back (like `chat_id`).                                             |

To create a one-way channel, omit `capabilities.tools`. This example shows a two-way setup with the channel capability, tools, and instructions set:

```python
import { Server } from '@modelcontextprotocol/sdk/server/index.js'

const mcp = new Server(
  { name: 'your-channel', version: '0.0.1' },
  {
    capabilities: {
      experimental: { 'claude/channel': {} },  // registers the channel listener
      tools: {},  // omit for one-way channels
    },
    // added to Claude's system prompt so it knows how to handle your events
    instructions: 'Messages arrive as <channel source="your-channel" ...>. Reply with the reply tool.',
  },
)
```

To push an event, call `mcp.notification()` with method `notifications/claude/channel`. The params are in the next section.


Notification format

Your server emits `notifications/claude/channel` with two params:

| Field     | Type                     | Description                                                                                                                                                                                                                                                           |
|:----------|:-------------------------|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `content` | `string`                 | The event body. Delivered as the body of the `<channel>` tag.                                                                                                                                                                                                         |
| `meta`    | `Record<string, string>` | Optional. Each entry becomes an attribute on the `<channel>` tag for routing context like chat ID, sender name, or alert severity. Keys must be identifiers: letters, digits, and underscores only. Keys containing hyphens or other characters are silently dropped. |

Your server pushes events by calling `mcp.notification()` on the `Server` instance. This example pushes a CI failure alert with two meta keys:

```python
await mcp.notification({
  method: 'notifications/claude/channel',
  params: {
    content: 'build failed on main: https://ci.example.com/run/1234',
    meta: { severity: 'high', run_id: '1234' },
  },
})
```

The event arrives in Claude’s context wrapped in a `<channel>` tag. The `source` attribute is set automatically from your server’s configured name:

```python
<channel source="your-channel" severity="high" run_id="1234">
build failed on main: https://ci.example.com/run/1234
</channel>
```

Notifications are not acknowledged. 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, events are dropped silently with no error returned to your server. If you need delivery confirmation, track event state in your server and expose a [reply tool](#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

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:

1.  A `tools: {}` entry in your `Server` constructor capabilities so Claude Code discovers the tool
2.  Tool handlers that define the tool’s schema and implement the send logic
3.  An `instructions` string in your `Server` constructor that tells Claude when and how to call the tool

To add these to the [webhook receiver above](#example-build-a-webhook-receiver):

1


Enable tool discovery

In your `Server` constructor in `webhook.ts`, add `tools: {}` to the capabilities so Claude Code knows your server offers tools:

```python
capabilities: {
  experimental: { 'claude/channel': {} },
  tools: {},  // enables tool discovery
},
```

2


Register the reply tool

Add the following to `webhook.ts`. The `import` goes at the top of the file with your other imports; the two handlers go between the `Server` constructor and `mcp.connect()`. This registers a `reply` tool that Claude can call with a `chat_id` and `text`:

```python
// Add this import at the top of webhook.ts
import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js'

// Claude queries this at startup to discover what tools your server offers
mcp.setRequestHandler(ListToolsRequestSchema, async () => ({
  tools: [{
    name: 'reply',
    description: 'Send a message back over this channel',
    // inputSchema tells Claude what arguments to pass
    inputSchema: {
      type: 'object',
      properties: {
        chat_id: { type: 'string', description: 'The conversation to reply in' },
        text: { type: 'string', description: 'The message to send' },
      },
      required: ['chat_id', 'text'],
    },
  }],
}))

// Claude calls this when it wants to invoke a tool
mcp.setRequestHandler(CallToolRequestSchema, async req => {
  if (req.params.name === 'reply') {
    const { chat_id, text } = req.params.arguments as { chat_id: string; text: string }
    // send() is your outbound: POST to your chat platform, or for local
    // testing the SSE broadcast shown in the full example below.
    send(`Reply to ${chat_id}: ${text}`)
    return { content: [{ type: 'text', text: 'sent' }] }
  }
  throw new Error(`unknown tool: ${req.params.name}`)
})
```

3


Update the instructions

Update the `instructions` string in your `Server` constructor so Claude knows to route replies back through the tool. This example tells Claude to pass `chat_id` from the inbound tag:

```python
instructions: 'Messages arrive as <channel source="webhook" chat_id="...">. Reply with the reply tool, passing the chat_id from the tag.'
```

Here’s the complete `webhook.ts` with two-way support. Outbound replies stream over `GET /events` using [Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) (SSE), so `curl -N localhost:8788/events` can watch them live; inbound chat arrives on `POST /`:

Full webhook.ts with reply tool

```python
#!/usr/bin/env bun
import { Server } from '@modelcontextprotocol/sdk/server/index.js'
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js'

// --- Outbound: write to any curl -N listeners on /events --------------------
// A real bridge would POST to your chat platform instead.
const listeners = new Set<(chunk: string) => void>()
function send(text: string) {
  const chunk = text.split('\n').map(l => `data: ${l}\n`).join('') + '\n'
  for (const emit of listeners) emit(chunk)
}

const mcp = new Server(
  { name: 'webhook', version: '0.0.1' },
  {
    capabilities: {
      experimental: { 'claude/channel': {} },
      tools: {},
    },
    instructions: 'Messages arrive as <channel source="webhook" chat_id="...">. Reply with the reply tool, passing the chat_id from the tag.',
  },
)

mcp.setRequestHandler(ListToolsRequestSchema, async () => ({
  tools: [{
    name: 'reply',
    description: 'Send a message back over this channel',
    inputSchema: {
      type: 'object',
      properties: {
        chat_id: { type: 'string', description: 'The conversation to reply in' },
        text: { type: 'string', description: 'The message to send' },
      },
      required: ['chat_id', 'text'],
    },
  }],
}))

mcp.setRequestHandler(CallToolRequestSchema, async req => {
  if (req.params.name === 'reply') {
    const { chat_id, text } = req.params.arguments as { chat_id: string; text: string }
    send(`Reply to ${chat_id}: ${text}`)
    return { content: [{ type: 'text', text: 'sent' }] }
  }
  throw new Error(`unknown tool: ${req.params.name}`)
})

await mcp.connect(new StdioServerTransport())

let nextId = 1
Bun.serve({
  port: 8788,
  hostname: '127.0.0.1',
  idleTimeout: 0,  // don't close idle SSE streams
  async fetch(req) {
    const url = new URL(req.url)

    // GET /events: SSE stream so curl -N can watch Claude's replies live
    if (req.method === 'GET' && url.pathname === '/events') {
      const stream = new ReadableStream({
        start(ctrl) {
          ctrl.enqueue(': connected\n\n')  // so curl shows something immediately
          const emit = (chunk: string) => ctrl.enqueue(chunk)
          listeners.add(emit)
          req.signal.addEventListener('abort', () => listeners.delete(emit))
        },
      })
      return new Response(stream, {
        headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' },
      })
    }

    // POST: forward to Claude as a channel event
    const body = await req.text()
    const chat_id = String(nextId++)
    await mcp.notification({
      method: 'notifications/claude/channel',
      params: {
        content: body,
        meta: { chat_id, path: url.pathname, method: req.method },
      },
    })
    return new Response('ok')
  },
})
```

See all 86 lines

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

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:

```python
const allowed = new Set(loadAllowlist())  // from your access.json or equivalent

// inside your message handler, before emitting:
if (!allowed.has(message.from.id)) {  // sender, not room
  return  // drop silently
}
await mcp.notification({ ... })
```

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: the user DMs the bot, the bot replies with a pairing code, the user approves it in their Claude Code session, and their platform ID is added. 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

Permission relay requires Claude Code v2.1.81 or later. Earlier versions ignore the `claude/channel/permission` capability.

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.


How relay works

When a permission prompt opens, the relay loop has four steps:

1.  Claude Code generates a short request ID and notifies your server
2.  Your server forwards the prompt and ID to your chat app
3.  The remote user replies with a yes or no and that ID
4.  Your inbound handler parses the reply into a verdict, and Claude Code applies it only if the ID matches an open request

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

The outbound notification from Claude Code is `notifications/claude/channel/permission_request`. Like the [channel notification](#notification-format), 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:

| Field           | Description                                                                                                                                                                                                                                                                                                                                                    |
|-----------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `request_id`    | Five lowercase letters drawn from `a`-`z` without `l`, so it never reads as a `1` or `I` when typed on a phone. Include it in your outgoing prompt so it can be echoed in the reply. Claude Code only accepts a verdict that carries an ID it issued. The local terminal dialog doesn’t display this ID, so your outbound handler is the only way to learn it. |
| `tool_name`     | Name of the tool Claude wants to use, for example `Bash` or `Write`.                                                                                                                                                                                                                                                                                           |
| `description`   | Human-readable summary of what this specific tool call does, the same text the local terminal dialog shows. For a Bash call this is Claude’s description of the command, or the command itself if none was given.                                                                                                                                              |
| `input_preview` | The tool’s arguments as a JSON string, truncated to 200 characters. For Bash this is the command; for Write it’s the file path and a prefix of the content. Omit it from your prompt if you only have room for a one-line message. Your server decides what to show.                                                                                           |

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, the same as answering No in the local dialog. Neither verdict affects future calls.


Add relay to a chat bridge

Adding permission relay to a two-way channel takes three components:

1.  A `claude/channel/permission: {}` entry under `experimental` capabilities in your `Server` constructor so Claude Code knows to forward prompts
2.  A notification handler for `notifications/claude/channel/permission_request` that formats the prompt and sends it out through your platform API
3.  A check in your inbound message handler that recognizes `yes <id>` or `no <id>` and emits a `notifications/claude/channel/permission` verdict instead of forwarding the text to Claude

Only declare the capability if your channel [authenticates the sender](#gate-inbound-messages), because anyone who can reply through your channel can approve or deny tool use in your session. To add these to a two-way chat bridge like the one assembled in [Expose a reply tool](#expose-a-reply-tool):

1


Declare the permission capability

In your `Server` constructor, add `claude/channel/permission: {}` alongside `claude/channel` under `experimental`:

```python
capabilities: {
  experimental: {
    'claude/channel': {},
    'claude/channel/permission': {},  // opt in to permission relay
  },
  tools: {},
},
```

2


Handle the incoming request

Register a notification handler between your `Server` constructor and `mcp.connect()`. Claude Code calls it with the [four request fields](#permission-request-fields) when a permission dialog opens. Your handler formats the prompt for your platform and includes instructions for replying with the ID:

```python
import { z } from 'zod'

// setNotificationHandler routes by z.literal on the method field,
// so this schema is both the validator and the dispatch key
const PermissionRequestSchema = z.object({
  method: z.literal('notifications/claude/channel/permission_request'),
  params: z.object({
    request_id: z.string(),     // five lowercase letters, include verbatim in your prompt
    tool_name: z.string(),      // e.g. "Bash", "Write"
    description: z.string(),    // human-readable summary of this call
    input_preview: z.string(),  // tool args as JSON, truncated to ~200 chars
  }),
})

mcp.setNotificationHandler(PermissionRequestSchema, async ({ params }) => {
  // send() is your outbound: POST to your chat platform, or for local
  // testing the SSE broadcast shown in the full example below.
  send(
    `Claude wants to run ${params.tool_name}: ${params.description}\n\n` +
    // the ID in the instruction is what your inbound handler parses in Step 3
    `Reply "yes ${params.request_id}" or "no ${params.request_id}"`,
  )
})
```

3


Intercept the verdict in your inbound handler

Your inbound handler is the loop or callback that receives messages from your platform: the same place you [gate on sender](#gate-inbound-messages) and emit `notifications/claude/channel` to forward chat to Claude. Add a check before the chat-forwarding call that recognizes the verdict format and emits the permission notification instead.The regex matches the ID format Claude Code generates: five letters, never `l`. The `/i` flag tolerates phone autocorrect capitalizing the reply; lowercase the captured ID before sending it back.

```python
// matches "y abcde", "yes abcde", "n abcde", "no abcde"
// [a-km-z] is the ID alphabet Claude Code uses (lowercase, skips 'l')
// /i tolerates phone autocorrect; lowercase the capture before sending
const PERMISSION_REPLY_RE = /^\s*(y|yes|n|no)\s+([a-km-z]{5})\s*$/i

async function onInbound(message: PlatformMessage) {
  if (!allowed.has(message.from.id)) return  // gate on sender first

  const m = PERMISSION_REPLY_RE.exec(message.text)
  if (m) {
    // m[1] is the verdict word, m[2] is the request ID
    // emit the verdict notification back to Claude Code instead of chat
    await mcp.notification({
      method: 'notifications/claude/channel/permission',
      params: {
        request_id: m[2].toLowerCase(),  // normalize in case of autocorrect caps
        behavior: m[1].toLowerCase().startsWith('y') ? 'allow' : 'deny',
      },
    })
    return  // handled as verdict, don't also forward as chat
  }

  // didn't match verdict format: fall through to the normal chat path
  await mcp.notification({
    method: 'notifications/claude/channel',
    params: { content: message.text, meta: { chat_id: String(message.chat.id) } },
  })
}
```

Claude Code also keeps the local terminal dialog open, so you can answer in either place, and the first answer to arrive is applied. A remote reply that doesn’t exactly match the expected format fails in one of two ways, and in both cases the dialog stays open:

- **Different format**: your inbound handler’s regex fails to match, so text like `approve it` or `yes` without an ID falls through as a normal message to Claude.
- **Right format, wrong ID**: your server emits a verdict, but Claude Code finds no open request with that ID and drops it silently.


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](#example-build-a-webhook-receiver) from the initial walkthrough. To make both directions testable from curl, the HTTP listener serves two paths:

- **`GET /events`**: holds an SSE stream open and pushes each outbound message as a `data:` line, so `curl -N` can watch Claude’s replies and permission prompts arrive live.
- **`POST /`**: the inbound side, the same handler as earlier, now with the verdict-format check inserted before the chat-forward branch.

Full webhook.ts with permission relay

```python
#!/usr/bin/env bun
import { Server } from '@modelcontextprotocol/sdk/server/index.js'
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js'
import { z } from 'zod'

// --- Outbound: write to any curl -N listeners on /events --------------------
// A real bridge would POST to your chat platform instead.
const listeners = new Set<(chunk: string) => void>()
function send(text: string) {
  const chunk = text.split('\n').map(l => `data: ${l}\n`).join('') + '\n'
  for (const emit of listeners) emit(chunk)
}

// Sender allowlist. For the local walkthrough we trust the single X-Sender
// header value "dev"; a real bridge would check the platform's user ID.
const allowed = new Set(['dev'])

const mcp = new Server(
  { name: 'webhook', version: '0.0.1' },
  {
    capabilities: {
      experimental: {
        'claude/channel': {},
        'claude/channel/permission': {},  // opt in to permission relay
      },
      tools: {},
    },
    instructions:
      'Messages arrive as <channel source="webhook" chat_id="...">. ' +
      'Reply with the reply tool, passing the chat_id from the tag.',
  },
)

// --- reply tool: Claude calls this to send a message back -------------------
mcp.setRequestHandler(ListToolsRequestSchema, async () => ({
  tools: [{
    name: 'reply',
    description: 'Send a message back over this channel',
    inputSchema: {
      type: 'object',
      properties: {
        chat_id: { type: 'string', description: 'The conversation to reply in' },
        text: { type: 'string', description: 'The message to send' },
      },
      required: ['chat_id', 'text'],
    },
  }],
}))

mcp.setRequestHandler(CallToolRequestSchema, async req => {
  if (req.params.name === 'reply') {
    const { chat_id, text } = req.params.arguments as { chat_id: string; text: string }
    send(`Reply to ${chat_id}: ${text}`)
    return { content: [{ type: 'text', text: 'sent' }] }
  }
  throw new Error(`unknown tool: ${req.params.name}`)
})

// --- permission relay: Claude Code (not Claude) calls this when a dialog opens
const PermissionRequestSchema = z.object({
  method: z.literal('notifications/claude/channel/permission_request'),
  params: z.object({
    request_id: z.string(),
    tool_name: z.string(),
    description: z.string(),
    input_preview: z.string(),
  }),
})

mcp.setNotificationHandler(PermissionRequestSchema, async ({ params }) => {
  send(
    `Claude wants to run ${params.tool_name}: ${params.description}\n\n` +
    `Reply "yes ${params.request_id}" or "no ${params.request_id}"`,
  )
})

await mcp.connect(new StdioServerTransport())

// --- HTTP on :8788: GET /events streams outbound, POST routes inbound -------
const PERMISSION_REPLY_RE = /^\s*(y|yes|n|no)\s+([a-km-z]{5})\s*$/i
let nextId = 1

Bun.serve({
  port: 8788,
  hostname: '127.0.0.1',
  idleTimeout: 0,  // don't close idle SSE streams
  async fetch(req) {
    const url = new URL(req.url)

    // GET /events: SSE stream so curl -N can watch replies and prompts live
    if (req.method === 'GET' && url.pathname === '/events') {
      const stream = new ReadableStream({
        start(ctrl) {
          ctrl.enqueue(': connected\n\n')  // so curl shows something immediately
          const emit = (chunk: string) => ctrl.enqueue(chunk)
          listeners.add(emit)
          req.signal.addEventListener('abort', () => listeners.delete(emit))
        },
      })
      return new Response(stream, {
        headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' },
      })
    }

    // everything else is inbound: gate on sender first
    const body = await req.text()
    const sender = req.headers.get('X-Sender') ?? ''
    if (!allowed.has(sender)) return new Response('forbidden', { status: 403 })

    // check for verdict format before treating as chat
    const m = PERMISSION_REPLY_RE.exec(body)
    if (m) {
      await mcp.notification({
        method: 'notifications/claude/channel/permission',
        params: {
          request_id: m[2].toLowerCase(),
          behavior: m[1].toLowerCase().startsWith('y') ? 'allow' : 'deny',
        },
      })
      return new Response('verdict recorded')
    }

    // normal chat: forward to Claude as a channel event
    const chat_id = String(nextId++)
    await mcp.notification({
      method: 'notifications/claude/channel',
      params: { content: body, meta: { chat_id, path: url.pathname } },
    })
    return new Response('ok')
  },
})
```

See all 132 lines

Test the verdict path in three terminals. The first is your Claude Code session, started with the [development flag](#test-during-the-research-preview) so it spawns `webhook.ts`:

```python
claude --dangerously-load-development-channels server:webhook
```

In the second, stream the outbound side so you can see Claude’s replies and any permission prompts as they fire:

```python
curl -N localhost:8788/events
```

In the third, send a message that will make Claude try to run a command:

```python
curl -d "list the files in this directory" -H "X-Sender: dev" localhost:8788
```

The local permission dialog opens in your Claude Code terminal. A moment later the prompt appears in the `/events` stream, including the five-letter ID. Approve it from the remote side:

```python
curl -d "yes <id>" -H "X-Sender: dev" localhost:8788
```

The local dialog closes and the tool runs. Claude’s reply comes back through the `reply` tool and lands in the stream too. The three channel-specific pieces in this file:

- **Capabilities** in the `Server` constructor: `claude/channel` registers the notification listener, `claude/channel/permission` opts in to permission relay, `tools` lets Claude discover the reply tool.
- **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

To make your channel installable and shareable, wrap it in a [plugin](/docs/en/plugins) and publish it to a [marketplace](/docs/en/plugin-marketplaces). 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`, which Anthropic curates at its discretion. The [in-app submission forms](/docs/en/plugins#submit-your-plugin-to-the-community-marketplace) add plugins to the community marketplace, which 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

- [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
- [MCP](/docs/en/mcp) for the underlying protocol that channel servers implement
- [Plugins](/docs/en/plugins) to package your channel so users can install it with `/plugin install`


---
## channels-reference.md

# Channels reference

Build an MCP server that pushes webhooks, alerts, and chat messages into a Claude Code session. Reference for the channel contract: capability declaration, notification events, reply tools, sender gating, and permission relay.

> Channels are in research preview and require Claude Code v2.1.80 or later. They require claude.ai login. Console and API key authentication is not supported. Team and Enterprise organizations must explicitly enable them.

A channel is an MCP server that pushes events into a Claude Code session so Claude can react to things happening outside the terminal.

You can build a one-way or two-way channel. One-way channels forward alerts, webhooks, or monitoring events for Claude to act on. Two-way channels also expose a reply tool so Claude can send messages back. A channel with a trusted sender path can also opt in to relay permission prompts so you can approve or deny tool use remotely.

## Overview

A channel is an MCP server that runs on the same machine as Claude Code. Claude Code spawns it as a subprocess and communicates over stdio.

- **Chat platforms** (Telegram, Discord): your plugin runs locally and polls the platform's API for new messages
- **Webhooks** (CI, monitoring): your server listens on a local HTTP port. External systems POST to that port

## What you need

The only hard requirement is the `@modelcontextprotocol/sdk` package and a Node.js-compatible runtime (Bun, Node, or Deno).

Your server needs to:

1. Declare the `claude/channel` capability so Claude Code registers a notification listener
2. Emit `notifications/claude/channel` events when something happens
3. Connect over stdio transport

## Example: build a webhook receiver

```ts
#!/usr/bin/env bun
import { Server } from '@modelcontextprotocol/sdk/server/index.js'
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'

const mcp = new Server(
  { name: 'webhook', version: '0.0.1' },
  {
    capabilities: { experimental: { 'claude/channel': {} } },
    instructions: 'Events from the webhook channel arrive as <channel source="webhook" ...>. Read them and act, no reply expected.',
  },
)

await mcp.connect(new StdioServerTransport())

Bun.serve({
  port: 8788,
  hostname: '127.0.0.1',
  async fetch(req) {
    const body = await req.text()
    await mcp.notification({
      method: 'notifications/claude/channel',
      params: {
        content: body,
        meta: { path: new URL(req.url).pathname, method: req.method },
      },
    })
    return new Response('ok')
  },
})
```

Register in `.mcp.json`:

```json
{
  "mcpServers": {
    "webhook": { "command": "bun", "args": ["./webhook.ts"] }
  }
}
```

Test with the development flag:

```bash
claude --dangerously-load-development-channels server:webhook
```

Then from another terminal:

```bash
curl -X POST localhost:8788 -d "build failed on main: https://ci.example.com/run/1234"
```

## Server options

| Field                                                    | Type     | Description                                                     |
| :------------------------------------------------------- | :------- | :-------------------------------------------------------------- |
| `capabilities.experimental['claude/channel']`            | `object` | Required. Always `{}`. Registers the notification listener.     |
| `capabilities.experimental['claude/channel/permission']` | `object` | Optional. Declares channel can receive permission relay requests.|
| `capabilities.tools`                                     | `object` | Two-way only. Standard MCP tool capability.                     |
| `instructions`                                           | `string` | Added to Claude's system prompt.                                |

## Notification format

| Field     | Type                     | Description                                            |
| :-------- | :----------------------- | :----------------------------------------------------- |
| `content` | `string`                 | The event body, delivered as body of `<channel>` tag.  |
| `meta`    | `Record<string, string>` | Optional. Each entry becomes a tag attribute.          |

## Expose a reply tool

For two-way channels, expose a standard MCP tool:

1. Add `tools: {}` to capabilities
2. Register `ListToolsRequestSchema` and `CallToolRequestSchema` handlers
3. Update `instructions` to tell Claude when to call the tool

## Gate inbound messages

Check the sender against an allowlist before calling `mcp.notification()`:

```ts
const allowed = new Set(loadAllowlist())
if (!allowed.has(message.from.id)) {
  return  // drop silently
}
await mcp.notification({ ... })
```

Gate on the **sender's identity**, not the chat or room identity.

## Relay permission prompts

> Permission relay requires Claude Code v2.1.81 or later.

When Claude calls a tool that needs approval, a two-way channel can receive the same prompt and relay it remotely.

### Permission request fields

| Field           | Description                                              |
| --------------- | -------------------------------------------------------- |
| `request_id`    | Five lowercase letters (a-z without l)                   |
| `tool_name`     | Name of the tool Claude wants to use                     |
| `description`   | Human-readable summary of what the tool call does        |
| `input_preview` | Tool arguments as JSON, truncated to 200 characters      |

The verdict sends `notifications/claude/channel/permission` with `request_id` and `behavior` set to `'allow'` or `'deny'`.

### Add relay to a chat bridge

1. Declare `claude/channel/permission: {}` capability
2. Handle `notifications/claude/channel/permission_request` notifications
3. Check inbound for `yes <id>` / `no <id>` verdict pattern

## Package as a plugin

Wrap in a plugin and publish to a marketplace. Users install with `/plugin install`, then enable per session with `--channels plugin:<name>@<marketplace>`.

## See Also

- [Channels](channels.md) — Install and use Telegram, Discord, iMessage, or fakechat
- [Working channel implementations](https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins)
- [MCP](../06-MCP-Tools/General/connect-claude-code-to-tools-via-mcp-claude-code-docs.md) — The underlying protocol
- [Plugins](../08-Plugins-Skills/create-plugins-claude-code-docs.md) — Package your channel for installation


---
## channels.md

# Push events into a running session with channels

Use channels to push messages, alerts, and webhooks into your Claude Code session from an MCP server. Forward CI results, chat messages, and monitoring events so Claude can react while you're away.

> Channels are in research preview and require Claude Code v2.1.80 or later. They require claude.ai login. Console and API key authentication is not supported. Team and Enterprise organizations must explicitly enable them.

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.

You install a channel as a plugin and configure it with your own credentials. Telegram, Discord, and iMessage are included in the research preview.

## Supported channels

Each supported channel is a plugin that requires [Bun](https://bun.sh).

### Telegram

1. **Create a Telegram bot**: Open BotFather in Telegram and send `/newbot`. Copy the token.
2. **Install the plugin**: `/plugin install telegram@claude-plugins-official`
3. **Configure your token**: `/telegram:configure <token>`
4. **Restart with channels enabled**: `claude --channels plugin:telegram@claude-plugins-official`
5. **Pair your account**: Send any message to your bot, get the pairing code, run `/telegram:access pair <code>`, then `/telegram:access policy allowlist`

### Discord

1. **Create a Discord bot**: Go to Discord Developer Portal, create application, enable Message Content Intent
2. **Invite the bot**: OAuth2 > URL Generator, select `bot` scope with View Channels, Send Messages, Read Message History permissions
3. **Install the plugin**: `/plugin install discord@claude-plugins-official`
4. **Configure your token**: `/discord:configure <token>`
5. **Restart with channels enabled**: `claude --channels plugin:discord@claude-plugins-official`
6. **Pair your account**: DM your bot, get pairing code, run `/discord:access pair <code>`

### iMessage

The iMessage channel reads your Messages database directly and sends replies through AppleScript. Requires macOS.

1. **Grant Full Disk Access** for your terminal
2. **Install the plugin**: `/plugin install imessage@claude-plugins-official`
3. **Restart with channels enabled**: `claude --channels plugin:imessage@claude-plugins-official`
4. **Text yourself**: Self-chat bypasses access control
5. **Allow other senders**: `/imessage:access allow +15551234567`

You can also build your own channel — see the Channels reference.

## Quickstart with fakechat

Fakechat is a demo channel that runs a chat UI on localhost:

1. Install: `/plugin install fakechat@claude-plugins-official`
2. Restart: `claude --channels plugin:fakechat@claude-plugins-official`
3. Open http://localhost:8787 and type a message

## 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. iMessage detects the user's own addresses automatically.

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 if the channel declares it. Anyone who can reply through the channel can approve or deny tool use in your session.

## Enterprise controls

On Team and Enterprise plans, channels are off by default. Admins control availability through two managed settings:

| Setting                 | Purpose                                                    | When not configured            |
| :---------------------- | :--------------------------------------------------------- | :----------------------------- |
| `channelsEnabled`       | Master switch. Must be `true` for any channel to deliver.  | Channels blocked               |
| `allowedChannelPlugins` | Which plugins can register once channels are enabled.      | Anthropic default list applies |

Pro and Max users without an organization skip these checks entirely.

### Enable channels for your organization

Admins can enable channels from **claude.ai → Admin settings → Claude Code → Channels**, or by setting `channelsEnabled` to `true` in managed settings.

### Restrict which channel plugins can run

```json
{
  "channelsEnabled": true,
  "allowedChannelPlugins": [
    { "marketplace": "claude-plugins-official", "plugin": "telegram" },
    { "marketplace": "claude-plugins-official", "plugin": "discord" },
    { "marketplace": "acme-corp-plugins", "plugin": "internal-alerts" }
  ]
}
```

## How channels compare

| Feature                | What it does                                                    | Good for                                              |
| :--------------------- | :-------------------------------------------------------------- | :---------------------------------------------------- |
| Claude Code on the web | Runs tasks in a fresh cloud sandbox                             | Delegating self-contained async work                  |
| Claude in Slack        | Spawns a web session from an `@Claude` mention                  | Starting tasks from team conversation                 |
| Standard MCP server    | Claude queries it during a task; nothing is pushed              | Giving Claude on-demand access to a system            |
| Remote Control         | You drive your local session from claude.ai or mobile           | Steering in-progress work from another device         |
| **Channels**           | Push events from non-Claude sources into your running session   | Reacting to CI failures, chat messages, webhooks      |

## See Also

- [Channels reference](channels-reference.md) — Build your own channel
- [Remote Control](remote-control.md)
- [Scheduled tasks](run-prompts-on-a-schedule-claude-code-docs.md)


---
## checkpointing-94f7cd24eb.md

> ## Documentation Index
> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Checkpointing

> Track, rewind, and summarize Claude's edits and conversation to manage session state.

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

As you work with Claude, checkpointing automatically captures the state of your code before each edit. This safety net lets you pursue ambitious, wide-scale tasks knowing you can always return to a prior code state.

### Automatic tracking

Claude Code tracks all changes made by its file editing tools:

* Every user prompt creates a new checkpoint
* Checkpoints persist across sessions, so you can access them in resumed conversations
* Automatically cleaned up along with sessions after 30 days (configurable)

### Rewind and summarize

Press `Esc` twice (`Esc` + `Esc`) or use the `/rewind` command to open the rewind menu. A scrollable list shows each of your prompts from the session. Select the point you want to act on, then choose an action:

* **Restore code and conversation**: revert both code and conversation to that point
* **Restore conversation**: rewind to that message while keeping current code
* **Restore code**: revert file changes while keeping the conversation
* **Summarize from here**: compress the conversation from this point forward into a summary, freeing context window space
* **Never mind**: return to the message list without making changes

After restoring the conversation or summarizing, the original prompt from the selected message is restored into the input field so you can re-send or edit it.

#### Restore vs. summarize

The three restore options revert state: they undo code changes, conversation history, or both. "Summarize from here" works differently:

* Messages before the selected message stay intact
* The selected message and all subsequent messages get replaced with a compact AI-generated summary
* No files on disk are changed
* The original messages are preserved in the session transcript, so Claude can reference the details if needed

This is similar to `/compact`, but targeted: instead of summarizing the entire conversation, you keep early context in full detail and only compress the parts that are using up space. You can type optional instructions to guide what the summary focuses on.

<Note>
  Summarize keeps you in the same session and compresses context. If you want to branch off and try a different approach while preserving the original session intact, use [fork](/en/how-claude-code-works#resume-or-fork-sessions) instead (`claude --continue --fork-session`).
</Note>

## Common use cases

Checkpoints are particularly useful when:

* **Exploring alternatives**: try different implementation approaches without losing your starting point
* **Recovering from mistakes**: quickly undo changes that introduced bugs or broke functionality
* **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

### Bash command changes not tracked

Checkpointing does not track files modified by bash commands. For example, if Claude Code runs:

```bash theme={null}
rm file.txt
mv old.txt new.txt
cp source.txt dest.txt
```

These file modifications cannot be undone through rewind. Only direct file edits made through Claude's file editing tools are 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.

### Not a replacement for version control

Checkpoints are designed for quick, session-level recovery. For permanent version history and collaboration:

* Continue using version control (ex. Git) for commits, branches, and long-term history
* Checkpoints complement but don't replace proper version control
* Think of checkpoints as "local undo" and Git as "permanent history"

## See also

* [Interactive mode](interactive-mode-c5c4efb32c.md) - Keyboard shortcuts and session controls
* [Commands](built-in-commands-claude-code-docs.md) - Accessing checkpoints using `/rewind`
* [CLI reference](cli-reference-7bb98e3312.md) - Command-line options


---
## checkpointing-claude-code-docs-49f31e05d8.md

# Checkpointing


Track, rewind, and summarize Claude’s edits and conversation to manage session state.


> ## Documentation Index
>
> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt>
>
> Use this file to discover all available pages before exploring further.

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

As you work with Claude, checkpointing automatically captures the state of your code before each edit. This safety net lets you pursue ambitious, wide-scale tasks knowing you can always return to a prior code state.


Automatic tracking

Claude Code tracks all changes made by its file editing tools:

- Every user prompt creates a new checkpoint
- Checkpoints persist across sessions, so you can access them in resumed conversations
- Automatically cleaned up along with sessions after 30 days (configurable)


Rewind and summarize

Press `Esc` twice (`Esc` + `Esc`) or use the `/rewind` command to open the rewind menu. A scrollable list shows each of your prompts from the session. Select the point you want to act on, then choose an action:

- **Restore code and conversation**: revert both code and conversation to that point
- **Restore conversation**: rewind to that message while keeping current code
- **Restore code**: revert file changes while keeping the conversation
- **Summarize from here**: compress the conversation from this point forward into a summary, freeing context window space
- **Summarize up to here**: compress the conversation before this point into a summary, keeping later messages intact
- **Never mind**: return to the message list without making changes

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.


Restore vs. summarize

The restore options revert state: they undo code changes, conversation history, or both. The summarize options compress part of the conversation into an AI-generated summary without changing files on disk:

- **Summarize from here**: messages before the selected message stay intact. The selected message and everything after it are replaced with a summary. Use this to discard a side discussion while keeping early context in full detail.
- **Summarize up to here**: messages before the selected message are replaced with a summary. The selected message and everything after it stay intact, and you remain at the end of the conversation. Use this to compress early setup discussion while keeping recent work in full detail.

In both cases the original messages are preserved in the session transcript, so Claude can reference the details if needed. You can type optional instructions to guide what the summary focuses on. This is similar to `/compact`, but targeted: instead of summarizing the entire conversation, you choose which side of the selected message to compress.

Summarize keeps you in the same session and compresses context. If you want to branch off and try a different approach while preserving the original session intact, use [fork](/docs/en/sessions#branch-a-session) instead (`claude --continue --fork-session`).


Common use cases

Checkpoints are particularly useful when:

- **Exploring alternatives**: try different implementation approaches without losing your starting point
- **Recovering from mistakes**: quickly undo changes that introduced bugs or broke functionality
- **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


Bash command changes not tracked

Checkpointing does not track files modified by bash commands. For example, if Claude Code runs:

```python
rm file.txt
mv old.txt new.txt
cp source.txt dest.txt
```

These file modifications cannot be undone through rewind. Only direct file edits made through Claude’s file editing tools are 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.


Not a replacement for version control

Checkpoints are designed for quick, session-level recovery. For permanent version history and collaboration:

- Continue using version control (ex. Git) for commits, branches, and long-term history
- Checkpoints complement but don’t replace proper version control
- Think of checkpoints as “local undo” and Git as “permanent history”


See also

- [Interactive mode](/docs/en/interactive-mode) - Keyboard shortcuts and session controls
- [Commands](/docs/en/commands) - Accessing checkpoints using `/rewind`
- [CLI reference](/docs/en/cli-reference) - Command-line options


---
## checkpointing-claude-code-docs.md

# Checkpointing


Track, rewind, and summarize Claude’s edits and conversation to manage session state.


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

As you work with Claude, checkpointing automatically captures the state of your code before each edit. This safety net lets you pursue ambitious, wide-scale tasks knowing you can always return to a prior code state.


Automatic tracking

Claude Code tracks all changes made by its file editing tools:

- Every user prompt creates a new checkpoint
- Checkpoints persist across sessions, so you can access them in resumed conversations
- Automatically cleaned up along with sessions after 30 days (configurable)


Rewind and summarize

Press `Esc` twice (`Esc` + `Esc`) or use the `/rewind` command to open the rewind menu. A scrollable list shows each of your prompts from the session. Select the point you want to act on, then choose an action:

- **Restore code and conversation**: revert both code and conversation to that point
- **Restore conversation**: rewind to that message while keeping current code
- **Restore code**: revert file changes while keeping the conversation
- **Summarize from here**: compress the conversation from this point forward into a summary, freeing context window space
- **Never mind**: return to the message list without making changes

After restoring the conversation or summarizing, the original prompt from the selected message is restored into the input field so you can re-send or edit it.


Restore vs. summarize

The three restore options revert state: they undo code changes, conversation history, or both. “Summarize from here” works differently:

- Messages before the selected message stay intact
- The selected message and all subsequent messages get replaced with a compact AI-generated summary
- No files on disk are changed
- The original messages are preserved in the session transcript, so Claude can reference the details if needed

This is similar to `/compact`, but targeted: instead of summarizing the entire conversation, you keep early context in full detail and only compress the parts that are using up space. You can type optional instructions to guide what the summary focuses on.

Summarize keeps you in the same session and compresses context. If you want to branch off and try a different approach while preserving the original session intact, use [fork](/docs/en/how-claude-code-works#resume-or-fork-sessions) instead (`claude --continue --fork-session`).


Common use cases

Checkpoints are particularly useful when:

- **Exploring alternatives**: try different implementation approaches without losing your starting point
- **Recovering from mistakes**: quickly undo changes that introduced bugs or broke functionality
- **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


Bash command changes not tracked

Checkpointing does not track files modified by bash commands. For example, if Claude Code runs:

```python
rm file.txt
mv old.txt new.txt
cp source.txt dest.txt
```

These file modifications cannot be undone through rewind. Only direct file edits made through Claude’s file editing tools are 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.


Not a replacement for version control

Checkpoints are designed for quick, session-level recovery. For permanent version history and collaboration:

- Continue using version control (ex. Git) for commits, branches, and long-term history
- Checkpoints complement but don’t replace proper version control
- Think of checkpoints as “local undo” and Git as “permanent history”


See also

- [Interactive mode](/docs/en/interactive-mode) - Keyboard shortcuts and session controls
- [Commands](/docs/en/commands) - Accessing checkpoints using `/rewind`
- [CLI reference](/docs/en/cli-reference) - Command-line options


---
## checkpointing.md

> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Checkpointing

> Automatically track and rewind Claude's edits to quickly recover from unwanted changes.

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

As you work with Claude, checkpointing automatically captures the state of your code before each edit. This safety net lets you pursue ambitious, wide-scale tasks knowing you can always return to a prior code state.

### Automatic tracking

Claude Code tracks all changes made by its file editing tools:

* Every user prompt creates a new checkpoint
* Checkpoints persist across sessions, so you can access them in resumed conversations
* Automatically cleaned up along with sessions after 30 days (configurable)

### Rewinding changes

Press `Esc` twice (`Esc` + `Esc`) or use the `/rewind` command to open up the rewind menu. You can choose to restore:

* **Conversation only**: Rewind to a user message while keeping code changes
* **Code only**: Revert file changes while keeping the conversation
* **Both code and conversation**: Restore both to a prior point in the session

## Common use cases

Checkpoints are particularly useful when:

* **Exploring alternatives**: Try different implementation approaches without losing your starting point
* **Recovering from mistakes**: Quickly undo changes that introduced bugs or broke functionality
* **Iterating on features**: Experiment with variations knowing you can revert to working states

## Limitations

### Bash command changes not tracked

Checkpointing does not track files modified by bash commands. For example, if Claude Code runs:

```bash  theme={null}
rm file.txt
mv old.txt new.txt
cp source.txt dest.txt
```

These file modifications cannot be undone through rewind. Only direct file edits made through Claude's file editing tools are 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.

### Not a replacement for version control

Checkpoints are designed for quick, session-level recovery. For permanent version history and collaboration:

* Continue using version control (ex. Git) for commits, branches, and long-term history
* Checkpoints complement but don't replace proper version control
* Think of checkpoints as "local undo" and Git as "permanent history"

## See also

* [Interactive mode](interactive-mode-claude-code-docs.md) - Keyboard shortcuts and session controls
* [Built-in commands](/en/interactive-mode#built-in-commands) - Accessing checkpoints using `/rewind`
* [CLI reference](cli-reference-7bb98e3312.md) - Command-line options


---
## choose-a-permission-mode-claude-code-docs-c8a9703cc1.md

# Choose a permission mode


Control whether Claude asks before editing files or running commands. Cycle modes with Shift+Tab in the CLI or use the mode selector in VS Code, Desktop, and claude.ai.


> ## Documentation Index
>
> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt>
>
> Use this file to discover all available pages before exploring further.

When Claude wants to edit a file, run a shell command, or make a network request, it pauses and asks you to approve the action. Permission modes control how often that pause happens. The mode you pick shapes the flow of a session: default mode has you review each action as it comes, while looser modes let Claude work in longer uninterrupted stretches and report back when done. Pick more oversight for sensitive work, or fewer interruptions when you trust the direction.


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.

| Mode                                                                | What runs without asking                                                               | Best for                                |
|:--------------------------------------------------------------------|:---------------------------------------------------------------------------------------|:----------------------------------------|
| `default`                                                           | Reads only                                                                             | Getting started, sensitive work         |
| [`acceptEdits`](#auto-approve-file-edits-with-acceptedits-mode)     | Reads, file edits, and common filesystem commands (`mkdir`, `touch`, `mv`, `cp`, etc.) | Iterating on code you’re reviewing      |
| [`plan`](#analyze-before-you-edit-with-plan-mode)                   | Reads only                                                                             | Exploring a codebase before changing it |
| [`auto`](#eliminate-prompts-with-auto-mode)                         | Everything, with background safety checks                                              | Long tasks, reducing prompt fatigue     |
| [`dontAsk`](#allow-only-pre-approved-tools-with-dontask-mode)       | Only pre-approved tools                                                                | Locked-down CI and scripts              |
| [`bypassPermissions`](#skip-all-checks-with-bypasspermissions-mode) | Everything                                                                             | Isolated containers and VMs only        |

In every mode except `bypassPermissions`, writes to [protected paths](#protected-paths) are never auto-approved, guarding repository state and Claude’s own configuration against accidental corruption. Modes set the baseline. Layer [permission rules](/docs/en/permissions#manage-permissions) on top to pre-approve or block specific tools in any mode except `bypassPermissions`, which skips the permission layer entirely.


Switch permission modes

You can switch modes mid-session, at startup, or as a persistent default. The mode is set through these controls, not by asking Claude in chat. Select your interface below to see how to change it.

- CLI

- VS Code

- JetBrains

- Desktop

- Web and mobile

**During a session**: press `Shift+Tab` to cycle `default` → `acceptEdits` → `plan`. The current mode appears in the status bar. Not every mode is in the default cycle:

- `auto`: appears when your account meets the [auto mode requirements](#eliminate-prompts-with-auto-mode); cycling to auto shows an opt-in prompt until you accept it, or select **No, don’t ask again** to remove auto from the cycle
- `bypassPermissions`: appears after you start with `--permission-mode bypassPermissions`, `--dangerously-skip-permissions`, or `--allow-dangerously-skip-permissions`; the `--allow-` variant adds the mode to the cycle without activating it
- `dontAsk`: never appears in the cycle; set it with `--permission-mode dontAsk`

Enabled optional modes slot in after `plan`, with `bypassPermissions` first and `auto` last. If you have both enabled, you will cycle through `bypassPermissions` on the way to `auto`.**At startup**: pass the mode as a flag.

```python
claude --permission-mode plan
```

**As a default**: set `defaultMode` in [settings](/docs/en/settings#settings-files).

```python
{
  "permissions": {
    "defaultMode": "acceptEdits"
  }
}
```

The same `--permission-mode` flag works with `-p` for [non-interactive runs](/docs/en/headless).

**During a session**: click the mode indicator at the bottom of the prompt box.**As a default**: set `claudeCode.initialPermissionMode` in VS Code settings, or use the Claude Code extension settings panel.The mode indicator shows these labels, mapped to the mode each one applies:

| UI label           | Mode                |
|:-------------------|:--------------------|
| Ask before edits   | `default`           |
| Edit automatically | `acceptEdits`       |
| Plan mode          | `plan`              |
| Auto mode          | `auto`              |
| Bypass permissions | `bypassPermissions` |

Auto mode appears in the mode indicator after you enable **Allow dangerously skip permissions** in the extension settings, but it stays unavailable until your account meets every requirement listed in the [auto mode section](#eliminate-prompts-with-auto-mode). The `claudeCode.initialPermissionMode` setting does not accept `auto`. To start in auto mode by default, set `defaultMode` in your [user settings](/docs/en/settings#settings-files) instead. Claude Code ignores `defaultMode: "auto"` in project and local settings.Bypass permissions also requires the **Allow dangerously skip permissions** toggle before it appears in the mode indicator.See the [VS Code guide](/docs/en/vs-code) for extension-specific details.

The JetBrains plugin runs Claude Code in the IDE terminal, so switching modes works the same as in the CLI: press `Shift+Tab` to cycle, or pass `--permission-mode` when launching.

Use the mode selector next to the send button. Auto and Bypass permissions appear only after you enable them in Desktop settings. See the [Desktop guide](/docs/en/desktop#choose-a-permission-mode).

Use the mode dropdown next to the prompt box on [claude.ai/code](https://claude.ai/code) or in the mobile app. Permission prompts appear in claude.ai for approval. Which modes appear depends on where the session runs:

- **Cloud sessions** on [Claude Code on the web](/docs/en/claude-code-on-the-web): Auto accept edits and Plan mode. Ask permissions, Auto, and Bypass permissions are not available.
- **[Remote Control](/docs/en/remote-control) sessions** on your local machine: Ask permissions, Auto accept edits, and Plan mode. Auto and Bypass permissions are not available.

For Remote Control, you can also set the starting mode when launching the host:

```python
claude remote-control --permission-mode acceptEdits
```


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`. 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`. Paths outside that scope, writes to [protected paths](#protected-paths), and all other Bash commands still prompt. When the [PowerShell tool](/docs/en/tools-reference#powershell-tool) is enabled, `acceptEdits` mode also auto-approves `Set-Content`, `Add-Content`, `Clear-Content`, and `Remove-Item` on in-scope paths, along with their common aliases. The same scope and protected-path rules apply. Use `acceptEdits` when you want to review changes in your editor or via `git diff` after the fact rather than approving each edit inline. Press `Shift+Tab` once from default mode to enter it, or start with it directly:

```python
claude --permission-mode acceptEdits
```


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. Permission prompts still apply the same as default mode. Enter plan mode by pressing `Shift+Tab` or prefixing a single prompt with `/plan`. You can also start in plan mode from the CLI:

```python
claude --permission-mode plan
```

Press `Shift+Tab` again to leave plan mode without approving a plan.


Review and approve a plan

When the plan is ready, Claude presents it and asks how to proceed. From that prompt you can:

- Approve and start in auto mode
- Approve and accept edits
- Approve and review each edit manually
- Keep planning with feedback
- Refine with [Ultraplan](/docs/en/ultraplan) for browser-based review

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#available-settings) is enabled, each approve option also offers to clear the planning context first. Accepting a plan also names the session from the plan content automatically, unless you’ve already set a name with `--name` or `/rename`.


Set plan mode as the default

To make plan mode the default for a project, set `defaultMode` in `.claude/settings.json`:

```python
{
  "permissions": {
    "defaultMode": "plan"
  }
}
```


Eliminate prompts with auto mode

Auto mode requires Claude Code v2.1.83 or later.

Auto mode lets Claude execute without 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. Auto mode also instructs Claude to execute immediately and minimize clarifying questions. To get that behavior while keeping permission prompts, set the [Proactive output style](/docs/en/output-styles) instead.

Auto mode is a research preview. It reduces prompts but does not guarantee safety. Use it for tasks where you trust the general direction, not as a replacement for review on sensitive operations.

Auto mode is available only when your account meets all of these requirements:

- **Plan**: Max, Team, Enterprise, or API. Not available on Pro.
- **Admin**: on Team and Enterprise, an admin must enable it in [Claude Code admin settings](https://claude.ai/admin-settings/claude-code) before users can turn it on. Admins can also lock it off by setting `permissions.disableAutoMode` to `"disable"` in [managed settings](/docs/en/permissions#managed-settings).
- **Model**: Claude Sonnet 4.6, Opus 4.6, or Opus 4.7 on Team, Enterprise, and API plans; Claude Opus 4.7 only on Max plans. Other models, including Haiku and claude-3 models, are not supported.
- **Provider**: Anthropic API only. Not available on Bedrock, Vertex, or Foundry.

If Claude Code reports auto mode as unavailable, one of these requirements is unmet; this is not a transient outage. A separate message that names a model and says auto mode “cannot determine the safety” of an action is a transient classifier outage; see the [error reference](/docs/en/errors#auto-mode-cannot-determine-the-safety-of-an-action). If you set `defaultMode: "auto"` in [settings](/docs/en/settings#available-settings) and the session starts in `default` mode with no error, the setting is likely in `.claude/settings.json` or `.claude/settings.local.json`. Claude Code ignores `auto` from those files so a repository cannot grant itself auto mode. Move it to `~/.claude/settings.json`.


What the classifier blocks by default

The classifier trusts your working directory and your repo’s configured remotes. Everything else is treated as external until you [configure trusted infrastructure](/docs/en/auto-mode-config). **Blocked by default**:

- Downloading and executing code, like `curl | bash`
- Sending sensitive data to external endpoints
- Production deploys and migrations
- Mass deletion on cloud storage
- Granting IAM or repo permissions
- Modifying shared infrastructure
- Irreversibly destroying files that existed before the session
- Force push, or pushing directly to `main`

**Allowed by default**:

- Local file operations in your working directory
- Installing dependencies declared in your lock files or manifests
- Forwarding request-scoped credentials to the matching first-party API endpoint
- Read-only HTTP requests
- Pushing to the branch you started on or one Claude created

Sandbox network access requests are routed through the classifier rather than allowed by default. Run `claude auto-mode defaults` to see the full rule lists. If routine actions get blocked, an administrator can add trusted repos, buckets, and services via the `autoMode.environment` setting: see [Configure auto mode](/docs/en/auto-mode-config).


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.


When auto mode falls back

Each denied action shows a notification and appears in `/permissions` under the Recently denied tab, where you can press `r` to retry it with a manual approval. If the classifier blocks an action 3 times in a row or 20 times total, auto mode pauses and Claude Code resumes prompting. Approving the prompted action resumes auto mode. These thresholds are not configurable. Any allowed action resets the consecutive counter, while the total counter persists for the session and resets only when its own limit triggers a fallback. In [non-interactive mode](/docs/en/headless) with the `-p` flag, repeated blocks abort the session since there is no user to prompt. Repeated blocks usually mean the classifier is missing context about your infrastructure. Use `/feedback` to report false positives, or have an administrator [configure trusted infrastructure](/docs/en/auto-mode-config).

How the classifier evaluates actions

Each action goes through a fixed decision order. The first matching step wins:

1.  Actions matching your [allow or deny rules](/docs/en/permissions#manage-permissions) resolve immediately
2.  Read-only actions and file edits in your working directory are auto-approved, except writes to [protected paths](#protected-paths)
3.  Everything else goes to the classifier
4.  If the classifier blocks, Claude receives the reason and tries an alternative

On entering auto mode, broad allow rules that grant arbitrary code execution are dropped:

- Blanket `Bash(*)` or `PowerShell(*)`
- Wildcarded interpreters like `Bash(python*)`
- Package-manager run commands
- `Agent` allow rules

Narrow rules like `Bash(npm test)` carry over. Dropped rules are restored when you leave auto mode.The classifier sees user messages, tool calls, and your CLAUDE.md content. Tool results are stripped, so hostile content in a file or web page cannot manipulate it directly. A separate server-side probe scans incoming tool results and flags suspicious content before Claude reads it. For more on how these layers work together, see the [auto mode announcement](https://claude.com/blog/auto-mode) and the [engineering deep dive](https://www.anthropic.com/engineering/claude-code-auto-mode).

How auto mode handles subagents

The classifier checks [subagent](/docs/en/sub-agents) work at three points:

1.  Before a subagent starts, the delegated task description is evaluated, so a dangerous-looking task is blocked at spawn time.
2.  While the subagent runs, each of its actions goes through the classifier with the same rules as the parent session, and any `permissionMode` in the subagent’s frontmatter is ignored.
3.  When the subagent finishes, the classifier reviews its full action history; if that return check flags a concern, a security warning is prepended to the subagent’s results.

Cost and latency

The classifier runs on a server-configured model that is independent of your `/model` selection, so switching models does not change classifier availability. Classifier calls count toward your token usage. Each check sends a portion of the transcript plus the pending action, adding a round-trip before execution. Reads and working-directory edits outside protected paths skip the classifier, so the overhead comes mainly from shell commands and network operations.


Allow only pre-approved tools with dontAsk mode

`dontAsk` mode auto-denies every tool call that would otherwise prompt. Only actions matching your `permissions.allow` rules and [read-only Bash commands](/docs/en/permissions#read-only-commands) can execute; explicit `ask` rules are denied rather than prompting. This makes the mode fully non-interactive for CI pipelines or restricted environments where you pre-define exactly what Claude may do. Set it at startup with the flag:

```python
claude --permission-mode dontAsk
```


Skip all checks with bypassPermissions mode

`bypassPermissions` mode disables permission prompts and safety checks so tool calls execute immediately. As of v2.1.126 this includes writes to [protected paths](#protected-paths), which earlier versions still prompted for. Removals targeting the filesystem root or home directory, such as `rm -rf /` and `rm -rf ~`, still prompt as a circuit breaker against model error. Only use this mode in isolated environments like containers, VMs, or dev containers without internet access, where Claude Code cannot damage your host system. You cannot enter `bypassPermissions` from a session that was started without one of the enabling flags; restart with one to enable it:

```python
claude --permission-mode bypassPermissions
```

The `--dangerously-skip-permissions` flag is equivalent. On Linux and macOS, Claude Code refuses to start in this mode when running as root or under `sudo`:

```python
--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons
```

The check is skipped automatically inside a recognized sandbox. To run autonomously in a container, use the [dev container](/docs/en/devcontainer) configuration, which runs Claude Code as a non-root user.

`bypassPermissions` offers no protection against prompt injection or unintended actions. For background safety checks without prompts, use [auto mode](#eliminate-prompts-with-auto-mode) instead. Administrators can block this mode by setting `permissions.disableBypassPermissionsMode` to `"disable"` in [managed settings](/docs/en/permissions#managed-settings).


Protected paths

Writes to a small set of paths are never auto-approved, in every mode except `bypassPermissions`. This prevents accidental corruption of repository state and Claude’s own configuration. In `default`, `acceptEdits`, and `plan` these writes prompt; in `auto` they route to the classifier; in `dontAsk` they are denied; in `bypassPermissions` they are allowed. Protected directories:

- `.git`
- `.vscode`
- `.idea`
- `.husky`
- `.claude`, except for `.claude/commands`, `.claude/agents`, `.claude/skills`, and `.claude/worktrees` where Claude routinely creates content

Protected files:

- `.gitconfig`, `.gitmodules`
- `.bashrc`, `.bash_profile`, `.zshrc`, `.zprofile`, `.profile`
- `.ripgreprc`
- `.mcp.json`, `.claude.json`


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
- [Hooks](/docs/en/hooks): custom permission logic via `PreToolUse` and `PermissionRequest` hooks
- [Ultraplan](/docs/en/ultraplan): run plan mode in a Claude Code on the web session with browser-based review
- [Security](/docs/en/security): safeguards and best practices
- [Sandboxing](/docs/en/sandboxing): filesystem and network isolation for Bash commands
- [Non-interactive mode](/docs/en/headless): run Claude Code with the `-p` flag


---
## chrome-8f9d762cc1.md

> ## Documentation Index
> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Use Claude Code with Chrome (beta)

> Connect Claude Code to your Chrome browser to test web apps, debug with console logs, automate form filling, and extract data from web pages.

Claude Code integrates with the [Claude in Chrome browser extension](https://chromewebstore.google.com/detail/claude/fcoeoabgfenejglbffodgkkbkcdhcgfn) to give you browser automation capabilities from the CLI or the [VS Code extension](/en/vs-code#automate-browser-tasks-with-chrome). Build your code, then test and debug in the browser without switching contexts.

Claude opens new tabs for browser tasks and shares your browser's login state, so it can access any site you're already signed into. Browser actions run in a visible Chrome window in real time. When Claude encounters a login page or CAPTCHA, it pauses and asks you to handle it manually.

<Note>
  Chrome integration is in beta and currently works with Google Chrome and Microsoft Edge. It is not yet supported on Brave, Arc, or other Chromium-based browsers. WSL (Windows Subsystem for Linux) is also not supported.
</Note>

## Capabilities

With Chrome connected, you can chain browser actions with coding tasks in a single workflow:

* **Live debugging**: read console errors and DOM state directly, then fix the code that caused them
* **Design verification**: build a UI from a Figma mock, then open it in the browser to verify it matches
* **Web app testing**: test form validation, check for visual regressions, or verify user flows
* **Authenticated web apps**: interact with Google Docs, Gmail, Notion, or any app you're logged into without API connectors
* **Data extraction**: pull structured information from web pages and save it locally
* **Task automation**: automate repetitive browser tasks like data entry, form filling, or multi-site workflows
* **Session recording**: record browser interactions as GIFs to document or share what happened

## Prerequisites

Before using Claude Code with Chrome, you need:

* [Google Chrome](https://www.google.com/chrome/) or [Microsoft Edge](https://www.microsoft.com/edge) browser
* [Claude in Chrome extension](https://chromewebstore.google.com/detail/claude/fcoeoabgfenejglbffodgkkbkcdhcgfn) version 1.0.36 or higher, available in the Chrome Web Store for both browsers
* [Claude Code](/en/quickstart#step-1-install-claude-code) version 2.0.73 or higher
* A direct Anthropic plan (Pro, Max, Team, or Enterprise)

<Note>
  Chrome integration is not available through third-party providers like Amazon Bedrock, Google Cloud Vertex AI, or Microsoft Foundry. If you access Claude exclusively through a third-party provider, you need a separate claude.ai account to use this feature.
</Note>

## Get started in the CLI

<Steps>
  <Step title="Launch Claude Code with Chrome">
    Start Claude Code with the `--chrome` flag:

    ```bash theme={null}
    claude --chrome
    ```

    You can also enable Chrome from within an existing session by running `/chrome`.
  </Step>

  <Step title="Ask Claude to use the browser">
    This example navigates to a page, interacts with it, and reports what it finds, all from your terminal or editor:

    ```text theme={null}
    Go to code.claude.com/docs, click on the search box,
    type "hooks", and tell me what results appear
    ```
  </Step>
</Steps>

Run `/chrome` at any time to check the connection status, manage permissions, or reconnect the extension.

For VS Code, see [browser automation in VS Code](/en/vs-code#automate-browser-tasks-with-chrome).

### Enable Chrome by default

To avoid passing `--chrome` each session, run `/chrome` and select "Enabled by default".

In the [VS Code extension](/en/vs-code#automate-browser-tasks-with-chrome), Chrome is available whenever the Chrome extension is installed. No additional flag is needed.

<Note>
  Enabling Chrome by default in the CLI increases context usage since browser tools are always loaded. If you notice increased context consumption, disable this setting and use `--chrome` only when needed.
</Note>

### 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.

## Example workflows

These examples show common ways to combine browser actions with coding tasks. Run `/mcp` and select `claude-in-chrome` to see the full list of available browser tools.

### Test a local web application

When developing a web app, ask Claude to verify your changes work correctly:

```text theme={null}
I just updated the login form validation. Can you open localhost:3000,
try submitting the form with invalid data, and check if the error
messages appear correctly?
```

Claude navigates to your local server, interacts with the form, and reports what it observes.

### 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:

```text theme={null}
Open the dashboard page and check the console for any errors when
the page loads.
```

Claude reads the console messages and can filter for specific patterns or error types.

### Automate form filling

Speed up repetitive data entry tasks:

```text theme={null}
I have a spreadsheet of customer contacts in contacts.csv. For each row,
go to the CRM at crm.example.com, click "Add Contact", and fill in the
name, email, and phone fields.
```

Claude reads your local file, navigates the web interface, and enters the data for each record.

### Draft content in Google Docs

Use Claude to write directly in your documents without API setup:

```text theme={null}
Draft a project update based on the recent commits and add it to my
Google Doc at docs.google.com/document/d/abc123
```

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

Pull structured information from websites:

```text theme={null}
Go to the product listings page and extract the name, price, and
availability for each item. Save the results as a CSV file.
```

Claude navigates to the page, reads the content, and compiles the data into a structured format.

### Run multi-site workflows

Coordinate tasks across multiple websites:

```text theme={null}
Check my calendar for meetings tomorrow, then for each meeting with
an external attendee, look up their company website and add a note
about what they do.
```

Claude works across tabs to gather information and complete the workflow.

### Record a demo GIF

Create shareable recordings of browser interactions:

```text theme={null}
Record a GIF showing how to complete the checkout flow, from adding
an item to the cart through to the confirmation page.
```

Claude records the interaction sequence and saves it as a GIF file.

## Troubleshooting

### Extension not detected

If Claude Code shows "Chrome extension not detected":

1. Verify the Chrome extension is installed and enabled in `chrome://extensions`
2. Verify Claude Code is up to date by running `claude --version`
3. Check that Chrome is running
4. Run `/chrome` and select "Reconnect extension" to re-establish the connection
5. If the issue persists, restart both Claude Code and Chrome

The first time you enable Chrome integration, Claude Code installs a native messaging host configuration file. Chrome reads this file on startup, so if the extension isn't detected on your first attempt, restart Chrome to pick up the new configuration.

If the connection still fails, verify the host configuration file exists at:

For Chrome:

* **macOS**: `~/Library/Application Support/Google/Chrome/NativeMessagingHosts/com.anthropic.claude_code_browser_extension.json`
* **Linux**: `~/.config/google-chrome/NativeMessagingHosts/com.anthropic.claude_code_browser_extension.json`
* **Windows**: check `HKCU\Software\Google\Chrome\NativeMessagingHosts\` in the Windows Registry

For Edge:

* **macOS**: `~/Library/Application Support/Microsoft Edge/NativeMessagingHosts/com.anthropic.claude_code_browser_extension.json`
* **Linux**: `~/.config/microsoft-edge/NativeMessagingHosts/com.anthropic.claude_code_browser_extension.json`
* **Windows**: check `HKCU\Software\Microsoft\Edge\NativeMessagingHosts\` in the Windows Registry

### Browser not responding

If Claude's browser commands stop working:

1. Check if a modal dialog (alert, confirm, prompt) is blocking the page. JavaScript dialogs block browser events and prevent Claude from receiving commands. Dismiss the dialog manually, then tell Claude to continue.
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

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".

### Windows-specific issues

On Windows, you may encounter:

* **Named pipe conflicts (EADDRINUSE)**: if another process is using the same named pipe, restart Claude Code. Close any other Claude Code sessions that might be using Chrome.
* **Native messaging host errors**: if the native messaging host crashes on startup, try reinstalling Claude Code to regenerate the host configuration.

### Common error messages

These are the most frequently encountered errors and how to resolve them:

| Error                                | Cause                                            | Fix                                                             |
| ------------------------------------ | ------------------------------------------------ | --------------------------------------------------------------- |
| "Browser extension is not connected" | Native messaging host cannot reach the extension | Restart Chrome and Claude Code, then run `/chrome` to reconnect |
| "Extension not detected"             | Chrome extension is not installed or is disabled | Install or enable the extension in `chrome://extensions`        |
| "No tab available"                   | Claude tried to act before a tab was ready       | Ask Claude to create a new tab and retry                        |
| "Receiving end does not exist"       | Extension service worker went idle               | Run `/chrome` and select "Reconnect extension"                  |

## See also

* [Computer use](computer-use-427032da98.md): control native macOS apps when a task can't be done in a browser
* [Use Claude Code in VS Code](/en/vs-code#automate-browser-tasks-with-chrome): browser automation in the VS Code extension
* [CLI reference](cli-reference-7bb98e3312.md): command-line flags including `--chrome`
* [Common workflows](common-workflows-c909406123.md): more ways to use Claude Code
* [Data and privacy](../22-Safety-Policy/data-usage-claude-code-docs-06b2864aaa.md): how Claude Code handles your data
* [Getting started with Claude in Chrome](../15-Claude-AI-Features/getting-started-with-claude-in-chrome.md): full documentation for the Chrome extension, including shortcuts, scheduling, and permissions


---
## chrome.md

# Use Claude Code with Chrome (beta)

Connect Claude Code to your Chrome browser to test web apps, debug with console logs, automate form filling, and extract data from web pages.

Claude Code integrates with the Claude in Chrome browser extension to give you browser automation capabilities from the CLI or the VS Code extension. Build your code, then test and debug in the browser without switching contexts.

Claude opens new tabs for browser tasks and shares your browser's login state, so it can access any site you're already signed into. Browser actions run in a visible Chrome window in real time.

> Chrome integration is in beta and currently works with Google Chrome and Microsoft Edge. WSL is not supported.

## Capabilities

- **Live debugging**: read console errors and DOM state, then fix the code
- **Design verification**: build a UI from a Figma mock, open it in browser to verify
- **Web app testing**: test form validation, check for visual regressions, verify user flows
- **Authenticated web apps**: interact with Google Docs, Gmail, Notion, or any app you're logged into
- **Data extraction**: pull structured information from web pages and save locally
- **Task automation**: automate repetitive browser tasks like data entry, form filling
- **Session recording**: record browser interactions as GIFs

## Prerequisites

- Google Chrome or Microsoft Edge
- Claude in Chrome extension v1.0.36+
- Claude Code v2.0.73+
- Direct Anthropic plan (Pro, Max, Team, or Enterprise)

> Not available through third-party providers (Bedrock, Vertex, Foundry).

## Get started

```bash
claude --chrome
```

Or enable from within a session with `/chrome`.

### Enable Chrome by default

Run `/chrome` and select "Enabled by default".

### Manage site permissions

Site-level permissions are inherited from the Chrome extension settings.

## Example workflows

### Test a local web application

```
I just updated the login form validation. Can you open localhost:3000,
try submitting the form with invalid data, and check if the error
messages appear correctly?
```

### Debug with console logs

```
Open the dashboard page and check the console for any errors when
the page loads.
```

### Automate form filling

```
I have a spreadsheet of customer contacts in contacts.csv. For each row,
go to the CRM at crm.example.com, click "Add Contact", and fill in the
name, email, and phone fields.
```

### Draft content in Google Docs

```
Draft a project update based on the recent commits and add it to my
Google Doc at docs.google.com/document/d/abc123
```

### Record a demo GIF

```
Record a GIF showing how to complete the checkout flow, from adding
an item to the cart through to the confirmation page.
```

## Troubleshooting

| Error                                | Cause                                            | Fix                                                             |
| ------------------------------------ | ------------------------------------------------ | --------------------------------------------------------------- |
| "Browser extension is not connected" | Native messaging host cannot reach the extension | Restart Chrome and Claude Code, then run `/chrome` to reconnect |
| "Extension not detected"             | Chrome extension not installed or disabled        | Install or enable in `chrome://extensions`                      |
| "No tab available"                   | Claude tried to act before a tab was ready       | Ask Claude to create a new tab and retry                        |
| "Receiving end does not exist"       | Extension service worker went idle               | Run `/chrome` and select "Reconnect extension"                  |

## See Also

- [Computer use](computer-use.md)
- [VS Code browser automation](/en/vs-code#automate-browser-tasks-with-chrome)
- [CLI reference](cli-reference-7bb98e3312.md)


---
## claude-code-architecture.md

# Claude Code Architecture for Zack's Setup

> Arch Linux (omarchy) · Ryzen 9800X3D · RTX 4090 · 10Gbps fiber
> Projects: SpecHO, definitelynot.ai, llmx, iOS RE toolkits, Iconics

## Design Principles

1. **Tool Search handles main context** - Don't fight it, leverage it
2. **MCP isolation for subagents** - Purpose-built agents get specific tools
3. **llmx as primary code search** - Replace/augment built-in Explore
4. **No plugin wrappers** - That strategy is obsolete
5. **Explicit over implicit** - Clear tool boundaries, no inheritance surprises

---

## Directory Structure

```
~/.claude/
├── settings.json              # Global settings, disabled built-ins
├── settings.local.json        # Machine-specific overrides (not synced)
├── mcp.json                   # User-scope MCP servers (always available)
├── agents/
│   ├── llmx-explorer.md       # Replaces Explore, uses llmx
│   ├── web-automation.md      # Playwright isolation
│   ├── github-ops.md          # GitHub MCP isolation  
│   ├── re-analyst.md          # Reverse engineering workflow
│   ├── specwriter.md          # Documentation/spec generation
│   └── clean-task.md          # MCP-free general purpose
├── commands/
│   ├── search.md              # /search - llmx semantic search
│   ├── re.md                  # /re - reverse engineering workflow
│   ├── detect.md              # /detect - AI detection pipeline
│   └── index.md               # /index - reindex with llmx
├── skills/
│   ├── specho-analysis/
│   │   └── SKILL.md           # SpecHO fingerprinting workflow
│   ├── re-patterns/
│   │   └── SKILL.md           # iOS/binary RE patterns
│   └── api-conventions/
│       └── SKILL.md           # Your API style guide
├── hooks/
│   └── mcp-guard.py           # PreToolUse hook for MCP auditing
└── plugins/
    └── (empty - not using plugin wrappers)

# Project-level (per repo)
.claude/
├── settings.json              # Project permissions
├── agents/                    # Project-specific agents
├── skills/                    # Project-specific skills
└── CLAUDE.md                  # Project context
```

---

## MCP Server Tiers

### Tier 1: Always-On (User Scope)
Low token cost, high utility, used across all projects.

```json
// ~/.claude/mcp.json
{
  "mcpServers": {
    "llmx": {
      "command": "/home/zack/dev/llmx/target/release/llmx-mcp",
      "env": {
        "LLMX_STORAGE_DIR": "/home/zack/.llmx/indexes",
        "LLMX_MODEL_PATH": "/home/zack/.llmx/models/bge-small-en-v1.5.onnx"
      }
    }
  }
}
```

**Why llmx only?** It's your local semantic search - lightweight, always useful, no external API calls. Everything else is situational.

### Tier 2: Project-Scope (Shared with team)
Tools specific to a project, checked into repo.

```json
// ~/dev/specho/.mcp.json
{
  "mcpServers": {
    "huggingface": {
      "command": "npx",
      "args": ["-y", "@huggingface/mcp-server"],
      "env": {
        "HF_TOKEN": "${HF_TOKEN}"
      }
    }
  }
}

// ~/dev/definitelynot.ai/.mcp.json  
{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": ["@anthropic-ai/mcp-server-playwright"]
    }
  }
}
```

### Tier 3: On-Demand via Subagent
Heavy/specialized tools that should NEVER pollute main context.

These aren't configured globally - they're started by subagents or enabled per-session:

- `playwright` - Only via `web-automation` subagent
- `github` - Only via `github-ops` subagent  
- Database servers - Only via project-specific agents
- Heavy API servers (Jira, Linear, etc.)

---

## Settings Configuration

### Global Settings
```json
// ~/.claude/settings.json
{
  "permissions": {
    "deny": [
      "Task(Explore)",
      "mcp__playwright__*",
      "mcp__github__*"
    ],
    "allow": [
      "mcp__llmx__*",
      "Read",
      "Grep", 
      "Glob"
    ]
  },
  "env": {
    "ENABLE_TOOL_SEARCH": "auto:5",
    "MAX_MCP_OUTPUT_TOKENS": "50000",
    "CLAUDE_AUTOCOMPACT_PCT_OVERRIDE": "85"
  },
  "model": "claude-sonnet-4-5-20250929",
  "cleanupPeriodDays": 14
}
```

**Key decisions:**
- `Task(Explore)` denied - replaced by `llmx-explorer`
- `mcp__playwright__*` denied in main context - only via subagent
- `mcp__github__*` denied in main context - only via subagent
- `ENABLE_TOOL_SEARCH=auto:5` - More aggressive lazy loading (5% threshold)
- `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=85` - Compact earlier to preserve context

### Project Settings Example
```json
// ~/dev/specho/.claude/settings.json
{
  "permissions": {
    "allow": [
      "mcp__huggingface__*",
      "Bash(python *)",
      "Bash(cargo *)"
    ]
  }
}
```

---

## Subagent Definitions

### 1. llmx-explorer.md (Replaces Explore)
```yaml
---
name: llmx-explorer
description: |
  Fast semantic code search and codebase exploration. Use for:
  - Finding relevant code by meaning, not just text
  - Understanding codebase structure and patterns
  - Locating implementations, definitions, usages
  - Architectural analysis
  Replaces built-in Explore with semantic search via llmx.
model: haiku
tools: Read, Grep, Glob, mcp__llmx__search, mcp__llmx__index_status
disallowedTools: Write, Edit, Bash, mcp__playwright__*, mcp__github__*
permissionMode: plan
---

You are a semantic code explorer powered by llmx.

## Primary Tool: mcp__llmx__search
Use semantic search FIRST for any code discovery task. Query with natural language descriptions of what you're looking for.

## Fallback Tools
- `Grep` - For exact string/regex matches after semantic search narrows scope
- `Glob` - For file pattern discovery
- `Read` - To examine files found via search

## Response Format
Return findings as:
1. **Relevant Files** - Ranked by semantic relevance
2. **Key Patterns** - Architectural observations
3. **Entry Points** - Where to start for the task

Never modify files. Summarize concisely for the main agent.
```

### 2. web-automation.md (Playwright Isolation)
```yaml
---
name: web-automation
description: |
  Browser automation and web scraping tasks. Use for:
  - Automated testing with Playwright
  - Web scraping and data extraction
  - Screenshot capture and visual testing
  - Form filling and interaction recording
  MUST run in foreground (MCP required).
model: inherit
tools: Read, Write, Bash, mcp__playwright__*
disallowedTools: mcp__github__*, mcp__llmx__*
permissionMode: acceptEdits
---

You are a browser automation specialist using Playwright MCP.

## Available Playwright Tools
- Navigate, click, fill, screenshot
- Wait for selectors, extract text
- Handle multiple pages/contexts

## Constraints
- Always close browser contexts when done
- Return screenshots as base64 when visual verification needed
- Summarize extracted data, don't dump raw HTML

## Response Format
Return:
1. **Actions Taken** - What you did
2. **Results** - Data extracted or verification status
3. **Screenshots** - If visual confirmation needed
```

### 3. github-ops.md (GitHub Isolation)
```yaml
---
name: github-ops
description: |
  GitHub operations and repository management. Use for:
  - Creating/reviewing pull requests
  - Issue management and triage
  - Repository search and analysis
  - Release management
  MUST run in foreground (MCP required).
model: inherit
tools: Read, Bash, mcp__github__*
disallowedTools: mcp__playwright__*, Write, Edit
permissionMode: default
---

You are a GitHub operations specialist.

## Available GitHub Tools
- Search repositories, issues, PRs
- Create/update issues and PRs
- Manage labels, milestones, releases
- Review and comment on code

## Constraints
- Confirm destructive operations before executing
- Summarize PR/issue content, don't dump full text
- Use rate limiting awareness

## Response Format
Return:
1. **Operation** - What was done
2. **Result** - Links to created/modified resources
3. **Summary** - Key information extracted
```

### 4. re-analyst.md (Reverse Engineering)
```yaml
---
name: re-analyst
description: |
  Binary analysis and reverse engineering tasks. Use for:
  - iOS/macOS binary analysis
  - Disassembly and decompilation review
  - Protocol reverse engineering
  - Security vulnerability analysis
  Specialized for RE workflows.
model: inherit
tools: Read, Bash, Grep, Glob
disallowedTools: mcp__*, Write, Edit
permissionMode: plan
skills:
  - re-patterns
---

You are a reverse engineering analyst.

## Methodology
1. Static analysis first (strings, headers, imports)
2. Identify interesting functions via symbols/patterns
3. Trace data flow and control flow
4. Document findings systematically

## Tools Available
- `Bash` for running analysis tools (otool, nm, strings, class-dump, frida)
- `Read` for examining output files
- `Grep/Glob` for pattern matching

## Response Format
Return:
1. **Target Info** - Binary metadata, architecture
2. **Interesting Findings** - Functions, strings, patterns
3. **Recommendations** - Next analysis steps
```

### 5. clean-task.md (MCP-Free General Purpose)
```yaml
---
name: clean-task
description: |
  General purpose task execution WITHOUT external tool access. Use for:
  - Code modifications that don't need external APIs
  - File operations and refactoring
  - Local testing and validation
  - Any task where MCP would be overhead
  Lightweight alternative to general-purpose.
model: inherit
tools: Read, Write, Edit, Bash, Grep, Glob
disallowedTools: mcp__*
permissionMode: acceptEdits
---

You are a focused task executor. No external API access.

Work efficiently with local tools only. If you need external data,
tell the main agent to use a specialized subagent instead.
```

### 6. specwriter.md (Documentation)
```yaml
---
name: specwriter
description: |
  Technical documentation and specification writing. Use for:
  - API documentation generation
  - Architecture decision records
  - README and guide creation
  - Code comment generation
  Read-heavy, write-focused.
model: inherit  
tools: Read, Write, Grep, Glob, mcp__llmx__search
disallowedTools: Bash, Edit, mcp__playwright__*, mcp__github__*
permissionMode: acceptEdits
---

You are a technical writer. Read code, write documentation.

## Process
1. Use llmx to find relevant code
2. Read and understand the implementation
3. Write clear, accurate documentation
4. Use consistent formatting (your conventions)

## Output Formats
- Markdown for docs
- JSDoc/docstrings for inline
- OpenAPI for APIs
```

---

## Slash Commands

### /search - Semantic Code Search
```yaml
# ~/.claude/commands/search.md
---
description: Semantic code search using llmx
argument-hint: "<natural language query>"
---

Use the llmx-explorer subagent to search for: $ARGUMENTS

Return the top 10 most relevant results with file paths and brief context.
```

### /index - Reindex Codebase
```yaml
# ~/.claude/commands/index.md
---
description: Reindex current project with llmx
---

Run the llmx indexer on the current project:

```bash
llmx index --path . --storage ~/.llmx/indexes/$(basename $(pwd))
```

Report indexing status when complete.
```

### /re - Reverse Engineering Session
```yaml
# ~/.claude/commands/re.md
---
description: Start reverse engineering analysis
argument-hint: "<binary path or description>"
---

Use the re-analyst subagent to analyze: $ARGUMENTS

Begin with static analysis, then report findings and recommended next steps.
```

### /detect - AI Detection Pipeline
```yaml
# ~/.claude/commands/detect.md
---
description: Run SpecHO AI text detection
argument-hint: "<text or file path>"
---

Analyze the provided content using SpecHO fingerprinting:

1. Extract linguistic features (148-dimensional)
2. Compare against known model signatures
3. Report confidence scores and model attribution

Input: $ARGUMENTS
```

---

## Skills

### specho-analysis/SKILL.md
```yaml
---
name: specho-analysis
description: |
  SpecHO AI text detection and model fingerprinting workflow.
  148-dimensional linguistic analysis for identifying AI-generated text
  and attributing specific models.
disable-model-invocation: false
---

# SpecHO Analysis Workflow

## Feature Extraction Pipeline
1. **Tokenization** - Split into sentences and tokens
2. **Lexical Features** - Vocabulary richness, word length distribution
3. **Syntactic Features** - POS patterns, dependency structures  
4. **Semantic Features** - Embedding-based coherence metrics
5. **Stylometric Features** - Punctuation patterns, sentence rhythm

## Model Signatures
Known fingerprints for: GPT-4, GPT-3.5, Claude 3, Claude 2, Llama, Mistral

## Usage
```python
from specho import SpecHODetector

detector = SpecHODetector()
result = detector.analyze(text)
print(f"AI Probability: {result.ai_score:.2%}")
print(f"Likely Model: {result.attribution}")
```

## Confidence Thresholds
- >0.95: High confidence AI
- 0.70-0.95: Likely AI, needs review
- 0.30-0.70: Uncertain
- <0.30: Likely human
```

### re-patterns/SKILL.md
```yaml
---
name: re-patterns
description: |
  iOS and macOS reverse engineering patterns and techniques.
  Common analysis workflows for binary analysis.
disable-model-invocation: true
---

# iOS/macOS RE Patterns

## Initial Triage
```bash
# Binary info
file <binary>
otool -h <binary>
otool -l <binary> | grep -A2 LC_ENCRYPTION

# Symbols
nm -u <binary>  # Undefined (imports)
nm -g <binary>  # Global (exports)

# Strings
strings -a <binary> | grep -i "api\|key\|secret\|token"

# Objective-C
class-dump <binary> > headers.h
```

## Frida Patterns
```javascript
// Hook method
Interceptor.attach(ObjC.classes.ClassName["- methodName:"].implementation, {
  onEnter: function(args) {
    console.log("Called with:", ObjC.Object(args[2]));
  }
});

// Trace class
ObjC.classes.ClassName.$methods.forEach(function(m) {
  console.log(m);
});
```

## Common Targets
- `SecItemCopyMatching` - Keychain access
- `CC_SHA256` / `CCCrypt` - Crypto operations
- `NSURLSession` - Network requests
- `UIApplication openURL` - URL schemes
```

---

## Hooks

### mcp-guard.py (Audit MCP Usage)
```python
#!/usr/bin/env python3
# ~/.claude/hooks/mcp-guard.py
"""
PreToolUse hook to audit and optionally block MCP tool usage.
Logs all MCP calls for review.
"""

import json
import sys
from datetime import datetime
from pathlib import Path

LOG_FILE = Path.home() / ".claude" / "mcp-audit.log"

def main():
    input_data = json.load(sys.stdin)
    tool_name = input_data.get("tool_name", "")
    
    # Only process MCP tools
    if not tool_name.startswith("mcp__"):
        sys.exit(0)
    
    # Log the call
    log_entry = {
        "timestamp": datetime.now().isoformat(),
        "tool": tool_name,
        "session": input_data.get("session_id", "unknown"),
        "input": input_data.get("tool_input", {})
    }
    
    with open(LOG_FILE, "a") as f:
        f.write(json.dumps(log_entry) + "\n")
    
    # Allow the call (exit 0)
    # To block: exit 2 with error message
    sys.exit(0)

if __name__ == "__main__":
    main()
```

### Hook Configuration
```json
// In ~/.claude/settings.json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "mcp__.*",
        "hooks": [
          {
            "type": "command",
            "command": "python3 ~/.claude/hooks/mcp-guard.py"
          }
        ]
      }
    ]
  }
}
```

---

## CLAUDE.md Template

```markdown
# Project: [Name]

## Quick Context
[2-3 sentences about what this project does]

## Tech Stack
- Language: [Rust/Python/TypeScript/etc]
- Framework: [if applicable]
- Key deps: [important libraries]

## Directory Structure
```
src/           - Main source
tests/         - Test files
docs/          - Documentation
```

## Development Commands
```bash
# Build
cargo build --release

# Test
cargo test

# Run
./target/release/[binary]
```

## Code Conventions
- [Your style preferences]
- [Naming conventions]
- [Error handling patterns]

## Subagent Guidelines
When delegating tasks:
- **Code search**: Use llmx-explorer (semantic search)
- **Web automation**: Use web-automation (foreground only)
- **GitHub ops**: Use github-ops (foreground only)
- **General tasks**: Use clean-task (no MCP overhead)
- **NEVER** give subagents MCP tools they don't explicitly need

## Current Focus
[What you're working on - update this]
```

---

## Workflow Integration

### Daily Workflow
```
1. Start session: `claude` (llmx always available)
2. Code search: `/search <query>` or natural language
3. Tasks needing GitHub: Claude auto-delegates to github-ops
4. Tasks needing browser: Claude auto-delegates to web-automation
5. Everything else: clean-task or inline

Tool Search handles main context. Subagents handle isolation.
```

### Project Onboarding
```bash
# Index new project
cd ~/dev/new-project
llmx index --path . --storage ~/.llmx/indexes/new-project

# Create project config if needed
mkdir -p .claude
cat > .claude/settings.json << 'EOF'
{
  "permissions": {
    "allow": ["Bash(cargo *)"]
  }
}
EOF

# Add project-specific MCP if needed
cat > .mcp.json << 'EOF'
{
  "mcpServers": {}
}
EOF
```

### Monitoring
```bash
# Check context usage
# In Claude Code: /context or /doctor

# Review MCP audit log
tail -f ~/.claude/mcp-audit.log | jq .

# Check llmx index status
llmx status
```

---

## Migration Checklist

- [ ] Backup existing `~/.claude/` directory
- [ ] Create directory structure above
- [ ] Move MCP servers from mcp.json to appropriate tiers
- [ ] Create subagent definitions
- [ ] Create slash commands
- [ ] Add hooks for MCP auditing
- [ ] Update CLAUDE.md in active projects
- [ ] Test subagent delegation with explicit prompts
- [ ] Verify Tool Search is working: `/doctor`

---

## Known Limitations

1. **Background subagents can't use MCP** - Always use foreground for MCP-heavy tasks
2. **Custom plugin subagents may not inherit MCP** - Known bug (#13605)
3. **No scoped MCP per-subagent** - Feature requested (#6915, #7289)
4. **Built-in agents can't be overridden by name** - Must disable + replace
5. **Tool Search threshold is global** - Can't set per-server

---

## Future Improvements (Watch These Issues)

- [ ] #6915 - MCP tools available only to subagent
- [ ] #7289 - Disable MCP in default, enable for subagents
- [ ] #13605 - Plugin subagents MCP access
- [ ] #13254 - Background subagents MCP access


---
## claude-code-built-in-tools-reference.md

This is a guide I created while exploring the built-in tools Claude Code ships with and how it’s trained/prompted to use them. Included below is every built-in tool, their parameters, usage patterns, and examples. This was basically all written by prompting Claude Code itself.

___

## Table of Contents[](https://www.vtrivedy.com/posts/claudecode-tools-reference#table-of-contents)

Open Table of Contents

-   [1\. Task](https://www.vtrivedy.com/posts/claudecode-tools-reference#1-task)
-   [2\. Bash](https://www.vtrivedy.com/posts/claudecode-tools-reference#2-bash)
-   [3\. Glob](https://www.vtrivedy.com/posts/claudecode-tools-reference#3-glob)
-   [4\. Grep](https://www.vtrivedy.com/posts/claudecode-tools-reference#4-grep)
-   [5\. Read, 6. Edit, 7. Write](https://www.vtrivedy.com/posts/claudecode-tools-reference#5-read-6-edit-7-write)
    -   [Read](https://www.vtrivedy.com/posts/claudecode-tools-reference#read)
    -   [Edit](https://www.vtrivedy.com/posts/claudecode-tools-reference#edit)
    -   [Write](https://www.vtrivedy.com/posts/claudecode-tools-reference#write)
-   [8\. NotebookEdit](https://www.vtrivedy.com/posts/claudecode-tools-reference#8-notebookedit)
-   [9\. WebFetch, 10. WebSearch](https://www.vtrivedy.com/posts/claudecode-tools-reference#9-webfetch-10-websearch)
    -   [WebFetch](https://www.vtrivedy.com/posts/claudecode-tools-reference#webfetch)
    -   [WebSearch](https://www.vtrivedy.com/posts/claudecode-tools-reference#websearch)
-   [11\. TodoWrite](https://www.vtrivedy.com/posts/claudecode-tools-reference#11-todowrite)
-   [12\. ExitPlanMode](https://www.vtrivedy.com/posts/claudecode-tools-reference#12-exitplanmode)
-   [13\. BashOutput, 14. KillShell](https://www.vtrivedy.com/posts/claudecode-tools-reference#13-bashoutput-14-killshell)
    -   [BashOutput](https://www.vtrivedy.com/posts/claudecode-tools-reference#bashoutput)
    -   [KillShell](https://www.vtrivedy.com/posts/claudecode-tools-reference#killshell)
-   [15\. SlashCommand](https://www.vtrivedy.com/posts/claudecode-tools-reference#15-slashcommand)
-   [Tool Usage Patterns & Best Practices](https://www.vtrivedy.com/posts/claudecode-tools-reference#tool-usage-patterns--best-practices)
    -   [Batch Operations](https://www.vtrivedy.com/posts/claudecode-tools-reference#batch-operations)
    -   [File Operations Workflow](https://www.vtrivedy.com/posts/claudecode-tools-reference#file-operations-workflow)
    -   [Complex Task Workflow](https://www.vtrivedy.com/posts/claudecode-tools-reference#complex-task-workflow)
    -   [Background Process Management](https://www.vtrivedy.com/posts/claudecode-tools-reference#background-process-management)
    -   [Searching Strategy](https://www.vtrivedy.com/posts/claudecode-tools-reference#searching-strategy)
    -   [Communication](https://www.vtrivedy.com/posts/claudecode-tools-reference#communication)
-   [Examples: Complete Workflows](https://www.vtrivedy.com/posts/claudecode-tools-reference#examples-complete-workflows)
    -   [Workflow 1: Add New Feature](https://www.vtrivedy.com/posts/claudecode-tools-reference#workflow-1-add-new-feature)
    -   [Workflow 2: Debug Issue](https://www.vtrivedy.com/posts/claudecode-tools-reference#workflow-2-debug-issue)
    -   [Workflow 3: Research Codebase](https://www.vtrivedy.com/posts/claudecode-tools-reference#workflow-3-research-codebase)
    -   [Workflow 4: Refactor Code](https://www.vtrivedy.com/posts/claudecode-tools-reference#workflow-4-refactor-code)
-   [Tool Selection Quick Reference](https://www.vtrivedy.com/posts/claudecode-tools-reference#tool-selection-quick-reference)
-   [Common Antipatterns to Avoid](https://www.vtrivedy.com/posts/claudecode-tools-reference#common-antipatterns-to-avoid)

## 1\. Task[](https://www.vtrivedy.com/posts/claudecode-tools-reference#1-task)

**Purpose**: Launch specialized sub-agents for complex, multi-step tasks that require autonomous work.

**Available Agent Types**:

-   `general-purpose`: Research, code search, multi-step tasks (has access to all tools)
-   `statusline-setup`: Configure status line settings (Read, Edit)
-   `output-style-setup`: Create output styles (Read, Write, Edit, Glob, Grep)

**Parameters**:

-   `subagent_type` (required): Which agent type to use
-   `prompt` (required): Detailed task description for the agent
-   `description` (required): Short 3-5 word description of the task

**When to Use**:

-   Complex tasks requiring multiple rounds of searching/reading
-   When you need an agent to work autonomously
-   Open-ended research tasks

**When NOT to Use**:

-   Reading a specific known file path (use Read instead)
-   Searching within 2-3 specific files (use Read instead)
-   Searching for specific class definitions (use Glob instead)

**Example**:

```
{
  "subagent_type": "general-purpose",
  "description": "Find authentication implementation",
  "prompt": "Search the codebase to find where user authentication is implemented. Look for login functions, JWT handling, and session management. Return the file paths and a summary of how authentication works."
}
```

**Key Notes**:

-   Launch multiple agents concurrently when possible (single message, multiple tool calls)
-   Agent returns one final message - cannot communicate back and forth
-   Agents are stateless - provide complete instructions upfront
-   Specify whether agent should write code or just research

___

## 2\. Bash[](https://www.vtrivedy.com/posts/claudecode-tools-reference#2-bash)

**Purpose**: Execute shell commands in a persistent bash session.

**Parameters**:

-   `command` (required): The shell command to execute
-   `description` (optional but recommended): Clear 5-10 word description
-   `timeout` (optional): Milliseconds before timeout (default: 120000ms, max: 600000ms)
-   `run_in_background` (optional): Boolean to run command in background

**When to Use**:

-   Terminal operations: git, npm, docker, pytest, etc.
-   Commands that modify system state
-   Running builds, tests, servers

**When NOT to Use**:

-   File reading (use Read instead of cat/head/tail)
-   File editing (use Edit instead of sed/awk)
-   File writing (use Write instead of echo >)
-   File searching (use Glob instead of find/ls)
-   Content searching (use Grep instead of grep/rg)

**Examples**:

Basic command:

```
{
  "command": "git status",
  "description": "Check git repository status"
}
```

With timeout:

```
{
  "command": "npm run build",
  "description": "Build production bundle",
  "timeout": 300000
}
```

Background process:

```
{
  "command": "npm run dev",
  "description": "Start development server",
  "run_in_background": true
}
```

Chained commands (sequential with &&):

```
{
  "command": "git add . && git commit -m \"Update features\" && git push",
  "description": "Stage, commit, and push changes"
}
```

Command with paths containing spaces:

```
{
  "command": "cd \"/path/with spaces/\" && ls",
  "description": "List files in directory with spaces"
}
```

**Git Commit Best Practices**:

1.  Run `git status`, `git diff`, and `git log` in parallel
2.  Draft commit message following repo style
3.  Add files and commit with co-authorship footer:

```
git commit -m "$(cat <<'EOF'
Your commit message here.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
EOF
)"
```

**Pull Request Creation**:

1.  Run `git status`, `git diff`, and `git log [base-branch]...HEAD` in parallel
2.  Draft PR summary from ALL commits (not just latest)
3.  Push and create PR:

```
gh pr create --title "PR title" --body "$(cat <<'EOF'
## Summary
- Bullet point 1
- Bullet point 2

## Test plan
- [ ] Test item 1
- [ ] Test item 2

🤖 Generated with [Claude Code](https://claude.com/claude-code)
EOF
)"
```

___

## 3\. Glob[](https://www.vtrivedy.com/posts/claudecode-tools-reference#3-glob)

**Purpose**: Fast file pattern matching for finding files by name patterns.

**Parameters**:

-   `pattern` (required): Glob pattern to match files
-   `path` (optional): Directory to search in (defaults to current working directory)

**Pattern Examples**:

-   `**/*.js` - All JavaScript files recursively
-   `src/**/*.ts` - All TypeScript files in src/
-   `*.{json,yaml}` - All JSON and YAML files in current directory
-   `test/**/*test.js` - All test files

**Examples**:

Find all TypeScript files:

Find config files in specific directory:

```
{
  "pattern": "*.config.{js,ts}",
  "path": "/Users/project/root"
}
```

Find React components:

```
{
  "pattern": "src/components/**/*.tsx"
}
```

**Key Notes**:

-   Returns files sorted by modification time
-   Works with any codebase size
-   Faster than bash find command
-   Use for open-ended searches with Agent tool

___

## 4\. Grep[](https://www.vtrivedy.com/posts/claudecode-tools-reference#4-grep)

**Purpose**: Powerful content search built on ripgrep for finding text/code patterns in files.

**Parameters**:

-   `pattern` (required): Regular expression to search for
-   `path` (optional): File or directory to search (defaults to current directory)
-   `output_mode` (optional): “content” (lines), “files\_with\_matches” (paths), “count” (counts)
-   `glob` (optional): Filter files by glob pattern (e.g., “\*.js”)
-   `type` (optional): Filter by file type (e.g., “js”, “py”, “rust”)
-   `-A` (optional): Lines to show after match (requires output\_mode: “content”)
-   `-B` (optional): Lines to show before match (requires output\_mode: “content”)
-   `-C` (optional): Lines to show before and after match (requires output\_mode: “content”)
-   `-i` (optional): Case insensitive search (boolean)
-   `-n` (optional): Show line numbers (requires output\_mode: “content”)
-   `multiline` (optional): Enable multiline matching where . matches newlines (boolean)
-   `head_limit` (optional): Limit output to first N results

**Pattern Syntax**:

-   Uses ripgrep (not grep)
-   Literal braces need escaping: `interface\\{\\}` to find `interface{}`
-   Standard regex: `log.*Error`, `function\\s+\\w+`

**Examples**:

Find files containing pattern:

```
{
  "pattern": "function authenticate",
  "output_mode": "files_with_matches"
}
```

Show matching lines with context:

```
{
  "pattern": "TODO",
  "output_mode": "content",
  "-n": true,
  "-C": 2
}
```

Case-insensitive search in TypeScript files:

```
{
  "pattern": "errorhandler",
  "-i": true,
  "type": "ts",
  "output_mode": "content"
}
```

Count occurrences:

```
{
  "pattern": "console\\.log",
  "output_mode": "count"
}
```

Search with glob filter:

```
{
  "pattern": "import.*React",
  "glob": "*.tsx",
  "output_mode": "content"
}
```

Multiline pattern matching:

```
{
  "pattern": "struct \\{[\\s\\S]*?field",
  "multiline": true,
  "output_mode": "content"
}
```

Limited results:

```
{
  "pattern": "export function",
  "output_mode": "content",
  "head_limit": 10
}
```

___

## 5\. Read, 6. Edit, 7. Write[](https://www.vtrivedy.com/posts/claudecode-tools-reference#5-read-6-edit-7-write)

### Read[](https://www.vtrivedy.com/posts/claudecode-tools-reference#read)

**Purpose**: Read files from the filesystem.

**Parameters**:

-   `file_path` (required): Absolute path to file
-   `offset` (optional): Line number to start reading from
-   `limit` (optional): Number of lines to read

**Supported File Types**:

-   Text files
-   Images (PNG, JPG) - displayed visually
-   PDFs - processed page by page
-   Jupyter notebooks (.ipynb) - all cells with outputs

**Examples**:

Read entire file:

```
{
  "file_path": "/Users/vivektrivedy/Desktop/personal_website/vtrivedy_website/src/config.ts"
}
```

Read specific line range:

```
{
  "file_path": "/path/to/large/file.log",
  "offset": 1000,
  "limit": 100
}
```

Read image:

```
{
  "file_path": "/var/folders/tmp/Screenshot.png"
}
```

**Key Notes**:

-   Returns content with line numbers (cat -n format)
-   Lines longer than 2000 characters are truncated
-   Default reads up to 2000 lines from start
-   Batch multiple Read calls in one response for performance

___

### Edit[](https://www.vtrivedy.com/posts/claudecode-tools-reference#edit)

**Purpose**: Perform exact string replacements in files.

**Parameters**:

-   `file_path` (required): Absolute path to file
-   `old_string` (required): Exact text to replace
-   `new_string` (required): Replacement text (must differ from old\_string)
-   `replace_all` (optional): Replace all occurrences (default: false)

**Requirements**:

-   MUST read file with Read tool first
-   `old_string` must be unique in file (unless using `replace_all`)
-   Preserve exact indentation from Read output (exclude line number prefix)

**Line Number Prefix Format**:

```
[spaces][line_number][tab][actual_content]
```

Only include `[actual_content]` in old\_string/new\_string.

**Examples**:

Simple replacement:

```
{
  "file_path": "/path/to/file.ts",
  "old_string": "const port = 3000;",
  "new_string": "const port = 4321;"
}
```

Multi-line replacement:

```
{
  "file_path": "/path/to/component.tsx",
  "old_string": "export default function Header() {\n  return <h1>Old Title</h1>;\n}",
  "new_string": "export default function Header() {\n  return <h1>New Title</h1>;\n}"
}
```

Replace all occurrences (renaming):

```
{
  "file_path": "/path/to/file.ts",
  "old_string": "oldFunctionName",
  "new_string": "newFunctionName",
  "replace_all": true
}
```

**Common Mistakes to Avoid**:

-   ❌ Including line numbers in old\_string: `"25\tconst x = 5;"`
-   ✅ Correct: `"const x = 5;"`
-   ❌ Wrong indentation: `" function foo()"` when file has tabs
-   ✅ Match exact whitespace from Read output

___

### Write[](https://www.vtrivedy.com/posts/claudecode-tools-reference#write)

**Purpose**: Write or overwrite files.

**Parameters**:

-   `file_path` (required): Absolute path to file
-   `content` (required): Complete file content

**Requirements**:

-   For existing files: MUST read with Read tool first
-   Prefer Edit over Write for existing files
-   Only create new files when absolutely necessary

**Examples**:

Create new file:

```
{
  "file_path": "/path/to/new/file.ts",
  "content": "export const API_URL = 'https://api.example.com';\n"
}
```

Overwrite existing file:

```
{
  "file_path": "/path/to/existing/config.json",
  "content": "{\n  \"version\": \"2.0\",\n  \"enabled\": true\n}\n"
}
```

___

## 8\. NotebookEdit[](https://www.vtrivedy.com/posts/claudecode-tools-reference#8-notebookedit)

**Purpose**: Edit Jupyter notebook (.ipynb) cells.

**Parameters**:

-   `notebook_path` (required): Absolute path to notebook
-   `new_source` (required): New cell content
-   `cell_id` (optional): ID of cell to edit (for insert: new cell inserted after this ID)
-   `cell_type` (optional): “code” or “markdown” (required for insert mode)
-   `edit_mode` (optional): “replace” (default), “insert”, “delete”

**Examples**:

Replace cell content:

```
{
  "notebook_path": "/path/to/notebook.ipynb",
  "cell_id": "abc123",
  "new_source": "import pandas as pd\ndf = pd.read_csv('data.csv')\ndf.head()"
}
```

Insert new code cell:

```
{
  "notebook_path": "/path/to/notebook.ipynb",
  "cell_id": "xyz789",
  "cell_type": "code",
  "edit_mode": "insert",
  "new_source": "# New analysis step\nresult = df.groupby('category').sum()"
}
```

Delete cell:

```
{
  "notebook_path": "/path/to/notebook.ipynb",
  "cell_id": "def456",
  "edit_mode": "delete",
  "new_source": ""
}
```

___

## 9\. WebFetch, 10. WebSearch[](https://www.vtrivedy.com/posts/claudecode-tools-reference#9-webfetch-10-websearch)

### WebFetch[](https://www.vtrivedy.com/posts/claudecode-tools-reference#webfetch)

**Purpose**: Fetch and process web content with AI analysis.

**Parameters**:

-   `url` (required): Fully-formed valid URL
-   `prompt` (required): What information to extract from the page

**Features**:

-   Converts HTML to markdown
-   Auto-upgrades HTTP to HTTPS
-   15-minute cache for repeated requests
-   Handles redirects (requires new request with redirect URL)

**Examples**:

Fetch documentation:

```
{
  "url": "https://docs.astro.build/en/getting-started/",
  "prompt": "Extract the commands needed to create a new Astro project and start the dev server"
}
```

Analyze article:

```
{
  "url": "https://example.com/blog/best-practices",
  "prompt": "Summarize the key best practices mentioned in this article"
}
```

Check API reference:

```
{
  "url": "https://api-docs.example.com/v2/authentication",
  "prompt": "What are the authentication methods supported and their required parameters?"
}
```

**Key Notes**:

-   Prefer MCP-provided web fetch tools if available (start with “mcp\_\_”)
-   Read-only operation
-   Results may be summarized for large content
-   When redirected to different host, make new request with redirect URL

___

### WebSearch[](https://www.vtrivedy.com/posts/claudecode-tools-reference#websearch)

**Purpose**: Search the web for current information beyond Claude’s knowledge cutoff.

**Parameters**:

-   `query` (required): Search query string (min 2 characters)
-   `allowed_domains` (optional): Array of domains to include
-   `blocked_domains` (optional): Array of domains to exclude

**Availability**: US only

**Examples**:

Basic search:

```
{
  "query": "Astro 4.0 new features 2025"
}
```

Search specific domains:

```
{
  "query": "TypeScript best practices",
  "allowed_domains": ["typescript-lang.org", "github.com"]
}
```

Exclude domains:

```
{
  "query": "React hooks tutorial",
  "blocked_domains": ["pinterest.com", "youtube.com"]
}
```

**Key Notes**:

-   Consider current date when forming queries
-   Returns search result blocks
-   Use for information beyond January 2025 knowledge cutoff

___

## 11\. TodoWrite[](https://www.vtrivedy.com/posts/claudecode-tools-reference#11-todowrite)

**Purpose**: Create and manage structured task lists for tracking progress.

**Parameters**:

-   `todos` (required): Array of todo objects with:
    -   `content` (required): Imperative form (e.g., “Run tests”)
    -   `activeForm` (required): Present continuous form (e.g., “Running tests”)
    -   `status` (required): “pending”, “in\_progress”, or “completed”

**When to Use**:

-   Complex multi-step tasks (3+ steps)
-   Non-trivial complex tasks requiring planning
-   User explicitly requests todo list
-   User provides multiple tasks
-   After receiving new instructions (capture requirements)
-   When starting work (mark as in\_progress BEFORE beginning)
-   After completing tasks (mark completed, add follow-ups)

**When NOT to Use**:

-   Single straightforward task
-   Trivial tasks providing no organizational benefit
-   Tasks completable in <3 trivial steps
-   Purely conversational/informational requests

**Critical Rules**:

-   EXACTLY ONE task must be “in\_progress” at any time
-   Mark tasks completed IMMEDIATELY after finishing (no batching)
-   Only mark completed when FULLY accomplished
-   Keep task in\_progress if: tests failing, implementation partial, unresolved errors, missing dependencies
-   Remove irrelevant tasks entirely

**Examples**:

Create initial todo list:

```
{
  "todos": [
    {
      "content": "Search codebase for authentication logic",
      "activeForm": "Searching codebase for authentication logic",
      "status": "in_progress"
    },
    {
      "content": "Implement OAuth2 flow",
      "activeForm": "Implementing OAuth2 flow",
      "status": "pending"
    },
    {
      "content": "Add authentication tests",
      "activeForm": "Adding authentication tests",
      "status": "pending"
    }
  ]
}
```

Update progress:

```
{
  "todos": [
    {
      "content": "Search codebase for authentication logic",
      "activeForm": "Searching codebase for authentication logic",
      "status": "completed"
    },
    {
      "content": "Implement OAuth2 flow",
      "activeForm": "Implementing OAuth2 flow",
      "status": "in_progress"
    },
    {
      "content": "Add authentication tests",
      "activeForm": "Adding authentication tests",
      "status": "pending"
    }
  ]
}
```

___

## 12\. ExitPlanMode[](https://www.vtrivedy.com/posts/claudecode-tools-reference#12-exitplanmode)

**Purpose**: Exit plan mode after presenting an implementation plan.

**Parameters**:

-   `plan` (required): The implementation plan (supports markdown)

**When to Use**:

-   ONLY for tasks requiring code implementation planning
-   After finishing planning implementation steps

**When NOT to Use**:

-   Research tasks (gathering information, searching, reading, understanding codebase)

**Example**:

```
{
  "plan": "## Implementation Plan\n\n1. Create authentication middleware in `src/middleware/auth.ts`\n2. Add JWT verification logic\n3. Protect API routes with middleware\n4. Add tests for authentication flow\n\nShall I proceed with this plan?"
}
```

___

## 13\. BashOutput, 14. KillShell[](https://www.vtrivedy.com/posts/claudecode-tools-reference#13-bashoutput-14-killshell)

### BashOutput[](https://www.vtrivedy.com/posts/claudecode-tools-reference#bashoutput)

**Purpose**: Retrieve output from running or completed background bash shells.

**Parameters**:

-   `bash_id` (required): ID of the background shell
-   `filter` (optional): Regular expression to filter output lines

**Returns**:

-   Only new output since last check
-   stdout and stderr
-   Shell status

**Example**:

```
{
  "bash_id": "shell_12345",
  "filter": "ERROR|WARN"
}
```

**Key Notes**:

-   Find shell IDs with `/bashes` command
-   Filtered lines are consumed (no longer available to read)

___

### KillShell[](https://www.vtrivedy.com/posts/claudecode-tools-reference#killshell)

**Purpose**: Terminate a running background bash shell.

**Parameters**:

-   `shell_id` (required): ID of shell to terminate

**Example**:

```
{
  "shell_id": "shell_12345"
}
```

___

## 15\. SlashCommand[](https://www.vtrivedy.com/posts/claudecode-tools-reference#15-slashcommand)

**Purpose**: Execute slash commands within the conversation.

**Parameters**:

-   `command` (required): Slash command with arguments (e.g., “/review-pr 123”)

**Restrictions**:

-   Only available commands can be executed
-   Don’t use if command with same name is already running
-   Check command-message tags for running status

**Example**:

___

### Batch Operations[](https://www.vtrivedy.com/posts/claudecode-tools-reference#batch-operations)

**Always batch independent tool calls in a single response for optimal performance.**

Example - Multiple file reads:

```
Call Read on file1.ts, file2.ts, file3.ts in single message
```

Example - Parallel git commands:

```
Call Bash("git status") and Bash("git diff") in single message
```

### File Operations Workflow[](https://www.vtrivedy.com/posts/claudecode-tools-reference#file-operations-workflow)

1.  **Search for files**: Use Glob (not find/ls)
2.  **Search content**: Use Grep (not bash grep/rg)
3.  **Read files**: Use Read (not cat/head/tail)
4.  **Edit files**: Use Edit (not sed/awk)
5.  **Write files**: Use Write (not echo >/heredoc)

### Complex Task Workflow[](https://www.vtrivedy.com/posts/claudecode-tools-reference#complex-task-workflow)

1.  Use TodoWrite to plan and track tasks
2.  Use Task agent for multi-step research
3.  Use Bash for terminal operations only
4.  Batch independent operations together
5.  Mark todos completed immediately after finishing

### Background Process Management[](https://www.vtrivedy.com/posts/claudecode-tools-reference#background-process-management)

1.  Start process: `Bash` with `run_in_background: true`
2.  Monitor output: `BashOutput` with bash\_id
3.  Filter if needed: Use `filter` parameter with regex
4.  Terminate when done: `KillShell` with shell\_id

### Searching Strategy[](https://www.vtrivedy.com/posts/claudecode-tools-reference#searching-strategy)

-   **Known file paths**: Use Read directly
-   **File name patterns**: Use Glob
-   **Content in specific files**: Read then search locally
-   **Content across codebase**: Use Grep
-   **Complex multi-round search**: Use Task with general-purpose agent

### Communication[](https://www.vtrivedy.com/posts/claudecode-tools-reference#communication)

-   Output text directly to user (not bash echo)
-   Use markdown formatting for readability
-   Include file references as links: `[filename.ts](src/filename.ts)` or `[filename.ts:42](src/filename.ts#L42)`
-   Be concise and direct (avoid preamble/postamble)

___

## Examples: Complete Workflows[](https://www.vtrivedy.com/posts/claudecode-tools-reference#examples-complete-workflows)

### Workflow 1: Add New Feature[](https://www.vtrivedy.com/posts/claudecode-tools-reference#workflow-1-add-new-feature)

```
1. TodoWrite: Plan the feature tasks
2. Grep: Find related existing implementations
3. Read: Read relevant files (batch multiple)
4. Edit: Modify existing files (or Write for new files)
5. Bash: Run tests
6. TodoWrite: Mark tasks completed
7. Bash: Commit changes (if requested)
```

### Workflow 2: Debug Issue[](https://www.vtrivedy.com/posts/claudecode-tools-reference#workflow-2-debug-issue)

```
1. TodoWrite: Create debugging task list
2. Grep: Search for error messages/patterns
3. Read: Read files with issues (batch multiple)
4. Bash: Run failing tests/reproduce issue
5. Edit: Apply fixes
6. Bash: Verify fix with tests
7. TodoWrite: Mark completed
```

### Workflow 3: Research Codebase[](https://www.vtrivedy.com/posts/claudecode-tools-reference#workflow-3-research-codebase)

```
1. Task: Launch general-purpose agent with research prompt
   (Agent will autonomously use Grep, Glob, Read to explore)
2. Agent returns findings
3. Present summary to user
```

### Workflow 4: Refactor Code[](https://www.vtrivedy.com/posts/claudecode-tools-reference#workflow-4-refactor-code)

```
1. TodoWrite: Break down refactoring tasks
2. Grep: Find all occurrences of code to refactor
3. Read: Read affected files (batch multiple)
4. Edit: Apply refactoring with replace_all for renames
5. Bash: Run tests and type checking
6. TodoWrite: Mark tasks completed
```

___

| Task | Use This Tool | NOT This |
| --- | --- | --- |
| Find files by name | Glob | Bash(find/ls) |
| Search content | Grep | Bash(grep/rg) |
| Read file | Read | Bash(cat/head/tail) |
| Edit file | Edit | Bash(sed/awk) |
| Create file | Write | Bash(echo >) |
| Run tests/builds | Bash | N/A |
| Multi-step research | Task | Multiple manual searches |
| Track complex tasks | TodoWrite | Comments/memory |
| Fetch web content | WebFetch | Bash(curl) |
| Search web | WebSearch | WebFetch with search engine |
| Background process | Bash(run\_in\_background) + BashOutput | Bash with & |

___

## Common Antipatterns to Avoid[](https://www.vtrivedy.com/posts/claudecode-tools-reference#common-antipatterns-to-avoid)

❌ **Don’t**: Use bash for file operations

✅ **Do**: Use Read tool

```
{"file_path": "src/config.ts"}
```

❌ **Don’t**: Use echo for communication

```
echo "Now processing files..."
```

✅ **Do**: Output text directly to user

❌ **Don’t**: Make sequential tool calls when independent

```
Call Read on file1, wait, then Read on file2, wait, then Read on file3
```

✅ **Do**: Batch independent calls

```
Call Read on file1, file2, file3 in single message
```

❌ **Don’t**: Forget to use TodoWrite for complex tasks

```
Start working without planning
```

✅ **Do**: Plan first with TodoWrite

❌ **Don’t**: Mark todos completed before actually finishing

```
{"status": "completed"} // but tests are failing
```

✅ **Do**: Only mark completed when fully done

```
{"status": "in_progress"} // keep working until tests pass
```

___

That’s all for now, I’ll try to update this guide with more tools or useful patterns as they come out. But really this is mostly just a reference to look back on when I need to.


---
## claude-code-github-actions-claude-code-docs-0d633fbd8a.md

# Claude Code GitHub Actions


Learn about integrating Claude Code into your development workflow with Claude Code GitHub Actions


> ## Documentation Index
>
> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt>
>
> Use this file to discover all available pages before exploring further.

Claude Code GitHub Actions brings AI-powered automation to your GitHub workflow. With a simple `@claude` mention in any PR or issue, Claude can analyze your code, create pull requests, implement features, and fix bugs - all while following your project’s standards. For automatic reviews posted on every PR without a trigger, see [GitHub Code Review](/docs/en/code-review).

Claude Code GitHub Actions is built on top of the [Claude Agent SDK](/docs/en/agent-sdk/overview), which enables programmatic integration of Claude Code into your applications. You can use the SDK to build custom automation workflows beyond GitHub Actions.

**Claude Opus 4.7 is now available.** Claude Code GitHub Actions default to Sonnet. To use Opus 4.7, configure the [model parameter](#breaking-changes-reference) to use `claude-opus-4-7`.


Why use Claude Code GitHub Actions?

- **Instant PR creation**: Describe what you need, and Claude creates a complete PR with all necessary changes
- **Automated code implementation**: Turn issues into working code with a single command
- **Follows your standards**: Claude respects your `CLAUDE.md` guidelines and existing code patterns
- **Simple setup**: Get started in minutes with our installer and API key
- **Secure by default**: Your code stays on Github’s runners


What can Claude do?

Claude Code provides a powerful GitHub Action that transforms how you work with code:


Claude Code Action

This GitHub Action allows you to run Claude Code within your GitHub Actions workflows. You can use this to build any custom workflow on top of Claude Code. [View repository →](https://github.com/anthropics/claude-code-action)


Setup


Quick setup

The easiest way to set up this action is through Claude Code in the terminal. Just open claude and run `/install-github-app`. This command will guide you through setting up the GitHub app and required secrets.

- You must be a repository admin to install the GitHub app and add secrets
- The GitHub app will request read & write permissions for Contents, Issues, and Pull requests
- This quickstart method is only available for direct Claude API users. If you’re using Amazon Bedrock or Google Vertex AI, see the [Using with Amazon Bedrock & Google Vertex AI](#using-with-amazon-bedrock-%26-google-vertex-ai) section.


Manual setup

If the `/install-github-app` command fails or you prefer manual setup, please follow these manual setup instructions:

1.  **Install the Claude GitHub app** to your repository: [https://github.com/apps/claude](https://github.com/apps/claude) The Claude GitHub app requires the following repository permissions:
    - **Contents**: Read & write (to modify repository files)
    - **Issues**: Read & write (to respond to issues)
    - **Pull requests**: Read & write (to create PRs and push changes)

    For more details on security and permissions, see the [security documentation](https://github.com/anthropics/claude-code-action/blob/main/docs/security.md).
2.  **Add ANTHROPIC_API_KEY** to your repository secrets ([Learn how to use secrets in GitHub Actions](https://docs.github.com/en/actions/security-guides/using-secrets-in-github-actions))
3.  **Copy the workflow file** from [examples/claude.yml](https://github.com/anthropics/claude-code-action/blob/main/examples/claude.yml) into your repository’s `.github/workflows/`

After completing either the quickstart or manual setup, test the action by tagging `@claude` in an issue or PR comment.


Upgrading from Beta

Claude Code GitHub Actions v1.0 introduces breaking changes that require updating your workflow files in order to upgrade to v1.0 from the beta version.

If you’re currently using the beta version of Claude Code GitHub Actions, we recommend that you update your workflows to use the GA version. The new version simplifies configuration while adding powerful new features like automatic mode detection.


Essential changes

All beta users must make these changes to their workflow files in order to upgrade:

1.  **Update the action version**: Change `@beta` to `@v1`
2.  **Remove mode configuration**: Delete `mode: "tag"` or `mode: "agent"` (now auto-detected)
3.  **Update prompt inputs**: Replace `direct_prompt` with `prompt`
4.  **Move CLI options**: Convert `max_turns`, `model`, `custom_instructions`, etc. to `claude_args`


Breaking Changes Reference

| Old Beta Input        | New v1.0 Input                        |
|-----------------------|---------------------------------------|
| `mode`                | *(Removed - auto-detected)*           |
| `direct_prompt`       | `prompt`                              |
| `override_prompt`     | `prompt` with GitHub variables        |
| `custom_instructions` | `claude_args: --append-system-prompt` |
| `max_turns`           | `claude_args: --max-turns`            |
| `model`               | `claude_args: --model`                |
| `allowed_tools`       | `claude_args: --allowedTools`         |
| `disallowed_tools`    | `claude_args: --disallowedTools`      |
| `claude_env`          | `settings` JSON format                |


Before and After Example

**Beta version:**

```python
- uses: anthropics/claude-code-action@beta
  with:
    mode: "tag"
    direct_prompt: "Review this PR for security issues"
    anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
    custom_instructions: "Follow our coding standards"
    max_turns: "10"
    model: "claude-sonnet-4-6"
```

**GA version (v1.0):**

```python
- uses: anthropics/claude-code-action@v1
  with:
    prompt: "Review this PR for security issues"
    anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
    claude_args: |
      --append-system-prompt "Follow our coding standards"
      --max-turns 10
      --model claude-sonnet-4-6
```

The action now automatically detects whether to run in interactive mode (responds to `@claude` mentions) or automation mode (runs immediately with a prompt) based on your configuration.


Example use cases

Claude Code GitHub Actions can help you with a variety of tasks. The [examples directory](https://github.com/anthropics/claude-code-action/tree/main/examples) contains ready-to-use workflows for different scenarios.


Basic workflow

```python
name: Claude Code
on:
  issue_comment:
    types: [created]
  pull_request_review_comment:
    types: [created]
jobs:
  claude:
    runs-on: ubuntu-latest
    steps:
      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          # Responds to @claude mentions in comments
```


Using skills

The `prompt` input accepts a [skill](/docs/en/skills) invocation as well as plain text:

- For a skill in your repository’s `.claude/skills/` directory, run `actions/checkout` before the action step and pass `/skill-name`.
- For a skill packaged in a plugin, install the plugin with the `plugin_marketplaces` and `plugins` inputs and pass the namespaced `/plugin-name:skill-name`.

The following workflow installs the `code-review` plugin and runs its skill on each new or updated pull request:

```python
name: Code Review
on:
  pull_request:
    types: [opened, synchronize]
jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          plugin_marketplaces: "https://github.com/anthropics/claude-code.git"
          plugins: "code-review@claude-code-plugins"
          prompt: "/code-review:code-review ${{ github.repository }}/pull/${{ github.event.pull_request.number }}"
```


Custom automation with prompts

```python
name: Daily Report
on:
  schedule:
    - cron: "0 9 * * *"
jobs:
  report:
    runs-on: ubuntu-latest
    steps:
      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          prompt: "Generate a summary of yesterday's commits and open issues"
          claude_args: "--model opus"
```


Common use cases

In issue or PR comments:

```python
@claude implement this feature based on the issue description
@claude how should I implement user authentication for this endpoint?
@claude fix the TypeError in the user dashboard component
```

Claude will automatically analyze the context and respond appropriately.


Best practices


CLAUDE.md configuration

Create a `CLAUDE.md` file in your repository root to define code style guidelines, review criteria, project-specific rules, and preferred patterns. This file guides Claude’s understanding of your project standards.


Security considerations

Never commit API keys directly to your repository.

For comprehensive security guidance including permissions, authentication, and best practices, see the [Claude Code Action security documentation](https://github.com/anthropics/claude-code-action/blob/main/docs/security.md). Always use GitHub Secrets for API keys:

- Add your API key as a repository secret named `ANTHROPIC_API_KEY`
- Reference it in workflows: `anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}`
- Limit action permissions to only what’s necessary
- Review Claude’s suggestions before merging

Always use GitHub Secrets (for example, `${{ secrets.ANTHROPIC_API_KEY }}`) rather than hardcoding API keys directly in your workflow files.


Optimizing performance

Use issue templates to provide context, keep your `CLAUDE.md` concise and focused, and configure appropriate timeouts for your workflows.


CI costs

When using Claude Code GitHub Actions, be aware of the associated costs: **GitHub Actions costs:**

- Claude Code runs on GitHub-hosted runners, which consume your GitHub Actions minutes
- See [GitHub’s billing documentation](https://docs.github.com/en/billing/managing-billing-for-your-products/managing-billing-for-github-actions/about-billing-for-github-actions) for detailed pricing and minute limits

**API costs:**

- Each Claude interaction consumes API tokens based on the length of prompts and responses
- Token usage varies by task complexity and codebase size
- See [Claude’s pricing page](https://claude.com/platform/api) for current token rates

**Cost optimization tips:**

- Use specific `@claude` commands to reduce unnecessary API calls
- Configure appropriate `--max-turns` in `claude_args` to prevent excessive iterations
- Set workflow-level timeouts to avoid runaway jobs
- Consider using GitHub’s concurrency controls to limit parallel runs


Configuration examples

The Claude Code Action v1 simplifies configuration with unified parameters:

```python
- uses: anthropics/claude-code-action@v1
  with:
    anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
    prompt: "Your instructions here" # Optional
    claude_args: "--max-turns 5" # Optional CLI arguments
```

Key features:

- **Unified prompt interface** - Use `prompt` for all instructions
- **Skills** - Invoke installed [skills](/docs/en/skills) directly from the prompt
- **CLI passthrough** - Any Claude Code CLI argument via `claude_args`
- **Flexible triggers** - Works with any GitHub event

Visit the [examples directory](https://github.com/anthropics/claude-code-action/tree/main/examples) for complete workflow files.

When responding to issue or PR comments, Claude automatically responds to @claude mentions. For other events, use the `prompt` parameter to provide instructions.


Using with Amazon Bedrock & Google Vertex AI

For enterprise environments, you can use Claude Code GitHub Actions with your own cloud infrastructure. This approach gives you control over data residency and billing while maintaining the same functionality.


Prerequisites

Before setting up Claude Code GitHub Actions with cloud providers, you need:


For Google Cloud Vertex AI:

1.  A Google Cloud Project with Vertex AI enabled
2.  Workload Identity Federation configured for GitHub Actions
3.  A service account with the required permissions
4.  A GitHub App (recommended) or use the default GITHUB_TOKEN


For Amazon Bedrock:

1.  An AWS account with Amazon Bedrock enabled
2.  GitHub OIDC Identity Provider configured in AWS
3.  An IAM role with Bedrock permissions
4.  A GitHub App (recommended) or use the default GITHUB_TOKEN

1


Create a custom GitHub App (Recommended for 3P Providers)

For best control and security when using 3P providers like Vertex AI or Bedrock, we recommend creating your own GitHub App:

1.  Go to [https://github.com/settings/apps/new](https://github.com/settings/apps/new)
2.  Fill in the basic information:
    - **GitHub App name**: Choose a unique name (e.g., “YourOrg Claude Assistant”)
    - **Homepage URL**: Your organization’s website or the repository URL
3.  Configure the app settings:
    - **Webhooks**: Uncheck “Active” (not needed for this integration)
4.  Set the required permissions:
    - **Repository permissions**:
      - Contents: Read & Write
      - Issues: Read & Write
      - Pull requests: Read & Write
5.  Click “Create GitHub App”
6.  After creation, click “Generate a private key” and save the downloaded `.pem` file
7.  Note your App ID from the app settings page
8.  Install the app to your repository:
    - From your app’s settings page, click “Install App” in the left sidebar
    - Select your account or organization
    - Choose “Only select repositories” and select the specific repository
    - Click “Install”
9.  Add the private key as a secret to your repository:
    - Go to your repository’s Settings → Secrets and variables → Actions
    - Create a new secret named `APP_PRIVATE_KEY` with the contents of the `.pem` file
10. Add the App ID as a secret:

- Create a new secret named `APP_ID` with your GitHub App’s ID

This app will be used with the [actions/create-github-app-token](https://github.com/actions/create-github-app-token) action to generate authentication tokens in your workflows.

**Alternative for Claude API or if you don’t want to setup your own Github app**: Use the official Anthropic app:

1.  Install from: [https://github.com/apps/claude](https://github.com/apps/claude)
2.  No additional configuration needed for authentication

2


Configure cloud provider authentication

Choose your cloud provider and set up secure authentication:

Amazon Bedrock

**Configure AWS to allow GitHub Actions to authenticate securely without storing credentials.**

> **Security Note**: Use repository-specific configurations and grant only the minimum required permissions.

**Required Setup**:

1.  **Enable Amazon Bedrock**:
    - Request access to Claude models in Amazon Bedrock
    - For cross-region models, request access in all required regions
2.  **Set up GitHub OIDC Identity Provider**:
    - Provider URL: `https://token.actions.githubusercontent.com`
    - Audience: `sts.amazonaws.com`
3.  **Create IAM Role for GitHub Actions**:
    - Trusted entity type: Web identity
    - Identity provider: `token.actions.githubusercontent.com`
    - Permissions: `AmazonBedrockFullAccess` policy
    - Configure trust policy for your specific repository

**Required Values**:After setup, you’ll need:

- **AWS_ROLE_TO_ASSUME**: The ARN of the IAM role you created

OIDC is more secure than using static AWS access keys because credentials are temporary and automatically rotated.

See [AWS documentation](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html) for detailed OIDC setup instructions.

Google Vertex AI

**Configure Google Cloud to allow GitHub Actions to authenticate securely without storing credentials.**

> **Security Note**: Use repository-specific configurations and grant only the minimum required permissions.

**Required Setup**:

1.  **Enable APIs** in your Google Cloud project:
    - IAM Credentials API
    - Security Token Service (STS) API
    - Vertex AI API
2.  **Create Workload Identity Federation resources**:
    - Create a Workload Identity Pool
    - Add a GitHub OIDC provider with:
      - Issuer: `https://token.actions.githubusercontent.com`
      - Attribute mappings for repository and owner
      - **Security recommendation**: Use repository-specific attribute conditions
3.  **Create a Service Account**:
    - Grant only `Vertex AI User` role
    - **Security recommendation**: Create a dedicated service account per repository
4.  **Configure IAM bindings**:
    - Allow the Workload Identity Pool to impersonate the service account
    - **Security recommendation**: Use repository-specific principal sets

**Required Values**:After setup, you’ll need:

- **GCP_WORKLOAD_IDENTITY_PROVIDER**: The full provider resource name
- **GCP_SERVICE_ACCOUNT**: The service account email address

Workload Identity Federation eliminates the need for downloadable service account keys, improving security.

For detailed setup instructions, consult the [Google Cloud Workload Identity Federation documentation](https://cloud.google.com/iam/docs/workload-identity-federation).

3


Add Required Secrets

Add the following secrets to your repository (Settings → Secrets and variables → Actions):


For Claude API (Direct):

1.  **For API Authentication**:
    - `ANTHROPIC_API_KEY`: Your Claude API key from [console.anthropic.com](https://console.anthropic.com)
2.  **For GitHub App (if using your own app)**:
    - `APP_ID`: Your GitHub App’s ID
    - `APP_PRIVATE_KEY`: The private key (.pem) content


For Google Cloud Vertex AI

1.  **For GCP Authentication**:
    - `GCP_WORKLOAD_IDENTITY_PROVIDER`
    - `GCP_SERVICE_ACCOUNT`
2.  **For GitHub App (if using your own app)**:
    - `APP_ID`: Your GitHub App’s ID
    - `APP_PRIVATE_KEY`: The private key (.pem) content


For Amazon Bedrock

1.  **For AWS Authentication**:
    - `AWS_ROLE_TO_ASSUME`
2.  **For GitHub App (if using your own app)**:
    - `APP_ID`: Your GitHub App’s ID
    - `APP_PRIVATE_KEY`: The private key (.pem) content

4


Create workflow files

Create GitHub Actions workflow files that integrate with your cloud provider. The examples below show complete configurations for both Amazon Bedrock and Google Vertex AI:

Amazon Bedrock workflow

**Prerequisites:**

- Amazon Bedrock access enabled with Claude model permissions
- GitHub configured as an OIDC identity provider in AWS
- IAM role with Bedrock permissions that trusts GitHub Actions

**Required GitHub secrets:**

| Secret Name          | Description                                       |
|----------------------|---------------------------------------------------|
| `AWS_ROLE_TO_ASSUME` | ARN of the IAM role for Bedrock access            |
| `APP_ID`             | Your GitHub App ID (from app settings)            |
| `APP_PRIVATE_KEY`    | The private key you generated for your GitHub App |

```python
name: Claude PR Action

permissions:
  contents: write
  pull-requests: write
  issues: write
  id-token: write

on:
  issue_comment:
    types: [created]
  pull_request_review_comment:
    types: [created]
  issues:
    types: [opened, assigned]

jobs:
  claude-pr:
    if: |
      (github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
      (github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
      (github.event_name == 'issues' && contains(github.event.issue.body, '@claude'))
    runs-on: ubuntu-latest
    env:
      AWS_REGION: us-west-2
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Generate GitHub App token
        id: app-token
        uses: actions/create-github-app-token@v2
        with:
          app-id: ${{ secrets.APP_ID }}
          private-key: ${{ secrets.APP_PRIVATE_KEY }}

      - name: Configure AWS Credentials (OIDC)
        uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: ${{ secrets.AWS_ROLE_TO_ASSUME }}
          aws-region: us-west-2

      - uses: anthropics/claude-code-action@v1
        with:
          github_token: ${{ steps.app-token.outputs.token }}
          use_bedrock: "true"
          claude_args: '--model us.anthropic.claude-sonnet-4-6 --max-turns 10'
```

The model ID format for Bedrock includes a region prefix (for example, `us.anthropic.claude-sonnet-4-6`).

Google Vertex AI workflow

**Prerequisites:**

- Vertex AI API enabled in your GCP project
- Workload Identity Federation configured for GitHub
- Service account with Vertex AI permissions

**Required GitHub secrets:**

| Secret Name                      | Description                                       |
|----------------------------------|---------------------------------------------------|
| `GCP_WORKLOAD_IDENTITY_PROVIDER` | Workload identity provider resource name          |
| `GCP_SERVICE_ACCOUNT`            | Service account email with Vertex AI access       |
| `APP_ID`                         | Your GitHub App ID (from app settings)            |
| `APP_PRIVATE_KEY`                | The private key you generated for your GitHub App |

```python
name: Claude PR Action

permissions:
  contents: write
  pull-requests: write
  issues: write
  id-token: write

on:
  issue_comment:
    types: [created]
  pull_request_review_comment:
    types: [created]
  issues:
    types: [opened, assigned]

jobs:
  claude-pr:
    if: |
      (github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
      (github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
      (github.event_name == 'issues' && contains(github.event.issue.body, '@claude'))
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Generate GitHub App token
        id: app-token
        uses: actions/create-github-app-token@v2
        with:
          app-id: ${{ secrets.APP_ID }}
          private-key: ${{ secrets.APP_PRIVATE_KEY }}

      - name: Authenticate to Google Cloud
        id: auth
        uses: google-github-actions/auth@v2
        with:
          workload_identity_provider: ${{ secrets.GCP_WORKLOAD_IDENTITY_PROVIDER }}
          service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }}

      - uses: anthropics/claude-code-action@v1
        with:
          github_token: ${{ steps.app-token.outputs.token }}
          trigger_phrase: "@claude"
          use_vertex: "true"
          claude_args: '--model claude-sonnet-4-5@20250929 --max-turns 10'
        env:
          ANTHROPIC_VERTEX_PROJECT_ID: ${{ steps.auth.outputs.project_id }}
          CLOUD_ML_REGION: us-east5
          VERTEX_REGION_CLAUDE_4_5_SONNET: us-east5
```

The project ID is automatically retrieved from the Google Cloud authentication step, so you don’t need to hardcode it.


Troubleshooting


Claude not responding to @claude commands

Verify the GitHub App is installed correctly, check that workflows are enabled, ensure API key is set in repository secrets, and confirm the comment contains `@claude` (not `/claude`).


CI not running on Claude’s commits

Ensure you’re using the GitHub App or custom app (not Actions user), check workflow triggers include the necessary events, and verify app permissions include CI triggers.


Authentication errors

Confirm API key is valid and has sufficient permissions. For Bedrock/Vertex, check credentials configuration and ensure secrets are named correctly in workflows.


Advanced configuration


Action parameters

The Claude Code Action v1 uses a simplified configuration:

| Parameter             | Description                                                             | Required |
|-----------------------|-------------------------------------------------------------------------|----------|
| `prompt`              | Instructions for Claude (plain text or a [skill](/docs/en/skills) name) | No\*     |
| `claude_args`         | CLI arguments passed to Claude Code                                     | No       |
| `plugin_marketplaces` | Newline-separated list of plugin marketplace Git URLs                   | No       |
| `plugins`             | Newline-separated list of plugin names to install before execution      | No       |
| `anthropic_api_key`   | Claude API key                                                          | Yes\*\*  |
| `github_token`        | GitHub token for API access                                             | No       |
| `trigger_phrase`      | Custom trigger phrase (default: “@claude”)                              | No       |
| `use_bedrock`         | Use Amazon Bedrock instead of Claude API                                | No       |
| `use_vertex`          | Use Google Vertex AI instead of Claude API                              | No       |

\*Prompt is optional - when omitted for issue/PR comments, Claude responds to trigger phrase  
\*\*Required for direct Claude API, not for Bedrock/Vertex


Pass CLI arguments

The `claude_args` parameter accepts any Claude Code CLI arguments:

```python
claude_args: "--max-turns 5 --model claude-sonnet-4-6 --mcp-config /path/to/config.json"
```

Common arguments:

- `--max-turns`: Maximum conversation turns (default: 10)
- `--model`: Model to use (for example, `claude-sonnet-4-6`)
- `--mcp-config`: Path to MCP configuration
- `--allowedTools`: Comma-separated list of allowed tools. The `--allowed-tools` alias also works.
- `--debug`: Enable debug output


Alternative integration methods

While the `/install-github-app` command is the recommended approach, you can also:

- **Custom GitHub App**: For organizations needing branded usernames or custom authentication flows. Create your own GitHub App with required permissions (contents, issues, pull requests) and use the actions/create-github-app-token action to generate tokens in your workflows.
- **Manual GitHub Actions**: Direct workflow configuration for maximum flexibility
- **MCP Configuration**: Dynamic loading of Model Context Protocol servers

See the [Claude Code Action documentation](https://github.com/anthropics/claude-code-action/blob/main/docs) for detailed guides on authentication, security, and advanced configuration.


Customizing Claude’s behavior

You can configure Claude’s behavior in two ways:

1.  **CLAUDE.md**: Define coding standards, review criteria, and project-specific rules in a `CLAUDE.md` file at the root of your repository. Claude will follow these guidelines when creating PRs and responding to requests. Check out our [Memory documentation](/docs/en/memory) for more details.
2.  **Custom prompts**: Use the `prompt` parameter in the workflow file to provide workflow-specific instructions. This allows you to customize Claude’s behavior for different workflows or tasks.

Claude will follow these guidelines when creating PRs and responding to requests.


---
## claude-code-gitlab-ci-cd-claude-code-docs-fbcd915fee.md

# Claude Code GitLab CI/CD


Learn about integrating Claude Code into your development workflow with GitLab CI/CD


> ## Documentation Index
>
> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt>
>
> Use this file to discover all available pages before exploring further.

Claude Code for GitLab CI/CD is currently in beta. Features and functionality may evolve as we refine the experience.This integration is maintained by GitLab. For support, see the following [GitLab issue](https://gitlab.com/gitlab-org/gitlab/-/issues/573776).

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?

- **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
- **Project-aware**: Claude follows your `CLAUDE.md` guidelines and existing code patterns
- **Simple setup**: Add one job to `.gitlab-ci.yml` and a masked CI/CD variable
- **Enterprise-ready**: Choose Claude API, Amazon Bedrock, or Google Vertex AI to meet data residency and procurement needs
- **Secure by default**: Runs in your GitLab runners with your branch protection and approvals


How it works

Claude Code uses GitLab CI/CD to run AI tasks in isolated jobs and commit results back via MRs:

1.  **Event-driven orchestration**: GitLab listens for your chosen triggers (for example, a comment that mentions `@claude` in an issue, MR, or review thread). The job collects context from the thread and repository, builds prompts from that input, and runs Claude Code.
2.  **Provider abstraction**: Use the provider that fits your environment:
    - Claude API (SaaS)
    - Amazon Bedrock (IAM-based access, cross-region options)
    - Google Vertex AI (GCP-native, Workload Identity Federation)
3.  **Sandboxed execution**: Each interaction runs in a container with strict network and filesystem rules. Claude Code enforces workspace-scoped permissions to constrain writes. Every change flows through an MR so reviewers see the diff and approvals still apply.

Pick regional endpoints to reduce latency and meet data-sovereignty requirements while using existing cloud agreements.


What can Claude do?

Claude Code enables powerful CI/CD workflows that transform how you work with code:

- Create and update MRs from issue descriptions or comments
- Analyze performance regressions and propose optimizations
- Implement features directly in a branch, then open an MR
- Fix bugs and regressions identified by tests or comments
- Respond to follow-up comments to iterate on requested changes


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.

1.  **Add a masked CI/CD variable**
    - Go to **Settings** → **CI/CD** → **Variables**
    - Add `ANTHROPIC_API_KEY` (masked, protected as needed)
2.  **Add a Claude job to `.gitlab-ci.yml`**

```python
stages:
  - ai

claude:
  stage: ai
  image: node:24-alpine3.21
  # Adjust rules to fit how you want to trigger the job:
  # - manual runs
  # - merge request events
  # - web/API triggers when a comment contains '@claude'
  rules:
    - if: '$CI_PIPELINE_SOURCE == "web"'
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
  variables:
    GIT_STRATEGY: fetch
  before_script:
    - apk update
    - apk add --no-cache git curl bash
    - curl -fsSL https://claude.ai/install.sh | bash
  script:
    # Optional: start a GitLab MCP server if your setup provides one
    - /bin/gitlab-mcp-server || true
    # Use AI_FLOW_* variables when invoking via web/API triggers with context payloads
    - echo "$AI_FLOW_INPUT for $AI_FLOW_CONTEXT on $AI_FLOW_EVENT"
    - >
      claude
      -p "${AI_FLOW_INPUT:-'Review this MR and implement the requested changes'}"
      --permission-mode acceptEdits
      --allowedTools "Bash Read Edit Write mcp__gitlab"
      --debug
```

After adding the job and your `ANTHROPIC_API_KEY` variable, test by running the job manually from **CI/CD** → **Pipelines**, or trigger it from an MR to let Claude propose updates in a branch and open an MR if needed.

To run on Amazon Bedrock or Google Vertex AI instead of the Claude API, see the [Using with Amazon Bedrock & Google Vertex AI](#using-with-amazon-bedrock--google-vertex-ai) section below for authentication and environment setup.


Manual setup (recommended for production)

If you prefer a more controlled setup or need enterprise providers:

1.  **Configure provider access**:
    - **Claude API**: Create and store `ANTHROPIC_API_KEY` as a masked CI/CD variable
    - **Amazon Bedrock**: **Configure GitLab** → **AWS OIDC** and create an IAM role for Bedrock
    - **Google Vertex AI**: **Configure Workload Identity Federation for GitLab** → **GCP**
2.  **Add project credentials for GitLab API operations**:
    - Use `CI_JOB_TOKEN` by default, or create a Project Access Token with `api` scope
    - Store as `GITLAB_ACCESS_TOKEN` (masked) if using a PAT
3.  **Add the Claude job to `.gitlab-ci.yml`** (see examples below)
4.  **(Optional) Enable mention-driven triggers**:
    - Add a project webhook for “Comments (notes)” to your event listener (if you use one)
    - Have the listener call the pipeline trigger API with variables like `AI_FLOW_INPUT` and `AI_FLOW_CONTEXT` when a comment contains `@claude`


Example use cases


Turn issues into MRs

In an issue comment:

```python
@claude implement this feature based on the issue description
```

Claude analyzes the issue and codebase, writes changes in a branch, and opens an MR for review.


Get implementation help

In an MR discussion:

```python
@claude suggest a concrete approach to cache the results of this API call
```

Claude proposes changes, adds code with appropriate caching, and updates the MR.


Fix bugs quickly

In an issue or MR comment:

```python
@claude fix the TypeError in the user dashboard component
```

Claude locates the bug, implements a fix, and updates the branch or opens a new MR.


Using with Amazon Bedrock & Google Vertex AI

For enterprise environments, you can run Claude Code entirely on your cloud infrastructure with the same developer experience.

- Amazon Bedrock

- Google Vertex AI


Prerequisites

Before setting up Claude Code with Amazon Bedrock, you need:

1.  An AWS account with Amazon Bedrock access to the desired Claude models
2.  GitLab configured as an OIDC identity provider in AWS IAM
3.  An IAM role with Bedrock permissions and a trust policy restricted to your GitLab project/refs
4.  GitLab CI/CD variables for role assumption:
    - `AWS_ROLE_TO_ASSUME` (role ARN)
    - `AWS_REGION` (Bedrock region)


Setup instructions

Configure AWS to allow GitLab CI jobs to assume an IAM role via OIDC (no static keys).**Required setup:**

1.  Enable Amazon Bedrock and request access to your target Claude models
2.  Create an IAM OIDC provider for GitLab if not already present
3.  Create an IAM role trusted by the GitLab OIDC provider, restricted to your project and protected refs
4.  Attach least-privilege permissions for Bedrock invoke APIs

**Required values to store in CI/CD variables:**

- `AWS_ROLE_TO_ASSUME`
- `AWS_REGION`

Add variables in Settings → CI/CD → Variables:

```python
# For Amazon Bedrock:
- AWS_ROLE_TO_ASSUME
- AWS_REGION
```

Use the Amazon Bedrock job example above to exchange the GitLab job token for temporary AWS credentials at runtime.


Prerequisites

Before setting up Claude Code with Google Vertex AI, you need:

1.  A Google Cloud project with:
    - Vertex AI API enabled
    - Workload Identity Federation configured to trust GitLab OIDC
2.  A dedicated service account with only the required Vertex AI roles
3.  GitLab CI/CD variables for WIF:
    - `GCP_WORKLOAD_IDENTITY_PROVIDER` (full resource name)
    - `GCP_SERVICE_ACCOUNT` (service account email)


Setup instructions

Configure Google Cloud to allow GitLab CI jobs to impersonate a service account via Workload Identity Federation.**Required setup:**

1.  Enable IAM Credentials API, STS API, and Vertex AI API
2.  Create a Workload Identity Pool and provider for GitLab OIDC
3.  Create a dedicated service account with Vertex AI roles
4.  Grant the WIF principal permission to impersonate the service account

**Required values to store in CI/CD variables:**

- `GCP_WORKLOAD_IDENTITY_PROVIDER`
- `GCP_SERVICE_ACCOUNT`

Add variables in Settings → CI/CD → Variables:

```python
# For Google Vertex AI:
- GCP_WORKLOAD_IDENTITY_PROVIDER
- GCP_SERVICE_ACCOUNT
- CLOUD_ML_REGION (for example, us-east5)
```

Use the Google Vertex AI job example above to authenticate without storing keys.


Configuration examples

Below are ready-to-use snippets you can adapt to your pipeline.


Basic .gitlab-ci.yml (Claude API)

```python
stages:
  - ai

claude:
  stage: ai
  image: node:24-alpine3.21
  rules:
    - if: '$CI_PIPELINE_SOURCE == "web"'
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
  variables:
    GIT_STRATEGY: fetch
  before_script:
    - apk update
    - apk add --no-cache git curl bash
    - curl -fsSL https://claude.ai/install.sh | bash
  script:
    - /bin/gitlab-mcp-server || true
    - >
      claude
      -p "${AI_FLOW_INPUT:-'Summarize recent changes and suggest improvements'}"
      --permission-mode acceptEdits
      --allowedTools "Bash Read Edit Write mcp__gitlab"
      --debug
  # Claude Code will use ANTHROPIC_API_KEY from CI/CD variables
```


Amazon Bedrock job example (OIDC)

**Prerequisites:**

- Amazon Bedrock enabled with access to your chosen Claude model(s)
- GitLab OIDC configured in AWS with a role that trusts your GitLab project and refs
- IAM role with Bedrock permissions (least privilege recommended)

**Required CI/CD variables:**

- `AWS_ROLE_TO_ASSUME`: ARN of the IAM role for Bedrock access
- `AWS_REGION`: Bedrock region (for example, `us-west-2`)

```python
claude-bedrock:
  stage: ai
  image: node:24-alpine3.21
  rules:
    - if: '$CI_PIPELINE_SOURCE == "web"'
  before_script:
    - apk add --no-cache bash curl jq git python3 py3-pip
    - pip install --no-cache-dir awscli
    - curl -fsSL https://claude.ai/install.sh | bash
    # Exchange GitLab OIDC token for AWS credentials
    - export AWS_WEB_IDENTITY_TOKEN_FILE="${CI_JOB_JWT_FILE:-/tmp/oidc_token}"
    - if [ -n "${CI_JOB_JWT_V2}" ]; then printf "%s" "$CI_JOB_JWT_V2" > "$AWS_WEB_IDENTITY_TOKEN_FILE"; fi
    - >
      aws sts assume-role-with-web-identity
      --role-arn "$AWS_ROLE_TO_ASSUME"
      --role-session-name "gitlab-claude-$(date +%s)"
      --web-identity-token "file://$AWS_WEB_IDENTITY_TOKEN_FILE"
      --duration-seconds 3600 > /tmp/aws_creds.json
    - export AWS_ACCESS_KEY_ID="$(jq -r .Credentials.AccessKeyId /tmp/aws_creds.json)"
    - export AWS_SECRET_ACCESS_KEY="$(jq -r .Credentials.SecretAccessKey /tmp/aws_creds.json)"
    - export AWS_SESSION_TOKEN="$(jq -r .Credentials.SessionToken /tmp/aws_creds.json)"
  script:
    - /bin/gitlab-mcp-server || true
    - >
      claude
      -p "${AI_FLOW_INPUT:-'Implement the requested changes and open an MR'}"
      --permission-mode acceptEdits
      --allowedTools "Bash Read Edit Write mcp__gitlab"
      --debug
  variables:
    AWS_REGION: "us-west-2"
```

Model IDs for 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.


Google Vertex AI job example (Workload Identity Federation)

**Prerequisites:**

- Vertex AI API enabled in your GCP project
- Workload Identity Federation configured to trust GitLab OIDC
- A service account with Vertex AI permissions

**Required CI/CD variables:**

- `GCP_WORKLOAD_IDENTITY_PROVIDER`: Full provider resource name
- `GCP_SERVICE_ACCOUNT`: Service account email
- `CLOUD_ML_REGION`: Vertex region (for example, `us-east5`)

```python
claude-vertex:
  stage: ai
  image: gcr.io/google.com/cloudsdktool/google-cloud-cli:slim
  rules:
    - if: '$CI_PIPELINE_SOURCE == "web"'
  before_script:
    - apt-get update && apt-get install -y git && apt-get clean
    - curl -fsSL https://claude.ai/install.sh | bash
    # Authenticate to Google Cloud via WIF (no downloaded keys)
    - >
      gcloud auth login --cred-file=<(cat <<EOF
      {
        "type": "external_account",
        "audience": "${GCP_WORKLOAD_IDENTITY_PROVIDER}",
        "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
        "service_account_impersonation_url": "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${GCP_SERVICE_ACCOUNT}:generateAccessToken",
        "token_url": "https://sts.googleapis.com/v1/token"
      }
      EOF
      )
    - gcloud config set project "$(gcloud projects list --format='value(projectId)' --filter="name:${CI_PROJECT_NAMESPACE}" | head -n1)" || true
  script:
    - /bin/gitlab-mcp-server || true
    - >
      CLOUD_ML_REGION="${CLOUD_ML_REGION:-us-east5}"
      claude
      -p "${AI_FLOW_INPUT:-'Review and update code as requested'}"
      --permission-mode acceptEdits
      --allowedTools "Bash Read Edit Write mcp__gitlab"
      --debug
  variables:
    CLOUD_ML_REGION: "us-east5"
```

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

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

**Never commit API keys or cloud credentials to your repository**. Always use GitLab CI/CD variables:

- Add `ANTHROPIC_API_KEY` as a masked variable (and protect it if needed)
- Use provider-specific OIDC where possible (no long-lived keys)
- Limit job permissions and network egress
- Review Claude’s MRs like any other contributor


Optimizing performance

- Keep `CLAUDE.md` focused and concise
- Provide clear issue/MR descriptions to reduce iterations
- Configure sensible job timeouts to avoid runaway runs
- Cache npm and package installs in runners where possible


CI costs

When using Claude Code with GitLab CI/CD, be aware of associated costs:

- **GitLab Runner time**:
  - Claude runs on your GitLab runners and consumes compute minutes
  - See your GitLab plan’s runner billing for details
- **API costs**:
  - Each Claude interaction consumes tokens based on prompt and response size
  - Token usage varies by task complexity and codebase size
  - See [Anthropic pricing](../17-Billing-Plans/about-claude-pricing-820bbf24dd.md) for details
- **Cost optimization tips**:
  - Use specific `@claude` commands to reduce unnecessary turns
  - Set appropriate `max_turns` and job timeout values
  - Limit concurrency to control parallel runs


Security and governance

- Each job runs in an isolated container with restricted network access
- Claude’s changes flow through MRs so reviewers see every diff
- Branch protection and approval rules apply to AI-generated code
- Claude Code uses workspace-scoped permissions to constrain writes
- Costs remain under your control because you bring your own provider credentials


Troubleshooting


Claude not responding to @claude commands

- Verify your pipeline is being triggered (manually, MR event, or via a note event listener/webhook)
- Ensure CI/CD variables (`ANTHROPIC_API_KEY` or cloud provider settings) are present and unmasked
- Check that the comment contains `@claude` (not `/claude`) and that your mention trigger is configured


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

- **For Claude API**: Confirm `ANTHROPIC_API_KEY` is valid and unexpired
- **For Bedrock/Vertex**: Verify OIDC/WIF configuration, role impersonation, and secret names; confirm region and model availability


Advanced configuration


Common parameters and variables

Claude Code supports these commonly used inputs:

- `prompt` / `prompt_file`: Provide instructions inline (`-p`) or via a file
- `max_turns`: Limit the number of back-and-forth iterations
- `timeout_minutes`: Limit total execution time
- `ANTHROPIC_API_KEY`: Required for the Claude API (not used for Bedrock/Vertex)
- Provider-specific environment: `AWS_REGION`, project/region vars for Vertex

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

You can guide Claude in two primary ways:

1.  **CLAUDE.md**: Define coding standards, security requirements, and project conventions. Claude reads this during runs and follows your rules.
2.  **Custom prompts**: Pass task-specific instructions via `prompt`/`prompt_file` in the job. Use different prompts for different jobs (for example, review, implement, refactor).


---
## claude-code-on-amazon-bedrock-claude-code-docs.md

# Claude Code on Amazon Bedrock


Learn about configuring Claude Code through Amazon Bedrock, including setup, IAM configuration, and troubleshooting.


## 

Prerequisites

Before configuring Claude Code with Bedrock, ensure you have:

- An AWS account with Bedrock access enabled
- Access to desired Claude models (for example, Claude Sonnet 4.6) in Bedrock
- AWS CLI installed and configured (optional - only needed if you don’t have another mechanism for getting credentials)
- Appropriate IAM permissions

If you are deploying Claude Code to multiple users, [pin your model versions](#4-pin-model-versions) to prevent breakage when Anthropic releases new models.

## 

Setup

### 

1. Submit use case details

First-time users of Anthropic models are required to submit use case details before invoking a model. This is done once per account.

1.  Ensure you have the right IAM permissions (see more on that below)
2.  Navigate to the [Amazon Bedrock console](https://console.aws.amazon.com/bedrock/)
3.  Select **Chat/Text playground**
4.  Choose any Anthropic model and you will be prompted to fill out the use case form

### 

2. Configure AWS credentials

Claude Code uses the default AWS SDK credential chain. Set up your credentials using one of these methods: **Option A: AWS CLI configuration**

Report incorrect code

Copy


``` shiki
aws configure
```

**Option B: Environment variables (access key)**

Report incorrect code

Copy


``` shiki
export AWS_ACCESS_KEY_ID=your-access-key-id
export AWS_SECRET_ACCESS_KEY=your-secret-access-key
export AWS_SESSION_TOKEN=your-session-token
```

**Option C: Environment variables (SSO profile)**

Report incorrect code

Copy


``` shiki
aws sso login --profile=<your-profile-name>

export AWS_PROFILE=your-profile-name
```

**Option D: AWS Management Console credentials**

Report incorrect code

Copy


``` shiki
aws login
```

[Learn more](https://docs.aws.amazon.com/signin/latest/userguide/command-line-sign-in.html) about `aws login`. **Option E: Bedrock API keys**

Report incorrect code

Copy


``` shiki
export AWS_BEARER_TOKEN_BEDROCK=your-bedrock-api-key
```

Bedrock API keys provide a simpler authentication method without needing full AWS credentials. [Learn more about Bedrock API keys](https://aws.amazon.com/blogs/machine-learning/accelerate-ai-development-with-amazon-bedrock-api-keys/).

#### 

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). When Claude Code detects that your AWS credentials are expired (either locally based on their timestamp or when Bedrock returns a credential error), it will automatically run your configured `awsAuthRefresh` and/or `awsCredentialExport` commands to obtain new credentials before retrying the request.

##### Example configuration

Report incorrect code

Copy


``` shiki
{
  "awsAuthRefresh": "aws sso login --profile myprofile",
  "env": {
    "AWS_PROFILE": "myprofile"
  }
}
```

##### Configuration settings explained

**`awsAuthRefresh`**: Use this for commands that modify the `.aws` directory, such as updating credentials, SSO cache, or config files. The command’s output is displayed to the user, but interactive input isn’t supported. This works well for browser-based SSO flows where the CLI displays a URL or code and you complete authentication in the browser. **`awsCredentialExport`**: Only use this if you can’t modify `.aws` and must directly return credentials. Output is captured silently and not shown to the user. The command must output JSON in this format:

Report incorrect code

Copy


``` shiki
{
  "Credentials": {
    "AccessKeyId": "value",
    "SecretAccessKey": "value",
    "SessionToken": "value"
  }
}
```

### 

3. Configure Claude Code

Set the following environment variables to enable Bedrock:

Report incorrect code

Copy


``` shiki
# Enable Bedrock integration
export CLAUDE_CODE_USE_BEDROCK=1
export AWS_REGION=us-east-1  # or your preferred region

# Optional: Override the region for the small/fast model (Haiku)
export ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION=us-west-2
```

When enabling Bedrock for Claude Code, keep the following in mind:

- `AWS_REGION` is a required environment variable. Claude Code does not read from the `.aws` config file for this setting.
- When using Bedrock, the `/login` and `/logout` commands are disabled since authentication is handled through AWS credentials.
- 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

Pin specific model versions for every deployment. If you use model aliases (`sonnet`, `opus`, `haiku`) without pinning, Claude Code may attempt to use a newer model version that isn’t available in your Bedrock account, breaking existing users when Anthropic releases updates.

Set these environment variables to specific Bedrock model IDs:

Report incorrect code

Copy


``` shiki
export ANTHROPIC_DEFAULT_OPUS_MODEL='us.anthropic.claude-opus-4-6-v1'
export ANTHROPIC_DEFAULT_SONNET_MODEL='us.anthropic.claude-sonnet-4-6'
export ANTHROPIC_DEFAULT_HAIKU_MODEL='us.anthropic.claude-haiku-4-5-20251001-v1:0'
```

These variables use cross-region inference profile IDs (with the `us.` prefix). If you use a different region prefix or application inference profiles, adjust accordingly. For current and legacy model IDs, see [Models overview](../20-Models/about-claude-models-overview.md). See [Model configuration](/docs/en/model-config#pin-models-for-third-party-deployments) for the full list of environment variables. Claude Code uses these default models when no pinning variables are set:

| Model type       | Default value                                 |
|:-----------------|:----------------------------------------------|
| Primary model    | `global.anthropic.claude-sonnet-4-6`          |
| Small/fast model | `us.anthropic.claude-haiku-4-5-20251001-v1:0` |

To customize models further, use one of these methods:

Report incorrect code

Copy


``` shiki
# Using inference profile ID
export ANTHROPIC_MODEL='global.anthropic.claude-sonnet-4-6'
export ANTHROPIC_SMALL_FAST_MODEL='us.anthropic.claude-haiku-4-5-20251001-v1:0'

# Using application inference profile ARN
export ANTHROPIC_MODEL='arn:aws:bedrock:us-east-2:your-account-id:application-inference-profile/your-model-id'

# Optional: Disable prompt caching if needed
export DISABLE_PROMPT_CACHING=1
```

[Prompt caching](../10-Prompting-Guides/build-with-claude-prompt-caching.md) may not be available in all regions.

#### 

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#settings-files) instead. This example maps three Opus versions to distinct ARNs so users can switch between them without bypassing your organization’s inference profiles:

Report incorrect code

Copy


``` shiki
{
  "modelOverrides": {
    "claude-opus-4-6": "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/opus-46-prod",
    "claude-opus-4-5-20251101": "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/opus-45-prod",
    "claude-opus-4-1-20250805": "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/opus-41-prod"
  }
}
```

When a user selects one of these versions in `/model`, Claude Code calls Bedrock with the mapped ARN. Versions without an override fall back to the built-in Bedrock model ID or any matching inference profile discovered at startup. 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.

## 

IAM configuration

Create an IAM policy with the required permissions for Claude Code:

Report incorrect code

Copy


``` shiki
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowModelAndInferenceProfileAccess",
      "Effect": "Allow",
      "Action": [
        "bedrock:InvokeModel",
        "bedrock:InvokeModelWithResponseStream",
        "bedrock:ListInferenceProfiles"
      ],
      "Resource": [
        "arn:aws:bedrock:*:*:inference-profile/*",
        "arn:aws:bedrock:*:*:application-inference-profile/*",
        "arn:aws:bedrock:*:*:foundation-model/*"
      ]
    },
    {
      "Sid": "AllowMarketplaceSubscription",
      "Effect": "Allow",
      "Action": [
        "aws-marketplace:ViewSubscriptions",
        "aws-marketplace:Subscribe"
      ],
      "Resource": "*",
      "Condition": {
        "StringEquals": {
          "aws:CalledViaLast": "bedrock.amazonaws.com"
        }
      }
    }
  ]
}
```

For more restrictive permissions, you can limit the Resource to specific inference profile ARNs. For details, see [Bedrock IAM documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/security-iam.html).

Create a dedicated AWS account for Claude Code to simplify cost tracking and access control.

## 

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/), publish a version, then add the Guardrail headers to your [settings file](/docs/en/settings). Enable Cross-Region inference on your Guardrail if you’re using cross-region inference profiles. Example configuration:

Report incorrect code

Copy


``` shiki
{
  "env": {
    "ANTHROPIC_CUSTOM_HEADERS": "X-Amzn-Bedrock-GuardrailIdentifier: your-guardrail-id\nX-Amzn-Bedrock-GuardrailVersion: 1"
  }
}
```

## 

Troubleshooting

If you encounter region issues:

- Check model availability: `aws bedrock list-inference-profiles --region your-region`
- Switch to a supported region: `export AWS_REGION=us-east-1`
- Consider using inference profiles for cross-region access

If you receive an error “on-demand throughput isn’t supported”:

- Specify the model as an [inference profile](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html) ID

Claude Code uses the Bedrock [Invoke API](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithResponseStream.html) and does not support the Converse API.

## 

Additional resources

- [Bedrock documentation](https://docs.aws.amazon.com/bedrock/)
- [Bedrock pricing](https://aws.amazon.com/bedrock/pricing/)
- [Bedrock inference profiles](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html)
- [Claude Code on Amazon Bedrock: Quick Setup Guide](https://community.aws/content/2tXkZKrZzlrlu0KfH8gST5Dkppq/claude-code-on-amazon-bedrock-quick-setup-guide)- [Claude Code Monitoring Implementation (Bedrock)](https://github.com/aws-solutions-library-samples/guidance-for-claude-code-with-amazon-bedrock/blob/main/assets/docs/MONITORING.md)


---
## claude-code-on-google-vertex-ai-claude-code-docs.md

# Claude Code on Google Vertex AI


Learn about configuring Claude Code through Google Vertex AI, including setup, IAM configuration, and troubleshooting.


## 

Prerequisites

Before configuring Claude Code with Vertex AI, ensure you have:

- A Google Cloud Platform (GCP) account with billing enabled
- A GCP project with Vertex AI API enabled
- Access to desired Claude models (for example, Claude Sonnet 4.6)
- Google Cloud SDK (`gcloud`) installed and configured
- Quota allocated in desired GCP region

If you are deploying Claude Code to multiple users, [pin your model versions](#5-pin-model-versions) to prevent breakage when Anthropic releases new models.

## 

Region Configuration

Claude Code can be used with both Vertex AI [global](https://cloud.google.com/blog/products/ai-machine-learning/global-endpoint-for-claude-models-generally-available-on-vertex-ai) and regional endpoints.

Vertex AI may not support the Claude Code default models in all [regions](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations#genai-partner-models) or on [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 region, use a regional endpoint, or specify a supported model.

## 

Setup

### 

1. Enable Vertex AI API

Enable the Vertex AI API in your GCP project:

Report incorrect code

Copy


``` shiki
# Set your project ID
gcloud config set project YOUR-PROJECT-ID

# Enable Vertex AI API
gcloud services enable aiplatform.googleapis.com
```

### 

2. Request model access

Request access to Claude models in Vertex AI:

1.  Navigate to the [Vertex AI Model Garden](https://console.cloud.google.com/vertex-ai/model-garden)
2.  Search for “Claude” models
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

Claude Code uses standard Google Cloud authentication. For more information, see [Google Cloud authentication documentation](https://cloud.google.com/docs/authentication).

When authenticating, Claude Code will automatically use the project ID from the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable. To override this, set one of these environment variables: `GCLOUD_PROJECT`, `GOOGLE_CLOUD_PROJECT`, or `GOOGLE_APPLICATION_CREDENTIALS`.

### 

4. Configure Claude Code

Set the following environment variables:

Report incorrect code

Copy


``` shiki
# Enable Vertex AI integration
export CLAUDE_CODE_USE_VERTEX=1
export CLOUD_ML_REGION=global
export ANTHROPIC_VERTEX_PROJECT_ID=YOUR-PROJECT-ID

# Optional: Disable prompt caching if needed
export DISABLE_PROMPT_CACHING=1

# When CLOUD_ML_REGION=global, override region for unsupported models
export VERTEX_REGION_CLAUDE_3_5_HAIKU=us-east5

# Optional: Override regions for other specific models
export VERTEX_REGION_CLAUDE_3_5_SONNET=us-east5
export VERTEX_REGION_CLAUDE_3_7_SONNET=us-east5
export VERTEX_REGION_CLAUDE_4_0_OPUS=europe-west1
export VERTEX_REGION_CLAUDE_4_0_SONNET=us-east5
export VERTEX_REGION_CLAUDE_4_1_OPUS=europe-west1
```

[Prompt caching](../10-Prompting-Guides/build-with-claude-prompt-caching.md) is automatically supported when you specify the `cache_control` ephemeral flag. To disable it, set `DISABLE_PROMPT_CACHING=1`. For heightened rate limits, contact Google Cloud support. When using Vertex AI, the `/login` and `/logout` commands are disabled since authentication is handled through Google Cloud credentials.

### 

5. Pin model versions

Pin specific model versions for every deployment. If you use model aliases (`sonnet`, `opus`, `haiku`) without pinning, Claude Code may attempt to use a newer model version that isn’t enabled in your Vertex AI project, breaking existing users when Anthropic releases updates.

Set these environment variables to specific Vertex AI model IDs:

Report incorrect code

Copy


``` shiki
export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-6'
export ANTHROPIC_DEFAULT_SONNET_MODEL='claude-sonnet-4-6'
export ANTHROPIC_DEFAULT_HAIKU_MODEL='claude-haiku-4-5@20251001'
```

For current and legacy model IDs, see [Models overview](../20-Models/about-claude-models-overview.md). See [Model configuration](/docs/en/model-config#pin-models-for-third-party-deployments) for the full list of environment variables. Claude Code uses these default models when no pinning variables are set:

| Model type       | Default value               |
|:-----------------|:----------------------------|
| Primary model    | `claude-sonnet-4-6`         |
| Small/fast model | `claude-haiku-4-5@20251001` |

To customize models further:

Report incorrect code

Copy


``` shiki
export ANTHROPIC_MODEL='claude-opus-4-6'
export ANTHROPIC_SMALL_FAST_MODEL='claude-haiku-4-5@20251001'
```

## 

IAM configuration

Assign the required IAM permissions: The `roles/aiplatform.user` role includes the required permissions:

- `aiplatform.endpoints.predict` - Required for model invocation and token counting

For more restrictive permissions, create a custom role with only the permissions above. For details, see [Vertex IAM documentation](https://cloud.google.com/vertex-ai/docs/general/access-control).

Create a dedicated GCP project for Claude Code to simplify cost tracking and access control.

## 

1M token context window

Claude Opus 4.6, Sonnet 4.6, Sonnet 4.5, and Sonnet 4 support the [1M token context window](../04-API-Reference/Guides/build-with-claude-context-windows-13ca780d1d.md#1m-token-context-window) on Vertex AI. Claude Code automatically enables the extended context window when you select a 1M model variant. To enable the 1M context window for your pinned model, 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.

## 

Troubleshooting

If you encounter quota issues:

- Check current quotas or request quota increase through [Cloud Console](https://cloud.google.com/docs/quotas/view-manage)

If you encounter “model not found” 404 errors:

- Confirm model is Enabled in [Model Garden](https://console.cloud.google.com/vertex-ai/model-garden)
- Verify you have access to the specified region
- If using `CLOUD_ML_REGION=global`, check that your models support global endpoints in [Model Garden](https://console.cloud.google.com/vertex-ai/model-garden) under “Supported features”. For models that don’t support global endpoints, either:
  - Specify a supported model via `ANTHROPIC_MODEL` or `ANTHROPIC_SMALL_FAST_MODEL`, or
  - Set a regional endpoint using `VERTEX_REGION_<MODEL_NAME>` environment variables

If you encounter 429 errors:

- 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

- [Vertex AI documentation](https://cloud.google.com/vertex-ai/docs)
- [Vertex AI pricing](https://cloud.google.com/vertex-ai/pricing)
- [Vertex AI quotas and limits](https://cloud.google.com/vertex-ai/docs/quotas)


---
## claude-code-on-microsoft-foundry-claude-code-docs.md

# Claude Code on Microsoft Foundry


Learn about configuring Claude Code through Microsoft Foundry, including setup, configuration, and troubleshooting.


## 

Prerequisites

Before configuring Claude Code with Microsoft Foundry, ensure you have:

- An Azure subscription with access to Microsoft Foundry
- RBAC permissions to create Microsoft Foundry resources and deployments
- Azure CLI installed and configured (optional - only needed if you don’t have another mechanism for getting credentials)

If you are deploying Claude Code to multiple users, [pin your model versions](#4-pin-model-versions) to prevent breakage when Anthropic releases new models.

## 

Setup

### 

1. Provision Microsoft Foundry resource

First, create a Claude resource in Azure:

1.  Navigate to the [Microsoft Foundry portal](https://ai.azure.com/)
2.  Create a new resource, noting your resource name
3.  Create deployments for the Claude models:
    - Claude Opus
    - Claude Sonnet
    - Claude Haiku

### 

2. Configure Azure credentials

Claude Code supports two authentication methods for Microsoft Foundry. Choose the method that best fits your security requirements. **Option A: API key authentication**

1.  Navigate to your resource in the Microsoft Foundry portal
2.  Go to the **Endpoints and keys** section
3.  Copy **API Key**
4.  Set the environment variable:

Report incorrect code

Copy


``` shiki
export ANTHROPIC_FOUNDRY_API_KEY=your-azure-api-key
```

**Option B: Microsoft Entra ID authentication** When `ANTHROPIC_FOUNDRY_API_KEY` is not set, Claude Code automatically 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 local environments, you commonly may use the Azure CLI:

Report incorrect code

Copy


``` shiki
az login
```

When using Microsoft Foundry, the `/login` and `/logout` commands are disabled since authentication is handled through Azure credentials.

### 

3. Configure Claude Code

Set the following environment variables to enable Microsoft Foundry:

Report incorrect code

Copy


``` shiki
# Enable Microsoft Foundry integration
export CLAUDE_CODE_USE_FOUNDRY=1

# Azure resource name (replace {resource} with your resource name)
export ANTHROPIC_FOUNDRY_RESOURCE={resource}
# Or provide the full base URL:
# export ANTHROPIC_FOUNDRY_BASE_URL=https://{resource}.services.ai.azure.com/anthropic
```

### 

4. Pin model versions

Pin specific model versions for every deployment. If you use model aliases (`sonnet`, `opus`, `haiku`) without pinning, Claude Code may attempt to use a newer model version that isn’t available in your Foundry account, breaking existing users when Anthropic releases updates. When you create Azure deployments, select a specific model version rather than “auto-update to latest.”

Set the model variables to match the deployment names you created in step 1:

Report incorrect code

Copy


``` shiki
export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-6'
export ANTHROPIC_DEFAULT_SONNET_MODEL='claude-sonnet-4-6'
export ANTHROPIC_DEFAULT_HAIKU_MODEL='claude-haiku-4-5'
```

For current and legacy model IDs, see [Models overview](../20-Models/about-claude-models-overview.md). See [Model configuration](/docs/en/model-config#pin-models-for-third-party-deployments) for the full list of environment variables.

## 

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:

Report incorrect code

Copy


``` shiki
{
  "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).

## 

Troubleshooting

If you receive an error “Failed to get token from azureADTokenProvider: ChainedTokenCredential authentication failed”:

- Configure Entra ID on the environment, or set `ANTHROPIC_FOUNDRY_API_KEY`.

## 

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)
- [Microsoft Foundry pricing](https://azure.microsoft.com/en-us/pricing/details/ai-foundry/)


---
## claude-code-on-the-web-69d53821d4.md

> ## Documentation Index
> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Use Claude Code on the web

> Configure cloud environments, setup scripts, network access, and Docker in Anthropic's sandbox. Move sessions between web and terminal with `--remote` and `--teleport`.

<Note>
  Claude Code on the web is in research preview for Pro, Max, and Team users, and for Enterprise users with premium seats or Chat + Claude Code seats.
</Note>

Claude Code on the web runs tasks on Anthropic-managed cloud infrastructure at [claude.ai/code](https://claude.ai/code). Sessions persist even if you close your browser, and you can monitor them from the Claude mobile app.

<Tip>
  New to Claude Code on the web? Start with [Get started](web-quickstart-de55c74651.md) to connect your GitHub account and submit your first task.
</Tip>

This page covers:

* [GitHub authentication options](#github-authentication-options): two ways to connect GitHub
* [The cloud environment](#the-cloud-environment): what config carries over, what tools are installed, and how to configure environments
* [Setup scripts](#setup-scripts) and dependency management
* [Network access](#network-access): levels, proxies, and the default allowlist
* [Move tasks between web and terminal](#move-tasks-between-web-and-terminal) with `--remote` and `--teleport`
* [Work with sessions](#work-with-sessions): reviewing, sharing, archiving, deleting
* [Auto-fix pull requests](#auto-fix-pull-requests): respond automatically to CI failures and review comments
* [Security and isolation](#security-and-isolation): how sessions are isolated
* [Limitations](#limitations): rate limits and platform restrictions

## GitHub authentication options

Cloud sessions need access to your GitHub repositories to clone code and push branches. You can grant access in two ways:

| Method           | How it works                                                                                                                                 | Best for                                        |
| :--------------- | :------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------- |
| **GitHub App**   | Install the Claude GitHub App on specific repositories during [web onboarding](web-quickstart-de55c74651.md). Access is scoped per repository.         | Teams that want explicit per-repo authorization |
| **`/web-setup`** | Run `/web-setup` in your terminal to sync your local `gh` CLI token to your Claude account. Access matches whatever your `gh` token can see. | Individual developers who already use `gh`      |

Either method works. [`/schedule`](routines-3111c7bd3a.md) checks for either form of access and prompts you to run `/web-setup` if neither is configured. See [Connect from your terminal](/en/web-quickstart#connect-from-your-terminal) for the `/web-setup` walkthrough.

The GitHub App is required for [Auto-fix](#auto-fix-pull-requests), which uses the App to receive PR webhooks. If you connect with `/web-setup` and later want Auto-fix, install the App on those repositories.

Team and Enterprise admins can disable `/web-setup` with the Quick web setup toggle at [claude.ai/admin-settings/claude-code](https://claude.ai/admin-settings/claude-code).

<Note>
  Organizations with [Zero Data Retention](../22-Safety-Policy/zero-data-retention-claude-code-docs-6ec9ee63f1.md) enabled cannot use `/web-setup` or other cloud session features.
</Note>

## The cloud environment

Each session runs in a fresh Anthropic-managed VM with your repository cloned. This section covers what's available when a session starts and how to customize it.

### What's available in cloud sessions

Cloud sessions start from a fresh clone of your repository. Anything committed to the repo is available. Anything you've installed or configured only on your own machine is not.

|                                                                       | Available in cloud sessions | Why                                                                                                                                              |
| :-------------------------------------------------------------------- | :-------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------- |
| Your repo's `CLAUDE.md`                                               | Yes                         | Part of the clone                                                                                                                                |
| Your repo's `.claude/settings.json` hooks                             | Yes                         | Part of the clone                                                                                                                                |
| Your repo's `.mcp.json` MCP servers                                   | Yes                         | Part of the clone                                                                                                                                |
| Your repo's `.claude/rules/`                                          | Yes                         | Part of the clone                                                                                                                                |
| Your repo's `.claude/skills/`, `.claude/agents/`, `.claude/commands/` | Yes                         | Part of the clone                                                                                                                                |
| Plugins declared in `.claude/settings.json`                           | Yes                         | Installed at session start from the [marketplace](../08-Plugins-Skills/create-and-distribute-a-plugin-marketplace-claude-code-docs-34a8f3c5e8.md) you declared. Requires network access to reach the marketplace source |
| Your user `~/.claude/CLAUDE.md`                                       | No                          | Lives on your machine, not in the repo                                                                                                           |
| Plugins enabled only in your user settings                            | No                          | User-scoped `enabledPlugins` lives in `~/.claude/settings.json`. Declare them in the repo's `.claude/settings.json` instead                      |
| MCP servers you added with `claude mcp add`                           | No                          | Those write to your local user config, not the repo. Declare the server in [`.mcp.json`](/en/mcp#project-scope) instead                          |
| Static API tokens and credentials                                     | No                          | No dedicated secrets store exists yet. See below                                                                                                 |
| Interactive auth like AWS SSO                                         | No                          | Not supported. SSO requires browser-based login that can't run in a cloud session                                                                |

To make configuration available in cloud sessions, commit it to the repo. A dedicated secrets store is not yet available. Both environment variables and setup scripts are stored in the environment configuration, visible to anyone who can edit that environment. If you need secrets in a cloud session, add them as environment variables with that visibility in mind.

### Installed tools

Cloud sessions come with common language runtimes, build tools, and databases pre-installed. The table below summarizes what's included by category.

| Category      | Included                                                                           |
| :------------ | :--------------------------------------------------------------------------------- |
| **Python**    | Python 3.x with pip, poetry, uv, black, mypy, pytest, ruff                         |
| **Node.js**   | 20, 21, and 22 via nvm, with npm, yarn, pnpm, bun¹, eslint, prettier, chromedriver |
| **Ruby**      | 3.1, 3.2, 3.3 with gem, bundler, rbenv                                             |
| **PHP**       | 8.4 with Composer                                                                  |
| **Java**      | OpenJDK 21 with Maven and Gradle                                                   |
| **Go**        | latest stable with module support                                                  |
| **Rust**      | rustc and cargo                                                                    |
| **C/C++**     | GCC, Clang, cmake, ninja, conan                                                    |
| **Docker**    | docker, dockerd, docker compose                                                    |
| **Databases** | PostgreSQL 16, Redis 7.0                                                           |
| **Utilities** | git, jq, yq, ripgrep, tmux, vim, nano                                              |

¹ Bun is installed but has known [proxy compatibility issues](#install-dependencies-with-a-sessionstart-hook) for package fetching.

For exact versions, ask Claude to run `check-tools` in a cloud session. This command only exists in cloud sessions.

### 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](#github-proxy) using whichever method you configured under [GitHub authentication options](#github-authentication-options), so your token never enters the container.

The `gh` CLI is not pre-installed. If you need a `gh` command the built-in tools don't cover, like `gh release` or `gh workflow run`, install and authenticate it yourself:

<Steps>
  <Step title="Install gh in your setup script">
    Add `apt update && apt install -y gh` to your [setup script](#setup-scripts).
  </Step>

  <Step title="Provide a token">
    Add a `GH_TOKEN` environment variable to your [environment settings](#configure-your-environment) with a GitHub personal access token. `gh` reads `GH_TOKEN` automatically, so no `gh auth login` step is needed.
  </Step>
</Steps>

### Link artifacts 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.

Ask Claude to construct the link from the environment variable. The following command prints the URL:

```bash theme={null}
echo "https://claude.ai/code/${CLAUDE_CODE_REMOTE_SESSION_ID}"
```

### Run tests, start services, and add packages

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 like pytest, jest, and cargo test work out of the box since they're pre-installed.

PostgreSQL and Redis are pre-installed but not running by default. Ask Claude to start each one during the session:

```bash theme={null}
service postgresql start
```

```bash theme={null}
service redis-server start
```

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](#access-levels), and the [Trusted defaults](#default-allowed-domains) include 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](#setup-scripts). The pulled images are saved in the [cached environment](#environment-caching), so each new session has them on disk. The cache stores files only, not running processes, so Claude still starts the containers each session.

To add packages that aren't pre-installed, use a [setup script](#setup-scripts). The script's output is [cached](#environment-caching), 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

Cloud sessions run with approximate resource ceilings that may change over time:

* 4 vCPUs
* 16 GB of RAM
* 30 GB of disk

Tasks requiring significantly more memory, such as large build jobs or memory-intensive tests, may fail or be terminated. For workloads beyond these limits, use [Remote Control](continue-local-sessions-from-any-device-with-remote-control-claude-code-docs-c1c03fd914.md) to run Claude Code on your own hardware.

### Configure your environment

Environments control [network access](#network-access), environment variables, and the [setup script](#setup-scripts) that runs before a session starts. See [Installed tools](#installed-tools) for what's available without any configuration. You can manage environments from the web interface or the terminal:

| Action                         | How                                                                                                                                                                                                                      |
| :----------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Add an environment             | Select the current environment to open the selector, then select **Add environment**. The dialog includes name, network access level, environment variables, and setup script.                                           |
| Edit an environment            | Select the settings icon to the right of the environment name.                                                                                                                                                           |
| Archive an environment         | Open the environment for editing and select **Archive**. Archived environments are hidden from the selector but existing sessions keep running.                                                                          |
| Set the default for `--remote` | Run `/remote-env` in your terminal. If you have a single environment, this command shows your current configuration. `/remote-env` only selects the default; add, edit, and archive environments from the web interface. |

Environment variables use `.env` format with one `KEY=value` pair per line. Don't wrap values in quotes, since quotes are stored as part of the value.

```text theme={null}
NODE_ENV=development
LOG_LEVEL=debug
DATABASE_URL=postgres://localhost:5432/myapp
```

## 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.

To add a setup script, open the environment settings dialog and enter your script in the **Setup script** field.

This example installs the `gh` CLI, which isn't pre-installed:

```bash theme={null}
#!/bin/bash
apt update && apt install -y gh
```

If the script exits non-zero, the session fails to start. Append `|| true` to non-critical commands to avoid blocking the session on an intermittent install failure.

<Note>
  Setup scripts that install packages need network access to reach registries. The default **Trusted** network access allows connections to [common package registries](#default-allowed-domains) including npm, PyPI, RubyGems, and crates.io. Scripts will fail to install packages if your environment uses **None** network access.
</Note>

### Environment caching

The setup script runs the first time you start a session in an environment. After it completes, 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 the setup script step is skipped. This keeps startup fast even when the script installs large toolchains or pulls container images.

The cache captures files, not running processes. Anything the setup script writes to disk carries over. Services or containers it starts do not, so start those per session by asking Claude or with a [SessionStart hook](#setup-scripts-vs-sessionstart-hooks).

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. Resuming an existing session never re-runs the setup script.

You don't need to enable caching or manage snapshots yourself.

### Setup scripts vs. SessionStart hooks

Use a setup script to install things the cloud needs but your laptop already has, like a language runtime or CLI tool. Use a [SessionStart hook](/en/hooks#sessionstart) for project setup that should run everywhere, cloud and local, like `npm install`.

Both run at the start of a session, but they belong to different places:

|               | Setup scripts                                                                                | SessionStart hooks                                             |
| ------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |
| Attached to   | The cloud environment                                                                        | Your repository                                                |
| Configured in | Cloud environment UI                                                                         | `.claude/settings.json` in your repo                           |
| Runs          | Before Claude Code launches, when no [cached environment](#environment-caching) is available | After Claude Code launches, on every session including resumed |
| Scope         | Cloud environments only                                                                      | Both local and cloud                                           |

SessionStart hooks can also be defined in your user-level `~/.claude/settings.json` locally, but user-level settings don't carry over to cloud sessions. In the cloud, only hooks committed to the repo run.

### Install dependencies with a SessionStart hook

To install dependencies only in cloud sessions, add a SessionStart hook to your repo's `.claude/settings.json`:

```json theme={null}
{
  "hooks": {
    "SessionStart": [
      {
        "matcher": "startup|resume",
        "hooks": [
          {
            "type": "command",
            "command": "\"$CLAUDE_PROJECT_DIR\"/scripts/install_pkgs.sh"
          }
        ]
      }
    ]
  }
}
```

Create the script at `scripts/install_pkgs.sh` and make it executable with `chmod +x`. The `CLAUDE_CODE_REMOTE` environment variable is set to `true` in cloud sessions, so you can use it to skip local execution:

```bash theme={null}
#!/bin/bash

if [ "$CLAUDE_CODE_REMOTE" != "true" ]; then
  exit 0
fi

npm install
pip install -r requirements.txt
exit 0
```

SessionStart hooks have some limitations in cloud sessions:

* **No cloud-only scoping**: hooks run in both local and cloud sessions. To skip local execution, check the `CLAUDE_CODE_REMOTE` environment variable as shown above.
* **Requires network access**: install commands need to reach package registries. If your environment uses **None** network access, these hooks fail. The [default allowlist](#default-allowed-domains) under **Trusted** covers npm, PyPI, RubyGems, and crates.io.
* **Proxy compatibility**: all outbound traffic passes through a [security proxy](#security-proxy). Some package managers don't work correctly with this proxy. Bun is a known example.
* **Adds startup latency**: hooks run each time a session starts or resumes, unlike setup scripts which benefit from [environment caching](#environment-caching). Keep install scripts fast by checking whether dependencies are already present before reinstalling.

To persist environment variables for subsequent Bash commands, write to the file at `$CLAUDE_ENV_FILE`. See [SessionStart hooks](/en/hooks#sessionstart) for details.

Replacing the base image with your own Docker image is not yet supported. Use a setup script to install what you need on top of the [provided image](#installed-tools), or run your image as a container alongside Claude with `docker compose`.

## Network access

Network access controls outbound connections from the cloud environment. Each environment specifies one access level, and you can extend it with custom allowed domains. The default is **Trusted**, which allows package registries and other [allowlisted domains](#default-allowed-domains).

### Access levels

Choose an access level when you create or edit an environment:

| Level       | Outbound connections                                                                         |
| :---------- | :------------------------------------------------------------------------------------------- |
| **None**    | No outbound network access                                                                   |
| **Trusted** | [Allowlisted domains](#default-allowed-domains) only: package registries, GitHub, cloud SDKs |
| **Full**    | Any domain                                                                                   |
| **Custom**  | Your own allowlist, optionally including the defaults                                        |

GitHub operations use a [separate proxy](#github-proxy) that is independent of this setting.

### Allow specific domains

To allow domains that aren't in the Trusted list, select **Custom** in the environment's network access settings. An **Allowed domains** field appears. Enter one domain per line:

```text theme={null}
api.example.com
*.internal.example.com
registry.example.com
```

Use `*.` for wildcard subdomain matching. Check **Also include default list of common package managers** to keep the [Trusted domains](#default-allowed-domains) alongside your custom entries, or leave it unchecked to allow only what you list.

### GitHub proxy

For security, all GitHub operations go through a dedicated proxy service that transparently handles all git interactions. Inside the sandbox, the git client authenticates using a custom-built scoped credential. This proxy:

* Manages GitHub authentication securely: the git client uses a scoped credential inside the sandbox, which the proxy verifies and translates to your actual GitHub authentication token
* Restricts git push operations to the current working branch for safety
* Enables cloning, fetching, and PR operations while maintaining security boundaries

### Security proxy

Environments run behind an HTTP/HTTPS network proxy for security and abuse prevention purposes. All outbound internet traffic passes through this proxy, which provides:

* Protection against malicious requests
* Rate limiting and abuse prevention
* Content filtering for enhanced security

### Default allowed domains

When using **Trusted** network access, the following domains are allowed by default. Domains marked with `*` indicate wildcard subdomain matching, so `*.gcr.io` allows any subdomain of `gcr.io`.

<AccordionGroup>
  <Accordion title="Anthropic services">
    * api.anthropic.com
    * statsig.anthropic.com
    * docs.claude.com
    * platform.claude.com
    * code.claude.com
    * claude.ai
  </Accordion>

  <Accordion title="Version control">
    * github.com
    * [www.github.com](http://www.github.com)
    * api.github.com
    * npm.pkg.github.com
    * raw\.githubusercontent.com
    * pkg-npm.githubusercontent.com
    * objects.githubusercontent.com
    * release-assets.githubusercontent.com
    * codeload.github.com
    * avatars.githubusercontent.com
    * camo.githubusercontent.com
    * gist.github.com
    * gitlab.com
    * [www.gitlab.com](http://www.gitlab.com)
    * registry.gitlab.com
    * bitbucket.org
    * [www.bitbucket.org](http://www.bitbucket.org)
    * api.bitbucket.org
  </Accordion>

  <Accordion title="Container registries">
    * registry-1.docker.io
    * auth.docker.io
    * index.docker.io
    * hub.docker.com
    * [www.docker.com](http://www.docker.com)
    * production.cloudflare.docker.com
    * download.docker.com
    * gcr.io
    * \*.gcr.io
    * ghcr.io
    * mcr.microsoft.com
    * \*.data.mcr.microsoft.com
    * public.ecr.aws
  </Accordion>

  <Accordion title="Cloud platforms">
    * cloud.google.com
    * accounts.google.com
    * gcloud.google.com
    * \*.googleapis.com
    * storage.googleapis.com
    * compute.googleapis.com
    * container.googleapis.com
    * azure.com
    * portal.azure.com
    * microsoft.com
    * [www.microsoft.com](http://www.microsoft.com)
    * \*.microsoftonline.com
    * packages.microsoft.com
    * dotnet.microsoft.com
    * dot.net
    * visualstudio.com
    * dev.azure.com
    * \*.amazonaws.com
    * \*.api.aws
    * oracle.com
    * [www.oracle.com](http://www.oracle.com)
    * java.com
    * [www.java.com](http://www.java.com)
    * java.net
    * [www.java.net](http://www.java.net)
    * download.oracle.com
    * yum.oracle.com
  </Accordion>

  <Accordion title="JavaScript and Node package managers">
    * registry.npmjs.org
    * [www.npmjs.com](http://www.npmjs.com)
    * [www.npmjs.org](http://www.npmjs.org)
    * npmjs.com
    * npmjs.org
    * yarnpkg.com
    * registry.yarnpkg.com
  </Accordion>

  <Accordion title="Python package managers">
    * pypi.org
    * [www.pypi.org](http://www.pypi.org)
    * files.pythonhosted.org
    * pythonhosted.org
    * test.pypi.org
    * pypi.python.org
    * pypa.io
    * [www.pypa.io](http://www.pypa.io)
  </Accordion>

  <Accordion title="Ruby package managers">
    * rubygems.org
    * [www.rubygems.org](http://www.rubygems.org)
    * api.rubygems.org
    * index.rubygems.org
    * ruby-lang.org
    * [www.ruby-lang.org](http://www.ruby-lang.org)
    * rubyforge.org
    * [www.rubyforge.org](http://www.rubyforge.org)
    * rubyonrails.org
    * [www.rubyonrails.org](http://www.rubyonrails.org)
    * rvm.io
    * get.rvm.io
  </Accordion>

  <Accordion title="Rust package managers">
    * crates.io
    * [www.crates.io](http://www.crates.io)
    * index.crates.io
    * static.crates.io
    * rustup.rs
    * static.rust-lang.org
    * [www.rust-lang.org](http://www.rust-lang.org)
  </Accordion>

  <Accordion title="Go package managers">
    * proxy.golang.org
    * sum.golang.org
    * index.golang.org
    * golang.org
    * [www.golang.org](http://www.golang.org)
    * goproxy.io
    * pkg.go.dev
  </Accordion>

  <Accordion title="JVM package managers">
    * maven.org
    * repo.maven.org
    * central.maven.org
    * repo1.maven.org
    * repo.maven.apache.org
    * jcenter.bintray.com
    * gradle.org
    * [www.gradle.org](http://www.gradle.org)
    * services.gradle.org
    * plugins.gradle.org
    * kotlinlang.org
    * [www.kotlinlang.org](http://www.kotlinlang.org)
    * spring.io
    * repo.spring.io
  </Accordion>

  <Accordion title="Other package managers">
    * packagist.org (PHP Composer)
    * [www.packagist.org](http://www.packagist.org)
    * repo.packagist.org
    * nuget.org (.NET NuGet)
    * [www.nuget.org](http://www.nuget.org)
    * api.nuget.org
    * pub.dev (Dart/Flutter)
    * api.pub.dev
    * hex.pm (Elixir/Erlang)
    * [www.hex.pm](http://www.hex.pm)
    * cpan.org (Perl CPAN)
    * [www.cpan.org](http://www.cpan.org)
    * metacpan.org
    * [www.metacpan.org](http://www.metacpan.org)
    * api.metacpan.org
    * cocoapods.org (iOS/macOS)
    * [www.cocoapods.org](http://www.cocoapods.org)
    * cdn.cocoapods.org
    * haskell.org
    * [www.haskell.org](http://www.haskell.org)
    * hackage.haskell.org
    * swift.org
    * [www.swift.org](http://www.swift.org)
  </Accordion>

  <Accordion title="Linux distributions">
    * archive.ubuntu.com
    * security.ubuntu.com
    * ubuntu.com
    * [www.ubuntu.com](http://www.ubuntu.com)
    * \*.ubuntu.com
    * ppa.launchpad.net
    * launchpad.net
    * [www.launchpad.net](http://www.launchpad.net)
    * \*.nixos.org
  </Accordion>

  <Accordion title="Development tools and platforms">
    * dl.k8s.io (Kubernetes)
    * pkgs.k8s.io
    * k8s.io
    * [www.k8s.io](http://www.k8s.io)
    * releases.hashicorp.com (HashiCorp)
    * apt.releases.hashicorp.com
    * rpm.releases.hashicorp.com
    * archive.releases.hashicorp.com
    * hashicorp.com
    * [www.hashicorp.com](http://www.hashicorp.com)
    * repo.anaconda.com (Anaconda/Conda)
    * conda.anaconda.org
    * anaconda.org
    * [www.anaconda.com](http://www.anaconda.com)
    * anaconda.com
    * continuum.io
    * apache.org (Apache)
    * [www.apache.org](http://www.apache.org)
    * archive.apache.org
    * downloads.apache.org
    * eclipse.org (Eclipse)
    * [www.eclipse.org](http://www.eclipse.org)
    * download.eclipse.org
    * nodejs.org (Node.js)
    * [www.nodejs.org](http://www.nodejs.org)
    * developer.apple.com
    * developer.android.com
    * pkg.stainless.com
    * binaries.prisma.sh
  </Accordion>

  <Accordion title="Cloud services and monitoring">
    * statsig.com
    * [www.statsig.com](http://www.statsig.com)
    * api.statsig.com
    * sentry.io
    * \*.sentry.io
    * downloads.sentry-cdn.com
    * http-intake.logs.datadoghq.com
    * \*.datadoghq.com
    * \*.datadoghq.eu
    * api.honeycomb.io
  </Accordion>

  <Accordion title="Content delivery and mirrors">
    * sourceforge.net
    * \*.sourceforge.net
    * packagecloud.io
    * \*.packagecloud.io
    * fonts.googleapis.com
    * fonts.gstatic.com
  </Accordion>

  <Accordion title="Schema and configuration">
    * json-schema.org
    * [www.json-schema.org](http://www.json-schema.org)
    * json.schemastore.org
    * [www.schemastore.org](http://www.schemastore.org)
  </Accordion>

  <Accordion title="Model Context Protocol">
    * \*.modelcontextprotocol.io
  </Accordion>
</AccordionGroup>

## Move tasks between web and terminal

These workflows require the [Claude Code CLI](../01-Getting-Started/quickstart-claude-code-docs-a21b84bdea.md) 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.

<Note>
  From the CLI, session handoff is one-way: you can pull cloud sessions into your terminal with `--teleport`, but you can't push an existing terminal session to the web. The `--remote` flag creates a new cloud session for your current repository. The [Desktop app](/en/desktop#continue-in-another-surface) provides a Continue in menu that can send a local session to the web.
</Note>

### From terminal to web

Start a cloud session from the command line with the `--remote` flag:

```bash theme={null}
claude --remote "Fix the authentication bug in src/auth/login.ts"
```

This creates a new cloud session on claude.ai. The session clones your current directory's GitHub remote at your current branch, so push first if you have local commits, since the VM clones from GitHub rather than your machine. `--remote` works with a single repository at a time. The task runs in the cloud while you continue working locally.

<Note>
  `--remote` creates cloud sessions. `--remote-control` is unrelated: it exposes a local CLI session for monitoring from the web. See [Remote Control](continue-local-sessions-from-any-device-with-remote-control-claude-code-docs-c1c03fd914.md).
</Note>

Use `/tasks` in the Claude Code CLI to check progress, or open the session on claude.ai or the Claude mobile app to interact directly. From there you can steer Claude, provide feedback, or answer questions just like any other conversation.

#### Tips for cloud tasks

**Plan locally, execute remotely**: for complex tasks, start Claude in plan mode to collaborate on the approach, then send work to the cloud:

```bash theme={null}
claude --permission-mode plan
```

In plan mode, Claude reads files, runs commands to explore, and proposes a plan without editing source code. Once you're satisfied, save the plan to the repo, commit, and push so the cloud VM can clone it. Then start a cloud session for autonomous execution:

```bash theme={null}
claude --remote "Execute the migration plan in docs/migration-plan.md"
```

This pattern gives you control over the strategy while letting Claude execute autonomously in the cloud.

**Plan in the cloud with ultraplan**: to draft and review the plan itself in a web session, use [ultraplan](ultraplan-14dfb476fe.md). Claude generates the plan on Claude Code on the web while you keep working, then you comment on sections in your browser and choose to execute remotely or send the plan back to your terminal.

**Run tasks in parallel**: each `--remote` command creates its own cloud session that runs independently. You can start multiple tasks and they'll all run simultaneously in separate sessions:

```bash theme={null}
claude --remote "Fix the flaky test in auth.spec.ts"
claude --remote "Update the API documentation"
claude --remote "Refactor the logger to use structured output"
```

Monitor all sessions with `/tasks` in the Claude Code CLI. When a session completes, you can create a PR from the web interface or [teleport](#from-web-to-terminal) the session to your terminal to continue working.

#### Send local repositories without GitHub

When you run `claude --remote` from a repository that isn't connected to GitHub, Claude Code bundles your local repository and uploads it directly to the cloud session. The bundle includes your full repository history across all branches, plus any uncommitted changes to tracked files.

This fallback activates automatically when GitHub access isn't available. To force it even when GitHub is connected, set `CCR_FORCE_BUNDLE=1`:

```bash theme={null}
CCR_FORCE_BUNDLE=1 claude --remote "Run the test suite and fix any failures"
```

Bundled repositories must meet these limits:

* The directory must be a git repository with at least one commit
* The bundled repository must be under 100 MB. Larger repositories fall back to bundling only the current branch, then to a single squashed snapshot of the working tree, and fail only if the snapshot is still too large
* Untracked files are not included; run `git add` on files you want the cloud session to see
* Sessions created from a bundle can't push back to a remote unless you also have [GitHub authentication](#github-authentication-options) configured

### From web to terminal

Pull a cloud session into your terminal using any of these:

* **Using `--teleport`**: from the command line, run `claude --teleport` for an interactive session picker, or `claude --teleport <session-id>` to resume a specific session directly. If you have uncommitted changes, you'll be prompted to stash them first.
* **Using `/teleport`**: inside an existing CLI session, run `/teleport` (or `/tp`) to open the same session picker without restarting Claude Code.
* **From `/tasks`**: run `/tasks` to see your background sessions, then press `t` to teleport into one
* **From the web interface**: select **Open in CLI** to copy a command you can paste into your terminal

When you teleport a session, Claude verifies you're in the correct repository, fetches and checks out the branch from the cloud session, and loads the full conversation history into your terminal.

`--teleport` is distinct from `--resume`. `--resume` reopens a conversation from this machine's local history and doesn't list cloud sessions; `--teleport` pulls a cloud session and its branch.

#### 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.

| Requirement        | Details                                                                                                                  |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------ |
| Clean git state    | Your working directory must have no uncommitted changes. Teleport prompts you to stash changes if needed.                |
| Correct repository | You must run `--teleport` from a checkout of the same repository, not a fork.                                            |
| Branch available   | The branch from the cloud session must have been pushed to the remote. Teleport automatically fetches and checks it out. |
| Same account       | You must be authenticated to the same claude.ai account used in the cloud session.                                       |

#### `--teleport` is unavailable

Teleport requires claude.ai subscription authentication. If you're authenticated via API key, Bedrock, Vertex AI, or Microsoft Foundry, run `/login` to sign in with your claude.ai account instead. If you're already signed in via claude.ai and `--teleport` is still unavailable, your organization may have disabled cloud 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.

### Manage context

Cloud sessions support [built-in commands](built-in-commands-claude-code-docs.md) that produce text output. Commands that open an interactive terminal picker, like `/model` or `/config`, are not available.

For context management specifically:

| Command    | Works in cloud sessions | Notes                                                                                                                    |
| :--------- | :---------------------- | :----------------------------------------------------------------------------------------------------------------------- |
| `/compact` | Yes                     | Summarizes the conversation to free up context. Accepts optional focus instructions like `/compact keep the test output` |
| `/context` | Yes                     | Shows what's currently in the context window                                                                             |
| `/clear`   | No                      | Start a new session from the sidebar instead                                                                             |

Auto-compaction runs automatically when the context window approaches capacity, the same as in the CLI. To trigger it earlier, set [`CLAUDE_AUTOCOMPACT_PCT_OVERRIDE`](env-vars-5c624d392b.md) in your [environment variables](#configure-your-environment). For example, `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=70` compacts at 70% capacity instead of the default \~95%. To change the effective window size for compaction calculations, use [`CLAUDE_CODE_AUTO_COMPACT_WINDOW`](env-vars-5c624d392b.md).

[Subagents](../09-Agents-Patterns/create-custom-subagents-claude-code-docs-7dc93e85c0.md) work the same way they do locally. Claude can spawn them with the Task tool to offload research or parallel work into a separate context window, keeping the main conversation lighter. Subagents defined in your repo's `.claude/agents/` are picked up automatically. [Agent teams](../09-Agents-Patterns/agent-teams-e29da6ed1b.md) are off by default but can be enabled by adding `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` to your [environment variables](#configure-your-environment).

### Review changes

Each session shows a diff indicator with lines added and removed, like `+42 -18`. Select it to open the diff view, leave inline comments on specific lines, and send them to Claude with your next message. See [Review and iterate](/en/web-quickstart#review-and-iterate) for the full walkthrough including PR creation. To have Claude monitor the PR for CI failures and review comments automatically, see [Auto-fix pull requests](#auto-fix-pull-requests).

### 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

For Enterprise and Team accounts, the two visibility options are **Private** and **Team**. Team visibility makes the session visible to other members of your claude.ai organization. Repository access verification is enabled by default, based on the GitHub account connected to the recipient's account. Your account's display name is visible to all recipients with access. [Claude in Slack](../14-Connectors/claude-code-in-slack-claude-code-docs-c62a093e92.md) sessions are automatically shared with Team visibility.

#### Share from a Max or Pro account

For Max and Pro accounts, the two visibility options are **Private** and **Public**. Public visibility makes the session visible to any user logged into claude.ai.

Check your session for sensitive content before sharing. Sessions may contain code and credentials from private GitHub repositories. Repository access verification is not enabled by default.

To require recipients to have repository access, or to hide your name from shared sessions, go to Settings > Claude Code > Sharing settings.

### Archive sessions

You can archive sessions to keep your session list organized. Archived sessions are hidden from the default session list but can be viewed by filtering for archived sessions.

To archive a session, hover over the session in the sidebar and select the archive icon.

### Delete sessions

Deleting a session permanently removes the session and its data. This action cannot be undone. You can delete a session in two ways:

* **From the sidebar**: filter for archived sessions, then hover over the session you want to delete and select the delete icon
* **From the session menu**: open a session, select the dropdown next to the session title, and select **Delete**

You will be asked to confirm before a session is deleted.

## 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.

<Note>
  Auto-fix requires the Claude GitHub App to be installed on your repository. If you haven't already, install it from the [GitHub App page](https://github.com/apps/claude) or when prompted during [setup](/en/web-quickstart#connect-github-and-create-an-environment).
</Note>

There are a few ways to turn on auto-fix depending on where the PR came from and what device you're using:

* **PRs created in Claude Code on the web**: open the CI status bar and select **Auto-fix**
* **From your terminal**: run [`/autofix-pr`](built-in-commands-claude-code-docs.md) while on the PR's branch. Claude Code detects the open PR with `gh`, spawns a web session, and turns on auto-fix in one step
* **From the mobile app**: tell Claude to auto-fix the PR, for example "watch this PR and fix any CI failures or review comments"
* **Any existing PR**: paste the PR URL into a session and tell Claude to auto-fix it

### 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:

* **Clear fixes**: if Claude is confident in a fix and it doesn't conflict with earlier instructions, Claude makes the change, pushes it, and explains what was done in the session
* **Ambiguous requests**: if a reviewer's comment could be interpreted multiple ways or involves something architecturally significant, Claude asks you before acting
* **Duplicate or no-action events**: if an event is a duplicate or requires no change, Claude notes it in the session and moves on

Claude may reply to review comment threads on GitHub as part of resolving them. These replies are posted using your GitHub account, so they appear under your username, but each reply is labeled as coming from Claude Code so reviewers know it was written by the agent and not by you directly.

<Warning>
  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.
</Warning>

## Security and isolation

Each cloud session is separated from your machine and from other sessions through several layers:

* **Isolated virtual machines**: each session runs in an isolated, Anthropic-managed VM
* **Network access controls**: network access is limited by default, and can be disabled. When running with network access disabled, Claude Code can still communicate with the Anthropic API, which may allow data to exit the VM.
* **Credential protection**: sensitive credentials such as git credentials or signing keys are never inside the sandbox with Claude Code. Authentication is handled through a secure proxy using scoped credentials.
* **Secure analysis**: code is analyzed and modified within isolated VMs before creating PRs

## 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](errors-8648349cb4.md). 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

If a new session fails to start with `Session creation failed` or stalls at provisioning, Claude Code could not allocate a cloud environment.

* Check [status.claude.com](https://status.claude.com) for cloud session incidents
* Retry after a minute, as capacity is provisioned on demand
* Confirm your repository is reachable. Private repositories require either the GitHub App installed with access to that repository, or a `gh` token synced via `/web-setup`. See [GitHub authentication options](#github-authentication-options).

### 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 has expired` or `Access denied`. The connection token is short-lived and scoped to your account.

* Run `/login` locally to refresh your credentials, then reconnect
* 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`, your admin has not enabled remote sessions for your plan

### Environment expired

Cloud sessions stop after a period of inactivity and the underlying environment is reclaimed. From a local terminal, this surfaces as `Could not resume session ... its environment has expired. Creating a fresh session instead.` On the web, the session is marked expired in the session list.

Reopen the session from [claude.ai/code](https://claude.ai/code) to provision a fresh environment with your conversation history restored.

## Limitations

Before relying on cloud sessions for a workflow, account for these constraints:

* **Rate limits**: Claude Code on the web shares rate limits with all other Claude and Claude Code usage within your account. Running multiple tasks in parallel consumes more rate limits proportionately. There is no separate compute charge for the cloud VM.
* **Repository authentication**: you can only move sessions from web to local when you are authenticated to the same account
* **Platform restrictions**: repository cloning and pull request creation require GitHub. Self-hosted [GitHub Enterprise Server](../03-IDE-Integrations/github-enterprise-server.md) instances are supported for Team and Enterprise plans. GitLab, Bitbucket, and other non-GitHub repositories can be sent to cloud sessions as a [local bundle](#send-local-repositories-without-github), but the session can't push results back to the remote

## Related resources

* [Ultraplan](ultraplan-14dfb476fe.md): draft a plan in a cloud session and review it in your browser
* [Ultrareview](ultrareview-78bb971406.md): run a deep multi-agent code review in a cloud sandbox
* [Routines](routines-3111c7bd3a.md): automate work on a schedule, via API call, or in response to GitHub events
* [Hooks configuration](../07-Hooks/hooks-9168ed62a4.md): run scripts at session lifecycle events
* [Settings reference](claude-code-settings-claude-code-docs-d4420b4b52.md): all configuration options
* [Security](../22-Safety-Policy/security-claude-code-docs-7538e94c51.md): isolation guarantees and data handling
* [Data usage](../22-Safety-Policy/data-usage-claude-code-docs-06b2864aaa.md): what Anthropic retains from cloud sessions


---
## claude-code-on-the-web.md

> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Claude Code on the web

> Run Claude Code tasks asynchronously on secure cloud infrastructure

<Note>
  Claude Code on the web is currently in research preview.
</Note>

## What is Claude Code on the web?

Claude Code on the web lets developers kick off Claude Code from the Claude app. This is perfect for:

* **Answering questions**: Ask about code architecture and how features are implemented
* **Bug fixes and routine tasks**: Well-defined tasks that don't require frequent steering
* **Parallel work**: Tackle multiple bug fixes in parallel
* **Repositories not on your local machine**: Work on code you don't have checked out locally
* **Backend changes**: Where Claude Code can write tests and then write code to pass those tests

Claude Code is also available on the Claude iOS app for kicking off tasks on the go and monitoring work in progress.

You can move between local and remote development: [send tasks from your terminal to run on the web](#from-terminal-to-web) with the `&` prefix, or [teleport web sessions back to your terminal](#from-web-to-terminal) to continue locally.

## Who can use Claude Code on the web?

Claude Code on the web is available in research preview to:

* **Pro users**
* **Max users**
* **Team premium seat users**
* **Enterprise premium seat users**

## Getting started

1. Visit [claude.ai/code](https://claude.ai/code)
2. Connect your GitHub account
3. Install the Claude GitHub app in your repositories
4. Select your default environment
5. Submit your coding task
6. Review changes in diff view, iterate with comments, then create a pull request

## How it works

When you start a task on Claude Code on the web:

1. **Repository cloning**: Your repository is cloned to an Anthropic-managed virtual machine
2. **Environment setup**: Claude prepares a secure cloud environment with your code
3. **Network configuration**: Internet access is configured based on your settings
4. **Task execution**: Claude analyzes code, makes changes, runs tests, and checks its work
5. **Completion**: You're notified when finished and can create a PR with the changes
6. **Results**: Changes are pushed to a branch, ready for pull request creation

## Review changes with diff view

Diff view lets you see exactly what Claude changed before creating a pull request. Instead of clicking "Create PR" to review changes in GitHub, view the diff directly in the app and iterate with Claude until the changes are ready.

When Claude makes changes to files, a diff stats indicator appears showing the number of lines added and removed (for example, `+12 -1`). Select this indicator to open the diff viewer, which displays a file list on the left and the changes for each file on the right.

From the diff view, you can:

* Review changes file by file
* Comment on specific changes to request modifications
* Continue iterating with Claude based on what you see

This lets you refine changes through multiple rounds of feedback without creating draft PRs or switching to GitHub.

## Moving tasks between web and terminal

You can start tasks on the web and continue them in your terminal, or send tasks from your terminal to run on the web. Web sessions persist even if you close your laptop, and you can monitor them from anywhere including the Claude iOS app.

<Note>
  Session handoff is one-way: you can pull web sessions into your terminal, but you can't push an existing terminal session to the web. The [`&` prefix](#from-terminal-to-web) creates a *new* web session with your current conversation context.
</Note>

### From terminal to web

Start a message with `&` inside Claude Code to send a task to run on the web:

```
& Fix the authentication bug in src/auth/login.ts
```

This creates a new web session on claude.ai with your current conversation context. The task runs in the cloud while you continue working locally. Use `/tasks` to check progress, or open the session on claude.ai or the Claude iOS app to interact directly. From there you can steer Claude, provide feedback, or answer questions just like any other conversation.

You can also start a web session directly from the command line:

```bash  theme={null}
claude --remote "Fix the authentication bug in src/auth/login.ts"
```

#### Tips for background tasks

**Plan locally, execute remotely**: For complex tasks, start Claude in plan mode to collaborate on the approach before sending work to the web:

```bash  theme={null}
claude --permission-mode plan
```

In plan mode, Claude can only read files and explore the codebase. Once you're satisfied with the plan, send it to the web for autonomous execution:

```
& Execute the migration plan we discussed
```

This pattern gives you control over the strategy while letting Claude execute autonomously in the cloud.

**Run tasks in parallel**: Each `&` command creates its own web session that runs independently. You can kick off multiple tasks and they'll all run simultaneously in separate sessions:

```
& Fix the flaky test in auth.spec.ts
& Update the API documentation
& Refactor the logger to use structured output
```

Monitor all sessions with `/tasks`. When a session completes, you can create a PR from the web interface or [teleport](#from-web-to-terminal) the session to your terminal to continue working.

### From web to terminal

There are several ways to pull a web session into your terminal:

* **Using `/teleport`**: From within Claude Code, run `/teleport` (or `/tp`) to see an interactive picker of your web sessions. If you have uncommitted changes, you'll be prompted to stash them first.
* **Using `--teleport`**: From the command line, run `claude --teleport` for an interactive session picker, or `claude --teleport <session-id>` to resume a specific session directly.
* **From `/tasks`**: Run `/tasks` to see your background sessions, then press `t` to teleport into one
* **From the web interface**: Click "Open in CLI" to copy a command you can paste into your terminal

When you teleport a session, Claude verifies you're in the correct repository, fetches and checks out the branch from the remote session, and loads the full conversation history into your terminal.

#### Requirements for teleporting

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.

| Requirement        | Details                                                                                                                |
| ------------------ | ---------------------------------------------------------------------------------------------------------------------- |
| Clean git state    | Your working directory must have no uncommitted changes. Teleport prompts you to stash changes if needed.              |
| Correct repository | You must run `--teleport` from a checkout of the same repository, not a fork.                                          |
| Branch available   | The branch from the web session must have been pushed to the remote. Teleport automatically fetches and checks it out. |
| Same account       | You must be authenticated to the same Claude.ai account used in the web session.                                       |

## Cloud environment

### Default image

We build and maintain a universal image with common toolchains and language ecosystems pre-installed. This image includes:

* Popular programming languages and runtimes
* Common build tools and package managers
* Testing frameworks and linters

#### Checking available tools

To see what's pre-installed in your environment, ask Claude Code to run:

```bash  theme={null}
check-tools
```

This command displays:

* Programming languages and their versions
* Available package managers
* Installed development tools

#### Language-specific setups

The universal image includes pre-configured environments for:

* **Python**: Python 3.x with pip, poetry, and common scientific libraries
* **Node.js**: Latest LTS versions with npm, yarn, pnpm, and bun
* **Ruby**: Versions 3.1.6, 3.2.6, 3.3.6 (default: 3.3.6) with gem, bundler, and rbenv for version management
* **PHP**: Version 8.4.14
* **Java**: OpenJDK with Maven and Gradle
* **Go**: Latest stable version with module support
* **Rust**: Rust toolchain with cargo
* **C++**: GCC and Clang compilers

#### Databases

The universal image includes the following databases:

* **PostgreSQL**: Version 16
* **Redis**: Version 7.0

### Environment configuration

When you start a session in Claude Code on the web, here's what happens under the hood:

1. **Environment preparation**: We clone your repository and run any configured Claude hooks for initialization. The repo will be cloned with the default branch on your GitHub repo. If you would like to check out a specific branch, you can specify that in the prompt.

2. **Network configuration**: We configure internet access for the agent. Internet access is limited by default, but you can configure the environment to have no internet or full internet access based on your needs.

3. **Claude Code execution**: Claude Code runs to complete your task, writing code, running tests, and checking its work. You can guide and steer Claude throughout the session via the web interface. Claude respects context you've defined in your `CLAUDE.md`.

4. **Outcome**: When Claude completes its work, it will push the branch to remote. You will be able to create a PR for the branch.

<Note>
  Claude operates entirely through the terminal and CLI tools available in the environment. It uses the pre-installed tools in the universal image and any additional tools you install through hooks or dependency management.
</Note>

**To add a new environment:** Select the current environment to open the environment selector, and then select "Add environment". This will open a dialog where you can specify the environment name, network access level, and any environment variables you want to set.

**To update an existing environment:** Select the current environment, to the right of the environment name, and select the settings button. This will open a dialog where you can update the environment name, network access, and environment variables.

**To select your default environment from the terminal:** If you have multiple environments configured, run `/remote-env` to choose which one to use when starting web sessions from your terminal with `&` or `--remote`. With a single environment, this command shows your current configuration.

<Note>
  Environment variables must be specified as key-value pairs, in [`.env` format](https://www.dotenv.org/). For example:

  ```
  API_KEY=your_api_key
  DEBUG=true
  ```
</Note>

### Dependency management

Configure automatic dependency installation using [SessionStart hooks](/en/hooks#sessionstart). This can be configured in your repository's `.claude/settings.json` file:

```json  theme={null}
{
  "hooks": {
    "SessionStart": [
      {
        "matcher": "startup",
        "hooks": [
          {
            "type": "command",
            "command": "\"$CLAUDE_PROJECT_DIR\"/scripts/install_pkgs.sh"
          }
        ]
      }
    ]
  }
}
```

Create the corresponding script at `scripts/install_pkgs.sh`:

```bash  theme={null}
#!/bin/bash
npm install
pip install -r requirements.txt
exit 0
```

Make it executable: `chmod +x scripts/install_pkgs.sh`

#### Local vs remote execution

By default, all hooks execute both locally and in remote (web) environments. To run a hook only in one environment, check the `CLAUDE_CODE_REMOTE` environment variable in your hook script.

```bash  theme={null}
#!/bin/bash

# Example: Only run in remote environments
if [ "$CLAUDE_CODE_REMOTE" != "true" ]; then
  exit 0
fi

npm install
pip install -r requirements.txt
```

#### Persisting environment variables

SessionStart hooks can persist environment variables for subsequent bash commands by writing to the file specified in the `CLAUDE_ENV_FILE` environment variable. For details, see [SessionStart hooks](/en/hooks#sessionstart) in the hooks reference.

## Network access and security

### Network policy

#### GitHub proxy

For security, all GitHub operations go through a dedicated proxy service that transparently handles all git interactions. Inside the sandbox, the git client authenticates using a custom-built scoped credential. This proxy:

* Manages GitHub authentication securely - the git client uses a scoped credential inside the sandbox, which the proxy verifies and translates to your actual GitHub authentication token
* Restricts git push operations to the current working branch for safety
* Enables seamless cloning, fetching, and PR operations while maintaining security boundaries

#### Security proxy

Environments run behind an HTTP/HTTPS network proxy for security and abuse prevention purposes. All outbound internet traffic passes through this proxy, which provides:

* Protection against malicious requests
* Rate limiting and abuse prevention
* Content filtering for enhanced security

### Access levels

By default, network access is limited to [allowlisted domains](#default-allowed-domains).

You can configure custom network access, including disabling network access.

### Default allowed domains

When using "Limited" network access, the following domains are allowed by default:

#### Anthropic Services

* api.anthropic.com
* statsig.anthropic.com
* docs.claude.com
* code.claude.com
* claude.ai

#### Version Control

* github.com
* [www.github.com](http://www.github.com)
* api.github.com
* npm.pkg.github.com
* raw\.githubusercontent.com
* pkg-npm.githubusercontent.com
* objects.githubusercontent.com
* codeload.github.com
* avatars.githubusercontent.com
* camo.githubusercontent.com
* gist.github.com
* gitlab.com
* [www.gitlab.com](http://www.gitlab.com)
* registry.gitlab.com
* bitbucket.org
* [www.bitbucket.org](http://www.bitbucket.org)
* api.bitbucket.org

#### Container Registries

* registry-1.docker.io
* auth.docker.io
* index.docker.io
* hub.docker.com
* [www.docker.com](http://www.docker.com)
* production.cloudflare.docker.com
* download.docker.com
* gcr.io
* \*.gcr.io
* ghcr.io
* mcr.microsoft.com
* \*.data.mcr.microsoft.com
* public.ecr.aws

#### Cloud Platforms

* cloud.google.com
* accounts.google.com
* gcloud.google.com
* \*.googleapis.com
* storage.googleapis.com
* compute.googleapis.com
* container.googleapis.com
* azure.com
* portal.azure.com
* microsoft.com
* [www.microsoft.com](http://www.microsoft.com)
* \*.microsoftonline.com
* packages.microsoft.com
* dotnet.microsoft.com
* dot.net
* visualstudio.com
* dev.azure.com
* \*.amazonaws.com
* \*.api.aws
* oracle.com
* [www.oracle.com](http://www.oracle.com)
* java.com
* [www.java.com](http://www.java.com)
* java.net
* [www.java.net](http://www.java.net)
* download.oracle.com
* yum.oracle.com

#### Package Managers - JavaScript/Node

* registry.npmjs.org
* [www.npmjs.com](http://www.npmjs.com)
* [www.npmjs.org](http://www.npmjs.org)
* npmjs.com
* npmjs.org
* yarnpkg.com
* registry.yarnpkg.com

#### Package Managers - Python

* pypi.org
* [www.pypi.org](http://www.pypi.org)
* files.pythonhosted.org
* pythonhosted.org
* test.pypi.org
* pypi.python.org
* pypa.io
* [www.pypa.io](http://www.pypa.io)

#### Package Managers - Ruby

* rubygems.org
* [www.rubygems.org](http://www.rubygems.org)
* api.rubygems.org
* index.rubygems.org
* ruby-lang.org
* [www.ruby-lang.org](http://www.ruby-lang.org)
* rubyforge.org
* [www.rubyforge.org](http://www.rubyforge.org)
* rubyonrails.org
* [www.rubyonrails.org](http://www.rubyonrails.org)
* rvm.io
* get.rvm.io

#### Package Managers - Rust

* crates.io
* [www.crates.io](http://www.crates.io)
* index.crates.io
* static.crates.io
* rustup.rs
* static.rust-lang.org
* [www.rust-lang.org](http://www.rust-lang.org)

#### Package Managers - Go

* proxy.golang.org
* sum.golang.org
* index.golang.org
* golang.org
* [www.golang.org](http://www.golang.org)
* goproxy.io
* pkg.go.dev

#### Package Managers - JVM

* maven.org
* repo.maven.org
* central.maven.org
* repo1.maven.org
* jcenter.bintray.com
* gradle.org
* [www.gradle.org](http://www.gradle.org)
* services.gradle.org
* plugins.gradle.org
* kotlin.org
* [www.kotlin.org](http://www.kotlin.org)
* spring.io
* repo.spring.io

#### Package Managers - Other Languages

* packagist.org (PHP Composer)
* [www.packagist.org](http://www.packagist.org)
* repo.packagist.org
* nuget.org (.NET NuGet)
* [www.nuget.org](http://www.nuget.org)
* api.nuget.org
* pub.dev (Dart/Flutter)
* api.pub.dev
* hex.pm (Elixir/Erlang)
* [www.hex.pm](http://www.hex.pm)
* cpan.org (Perl CPAN)
* [www.cpan.org](http://www.cpan.org)
* metacpan.org
* [www.metacpan.org](http://www.metacpan.org)
* api.metacpan.org
* cocoapods.org (iOS/macOS)
* [www.cocoapods.org](http://www.cocoapods.org)
* cdn.cocoapods.org
* haskell.org
* [www.haskell.org](http://www.haskell.org)
* hackage.haskell.org
* swift.org
* [www.swift.org](http://www.swift.org)

#### Linux Distributions

* archive.ubuntu.com
* security.ubuntu.com
* ubuntu.com
* [www.ubuntu.com](http://www.ubuntu.com)
* \*.ubuntu.com
* ppa.launchpad.net
* launchpad.net
* [www.launchpad.net](http://www.launchpad.net)

#### Development Tools & Platforms

* dl.k8s.io (Kubernetes)
* pkgs.k8s.io
* k8s.io
* [www.k8s.io](http://www.k8s.io)
* releases.hashicorp.com (HashiCorp)
* apt.releases.hashicorp.com
* rpm.releases.hashicorp.com
* archive.releases.hashicorp.com
* hashicorp.com
* [www.hashicorp.com](http://www.hashicorp.com)
* repo.anaconda.com (Anaconda/Conda)
* conda.anaconda.org
* anaconda.org
* [www.anaconda.com](http://www.anaconda.com)
* anaconda.com
* continuum.io
* apache.org (Apache)
* [www.apache.org](http://www.apache.org)
* archive.apache.org
* downloads.apache.org
* eclipse.org (Eclipse)
* [www.eclipse.org](http://www.eclipse.org)
* download.eclipse.org
* nodejs.org (Node.js)
* [www.nodejs.org](http://www.nodejs.org)

#### Cloud Services & Monitoring

* statsig.com
* [www.statsig.com](http://www.statsig.com)
* api.statsig.com
* sentry.io
* \*.sentry.io
* http-intake.logs.datadoghq.com
* \*.datadoghq.com
* \*.datadoghq.eu

#### Content Delivery & Mirrors

* sourceforge.net
* \*.sourceforge.net
* packagecloud.io
* \*.packagecloud.io

#### Schema & Configuration

* json-schema.org
* [www.json-schema.org](http://www.json-schema.org)
* json.schemastore.org
* [www.schemastore.org](http://www.schemastore.org)

#### Model Context Protocol

* \*.modelcontextprotocol.io

<Note>
  Domains marked with `*` indicate wildcard subdomain matching. For example, `*.gcr.io` allows access to any subdomain of `gcr.io`.
</Note>

### Security best practices for customized network access

1. **Principle of least privilege**: Only enable the minimum network access required
2. **Audit regularly**: Review allowed domains periodically
3. **Use HTTPS**: Always prefer HTTPS endpoints over HTTP

## Security and isolation

Claude Code on the web provides strong security guarantees:

* **Isolated virtual machines**: Each session runs in an isolated, Anthropic-managed VM
* **Network access controls**: Network access is limited by default, and can be disabled

<Note>
  When running with network access disabled, Claude Code is allowed to communicate with the Anthropic API which may still allow data to exit the isolated Claude Code VM.
</Note>

* **Credential protection**: Sensitive credentials (such as git credentials or signing keys) are never inside the sandbox with Claude Code. Authentication is handled through a secure proxy using scoped credentials
* **Secure analysis**: Code is analyzed and modified within isolated VMs before creating PRs

## Pricing and rate limits

Claude Code on the web shares rate limits with all other Claude and Claude Code usage within your account. Running multiple tasks in parallel will consume more rate limits proportionately.

## Limitations

* **Repository authentication**: You can only move sessions from web to local when you are authenticated to the same account
* **Platform restrictions**: Claude Code on the web only works with code hosted in GitHub. GitLab and other non-GitHub repositories cannot be used with cloud sessions

## Best practices

1. **Use Claude Code hooks**: Configure [SessionStart hooks](/en/hooks#sessionstart) to automate environment setup and dependency installation.
2. **Document requirements**: Clearly specify dependencies and commands in your `CLAUDE.md` file. If you have an `AGENTS.md` file, you can source it in your `CLAUDE.md` using `@AGENTS.md` to maintain a single source of truth.

## Related resources

* [Hooks configuration](../07-Hooks/hooks-reference-claude-code-docs.md)
* [Settings reference](claude-code-settings-claude-code-docs-d4420b4b52.md)
* [Security](security-claude-code-docs.md)
* [Data usage](../22-Safety-Policy/data-usage-claude-code-docs-06b2864aaa.md)


---
## claude-code-overview-claude-code-docs-c23f3e7cbb.md

# Claude Code overview


Claude Code is an agentic coding tool that reads your codebase, edits files, runs commands, and integrates with your development tools. Available in your terminal, IDE, desktop app, and browser.


Claude Code is an AI-powered coding assistant that helps you build features, fix bugs, and automate development tasks. It understands your entire codebase and can work across multiple files and tools to get things done.


Get started

Choose your environment to get started. Most surfaces require a [Claude subscription](https://claude.com/pricing?utm_source=claude_code&utm_medium=docs&utm_content=overview_pricing) or [Anthropic Console](https://console.anthropic.com/) account. The Terminal CLI and VS Code also support [third-party providers](/docs/en/third-party-integrations).

- Terminal

- VS Code

- Desktop app

- Web

- JetBrains

The full-featured CLI for working with Claude Code directly in your terminal. Edit files, run commands, and manage your entire project from the command line.To install Claude Code, use one of the following methods:

- Native Install (Recommended)

- Homebrew

- WinGet

**macOS, Linux, WSL:**

```python
curl -fsSL https://claude.ai/install.sh | bash
```

**Windows PowerShell:**

```python
irm https://claude.ai/install.ps1 | iex
```

**Windows CMD:**

```python
curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd
```

If you see `The token '&&' is not a valid statement separator`, you’re in PowerShell, not CMD. If you see `'irm' is not recognized as an internal or external command`, you’re in CMD, not PowerShell. Your prompt shows `PS C:\` when you’re in PowerShell and `C:\` without the `PS` when you’re in CMD.**Native Windows setups require [Git for Windows](https://git-scm.com/downloads/win).** Install it first if you don’t have it. WSL setups do not need it.

Native installations automatically update in the background to keep you on the latest version.

```python
brew install --cask claude-code
```

Homebrew offers two casks. `claude-code` tracks the stable release channel, which is typically about a week behind and skips releases with major regressions. `claude-code@latest` tracks the latest channel and receives new versions as soon as they ship.

Homebrew installations do not auto-update. Run `brew upgrade claude-code` or `brew upgrade claude-code@latest`, depending on which cask you installed, to get the latest features and security fixes.

```python
winget install Anthropic.ClaudeCode
```

WinGet installations do not auto-update. Run `winget upgrade Anthropic.ClaudeCode` periodically to get the latest features and security fixes.

You can also install with [apt, dnf, or apk](/docs/en/setup#install-with-linux-package-managers) on Debian, Fedora, RHEL, and Alpine.Then start Claude Code in any project:

```python
cd your-project
claude
```

You’ll be prompted to log in on first use. That’s it! [Continue with the Quickstart →](/docs/en/quickstart)

See [advanced setup](/docs/en/setup) for installation options, manual updates, or uninstallation instructions. Visit [troubleshooting](/docs/en/troubleshooting) if you hit issues.

The VS Code extension provides inline diffs, @-mentions, plan review, and conversation history directly in your editor.

- [Install for VS Code](vscode:extension/anthropic.claude-code)
- [Install for Cursor](cursor:extension/anthropic.claude-code)

Or search for “Claude Code” in the Extensions view (`Cmd+Shift+X` on Mac, `Ctrl+Shift+X` on Windows/Linux). After installing, open the Command Palette (`Cmd+Shift+P` / `Ctrl+Shift+P`), type “Claude Code”, and select **Open in New Tab**.[Get started with VS Code →](/docs/en/vs-code#get-started)

A standalone app for running Claude Code outside your IDE or terminal. Review diffs visually, run multiple sessions side by side, schedule recurring tasks, and kick off cloud sessions.Download and install:

- [macOS](https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code&utm_medium=docs) (Intel and Apple Silicon)
- [Windows](https://claude.ai/api/desktop/win32/x64/setup/latest/redirect?utm_source=claude_code&utm_medium=docs) (x64)
- [Windows ARM64](https://claude.ai/api/desktop/win32/arm64/setup/latest/redirect?utm_source=claude_code&utm_medium=docs)

After installing, launch Claude, sign in, and click the **Code** tab to start coding. A [paid subscription](https://claude.com/pricing?utm_source=claude_code&utm_medium=docs&utm_content=overview_desktop_pricing) is required.[Learn more about the desktop app →](/docs/en/desktop-quickstart)

Run Claude Code in your browser with no local setup. Kick off long-running tasks and check back when they’re done, work on repos you don’t have locally, or run multiple tasks in parallel. Available on desktop browsers and the Claude iOS app.Start coding at [claude.ai/code](https://claude.ai/code).[Get started on the web →](/docs/en/web-quickstart)

A plugin for IntelliJ IDEA, PyCharm, WebStorm, and other JetBrains IDEs with interactive diff viewing and selection context sharing.Install the [Claude Code plugin](https://plugins.jetbrains.com/plugin/27310-claude-code-beta-) from the JetBrains Marketplace and restart your IDE.[Get started with JetBrains →](/docs/en/jetbrains)


What you can do

Here are some of the ways you can use Claude Code:

Automate the work you keep putting off

Claude Code handles the tedious tasks that eat up your day: writing tests for untested code, fixing lint errors across a project, resolving merge conflicts, updating dependencies, and writing release notes.

```python
claude "write tests for the auth module, run them, and fix any failures"
```

Build features and fix bugs

Describe what you want in plain language. Claude Code plans the approach, writes the code across multiple files, and verifies it works.For bugs, paste an error message or describe the symptom. Claude Code traces the issue through your codebase, identifies the root cause, and implements a fix. See [common workflows](/docs/en/common-workflows) for more examples.

Create commits and pull requests

Claude Code works directly with git. It stages changes, writes commit messages, creates branches, and opens pull requests.

```python
claude "commit my changes with a descriptive message"
```

In CI, you can automate code review and issue triage with [GitHub Actions](/docs/en/github-actions) or [GitLab CI/CD](/docs/en/gitlab-ci-cd).

Connect your tools with MCP

The [Model Context Protocol (MCP)](/docs/en/mcp) is an open standard for connecting AI tools to external data sources. With MCP, Claude Code can read your design docs in Google Drive, update tickets in Jira, pull data from Slack, or use your own custom tooling.

Customize with instructions, skills, and hooks

[`CLAUDE.md`](/docs/en/memory) is a markdown file you add to your project root that Claude Code reads at the start of every session. Use it to set coding standards, architecture decisions, preferred libraries, and review checklists. Claude also builds [auto memory](/docs/en/memory#auto-memory) as it works, saving learnings like build commands and debugging insights across sessions without you writing anything.Create [custom commands](/docs/en/skills) to package repeatable workflows your team can share, like `/review-pr` or `/deploy-staging`.[Hooks](/docs/en/hooks) let you run shell commands before or after Claude Code actions, like auto-formatting after every file edit or running lint before a commit.

Run agent teams and build custom agents

Spawn [multiple Claude Code agents](/docs/en/sub-agents) that work on different parts of a task simultaneously. A lead agent coordinates the work, assigns subtasks, and merges results.For fully custom workflows, the [Agent SDK](/docs/en/agent-sdk/overview) lets you build your own agents powered by Claude Code’s tools and capabilities, with full control over orchestration, tool access, and permissions.

Pipe, script, and automate with the CLI

Claude Code is composable and follows the Unix philosophy. Pipe logs into it, run it in CI, or chain it with other tools:

```python
# Analyze recent log output
tail -200 app.log | claude -p "Slack me if you see any anomalies"

# Automate translations in CI
claude -p "translate new strings into French and raise a PR for review"

# Bulk operations across files
git diff main --name-only | claude -p "review these changed files for security issues"
```

See the [CLI reference](/docs/en/cli-reference) for the full set of commands and flags.

Schedule recurring tasks

Run Claude on a schedule to automate work that repeats: morning PR reviews, overnight CI failure analysis, weekly dependency audits, or syncing docs after PRs merge.

- [Routines](/docs/en/routines) run on Anthropic-managed infrastructure, so they keep running even when your computer is off. They can also trigger on API calls or GitHub events. Create them from the web, the Desktop app, or by running `/schedule` in the CLI.
- [Desktop scheduled tasks](/docs/en/desktop-scheduled-tasks) run on your machine, with direct access to your local files and tools
- [`/loop`](/docs/en/scheduled-tasks) repeats a prompt within a CLI session for quick polling

Work from anywhere

Sessions aren’t tied to a single surface. Move work between environments as your context changes:

- Step away from your desk and keep working from your phone or any browser with [Remote Control](/docs/en/remote-control)
- Message [Dispatch](/docs/en/desktop#sessions-from-dispatch) a task from your phone and open the Desktop session it creates
- Kick off a long-running task on the [web](/docs/en/claude-code-on-the-web) or [iOS app](https://apps.apple.com/app/claude-by-anthropic/id6473753684), then pull it into your terminal with `claude --teleport`
- Hand off a terminal session to the [Desktop app](/docs/en/desktop) with `/desktop` for visual diff review
- Route tasks from team chat: mention `@Claude` in [Slack](/docs/en/slack) with a bug report and get a pull request back


Use Claude Code everywhere

Each surface connects to the same underlying Claude Code engine, so your CLAUDE.md files, settings, and MCP servers work across all of them. Beyond the [Terminal](/docs/en/quickstart), [VS Code](/docs/en/vs-code), [JetBrains](/docs/en/jetbrains), [Desktop](/docs/en/desktop), and [Web](/docs/en/claude-code-on-the-web) environments above, Claude Code integrates with CI/CD, chat, and browser workflows:

| I want to… | Best option |
|----|----|
| Continue a local session from my phone or another device | [Remote Control](/docs/en/remote-control) |
| Push events from Telegram, Discord, iMessage, or my own webhooks into a session | [Channels](/docs/en/channels) |
| Start a task locally, continue on mobile | [Web](/docs/en/claude-code-on-the-web) or [Claude iOS app](https://apps.apple.com/app/claude-by-anthropic/id6473753684) |
| Run Claude on a recurring schedule | [Routines](/docs/en/routines) or [Desktop scheduled tasks](/docs/en/desktop-scheduled-tasks) |
| Automate PR reviews and issue triage | [GitHub Actions](/docs/en/github-actions) or [GitLab CI/CD](/docs/en/gitlab-ci-cd) |
| Get automatic code review on every PR | [GitHub Code Review](/docs/en/code-review) |
| Route bug reports from Slack to pull requests | [Slack](/docs/en/slack) |
| Debug live web applications | [Chrome](/docs/en/chrome) |
| Build custom agents for your own workflows | [Agent SDK](/docs/en/agent-sdk/overview) |


Next steps

Once you’ve installed Claude Code, these guides help you go deeper.

- [Quickstart](/docs/en/quickstart): walk through your first real task, from exploring a codebase to committing a fix
- [Store instructions and memories](/docs/en/memory): give Claude persistent instructions with CLAUDE.md files and auto memory
- [Common workflows](/docs/en/common-workflows) and [best practices](/docs/en/best-practices): patterns for getting the most out of Claude Code
- [Settings](/docs/en/settings): customize Claude Code for your workflow
- [Troubleshooting](/docs/en/troubleshooting): solutions for common issues
- [code.claude.com](https://code.claude.com/): demos, pricing, and product details


---
## claude-code-overview-claude-code-docs.md

# Claude Code overview


Claude Code is an agentic coding tool that reads your codebase, edits files, runs commands, and integrates with your development tools. Available in your terminal, IDE, desktop app, and browser.


Claude Code is an AI-powered coding assistant that helps you build features, fix bugs, and automate development tasks. It understands your entire codebase and can work across multiple files and tools to get things done.

## 

Get started

Choose your environment to get started. Most surfaces require a [Claude subscription](https://claude.com/pricing) or [Anthropic Console](https://console.anthropic.com/) account. The Terminal CLI and VS Code also support [third-party providers](/docs/en/third-party-integrations).

- Terminal

- VS Code

- Desktop app

- Web

- JetBrains

The full-featured CLI for working with Claude Code directly in your terminal. Edit files, run commands, and manage your entire project from the command line.To install Claude Code, use one of the following methods:

- Native Install (Recommended)

- Homebrew

- WinGet

**macOS, Linux, WSL:**

Report incorrect code

Copy


``` shiki
curl -fsSL https://claude.ai/install.sh | bash
```

**Windows PowerShell:**

Report incorrect code

Copy


``` shiki
irm https://claude.ai/install.ps1 | iex
```

**Windows CMD:**

Report incorrect code

Copy


``` shiki
curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd
```

**Windows requires [Git for Windows](https://git-scm.com/downloads/win).** Install it first if you don’t have it.

Native installations automatically update in the background to keep you on the latest version.

Report incorrect code

Copy


``` shiki
brew install --cask claude-code
```

Homebrew installations do not auto-update. Run `brew upgrade claude-code` periodically to get the latest features and security fixes.

Report incorrect code

Copy


``` shiki
winget install Anthropic.ClaudeCode
```

WinGet installations do not auto-update. Run `winget upgrade Anthropic.ClaudeCode` periodically to get the latest features and security fixes.

Then start Claude Code in any project:

Report incorrect code

Copy


``` shiki
cd your-project
claude
```

You’ll be prompted to log in on first use. That’s it! [Continue with the Quickstart →](/docs/en/quickstart)

See [advanced setup](/docs/en/setup) for installation options, manual updates, or uninstallation instructions. Visit [troubleshooting](/docs/en/troubleshooting) if you hit issues.

The VS Code extension provides inline diffs, @-mentions, plan review, and conversation history directly in your editor.

- [Install for VS Code](vscode:extension/anthropic.claude-code)
- [Install for Cursor](cursor:extension/anthropic.claude-code)

Or search for “Claude Code” in the Extensions view (`Cmd+Shift+X` on Mac, `Ctrl+Shift+X` on Windows/Linux). After installing, open the Command Palette (`Cmd+Shift+P` / `Ctrl+Shift+P`), type “Claude Code”, and select **Open in New Tab**.[Get started with VS Code →](/docs/en/vs-code#get-started)

A standalone app for running Claude Code outside your IDE or terminal. Review diffs visually, run multiple sessions side by side, schedule recurring tasks, and kick off cloud sessions.Download and install:

- [macOS](https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code&utm_medium=docs) (Intel and Apple Silicon)
- [Windows](https://claude.ai/api/desktop/win32/x64/exe/latest/redirect?utm_source=claude_code&utm_medium=docs) (x64)
- [Windows ARM64](https://claude.ai/api/desktop/win32/arm64/exe/latest/redirect?utm_source=claude_code&utm_medium=docs) (remote sessions only)

After installing, launch Claude, sign in, and click the **Code** tab to start coding. A [paid subscription](https://claude.com/pricing) is required.[Learn more about the desktop app →](/docs/en/desktop-quickstart)

Run Claude Code in your browser with no local setup. Kick off long-running tasks and check back when they’re done, work on repos you don’t have locally, or run multiple tasks in parallel. Available on desktop browsers and the Claude iOS app.Start coding at [claude.ai/code](https://claude.ai/code).[Get started on the web →](/docs/en/claude-code-on-the-web#getting-started)

A plugin for IntelliJ IDEA, PyCharm, WebStorm, and other JetBrains IDEs with interactive diff viewing and selection context sharing.Install the [Claude Code plugin](https://plugins.jetbrains.com/plugin/27310-claude-code-beta-) from the JetBrains Marketplace and restart your IDE.[Get started with JetBrains →](/docs/en/jetbrains)

## 

What you can do

Here are some of the ways you can use Claude Code:

Automate the work you keep putting off

Claude Code handles the tedious tasks that eat up your day: writing tests for untested code, fixing lint errors across a project, resolving merge conflicts, updating dependencies, and writing release notes.

Report incorrect code

Copy


``` shiki
claude "write tests for the auth module, run them, and fix any failures"
```

Build features and fix bugs

Describe what you want in plain language. Claude Code plans the approach, writes the code across multiple files, and verifies it works.For bugs, paste an error message or describe the symptom. Claude Code traces the issue through your codebase, identifies the root cause, and implements a fix. See [common workflows](/docs/en/common-workflows) for more examples.

Create commits and pull requests

Claude Code works directly with git. It stages changes, writes commit messages, creates branches, and opens pull requests.

Report incorrect code

Copy


``` shiki
claude "commit my changes with a descriptive message"
```

In CI, you can automate code review and issue triage with [GitHub Actions](/docs/en/github-actions) or [GitLab CI/CD](/docs/en/gitlab-ci-cd).

Connect your tools with MCP

The [Model Context Protocol (MCP)](/docs/en/mcp) is an open standard for connecting AI tools to external data sources. With MCP, Claude Code can read your design docs in Google Drive, update tickets in Jira, pull data from Slack, or use your own custom tooling.

Customize with instructions, skills, and hooks

[`CLAUDE.md`](/docs/en/memory) is a markdown file you add to your project root that Claude Code reads at the start of every session. Use it to set coding standards, architecture decisions, preferred libraries, and review checklists. Claude also builds [auto memory](/docs/en/memory#auto-memory) as it works, saving learnings like build commands and debugging insights across sessions without you writing anything.Create [custom commands](/docs/en/skills) to package repeatable workflows your team can share, like `/review-pr` or `/deploy-staging`.[Hooks](/docs/en/hooks) let you run shell commands before or after Claude Code actions, like auto-formatting after every file edit or running lint before a commit.

Run agent teams and build custom agents

Spawn [multiple Claude Code agents](/docs/en/sub-agents) that work on different parts of a task simultaneously. A lead agent coordinates the work, assigns subtasks, and merges results.For fully custom workflows, the [Agent SDK](../05-Agent-SDK/agent-sdk-overview.md) lets you build your own agents powered by Claude Code’s tools and capabilities, with full control over orchestration, tool access, and permissions.

Pipe, script, and automate with the CLI

Claude Code is composable and follows the Unix philosophy. Pipe logs into it, run it in CI, or chain it with other tools:

Report incorrect code

Copy


``` shiki
# Monitor logs and get alerted
tail -f app.log | claude -p "Slack me if you see any anomalies"

# Automate translations in CI
claude -p "translate new strings into French and raise a PR for review"

# Bulk operations across files
git diff main --name-only | claude -p "review these changed files for security issues"
```

See the [CLI reference](/docs/en/cli-reference) for the full set of commands and flags.

Work from anywhere

Sessions aren’t tied to a single surface. Move work between environments as your context changes:

- Step away from your desk and keep working from your phone or any browser with [Remote Control](/docs/en/remote-control)
- Kick off a long-running task on the [web](/docs/en/claude-code-on-the-web) or [iOS app](https://apps.apple.com/app/claude-by-anthropic/id6473753684), then pull it into your terminal with `/teleport`
- Hand off a terminal session to the [Desktop app](/docs/en/desktop) with `/desktop` for visual diff review
- Route tasks from team chat: mention `@Claude` in [Slack](/docs/en/slack) with a bug report and get a pull request back

## 

Use Claude Code everywhere

Each surface connects to the same underlying Claude Code engine, so your CLAUDE.md files, settings, and MCP servers work across all of them. Beyond the [Terminal](/docs/en/quickstart), [VS Code](/docs/en/vs-code), [JetBrains](/docs/en/jetbrains), [Desktop](/docs/en/desktop), and [Web](/docs/en/claude-code-on-the-web) environments above, Claude Code integrates with CI/CD, chat, and browser workflows:

| I want to… | Best option |
|----|----|
| Continue a local session from my phone or another device | [Remote Control](/docs/en/remote-control) |
| Start a task locally, continue on mobile | [Web](/docs/en/claude-code-on-the-web) or [Claude iOS app](https://apps.apple.com/app/claude-by-anthropic/id6473753684) |
| Automate PR reviews and issue triage | [GitHub Actions](/docs/en/github-actions) or [GitLab CI/CD](/docs/en/gitlab-ci-cd) |
| Route bug reports from Slack to pull requests | [Slack](/docs/en/slack) |
| Debug live web applications | [Chrome](/docs/en/chrome) |
| Build custom agents for your own workflows | [Agent SDK](../05-Agent-SDK/agent-sdk-overview.md) |

## 

Next steps

Once you’ve installed Claude Code, these guides help you go deeper.

- [Quickstart](/docs/en/quickstart): walk through your first real task, from exploring a codebase to committing a fix
- [Store instructions and memories](/docs/en/memory): give Claude persistent instructions with CLAUDE.md files and auto memory
- [Common workflows](/docs/en/common-workflows) and [best practices](/docs/en/best-practices): patterns for getting the most out of Claude Code
- [Settings](/docs/en/settings): customize Claude Code for your workflow
- [Troubleshooting](/docs/en/troubleshooting): solutions for common issues
- [code.claude.com](https://code.claude.com/): demos, pricing, and product details


---
## claude-code-plan-mode.md

# Claude Code Plan Mode Configuration

Comprehensive guide to plan mode behavior, environment variables, and agent configuration.

## Two Plan Mode Variants

### V2 Phase-Based Mode (Default)
Structured 3-phase workflow with **mandatory parallel subagents**.

**Phases:**
1. **Phase 1: Initial Understanding** - Parallel exploration with Explore agents
2. **Phase 2: Design** - Architecture planning with Plan agents
3. **Phase 3: Review** - Main agent asks clarifying questions

**Characteristics:**
- Always spawns subagents (minimum 1 per phase)
- Structured workflow
- Less interactive upfront
- Gather everything → design → review

### Interview/Iterative Mode
Conversational plan mode with **optional subagents**.

**Workflow:**
- Iterative loop: Explore code → Update plan file → Ask user → Repeat
- Subagents are available but not mandatory
- More interactive and conversational
- Pair-planning approach

**Enable with:**
```bash
export CLAUDE_CODE_PLAN_MODE_INTERVIEW_PHASE=true
```

---

## Environment Variables

### CLAUDE_CODE_PLAN_MODE_INTERVIEW_PHASE

**Purpose:** Switch between V2 phase-based mode and interview mode.

**Accepted Values:**

Truthy (enable interview mode):
- `1`
- `true`
- `yes`
- `on`

Falsy (disable, use V2 phase-based):
- `0`
- `false`
- `no`
- `off`

**Notes:**
- Case-insensitive
- Values are trimmed
- Falls back to tengu flag `tengu_plan_mode_interview_phase` if unset (default: false)

**Implementation:**
```javascript
function tH(H) {  // isTruthy
  if (!H) return false;
  if (typeof H === "boolean") return H;
  let $ = H.toLowerCase().trim();
  return ["1", "true", "yes", "on"].includes($);
}

function CK(H) {  // isFalsy
  if (H === void 0) return false;
  if (typeof H === "boolean") return !H;
  if (!H) return false;
  let $ = H.toLowerCase().trim();
  return ["0", "false", "no", "off"].includes($);
}
```

---

### CLAUDE_CODE_PLAN_V2_AGENT_COUNT

**Purpose:** Number of Plan agents spawned in Phase 2.

**Validation:** Must be integer 1-10 (0 is rejected).

**Defaults:**
- `1` - standard models
- `3` - if model is "max" AND config is "default_claude_max_20x"
- `3` - if model is "enterprise" or "team"

**Implementation:**
```javascript
function a_D() {
  if (process.env.CLAUDE_CODE_PLAN_V2_AGENT_COUNT) {
    let A = parseInt(process.env.CLAUDE_CODE_PLAN_V2_AGENT_COUNT, 10);
    if (!isNaN(A) && A > 0 && A <= 10) return A;
  }
  let H = C9(), $ = Qb();
  if (H === "max" && $ === "default_claude_max_20x") return 3;
  if (H === "enterprise" || H === "team") return 3;
  return 1;
}
```

**Setting to 0:** Falls back to defaults (does NOT disable subagents).

---

### CLAUDE_CODE_PLAN_V2_EXPLORE_AGENT_COUNT

**Purpose:** Number of Explore agents spawned in Phase 1.

**Validation:** Must be integer 1-10 (0 is rejected).

**Default:** `3`

**Implementation:**
```javascript
function t_D() {
  if (process.env.CLAUDE_CODE_PLAN_V2_EXPLORE_AGENT_COUNT) {
    let H = parseInt(process.env.CLAUDE_CODE_PLAN_V2_EXPLORE_AGENT_COUNT, 10);
    if (!isNaN(H) && H > 0 && H <= 10) return H;
  }
  return 3;
}
```

**Setting to 0:** Falls back to 3 (does NOT disable subagents).

---

## Agent Configuration by Phase

### Phase 1: Initial Understanding

| Property | Value |
|----------|-------|
| **Agent Type** | `Explore` (zp.agentType) |
| **Default Count** | 3 |
| **Env Override** | `CLAUDE_CODE_PLAN_V2_EXPLORE_AGENT_COUNT` |
| **Valid Range** | 1-10 |
| **Model** | Haiku |
| **Mode** | READ-ONLY |

**Disallowed Tools:**
- Edit
- Write
- NotebookEdit
- EnterPlanMode
- ExitPlanMode

**Allowed Tools:**
- Read, Grep, Glob, Bash
- Agent (nested subagents)
- AskUserQuestion
- TaskCreate/TaskUpdate/TaskGet
- All MCP tools

**Template Variables:**
- `${A}` = explore agent count (3 default)
- `${zp.agentType}` = "Explore"

---

### Phase 2: Design

| Property | Value |
|----------|-------|
| **Agent Type** | `Plan` (UG$.agentType) |
| **Default Count** | 1 (or 3 for max/enterprise/team) |
| **Env Override** | `CLAUDE_CODE_PLAN_V2_AGENT_COUNT` |
| **Valid Range** | 1-10 |
| **Model** | Inherit from parent |
| **Mode** | READ-ONLY |

**Tool Restrictions:** Same as Phase 1 (references zp.tools)

**Template Variables:**
- `${$}` = plan agent count (1 or 3 default)
- `${UG$.agentType}` = "Plan"

---

### Phase 3: Review

| Property | Value |
|----------|-------|
| **Agent Type** | Main agent (no subagent) |
| **Tool Used** | `AskUserQuestion` (g7) |
| **Purpose** | Clarify remaining questions |

**Template Variable:**
- `${g7}` = AskUserQuestion tool

---

## Plan File Tools

Both modes use these tools for plan file management:

- `${Oj.name}` = Edit tool (for editing existing plan)
- `${fj.name}` = Write tool (for creating new plan)
- `${CY.name}` = Tool to request plan approval

---

## Interview Mode Details

When `CLAUDE_CODE_PLAN_MODE_INTERVIEW_PHASE=true`:

### Workflow
```
Repeat until plan is complete:
1. Explore - Use Read/Grep/Glob/Bash or optionally Explore agents
2. Update plan file - Capture findings incrementally
3. Ask user - Use AskUserQuestion when needed
```

### Key Differences from V2
- **No mandatory subagents** - direct tool use preferred for simple queries
- **Explore agents optional** - "You can use the Explore agent type... though for straightforward queries direct tools are simpler"
- **Incremental planning** - update plan file as you go
- **More user interaction** - ask questions throughout, not just at the end

### Turn Endings
Each turn must end with either:
- `AskUserQuestion` - to gather more information
- Plan approval tool - when plan is ready

### Plan File Structure
- **Context section** - why the change is needed
- **Recommended approach** - single approach, not all alternatives
- **Critical files** - paths to files to be modified
- **Reusable code** - existing functions/utilities with paths
- **Verification** - how to test changes

---

## Token Optimization Configuration

**Minimal subagent spawning:**
```bash
export CLAUDE_CODE_PLAN_MODE_INTERVIEW_PHASE=true  # Enable interview mode
export CLAUDE_CODE_PLAN_V2_AGENT_COUNT=1           # Minimum Plan agents if spawned
export CLAUDE_CODE_PLAN_V2_EXPLORE_AGENT_COUNT=1   # Minimum Explore agents if spawned
```

**Effect:**
- Interview mode makes subagents optional
- If subagents ARE spawned, only 1 will be created
- Most work happens in main agent context
- Significant token savings

---

## Function Reference

**Plan mode entry point:** `pe6()`
```javascript
// Selects between Interview and V2 modes
if (OP()) return Ue6(H);  // Interview mode
// else: V2 phase-based mode
```

**Mode selector:** `OP()`
```javascript
function OP() {
  let H = process.env.CLAUDE_CODE_PLAN_MODE_INTERVIEW_PHASE;
  if (tH(H)) return true;   // Interview mode
  if (CK(H)) return false;  // V2 mode
  return IA("tengu_plan_mode_interview_phase", false);  // Default: V2
}
```

**Interview mode template:** `Ue6(H)`
- Returns iterative workflow instructions
- No mandatory subagent spawning
- Emphasis on incremental planning

**V2 mode template:** (default pe6 path)
- Returns 3-phase structured workflow
- Mandatory parallel subagent spawning
- Explore → Plan → Review phases

---

## Summary Table

| Aspect | Interview Mode | V2 Phase-Based |
|--------|---------------|----------------|
| **Trigger** | `CLAUDE_CODE_PLAN_MODE_INTERVIEW_PHASE=true` | Default |
| **Subagents** | Optional | Mandatory |
| **Default Explore Count** | N/A (optional) | 3 |
| **Default Plan Count** | N/A (optional) | 1-3 |
| **Workflow** | Iterative loop | 3 structured phases |
| **User Interaction** | Throughout | Primarily at end |
| **Plan File Updates** | Incremental | After phase completion |
| **Token Usage** | Lower (fewer subagents) | Higher (parallel agents) |

---

## Validated in Binary Version

- **2.1.75** - All values confirmed via cli.js extraction
- Functions: `OP()`, `tH()`, `CK()`, `a_D()`, `t_D()`, `pe6()`, `Ue6()`


---
## claude-code-settings-claude-code-docs-d4420b4b52.md

# Claude Code settings


Configure Claude Code with global and project-level settings, and environment variables.


> ## Documentation Index
>
> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt>
>
> Use this file to discover all available pages before exploring further.

Claude Code offers a variety of settings to configure its behavior to meet your needs. You can configure Claude Code by running the `/config` command when using the interactive REPL, which opens a tabbed Settings interface where you can view status information and modify configuration options.


Configuration scopes

Claude Code uses a **scope system** to determine where configurations apply and who they’re shared with. Understanding scopes helps you decide how to configure Claude Code for personal use, team collaboration, or enterprise deployment.


Available scopes

| Scope       | Location                                                                           | Who it affects                       | Shared with team?      |
|:------------|:-----------------------------------------------------------------------------------|:-------------------------------------|:-----------------------|
| **Managed** | Server-managed settings, plist / registry, or system-level `managed-settings.json` | All users on the machine             | Yes (deployed by IT)   |
| **User**    | `~/.claude/` directory                                                             | You, across all projects             | No                     |
| **Project** | `.claude/` in repository                                                           | All collaborators on this repository | Yes (committed to git) |
| **Local**   | `.claude/settings.local.json`                                                      | You, in this repository only         | No (gitignored)        |


When to use each scope

**Managed scope** is for:

- Security policies that must be enforced organization-wide
- Compliance requirements that can’t be overridden
- Standardized configurations deployed by IT/DevOps

**User scope** is best for:

- Personal preferences you want everywhere (themes, editor settings)
- Tools and plugins you use across all projects
- API keys and authentication (stored securely)

**Project scope** is best for:

- Team-shared settings (permissions, hooks, MCP servers)
- Plugins the whole team should have
- Standardizing tooling across collaborators

**Local scope** is best for:

- Personal overrides for a specific project
- Testing configurations before sharing with the team
- Machine-specific settings that won’t work for others


How scopes interact

When the same setting appears in multiple scopes, Claude Code applies them in priority order:

1.  **Managed** (highest) - can’t be overridden by anything
2.  **Command line arguments** - temporary session overrides
3.  **Local** - overrides project and user settings
4.  **Project** - overrides user settings
5.  **User** (lowest) - applies when nothing else specifies the setting

For example, if your user settings set `spinnerTipsEnabled` to `true` and project settings set it to `false`, the project value applies. Permission rules behave differently because they merge across scopes rather than override. See [Settings precedence](#settings-precedence).


What uses scopes

Scopes apply to many Claude Code features:

| Feature         | User location             | Project location                   | Local location                 |
|:----------------|:--------------------------|:-----------------------------------|:-------------------------------|
| **Settings**    | `~/.claude/settings.json` | `.claude/settings.json`            | `.claude/settings.local.json`  |
| **Subagents**   | `~/.claude/agents/`       | `.claude/agents/`                  | None                           |
| **MCP servers** | `~/.claude.json`          | `.mcp.json`                        | `~/.claude.json` (per-project) |
| **Plugins**     | `~/.claude/settings.json` | `.claude/settings.json`            | `.claude/settings.local.json`  |
| **CLAUDE.md**   | `~/.claude/CLAUDE.md`     | `CLAUDE.md` or `.claude/CLAUDE.md` | `CLAUDE.local.md`              |

On Windows, paths shown as `~/.claude` resolve to `%USERPROFILE%\.claude`.

------------------------------------------------------------------------


Settings files

The `settings.json` file is the official mechanism for configuring Claude Code through hierarchical settings:

- **User settings** are defined in `~/.claude/settings.json` and apply to all projects.
- **Project settings** are saved in your project directory:
  - `.claude/settings.json` for settings that are checked into source control and shared with your team
  - `.claude/settings.local.json` for settings that are not checked in, useful for personal preferences and experimentation. Claude Code will configure git to ignore `.claude/settings.local.json` when it is created.
- **Managed settings**: For organizations that need centralized control, Claude Code supports multiple delivery mechanisms for managed settings. All use the same JSON format and cannot be overridden by user or project settings:
  - **Server-managed settings**: delivered from Anthropic’s servers via the Claude.ai admin console. See [server-managed settings](/docs/en/server-managed-settings).
  - **MDM/OS-level policies**: delivered through native device management on macOS and Windows:
    - macOS: `com.anthropic.claudecode` managed preferences domain. The plist’s top-level keys mirror `managed-settings.json`, with nested settings as dictionaries and arrays as plist arrays. Deploy via configuration profiles in Jamf, Iru (Kandji), or similar MDM tools.
    - Windows: `HKLM\SOFTWARE\Policies\ClaudeCode` registry key with a `Settings` value (REG_SZ or REG_EXPAND_SZ) containing JSON (deployed via Group Policy or Intune)
    - Windows (user-level): `HKCU\SOFTWARE\Policies\ClaudeCode` (lowest policy priority, only used when no admin-level source exists)
  - **File-based**: `managed-settings.json` and `managed-mcp.json` deployed to system directories:
    - macOS: `/Library/Application Support/ClaudeCode/`
    - Linux and WSL: `/etc/claude-code/`
    - Windows: `C:\Program Files\ClaudeCode\`

    The legacy Windows path `C:\ProgramData\ClaudeCode\managed-settings.json` is no longer supported as of v2.1.75. Administrators who deployed settings to that location must migrate files to `C:\Program Files\ClaudeCode\managed-settings.json`.

    File-based managed settings also support a drop-in directory at `managed-settings.d/` in the same system directory alongside `managed-settings.json`. This lets separate teams deploy independent policy fragments without coordinating edits to a single file. Following the systemd convention, `managed-settings.json` is merged first as the base, then all `*.json` files in the drop-in directory are sorted alphabetically and merged on top. Later files override earlier ones for scalar values; arrays are concatenated and de-duplicated; objects are deep-merged. Hidden files starting with `.` are ignored. Use numeric prefixes to control merge order, for example `10-telemetry.json` and `20-security.json`.

  See [managed settings](/docs/en/permissions#managed-only-settings) and [Managed MCP configuration](/docs/en/mcp#managed-mcp-configuration) for details. This [repository](https://github.com/anthropics/claude-code/tree/main/examples/mdm) includes starter deployment templates for Jamf, Iru (Kandji), Intune, and Group Policy. Use these as starting points and adjust them to fit your needs.

  Managed deployments can also restrict **plugin marketplace additions** using `strictKnownMarketplaces`. For more information, see [Managed marketplace restrictions](/docs/en/plugin-marketplaces#managed-marketplace-restrictions).
- **Other configuration** is stored in `~/.claude.json`. This file contains your OAuth session, [MCP server](/docs/en/mcp) configurations for user and local scopes, per-project state (allowed tools, trust settings), and various caches. Project-scoped MCP servers are stored separately in `.mcp.json`.

Claude Code automatically creates timestamped backups of configuration files and retains the five most recent backups to prevent data loss.

Example settings.json

```python
{
  "$schema": "https://json.schemastore.org/claude-code-settings.json",
  "permissions": {
    "allow": [
      "Bash(npm run lint)",
      "Bash(npm run test *)",
      "Read(~/.zshrc)"
    ],
    "deny": [
      "Bash(curl *)",
      "Read(./.env)",
      "Read(./.env.*)",
      "Read(./secrets/**)"
    ]
  },
  "env": {
    "CLAUDE_CODE_ENABLE_TELEMETRY": "1",
    "OTEL_METRICS_EXPORTER": "otlp"
  },
  "companyAnnouncements": [
    "Welcome to Acme Corp! Review our code guidelines at docs.acme.com",
    "Reminder: Code reviews required for all PRs",
    "New security policy in effect"
  ]
}
```

The `$schema` line in the example above points to the [official JSON schema](https://json.schemastore.org/claude-code-settings.json) for Claude Code settings. Adding it to your `settings.json` enables autocomplete and inline validation in VS Code, Cursor, and any other editor that supports JSON schema validation. The published schema is updated periodically and may not include settings added in the most recent CLI releases, so a validation warning on a recently documented field does not necessarily mean your configuration is invalid.


When edits take effect

Claude Code watches your settings files and reloads them when they change, so edits to most keys apply to the running session without a restart. This includes `permissions`, `hooks`, and credential helpers like `apiKeyHelper`. The reload covers user, project, local, and managed settings, and the [`ConfigChange` hook](/docs/en/hooks#configchange) fires for each detected change. A few keys are read once at session start and apply on the next restart instead:

- `model`: use [`/model`](/docs/en/model-config#setting-your-model) to switch mid-session
- [`outputStyle`](/docs/en/output-styles): part of the system prompt, which is rebuilt on `/clear` or restart


Available settings

`settings.json` supports a number of options:

| Key                               | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                | Example                                                                                                                        |
|:----------------------------------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:-------------------------------------------------------------------------------------------------------------------------------|
| `agent`                           | Run the main thread as a named subagent. Applies that subagent’s system prompt, tool restrictions, and model. See [Invoke subagents explicitly](/docs/en/sub-agents#invoke-subagents-explicitly)                                                                                                                                                                                                                                                                                                                                                           | `"code-reviewer"`                                                                                                              |
| `allowedChannelPlugins`           | (Managed settings only) Allowlist of channel plugins that may push messages. Replaces the default Anthropic allowlist when set. Undefined = fall back to the default, empty array = block all channel plugins. Requires `channelsEnabled: true`. See [Restrict which channel plugins can run](/docs/en/channels#restrict-which-channel-plugins-can-run)                                                                                                                                                                                                    | `[{ "marketplace": "claude-plugins-official", "plugin": "telegram" }]`                                                         |
| `allowedHttpHookUrls`             | Allowlist of URL patterns that HTTP hooks may target. Supports `*` as a wildcard. When set, hooks with non-matching URLs are blocked. Undefined = no restriction, empty array = block all HTTP hooks. Arrays merge across settings sources. See [Hook configuration](#hook-configuration)                                                                                                                                                                                                                                                                  | `["https://hooks.example.com/*"]`                                                                                              |
| `allowedMcpServers`               | When set in managed-settings.json, allowlist of MCP servers users can configure. Undefined = no restrictions, empty array = lockdown. Applies to all scopes. Denylist takes precedence. See [Managed MCP configuration](/docs/en/mcp#managed-mcp-configuration)                                                                                                                                                                                                                                                                                            | `[{ "serverName": "github" }]`                                                                                                 |
| `allowManagedHooksOnly`           | (Managed settings only) Only managed hooks, SDK hooks, and hooks from plugins force-enabled in managed settings `enabledPlugins` are loaded. User, project, and all other plugin hooks are blocked. See [Hook configuration](#hook-configuration)                                                                                                                                                                                                                                                                                                          | `true`                                                                                                                         |
| `allowManagedMcpServersOnly`      | (Managed settings only) Only `allowedMcpServers` from managed settings are respected. `deniedMcpServers` still merges from all sources. Users can still add MCP servers, but only the admin-defined allowlist applies. See [Managed MCP configuration](/docs/en/mcp#managed-mcp-configuration)                                                                                                                                                                                                                                                             | `true`                                                                                                                         |
| `allowManagedPermissionRulesOnly` | (Managed settings only) Prevent user and project settings from defining `allow`, `ask`, or `deny` permission rules. Only rules in managed settings apply. See [Managed-only settings](/docs/en/permissions#managed-only-settings)                                                                                                                                                                                                                                                                                                                          | `true`                                                                                                                         |
| `alwaysThinkingEnabled`           | Enable [extended thinking](/docs/en/model-config#extended-thinking) by default for all sessions. Typically configured via the `/config` command rather than editing directly. To force thinking off regardless of this setting, set [`CLAUDE_CODE_DISABLE_THINKING`](/docs/en/env-vars) in `env`                                                                                                                                                                                                                                                           | `true`                                                                                                                         |
| `apiKeyHelper`                    | Custom script, to be executed in `/bin/sh`, to generate an auth value. This value will be sent as `X-Api-Key` and `Authorization: Bearer` headers for model requests. Set the refresh interval with [`CLAUDE_CODE_API_KEY_HELPER_TTL_MS`](/docs/en/env-vars)                                                                                                                                                                                                                                                                                               | `/bin/generate_temp_api_key.sh`                                                                                                |
| `attribution`                     | Customize attribution for git commits and pull requests. See [Attribution settings](#attribution-settings)                                                                                                                                                                                                                                                                                                                                                                                                                                                 | `{"commit": "🤖 Generated with Claude Code", "pr": ""}`                                                                        |
| `autoMemoryDirectory`             | Custom directory for [auto memory](/docs/en/memory#storage-location) storage. Accepts an absolute path or a `~/`-prefixed path. Accepted from policy and user settings, and from the `--settings` flag. Not accepted from project or local settings, since a cloned repository could supply either file to redirect memory writes to sensitive locations                                                                                                                                                                                                   | `"~/my-memory-dir"`                                                                                                            |
| `autoMemoryEnabled`               | Enable [auto memory](/docs/en/memory#enable-or-disable-auto-memory). When `false`, Claude does not read from or write to the auto memory directory. Default: `true`. You can also toggle this with `/memory` during a session. To disable via environment variable, set [`CLAUDE_CODE_DISABLE_AUTO_MEMORY`](/docs/en/env-vars) in `env`                                                                                                                                                                                                                    | `false`                                                                                                                        |
| `autoMode`                        | Customize what the [auto mode](/docs/en/permission-modes#eliminate-prompts-with-auto-mode) classifier blocks and allows. Contains `environment`, `allow`, `soft_deny`, and `hard_deny` arrays of prose rules. Include the literal string `"$defaults"` in an array to inherit the built-in rules at that position. See [Configure auto mode](/docs/en/auto-mode-config). Not read from shared project settings                                                                                                                                             | `{"soft_deny": ["$defaults", "Never run terraform apply"]}`                                                                    |
| `autoScrollEnabled`               | In [fullscreen rendering](/docs/en/fullscreen), follow new output to the bottom of the conversation. Default: `true`. Appears in `/config` as **Auto-scroll**. Permission prompts still scroll into view when this is off                                                                                                                                                                                                                                                                                                                                  | `false`                                                                                                                        |
| `autoUpdatesChannel`              | Release channel to follow for updates. Use `"stable"` for a version that is typically about one week old and skips versions with major regressions, or `"latest"` (default) for the most recent release. To disable auto-updates entirely, set [`DISABLE_AUTOUPDATER`](/docs/en/setup#disable-auto-updates) in `env`                                                                                                                                                                                                                                       | `"stable"`                                                                                                                     |
| `availableModels`                 | Restrict which models users can select via `/model`, `--model`, or `ANTHROPIC_MODEL`. Does not affect the Default option. See [Restrict model selection](/docs/en/model-config#restrict-model-selection)                                                                                                                                                                                                                                                                                                                                                   | `["sonnet", "haiku"]`                                                                                                          |
| `awaySummaryEnabled`              | Show a one-line session recap when you return to the terminal after a few minutes away. Set to `false` or turn off Session recap in `/config` to disable. Same as [`CLAUDE_CODE_ENABLE_AWAY_SUMMARY`](/docs/en/env-vars)                                                                                                                                                                                                                                                                                                                                   | `true`                                                                                                                         |
| `awsAuthRefresh`                  | Custom script that modifies the `.aws` directory (see [advanced credential configuration](/docs/en/amazon-bedrock#advanced-credential-configuration))                                                                                                                                                                                                                                                                                                                                                                                                      | `aws sso login --profile myprofile`                                                                                            |
| `awsCredentialExport`             | Custom script that outputs JSON with AWS credentials (see [advanced credential configuration](/docs/en/amazon-bedrock#advanced-credential-configuration))                                                                                                                                                                                                                                                                                                                                                                                                  | `/bin/generate_aws_grant.sh`                                                                                                   |
| `blockedMarketplaces`             | (Managed settings only) Blocklist of marketplace sources. Enforced on marketplace add and on plugin install, update, refresh, and auto-update, so a marketplace added before the policy was set cannot be used to fetch plugins. Blocked sources are checked before downloading, so they never touch the filesystem. See [Managed marketplace restrictions](/docs/en/plugin-marketplaces#managed-marketplace-restrictions)                                                                                                                                 | `[{ "source": "github", "repo": "untrusted/plugins" }]`                                                                        |
| `channelsEnabled`                 | (Managed settings only) Allow [channels](/docs/en/channels) for the organization. On claude.ai Team and Enterprise plans, channels are blocked when this is unset or `false`. For [Anthropic Console](/docs/en/authentication#claude-console-authentication) accounts using API key authentication, channels are allowed by default unless your organization deploys managed settings, in which case this key must be set to `true`                                                                                                                        | `true`                                                                                                                         |
| `claudeMd`                        | (Managed settings only) CLAUDE.md-style instructions injected as organization-managed memory. Only honored when set in managed or policy settings and ignored in user, project, and local settings. See [organization-wide CLAUDE.md](/docs/en/memory#deploy-organization-wide-claude-md)                                                                                                                                                                                                                                                                  | `"Always run make lint before committing."`                                                                                    |
| `claudeMdExcludes`                | Glob patterns or absolute paths of `CLAUDE.md` files to skip when loading [memory](/docs/en/memory). Patterns match against absolute file paths. Only applies to user, project, and local memory; managed policy files cannot be excluded                                                                                                                                                                                                                                                                                                                  | `["**/vendor/**/CLAUDE.md"]`                                                                                                   |
| `cleanupPeriodDays`               | Session files older than this period are deleted at startup (default: 30 days, minimum 1). Setting to `0` is rejected with a validation error. Also controls the age cutoff for automatic removal of [orphaned subagent worktrees](/docs/en/worktrees#clean-up-worktrees) at startup. To disable transcript writes entirely, set the [`CLAUDE_CODE_SKIP_PROMPT_HISTORY`](/docs/en/env-vars) environment variable, or in non-interactive mode (`-p`) use the `--no-session-persistence` flag or the `persistSession: false` SDK option.                     | `20`                                                                                                                           |
| `companyAnnouncements`            | Announcement to display to users at startup. If multiple announcements are provided, they will be cycled through at random.                                                                                                                                                                                                                                                                                                                                                                                                                                | `["Welcome to Acme Corp! Review our code guidelines at docs.acme.com"]`                                                        |
| `defaultShell`                    | Default shell for input-box `!` commands. Accepts `"bash"` (default) or `"powershell"`. Setting `"powershell"` routes interactive `!` commands through PowerShell on Windows. Requires `CLAUDE_CODE_USE_POWERSHELL_TOOL=1`. See [PowerShell tool](/docs/en/tools-reference#powershell-tool)                                                                                                                                                                                                                                                                | `"powershell"`                                                                                                                 |
| `deniedMcpServers`                | When set in managed-settings.json, denylist of MCP servers that are explicitly blocked. Applies to all scopes including managed servers. Denylist takes precedence over allowlist. See [Managed MCP configuration](/docs/en/mcp#managed-mcp-configuration)                                                                                                                                                                                                                                                                                                 | `[{ "serverName": "filesystem" }]`                                                                                             |
| `disableAgentView`                | Set to `true` to turn off [background agents and agent view](/docs/en/agent-view): `claude agents`, `--bg`, `/background`, and the on-demand supervisor. Typically set in [managed settings](/docs/en/permissions#managed-settings). Equivalent to setting `CLAUDE_CODE_DISABLE_AGENT_VIEW` to `1`                                                                                                                                                                                                                                                         | `true`                                                                                                                         |
| `disableAllHooks`                 | Disable all [hooks](/docs/en/hooks) and any custom [status line](/docs/en/statusline)                                                                                                                                                                                                                                                                                                                                                                                                                                                                      | `true`                                                                                                                         |
| `disableAutoMode`                 | Set to `"disable"` to prevent [auto mode](/docs/en/permission-modes#eliminate-prompts-with-auto-mode) from being activated. Removes `auto` from the `Shift+Tab` cycle and rejects `--permission-mode auto` at startup. Most useful in [managed settings](/docs/en/permissions#managed-settings) where users cannot override it                                                                                                                                                                                                                             | `"disable"`                                                                                                                    |
| `disableDeepLinkRegistration`     | Set to `"disable"` to prevent Claude Code from registering the `claude-cli://` protocol handler with the operating system on startup. [Deep links](/docs/en/deep-links) let external tools open a Claude Code session with a pre-filled prompt. Useful in environments where protocol handler registration is restricted or managed separately                                                                                                                                                                                                             | `"disable"`                                                                                                                    |
| `disabledMcpjsonServers`          | List of specific MCP servers from `.mcp.json` files to reject                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              | `["filesystem"]`                                                                                                               |
| `disableRemoteControl`            | Disable [Remote Control](/docs/en/remote-control): blocks `claude remote-control`, the `--remote-control` flag, auto-start, and the in-session toggle. Typically placed in [managed settings](/docs/en/permissions#managed-settings) for per-device MDM enforcement, but works from any scope. Requires Claude Code v2.1.128 or later                                                                                                                                                                                                                      | `true`                                                                                                                         |
| `disableSkillShellExecution`      | Disable inline shell execution for `` !`...` `` and ```` ```! ```` blocks in [skills](/docs/en/skills) and custom commands from user, project, plugin, or additional-directory sources. Commands are replaced with `[shell command execution disabled by policy]` instead of being run. Bundled and managed skills are not affected. Most useful in [managed settings](/docs/en/permissions#managed-settings) where users cannot override it                                                                                                               | `true`                                                                                                                         |
| `editorMode`                      | Key binding mode for the input prompt: `"normal"` or `"vim"`. Default: `"normal"`. Appears in `/config` as **Editor mode**                                                                                                                                                                                                                                                                                                                                                                                                                                 | `"vim"`                                                                                                                        |
| `effortLevel`                     | Persist the [effort level](/docs/en/model-config#adjust-effort-level) across sessions. Accepts `"low"`, `"medium"`, `"high"`, or `"xhigh"`. Written automatically when you run `/effort` with one of those values. `--effort` and [`CLAUDE_CODE_EFFORT_LEVEL`](/docs/en/env-vars) override this for one session. See [Adjust effort level](/docs/en/model-config#adjust-effort-level) for supported models                                                                                                                                                 | `"xhigh"`                                                                                                                      |
| `enableAllProjectMcpServers`      | Automatically approve all MCP servers defined in project `.mcp.json` files                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 | `true`                                                                                                                         |
| `enabledMcpjsonServers`           | List of specific MCP servers from `.mcp.json` files to approve                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             | `["memory", "github"]`                                                                                                         |
| `env`                             | Environment variables applied to every session and to subprocesses Claude Code spawns from it. As of v2.1.143, `NO_COLOR` and `FORCE_COLOR` set here are passed to subprocesses but do not change Claude Code’s own interface colors. Set those in your shell before launching `claude` to change interface colors                                                                                                                                                                                                                                         | `{"FOO": "bar"}`                                                                                                               |
| `fastModePerSessionOptIn`         | When `true`, fast mode does not persist across sessions. Each session starts with fast mode off, requiring users to enable it with `/fast`. The user’s fast mode preference is still saved. See [Require per-session opt-in](/docs/en/fast-mode#require-per-session-opt-in)                                                                                                                                                                                                                                                                                | `true`                                                                                                                         |
| `feedbackSurveyRate`              | Probability (0–1) that the [session quality survey](/docs/en/data-usage#session-quality-surveys) appears when eligible. Set to `0` to suppress entirely, or set [`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY`](/docs/en/env-vars) in `env`. Useful when using Bedrock, Vertex, or Foundry where the default sample rate does not apply                                                                                                                                                                                                                            | `0.05`                                                                                                                         |
| `fileSuggestion`                  | Configure a custom script for `@` file autocomplete. See [File suggestion settings](#file-suggestion-settings)                                                                                                                                                                                                                                                                                                                                                                                                                                             | `{"type": "command", "command": "~/.claude/file-suggestion.sh"}`                                                               |
| `forceLoginMethod`                | Use `claudeai` to restrict login to Claude.ai accounts, `console` to restrict login to Claude Console (API usage billing) accounts                                                                                                                                                                                                                                                                                                                                                                                                                         | `claudeai`                                                                                                                     |
| `forceLoginOrgUUID`               | Require login to belong to a specific organization. Accepts a single UUID string, which also pre-selects that organization during login, or an array of UUIDs where any listed organization is accepted without pre-selection. When set in managed settings, login fails if the authenticated account does not belong to a listed organization; an empty array fails closed and blocks login with a misconfiguration message                                                                                                                               | `"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"` or `["xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy"]` |
| `forceRemoteSettingsRefresh`      | (Managed settings only) Block CLI startup until remote managed settings are freshly fetched from the server. If the fetch fails, the CLI exits rather than continuing with cached or no settings. When not set, startup continues without waiting for remote settings. See [fail-closed enforcement](/docs/en/server-managed-settings#enforce-fail-closed-startup)                                                                                                                                                                                         | `true`                                                                                                                         |
| `gcpAuthRefresh`                  | Custom script that refreshes GCP Application Default Credentials when they expire or cannot be loaded. See [advanced credential configuration](/docs/en/google-vertex-ai#advanced-credential-configuration)                                                                                                                                                                                                                                                                                                                                                | `gcloud auth application-default login`                                                                                        |
| `hooks`                           | Configure custom commands to run at lifecycle events. See [hooks documentation](/docs/en/hooks) for format                                                                                                                                                                                                                                                                                                                                                                                                                                                 | See [hooks](/docs/en/hooks)                                                                                                    |
| `httpHookAllowedEnvVars`          | Allowlist of environment variable names HTTP hooks may interpolate into headers. When set, each hook’s effective `allowedEnvVars` is the intersection with this list. Undefined = no restriction. Arrays merge across settings sources. See [Hook configuration](#hook-configuration)                                                                                                                                                                                                                                                                      | `["MY_TOKEN", "HOOK_SECRET"]`                                                                                                  |
| `includeCoAuthoredBy`             | **Deprecated**: Use `attribution` instead. Whether to include the `co-authored-by Claude` byline in git commits and pull requests (default: `true`)                                                                                                                                                                                                                                                                                                                                                                                                        | `false`                                                                                                                        |
| `includeGitInstructions`          | Include built-in commit and PR workflow instructions and the git status snapshot in Claude’s system prompt (default: `true`). Set to `false` to remove both, for example when using your own git workflow skills. The `CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS` environment variable takes precedence over this setting when set                                                                                                                                                                                                                              | `false`                                                                                                                        |
| `language`                        | Configure Claude’s preferred response language (e.g., `"japanese"`, `"spanish"`, `"french"`). Claude will respond in this language by default. Also sets the [voice dictation](/docs/en/voice-dictation#change-the-dictation-language) language                                                                                                                                                                                                                                                                                                            | `"japanese"`                                                                                                                   |
| `maxSkillDescriptionChars`        | Per-skill character cap on the combined `description` and `when_to_use` text in the [skill listing](/docs/en/skills#skill-descriptions-are-cut-short) Claude sees each turn (default: `1536`). Text longer than this is truncated. Raise to keep long descriptions intact at the cost of more context per turn; lower to fit more skills under [`skillListingBudgetFraction`](#available-settings). Requires Claude Code v2.1.105 or later                                                                                                                 | `2048`                                                                                                                         |
| `minimumVersion`                  | Floor that prevents background auto-updates and `claude update` from installing a version below this one. Switching from the `"latest"` channel to `"stable"` via `/config` prompts you to stay on the current version or allow the downgrade. Choosing to stay sets this value. Also useful in [managed settings](/docs/en/permissions#managed-settings) to pin an organization-wide minimum                                                                                                                                                              | `"2.1.100"`                                                                                                                    |
| `model`                           | Override the default model to use for Claude Code. `--model` and [`ANTHROPIC_MODEL`](/docs/en/model-config#environment-variables) override this for one session                                                                                                                                                                                                                                                                                                                                                                                            | `"claude-sonnet-4-6"`                                                                                                          |
| `modelOverrides`                  | Map Anthropic model IDs to provider-specific model IDs such as Bedrock inference profile ARNs. Each model picker entry uses its mapped value when calling the provider API. See [Override model IDs per version](/docs/en/model-config#override-model-ids-per-version)                                                                                                                                                                                                                                                                                     | `{"claude-opus-4-6": "arn:aws:bedrock:..."}`                                                                                   |
| `otelHeadersHelper`               | Script to generate dynamic OpenTelemetry headers. Runs at startup and periodically. 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)                                                                                                                                                                                                                                                                                                     | `/bin/generate_otel_headers.sh`                                                                                                |
| `outputStyle`                     | Configure an output style to adjust the system prompt. See [output styles documentation](/docs/en/output-styles)                                                                                                                                                                                                                                                                                                                                                                                                                                           | `"Explanatory"`                                                                                                                |
| `parentSettingsBehavior`          | (Managed settings only) Controls whether managed settings supplied programmatically by an embedding host process, such as the Agent SDK or an IDE extension, apply when an admin-deployed managed tier is also present. `"first-wins"`: the parent-supplied settings are dropped and only the admin tier applies. `"merge"`: the parent-supplied settings apply under the admin tier, filtered so they can tighten policy but not loosen it. Has no effect when no admin tier is deployed. Default: `"first-wins"`. Requires Claude Code v2.1.133 or later | `"merge"`                                                                                                                      |
| `permissions`                     | See table below for structure of permissions.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |                                                                                                                                |
| `plansDirectory`                  | Customize where plan files are stored. Path is relative to project root. Default: `~/.claude/plans`                                                                                                                                                                                                                                                                                                                                                                                                                                                        | `"./plans"`                                                                                                                    |
| `pluginTrustMessage`              | (Managed settings only) Custom message appended to the plugin trust warning shown before installation. Use this to add organization-specific context, for example to confirm that plugins from your internal marketplace are vetted.                                                                                                                                                                                                                                                                                                                       | `"All plugins from our marketplace are approved by IT"`                                                                        |
| `policyHelper`                    | Admin-deployed executable that computes managed settings dynamically at startup. Only honored from MDM or a system `managed-settings.json` file. See [Compute managed settings with a policy helper](#compute-managed-settings-with-a-policy-helper). Requires Claude Code v2.1.136 or later                                                                                                                                                                                                                                                               | `{"path": "/usr/local/bin/claude-policy"}`                                                                                     |
| `preferredNotifChannel`           | Method for task-complete and permission-prompt notifications: `"auto"`, `"terminal_bell"`, `"iterm2"`, `"iterm2_with_bell"`, `"kitty"`, `"ghostty"`, or `"notifications_disabled"`. Default: `"auto"`, which sends a desktop notification in iTerm2, Ghostty, and Kitty and does nothing in other terminals. Set `"terminal_bell"` to ring the bell character in any terminal. Appears in `/config` as **Notifications**. See [Get a terminal bell or notification](/docs/en/terminal-config#get-a-terminal-bell-or-notification)                          | `"terminal_bell"`                                                                                                              |
| `prefersReducedMotion`            | Reduce or disable UI animations (spinners, shimmer, flash effects) for accessibility                                                                                                                                                                                                                                                                                                                                                                                                                                                                       | `true`                                                                                                                         |
| `prUrlTemplate`                   | URL template for the PR badge shown in the footer and in tool-result summaries. Substitutes `{host}`, `{owner}`, `{repo}`, `{number}`, and `{url}` from the `gh`-reported PR URL. Use to point PR links at an internal code-review tool instead of `github.com`. Does not affect `#123` autolinks in Claude’s prose                                                                                                                                                                                                                                        | `"https://reviews.example.com/{owner}/{repo}/pull/{number}"`                                                                   |
| `respectGitignore`                | Control whether the `@` file picker respects `.gitignore` patterns. When `true` (default), files matching `.gitignore` patterns are excluded from suggestions                                                                                                                                                                                                                                                                                                                                                                                              | `false`                                                                                                                        |
| `showClearContextOnPlanAccept`    | Show the “clear context” option on the plan accept screen. Defaults to `false`. Set to `true` to restore the option                                                                                                                                                                                                                                                                                                                                                                                                                                        | `true`                                                                                                                         |
| `showThinkingSummaries`           | Show [extended thinking](/docs/en/model-config#extended-thinking) summaries in interactive sessions. When unset or `false` (default in interactive mode), thinking blocks are redacted by the API and shown as a collapsed stub. Redaction only changes 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. This setting has no effect in non-interactive mode (`-p`), the Agent SDK, or IDE extensions such as VS Code                         | `true`                                                                                                                         |
| `showTurnDuration`                | Show turn duration messages after responses, e.g. “Cooked for 1m 6s”. Default: `true`. Appears in `/config` as **Show turn duration**                                                                                                                                                                                                                                                                                                                                                                                                                      | `false`                                                                                                                        |
| `skillListingBudgetFraction`      | Fraction of the model’s context window reserved for the [skill listing](/docs/en/skills#skill-descriptions-are-cut-short) Claude sees each turn (default: `0.01` = 1%). When the listing exceeds the budget, descriptions for the least-used skills are collapsed to bare names so Claude can still invoke them but won’t see why. Raise to keep more descriptions visible at the cost of more context per turn. `/doctor` shows the current truncation count and which skills are affected. Requires Claude Code v2.1.105 or later                        | `0.02`                                                                                                                         |
| `skillOverrides`                  | Per-skill visibility overrides keyed by skill name. Value is `"on"`, `"name-only"`, `"user-invocable-only"`, or `"off"`. Lets you hide or collapse a skill without editing its SKILL.md. Does not apply to plugin skills, which are managed through `/plugin`. The `/skills` menu writes these to `.claude/settings.local.json`. See [Override skill visibility from settings](/docs/en/skills#override-skill-visibility-from-settings). Requires Claude Code v2.1.129 or later                                                                            | `{"legacy-context": "name-only", "deploy": "off"}`                                                                             |
| `skipWebFetchPreflight`           | Skip the [WebFetch domain safety check](/docs/en/data-usage#webfetch-domain-safety-check) that sends each requested hostname to `api.anthropic.com` before fetching. Set to `true` in environments that block traffic to Anthropic, such as Bedrock, Vertex AI, or Foundry deployments with restrictive egress. When skipped, WebFetch attempts any URL without consulting the blocklist                                                                                                                                                                   | `true`                                                                                                                         |
| `spinnerTipsEnabled`              | Show tips in the spinner while Claude is working. Set to `false` to disable tips (default: `true`)                                                                                                                                                                                                                                                                                                                                                                                                                                                         | `false`                                                                                                                        |
| `spinnerTipsOverride`             | Override spinner tips with custom strings. `tips`: array of tip strings. `excludeDefault`: if `true`, only show custom tips; if `false` or absent, custom tips are merged with built-in tips                                                                                                                                                                                                                                                                                                                                                               | `{ "excludeDefault": true, "tips": ["Use our internal tool X"] }`                                                              |
| `spinnerVerbs`                    | Customize the action verbs shown while a turn is in progress. Set `mode` to `"replace"` to use only your verbs, or `"append"` to add them to the defaults                                                                                                                                                                                                                                                                                                                                                                                                  | `{"mode": "append", "verbs": ["Pondering", "Crafting"]}`                                                                       |
| `sshConfigs`                      | SSH connections to show in the [Desktop](/docs/en/desktop#pre-configure-ssh-connections-for-your-team) environment dropdown. Each entry requires `id`, `name`, and `sshHost`; `sshPort`, `sshIdentityFile`, and `startDirectory` are optional. When set in managed settings, connections are read-only for users. Read from managed and user settings only                                                                                                                                                                                                 | `[{"id": "dev-vm", "name": "Dev VM", "sshHost": "user@dev.example.com"}]`                                                      |
| `statusLine`                      | Configure a custom status line to display context. See [`statusLine` documentation](/docs/en/statusline)                                                                                                                                                                                                                                                                                                                                                                                                                                                   | `{"type": "command", "command": "~/.claude/statusline.sh"}`                                                                    |
| `strictKnownMarketplaces`         | (Managed settings only) Allowlist of plugin marketplace sources. Undefined = no restrictions, empty array = lockdown. Enforced on marketplace add and on plugin install, update, refresh, and auto-update, so a marketplace added before the policy was set cannot be used to fetch plugins. See [Managed marketplace restrictions](/docs/en/plugin-marketplaces#managed-marketplace-restrictions)                                                                                                                                                         | `[{ "source": "github", "repo": "acme-corp/plugins" }]`                                                                        |
| `syntaxHighlightingDisabled`      | Disable syntax highlighting in diffs, code blocks, and file previews                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       | `true`                                                                                                                         |
| `teammateMode`                    | How [agent team](/docs/en/agent-teams) teammates display: `auto` (picks split panes in tmux or iTerm2, in-process otherwise), `in-process`, or `tmux`. `--teammate-mode` overrides this for one session. See [choose a display mode](/docs/en/agent-teams#choose-a-display-mode)                                                                                                                                                                                                                                                                           | `"in-process"`                                                                                                                 |
| `terminalProgressBarEnabled`      | Show the terminal progress bar in supported terminals: ConEmu, Ghostty 1.2.0+, and iTerm2 3.6.6+. Default: `true`. Appears in `/config` as **Terminal progress bar**                                                                                                                                                                                                                                                                                                                                                                                       | `false`                                                                                                                        |
| `tui`                             | Terminal UI renderer. Use `"fullscreen"` for the flicker-free [alt-screen renderer](/docs/en/fullscreen) with virtualized scrollback. Use `"default"` for the classic main-screen renderer. Set via `/tui`. You can also set the [`CLAUDE_CODE_NO_FLICKER`](/docs/en/env-vars) environment variable                                                                                                                                                                                                                                                        | `"fullscreen"`                                                                                                                 |
| `useAutoModeDuringPlan`           | Whether plan mode uses auto mode semantics when auto mode is available. Default: `true`. Not read from shared project settings. Appears in `/config` as “Use auto mode during plan”                                                                                                                                                                                                                                                                                                                                                                        | `false`                                                                                                                        |
| `viewMode`                        | Default transcript view mode on startup: `"default"`, `"verbose"`, or `"focus"`. Overrides the sticky `/focus` selection when set. The `--verbose` flag overrides this for one session                                                                                                                                                                                                                                                                                                                                                                     | `"verbose"`                                                                                                                    |
| `voice`                           | [Voice dictation](/docs/en/voice-dictation) settings: `enabled` turns dictation on, `mode` selects `"hold"` or `"tap"`, and `autoSubmit` sends the prompt on key release in hold mode. Written automatically when you run `/voice`. Requires a Claude.ai account                                                                                                                                                                                                                                                                                           | `{ "enabled": true, "mode": "tap" }`                                                                                           |
| `voiceEnabled`                    | Legacy alias for `voice.enabled`. Prefer the `voice` object                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                | `true`                                                                                                                         |
| `wslInheritsWindowsSettings`      | (Windows managed settings only) When `true`, Claude Code on WSL reads managed settings from the Windows policy chain in addition to `/etc/claude-code`, with Windows sources taking priority. Only honored when set in the HKLM registry key or `C:\Program Files\ClaudeCode\managed-settings.json`, both of which require Windows admin to write. For HKCU policy to also apply on WSL, the flag must additionally be set in HKCU itself. Has no effect on native Windows                                                                                 | `true`                                                                                                                         |


Global config settings

These settings are stored in `~/.claude.json` rather than `settings.json`. Adding them to `settings.json` will trigger a schema validation error.

Versions before v2.1.119 also store `autoScrollEnabled`, `editorMode`, `showTurnDuration`, `teammateMode`, and `terminalProgressBarEnabled` here instead of in `settings.json`.

| Key                       | Description                                                                                                                                                                                                                                                                                                                                | Example    |
|:--------------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:-----------|
| `autoConnectIde`          | Automatically connect to a running IDE when Claude Code starts from an external terminal. Default: `false`. Appears in `/config` as **Auto-connect to IDE (external terminal)** when running outside a VS Code or JetBrains terminal. The [`CLAUDE_CODE_AUTO_CONNECT_IDE`](/docs/en/env-vars) environment variable overrides this when set | `true`     |
| `autoInstallIdeExtension` | Automatically install the Claude Code IDE extension when running from a VS Code terminal. Default: `true`. Appears in `/config` as **Auto-install IDE extension** when running inside a VS Code or JetBrains terminal. You can also set the [`CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL`](/docs/en/env-vars) environment variable                  | `false`    |
| `externalEditorContext`   | Prepend Claude’s previous response as `#`-commented context when you open the external editor with `Ctrl+G`. Default: `false`. Appears in `/config` as **Show last response in external editor**                                                                                                                                           | `true`     |
| `teammateDefaultModel`    | Default model for [agent team](/docs/en/agent-teams) teammates when the spawn prompt doesn’t specify one. Set to a model alias such as `"sonnet"`, or `null` to inherit the lead’s current `/model` selection. Appears in `/config` as **Default teammate model**                                                                          | `"sonnet"` |


Worktree settings

Configure how `--worktree` creates and manages git worktrees.

| Key                           | Description                                                                                                                                                                                                                                                                                                                                  | Example                               |
|:------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:--------------------------------------|
| `worktree.baseRef`            | Which ref new worktrees branch from. `"fresh"` (default) 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. Applies to `--worktree`, the `EnterWorktree` tool, and subagent isolation | `"head"`                              |
| `worktree.symlinkDirectories` | Directories to symlink from the main repository into each worktree to avoid duplicating large directories on disk. No directories are symlinked by default                                                                                                                                                                                   | `["node_modules", ".cache"]`          |
| `worktree.sparsePaths`        | Directories to check out in each worktree via git sparse-checkout. Only the listed directories plus root-level files are written to disk, which is faster in large monorepos                                                                                                                                                                 | `["packages/my-app", "shared/utils"]` |
| `worktree.bgIsolation`        | Isolation mode for [background sessions](/docs/en/agent-view#how-file-edits-are-isolated). `"worktree"` (default) blocks `Edit`/`Write` in the main checkout until `EnterWorktree` is called. `"none"` lets background jobs edit the working copy directly. Requires Claude Code v2.1.143 or later                                           | `"none"`                              |

To copy gitignored files like `.env` into new worktrees, use a [`.worktreeinclude` file](/docs/en/worktrees#copy-gitignored-files-into-worktrees) in your project root instead of a setting.


Permission settings

| Keys                                | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  | Example                                                                |
|:------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:-----------------------------------------------------------------------|
| `allow`                             | Array of permission rules to allow tool use. See [Permission rule syntax](#permission-rule-syntax) below for pattern matching details                                                                                                                                                                                                                                                                                                                                                        | `[ "Bash(git diff *)" ]`                                               |
| `ask`                               | Array of permission rules to ask for confirmation upon tool use. See [Permission rule syntax](#permission-rule-syntax) below                                                                                                                                                                                                                                                                                                                                                                 | `[ "Bash(git push *)" ]`                                               |
| `deny`                              | Array of permission rules to deny tool use. Use this to exclude sensitive files from Claude Code access. See [Permission rule syntax](#permission-rule-syntax) and [Bash permission limitations](/docs/en/permissions#tool-specific-permission-rules)                                                                                                                                                                                                                                        | `[ "WebFetch", "Bash(curl *)", "Read(./.env)", "Read(./secrets/**)" ]` |
| `additionalDirectories`             | Additional [working directories](/docs/en/permissions#working-directories) for file access. Most `.claude/` configuration is [not discovered](/docs/en/permissions#additional-directories-grant-file-access-not-configuration) from these directories                                                                                                                                                                                                                                        | `[ "../docs/" ]`                                                       |
| `defaultMode`                       | Default [permission mode](/docs/en/permission-modes) when opening Claude Code. Valid values: `default`, `acceptEdits`, `plan`, `auto`, `dontAsk`, `bypassPermissions`. As of Claude Code v2.1.142, `auto` is ignored when set in project or local settings (`.claude/settings.json`, `.claude/settings.local.json`) so a repository cannot grant itself auto mode. Set it in `~/.claude/settings.json` instead. The `--permission-mode` CLI flag overrides this setting for a single session | `"acceptEdits"`                                                        |
| `disableBypassPermissionsMode`      | Set to `"disable"` to prevent `bypassPermissions` mode from being activated. This disables the `--dangerously-skip-permissions` command-line flag. Typically placed in [managed settings](/docs/en/permissions#managed-settings) to enforce organizational policy, but works from any scope                                                                                                                                                                                                  | `"disable"`                                                            |
| `skipDangerousModePermissionPrompt` | Skip the confirmation prompt shown before entering bypass permissions mode via `--dangerously-skip-permissions` or `defaultMode: "bypassPermissions"`. Ignored when set in project settings (`.claude/settings.json`) to prevent untrusted repositories from auto-bypassing the prompt                                                                                                                                                                                                       | `true`                                                                 |


Permission rule syntax

Permission rules follow the format `Tool` or `Tool(specifier)`. Rules are evaluated in order: deny rules first, then ask, then allow. The first matching rule wins. Quick examples:

| Rule                           | Effect                                   |
|:-------------------------------|:-----------------------------------------|
| `Bash`                         | Matches all Bash commands                |
| `Bash(npm run *)`              | Matches commands starting with `npm run` |
| `Read(./.env)`                 | Matches reading the `.env` file          |
| `WebFetch(domain:example.com)` | Matches fetch requests to example.com    |

For the complete rule syntax reference, including wildcard behavior, tool-specific patterns for Read, Edit, WebFetch, MCP, and Agent rules, and security limitations of Bash patterns, see [Permission rule syntax](/docs/en/permissions#permission-rule-syntax).


Sandbox settings

Configure advanced sandboxing behavior. Sandboxing isolates bash commands from your filesystem and network. See [Sandboxing](/docs/en/sandboxing) for details.

| Keys                                   | Description                                                                                                                                                                                                                                                                                                                                     | Example                           |
|:---------------------------------------|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:----------------------------------|
| `enabled`                              | Enable bash sandboxing (macOS, Linux, and WSL2). Default: false                                                                                                                                                                                                                                                                                 | `true`                            |
| `failIfUnavailable`                    | Exit with an error at startup if `sandbox.enabled` is true but the sandbox cannot start (missing dependencies or unsupported platform). When false (default), a warning is shown and commands run unsandboxed. Intended for managed settings deployments that require sandboxing as a hard gate                                                 | `true`                            |
| `autoAllowBashIfSandboxed`             | Auto-approve bash commands when sandboxed. Default: true                                                                                                                                                                                                                                                                                        | `true`                            |
| `excludedCommands`                     | Commands that should run outside of the sandbox                                                                                                                                                                                                                                                                                                 | `["docker *"]`                    |
| `allowUnsandboxedCommands`             | Allow commands to run outside the sandbox via an admin-gated escape-hatch parameter on the Bash tool input. When set to `false`, the escape hatch is completely disabled and all commands must run sandboxed (or be in `excludedCommands`). Useful for enterprise policies that require strict sandboxing. Default: true               | `false`                           |
| `filesystem.allowWrite`                | Additional paths where sandboxed commands can write. Arrays are merged across all settings scopes: user, project, and managed paths are combined, not replaced. Also merged with paths from `Edit(...)` allow permission rules. See [path prefixes](#sandbox-path-prefixes) below.                                                              | `["/tmp/build", "~/.kube"]`       |
| `filesystem.denyWrite`                 | Paths where sandboxed commands cannot write. Arrays are merged across all settings scopes. Also merged with paths from `Edit(...)` deny permission rules.                                                                                                                                                                                       | `["/etc", "/usr/local/bin"]`      |
| `filesystem.denyRead`                  | Paths where sandboxed commands cannot read. Arrays are merged across all settings scopes. Also merged with paths from `Read(...)` deny permission rules.                                                                                                                                                                                        | `["~/.aws/credentials"]`          |
| `filesystem.allowRead`                 | Paths to re-allow reading within `denyRead` regions. Takes precedence over `denyRead`. Arrays are merged across all settings scopes. Use this to create workspace-only read access patterns.                                                                                                                                                    | `["."]`                           |
| `filesystem.allowManagedReadPathsOnly` | (Managed settings only) Only `filesystem.allowRead` paths from managed settings are respected. `denyRead` still merges from all sources. Default: false                                                                                                                                                                                         | `true`                            |
| `network.allowUnixSockets`             | (macOS only) Unix socket paths accessible in sandbox. Ignored on Linux and WSL2, where the seccomp filter cannot inspect socket paths; use `allowAllUnixSockets` instead.                                                                                                                                                                       | `["~/.ssh/agent-socket"]`         |
| `network.allowAllUnixSockets`          | Allow all Unix socket connections in sandbox. On Linux and WSL2 this is the only way to permit Unix sockets, since it skips the seccomp filter that otherwise blocks `socket(AF_UNIX, ...)` calls. Default: false                                                                                                                               | `true`                            |
| `network.allowLocalBinding`            | Allow binding to localhost ports (macOS only). Default: false                                                                                                                                                                                                                                                                                   | `true`                            |
| `network.allowMachLookup`              | Additional XPC/Mach service names the sandbox may look up (macOS only). Supports a single trailing `*` for prefix matching. Needed for tools that communicate via XPC such as the iOS Simulator or Playwright.                                                                                                                                  | `["com.apple.coresimulator.*"]`   |
| `network.allowedDomains`               | Array of domains to allow for outbound network traffic. Supports wildcards (e.g., `*.example.com`).                                                                                                                                                                                                                                             | `["github.com", "*.npmjs.org"]`   |
| `network.deniedDomains`                | Array of domains to block for outbound network traffic. Supports the same wildcard syntax as `allowedDomains`. Takes precedence over `allowedDomains` when both match. Merged from all settings sources regardless of `allowManagedDomainsOnly`.                                                                                                | `["sensitive.cloud.example.com"]` |
| `network.allowManagedDomainsOnly`      | (Managed settings only) Only `allowedDomains` and `WebFetch(domain:...)` allow rules from managed settings are respected. Domains from user, project, and local settings are ignored. Non-allowed domains are blocked automatically without prompting the user. Denied domains are still respected from all sources. Default: false             | `true`                            |
| `network.httpProxyPort`                | HTTP proxy port used if you wish to bring your own proxy. If not specified, Claude will run its own proxy.                                                                                                                                                                                                                                      | `8080`                            |
| `network.socksProxyPort`               | SOCKS5 proxy port used if you wish to bring your own proxy. If not specified, Claude will run its own proxy.                                                                                                                                                                                                                                    | `8081`                            |
| `enableWeakerNestedSandbox`            | Enable weaker sandbox for unprivileged Docker environments (Linux and WSL2 only). **Reduces security.** Default: false                                                                                                                                                                                                                          | `true`                            |
| `enableWeakerNetworkIsolation`         | (macOS only) Allow access to the system TLS trust service (`com.apple.trustd.agent`) in the sandbox. Required for Go-based tools like `gh`, `gcloud`, and `terraform` to verify TLS certificates when using `httpProxyPort` with a MITM proxy and custom CA. **Reduces security** by opening a potential data exfiltration path. Default: false | `true`                            |
| `bwrapPath`                            | (Managed settings only, Linux/WSL2) Absolute path to the bubblewrap (`bwrap`) binary. Overrides automatic detection via `PATH`. Only honored from [managed settings](/docs/en/settings#settings-precedence), not from user or project settings. Useful when `bwrap` is installed at a non-standard location in managed environments.            | `/opt/admin/bwrap`                |
| `socatPath`                            | (Managed settings only, Linux/WSL2) Absolute path to the `socat` binary used for the sandbox network proxy. Overrides automatic detection via `PATH`. Only honored from managed settings.                                                                                                                                                       | `/opt/admin/socat`                |


Sandbox path prefixes

Paths in `filesystem.allowWrite`, `filesystem.denyWrite`, `filesystem.denyRead`, and `filesystem.allowRead` support these prefixes:

| Prefix            | Meaning                                                                                | Example                                                                   |
|:------------------|:---------------------------------------------------------------------------------------|:--------------------------------------------------------------------------|
| `/`               | Absolute path from filesystem root                                                     | `/tmp/build` stays `/tmp/build`                                           |
| `~/`              | Relative to home directory                                                             | `~/.kube` becomes `$HOME/.kube`                                           |
| `./` or no prefix | Relative to the project root for project settings, or to `~/.claude` for user settings | `./output` in `.claude/settings.json` resolves to `<project-root>/output` |

The older `//path` prefix for absolute paths still works. If you previously used single-slash `/path` expecting project-relative resolution, switch to `./path`. This syntax differs from [Read and Edit permission rules](/docs/en/permissions#read-and-edit), which use `//path` for absolute and `/path` for project-relative. Sandbox filesystem paths use standard conventions: `/tmp/build` is an absolute path. **Configuration example:**

```python
{
  "sandbox": {
    "enabled": true,
    "autoAllowBashIfSandboxed": true,
    "excludedCommands": ["docker *"],
    "filesystem": {
      "allowWrite": ["/tmp/build", "~/.kube"],
      "denyRead": ["~/.aws/credentials"]
    },
    "network": {
      "allowedDomains": ["github.com", "*.npmjs.org", "registry.yarnpkg.com"],
      "deniedDomains": ["uploads.github.com"],
      "allowUnixSockets": [
        "/var/run/docker.sock"
      ],
      "allowLocalBinding": true
    }
  }
}
```

**Filesystem and network restrictions** can be configured in two ways that are merged together:

- **`sandbox.filesystem` settings** (shown above): Control paths at the OS-level sandbox boundary. These restrictions apply to all subprocess commands (e.g., `kubectl`, `terraform`, `npm`), not just Claude’s file tools.
- **Permission rules**: Use `Edit` allow/deny rules to control Claude’s file tool access, `Read` deny rules to block reads, and `WebFetch` allow/deny rules to control network domains. Paths from these rules are also merged into the sandbox configuration.


Attribution settings

Claude Code adds attribution to git commits and pull requests. These are configured separately:

- Commits use [git trailers](https://git-scm.com/docs/git-interpret-trailers) (like `Co-Authored-By`) by default, which can be customized or disabled
- Pull request descriptions are plain text

| Keys     | Description                                                                                |
|:---------|:-------------------------------------------------------------------------------------------|
| `commit` | Attribution for git commits, including any trailers. Empty string hides commit attribution |
| `pr`     | Attribution for pull request descriptions. Empty string hides pull request attribution     |

**Default commit attribution:**

```python
🤖 Generated with [Claude Code](https://claude.com/claude-code)

   Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
```

**Default pull request attribution:**

```python
🤖 Generated with [Claude Code](https://claude.com/claude-code)
```

**Example:**

```python
{
  "attribution": {
    "commit": "Generated with AI\n\nCo-Authored-By: AI <ai@example.com>",
    "pr": ""
  }
}
```

The `attribution` setting takes precedence over the deprecated `includeCoAuthoredBy` setting. To hide all attribution, set `commit` and `pr` to empty strings.


File suggestion settings

Configure a custom command for `@` file path autocomplete. The built-in file suggestion uses fast filesystem traversal, but large monorepos may benefit from project-specific indexing such as a pre-built file index or custom tooling.

```python
{
  "fileSuggestion": {
    "type": "command",
    "command": "~/.claude/file-suggestion.sh"
  }
}
```

The command runs with the same environment variables as [hooks](/docs/en/hooks), including `CLAUDE_PROJECT_DIR`. It receives JSON via stdin with a `query` field:

```python
{"query": "src/comp"}
```

Output newline-separated file paths to stdout (currently limited to 15):

```python
src/components/Button.tsx
src/components/Modal.tsx
src/components/Form.tsx
```

**Example:**

```python
#!/bin/bash
query=$(cat | jq -r '.query')
your-repo-file-index --query "$query" | head -20
```


Hook configuration

These settings control which hooks are allowed to run and what HTTP hooks can access. The `allowManagedHooksOnly` setting can only be configured in [managed settings](#settings-files). The URL and env var allowlists can be set at any settings level and merge across sources. **Behavior when `allowManagedHooksOnly` is `true`:**

- Managed hooks and SDK hooks are loaded
- Hooks from plugins force-enabled in managed settings `enabledPlugins` are loaded. This lets administrators distribute vetted hooks through an organization marketplace while blocking everything else. Trust is granted by full `plugin@marketplace` ID, so a plugin with the same name from a different marketplace stays blocked
- User hooks, project hooks, and all other plugin hooks are blocked

**Restrict HTTP hook URLs:** Limit which URLs HTTP hooks can target. Supports `*` as a wildcard for matching. When the array is defined, HTTP hooks targeting non-matching URLs are silently blocked. Hostname matching is case-insensitive and ignores a trailing FQDN dot, matching DNS semantics.

```python
{
  "allowedHttpHookUrls": ["https://hooks.example.com/*", "http://localhost:*"]
}
```

**Restrict HTTP hook environment variables:** Limit which environment variable names HTTP hooks can interpolate into header values. Each hook’s effective `allowedEnvVars` is the intersection of its own list and this setting.

```python
{
  "httpHookAllowedEnvVars": ["MY_TOKEN", "HOOK_SECRET"]
}
```


Compute managed settings with a policy helper

The `policyHelper` setting points at an executable that computes managed settings at startup, so admins can derive policy from device posture, identity, or a remote service instead of a static file. Configure it from MDM or a system `managed-settings.json` file. Claude Code ignores `policyHelper` when it appears in any other scope, including user settings, project settings, the HKCU registry hive, and [server-managed settings](/docs/en/server-managed-settings). The setting accepts these keys:

| Key                 | Type   | Description                                                                                             |
|---------------------|--------|---------------------------------------------------------------------------------------------------------|
| `path`              | string | Absolute path to the helper executable                                                                  |
| `timeoutMs`         | number | How long to wait for the helper before treating the run as failed                                       |
| `refreshIntervalMs` | number | How often to re-run the helper in the background. Set to `0` to disable refresh, or to at least `60000` |

The helper writes a JSON envelope to stdout. Put the settings under a `managedSettings` key rather than at the top level, since a bare settings object parses with `managedSettings` undefined and applies nothing:

```python
{
  "managedSettings": {
    "permissions": { "deny": ["Read(//etc/secrets/**)"] }
  },
  "claudeMd": "# Organization context\n...",
  "appendSystemPrompt": "Always cite the internal style guide."
}
```

When the helper emits `managedSettings`, that object replaces the file-based managed settings for the run. When the helper exits non-zero at startup, Claude Code prints the error and refuses to start, so a helper that needs outage resilience should serve from its own cache and exit `0`.


Settings precedence

Settings apply in order of precedence. From highest to lowest:

1.  **Managed settings** ([server-managed](/docs/en/server-managed-settings), [MDM/OS-level policies](#configuration-scopes), or [managed settings](/docs/en/settings#settings-files))
    - Policies deployed by IT through server delivery, MDM configuration profiles, registry policies, or managed settings files
    - Cannot be overridden by any other level, including command line arguments
    - Within the managed tier, precedence is: server-managed \> MDM/OS-level policies \> file-based (`managed-settings.d/*.json` + `managed-settings.json`) \> HKCU registry (Windows only). Only one managed source is used; sources do not merge across tiers. Within the file-based tier, drop-in files and the base file are merged together.
    - Embedding hosts such as Claude Desktop can supply policy via the SDK `managedSettings` option. By default this is ignored when any managed-settings tier is present. Administrators can opt in by setting [`parentSettingsBehavior`](#available-settings) to `"merge"`. The embedder’s values are filtered so they can tighten managed policy but not loosen it.
2.  **Command line arguments**
    - Temporary overrides for a specific session. JSON passed via `--settings <file-or-json>` merges with file-based settings using the same rules as the other layers: a key set here overrides the same key in local, project, or user settings, and omitting a key leaves the lower-layer value in place
3.  **Local project settings** (`.claude/settings.local.json`)
    - Personal project-specific settings
4.  **Shared project settings** (`.claude/settings.json`)
    - Team-shared project settings in source control
5.  **User settings** (`~/.claude/settings.json`)
    - Personal global settings

This hierarchy ensures that organizational policies are always enforced while still allowing teams and individuals to customize their experience. The same precedence applies whether you run Claude Code from the CLI, the [VS Code extension](/docs/en/vs-code), or a [JetBrains IDE](/docs/en/jetbrains). For example, if your user settings set `permissions.defaultMode` to `acceptEdits` and a project’s shared settings set it to `default`, the project value applies. The example below covers how array-valued settings such as permission rules combine instead.

**Array settings merge across scopes.** When the same array-valued setting (such as `sandbox.filesystem.allowWrite` or `permissions.allow`) appears in multiple scopes, the arrays are **concatenated and deduplicated**, not replaced. This means lower-priority scopes can add entries without overriding those set by higher-priority scopes, and vice versa. For example, if managed settings set `allowWrite` to `["/opt/company-tools"]` and a user adds `["~/.kube"]`, both paths are included in the final configuration.


Verify active settings

Run `/status` inside Claude Code to see which settings sources are active. The Status tab includes a `Setting sources` line that lists each layer Claude Code loaded for the current session, such as `User settings` or `Project local settings`. When [managed settings](/docs/en/managed-settings) are in effect, the entry shows the delivery channel in parentheses, for example `Enterprise managed settings (remote)`, `(plist)`, `(HKLM)`, `(HKCU)`, or `(file)`. A layer appears in the list only when that source is loaded with at least one key, so an empty list means no settings sources were found. The `Setting sources` line confirms which sources are being read. It does not show which layer supplied each individual key. The Config tab in the same dialog is an editor for a fixed set of toggles such as theme and verbose output, not a view of your `settings.json` contents. If a settings file contains errors, such as invalid JSON or a value that fails validation, `/status` reports the issue so you can fix it.


Key points about the configuration system

- **Memory files (`CLAUDE.md`)**: Contain instructions and context that Claude loads at startup
- **Settings files (JSON)**: Configure permissions, environment variables, and tool behavior
- **Skills**: Custom prompts that can be invoked with `/skill-name` or loaded by Claude automatically
- **MCP servers**: Extend Claude Code with additional tools and integrations
- **Precedence**: Higher-level configurations (Managed) override lower-level ones (User/Project)
- **Inheritance**: Settings merge across scopes; scalar values from higher-priority scopes override, and arrays concatenate


System prompt

Claude Code’s internal system prompt is not published. To add custom instructions, use `CLAUDE.md` files or the `--append-system-prompt` flag.


Excluding sensitive files

To prevent Claude Code from accessing files containing sensitive information like API keys, secrets, and environment files, use the `permissions.deny` setting in your `.claude/settings.json` file:

```python
{
  "permissions": {
    "deny": [
      "Read(./.env)",
      "Read(./.env.*)",
      "Read(./secrets/**)",
      "Read(./config/credentials.json)",
      "Read(./build)"
    ]
  }
}
```

This replaces the deprecated `ignorePatterns` configuration. Files matching these patterns are excluded from file discovery and search results, and read operations on these files are denied.


Subagent configuration

Claude Code supports custom AI subagents that can be configured at both user and project levels. These subagents are stored as Markdown files with YAML frontmatter:

- **User subagents**: `~/.claude/agents/` - Available across all your projects
- **Project subagents**: `.claude/agents/` - Specific to your project and can be shared with your team

Subagent files define specialized AI assistants with custom prompts and tool permissions. Learn more about creating and using subagents in the [subagents documentation](/docs/en/sub-agents).


Plugin configuration

Claude Code supports a plugin system that lets you extend functionality with skills, agents, hooks, and MCP servers. Plugins are distributed through marketplaces and can be configured at both user and repository levels.


Plugin settings

Plugin-related settings in `settings.json`:

```python
{
  "enabledPlugins": {
    "formatter@acme-tools": true,
    "deployer@acme-tools": true,
    "analyzer@security-plugins": false
  },
  "extraKnownMarketplaces": {
    "acme-tools": {
      "source": {
        "source": "github",
        "repo": "acme-corp/claude-plugins"
      }
    }
  }
}
```


`enabledPlugins`

Controls which plugins are enabled. Format: `"plugin-name@marketplace-name": true/false` **Scopes**:

- **User settings** (`~/.claude/settings.json`): Personal plugin preferences
- **Project settings** (`.claude/settings.json`): Project-specific plugins shared with team
- **Local settings** (`.claude/settings.local.json`): Per-machine overrides (not committed)
- **Managed settings** (`managed-settings.json`): Organization-wide policy overrides that block installation at all scopes and hide the plugin from the marketplace

Project settings take precedence over user settings, so setting a plugin to `false` in `~/.claude/settings.json` does not 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 cannot be disabled this way, since managed settings override local settings.

**Example**:

```python
{
  "enabledPlugins": {
    "code-formatter@team-tools": true,
    "deployment-tools@team-tools": true,
    "experimental-features@personal": false
  }
}
```


`extraKnownMarketplaces`

Defines additional marketplaces that should be made available for the repository. Typically used in repository-level settings to ensure team members have access to required plugin sources. **When a repository includes `extraKnownMarketplaces`**:

1.  Team members are prompted to install the marketplace when they trust the folder
2.  Team members are then prompted to install plugins from that marketplace
3.  Users can skip unwanted marketplaces or plugins (stored in user settings)
4.  Installation respects trust boundaries and requires explicit consent

**Example**:

```python
{
  "extraKnownMarketplaces": {
    "acme-tools": {
      "source": {
        "source": "github",
        "repo": "acme-corp/claude-plugins"
      }
    },
    "security-plugins": {
      "source": {
        "source": "git",
        "url": "https://git.example.com/security/plugins.git"
      }
    }
  }
}
```

**Marketplace source types**:

- `github`: GitHub repository (uses `repo`)
- `git`: Any git URL (uses `url`)
- `directory`: Local filesystem path (uses `path`, for development only)
- `hostPattern`: regex pattern to match marketplace hosts (uses `hostPattern`)
- `settings`: inline marketplace declared directly in settings.json without a separate hosted repository (uses `name` and `plugins`)

Each marketplace entry also accepts an optional `autoUpdate` Boolean. Set `"autoUpdate": true` alongside `source` to make Claude Code refresh that marketplace and update its installed plugins at startup. When omitted, official Anthropic marketplaces default to `true` and all other marketplaces default to `false`. See [Configure auto-updates](/docs/en/discover-plugins#configure-auto-updates). Use `source: 'settings'` to declare a small set of plugins inline without setting up a hosted marketplace repository. Plugins listed here must reference external sources such as GitHub or npm. You still need to enable each plugin separately in `enabledPlugins`.

```python
{
  "extraKnownMarketplaces": {
    "team-tools": {
      "source": {
        "source": "settings",
        "name": "team-tools",
        "plugins": [
          {
            "name": "code-formatter",
            "source": {
              "source": "github",
              "repo": "acme-corp/code-formatter"
            }
          }
        ]
      }
    }
  }
}
```


`strictKnownMarketplaces`

**Managed settings only**: Controls which plugin marketplaces users are allowed to add and install plugins from. This setting can only be configured in [managed settings](/docs/en/settings#settings-files) and provides administrators with strict control over marketplace sources. **Managed settings file locations**:

- **macOS**: `/Library/Application Support/ClaudeCode/managed-settings.json`
- **Linux and WSL**: `/etc/claude-code/managed-settings.json`
- **Windows**: `C:\Program Files\ClaudeCode\managed-settings.json`

**Key characteristics**:

- Only available in managed settings (`managed-settings.json`)
- Cannot be overridden by user or project settings (highest precedence)
- Enforced BEFORE network/filesystem operations (blocked sources never execute)
- Uses exact matching for source specifications (including `ref`, `path` for git sources), except `hostPattern` and `pathPattern`, which use regex matching

**Allowlist behavior**:

- `undefined` (default): No restrictions - users can add any marketplace
- Empty array `[]`: Complete lockdown - users cannot add any new marketplaces
- List of sources: Users can only add marketplaces that match exactly

**All supported source types**: The allowlist supports multiple marketplace source types. Most sources use exact matching, while `hostPattern` and `pathPattern` use regex matching against the marketplace host and filesystem path respectively.

1.  **GitHub repositories**:

```python
{ "source": "github", "repo": "acme-corp/approved-plugins" }
{ "source": "github", "repo": "acme-corp/security-tools", "ref": "v2.0" }
{ "source": "github", "repo": "acme-corp/plugins", "ref": "main", "path": "marketplace" }
```

Fields: `repo` (required), `ref` (optional: branch/tag/SHA), `path` (optional: subdirectory)

2.  **Git repositories**:

```python
{ "source": "git", "url": "https://gitlab.example.com/tools/plugins.git" }
{ "source": "git", "url": "https://bitbucket.org/acme-corp/plugins.git", "ref": "production" }
{ "source": "git", "url": "ssh://git@git.example.com/plugins.git", "ref": "v3.1", "path": "approved" }
```

Fields: `url` (required), `ref` (optional: branch/tag/SHA), `path` (optional: subdirectory)

3.  **URL-based marketplaces**:

```python
{ "source": "url", "url": "https://plugins.example.com/marketplace.json" }
{ "source": "url", "url": "https://cdn.example.com/marketplace.json", "headers": { "Authorization": "Bearer ${TOKEN}" } }
```

Fields: `url` (required), `headers` (optional: HTTP headers for authenticated access)

URL-based marketplaces only download the `marketplace.json` file. They do not download plugin files from the server. Plugins in URL-based marketplaces must use external sources (GitHub, npm, or git URLs) rather than relative paths. For plugins with relative paths, use a Git-based marketplace instead. See [Troubleshooting](/docs/en/plugin-marketplaces#plugins-with-relative-paths-fail-in-url-based-marketplaces) for details.

4.  **NPM packages**:

```python
{ "source": "npm", "package": "@acme-corp/claude-plugins" }
{ "source": "npm", "package": "@acme-corp/approved-marketplace" }
```

Fields: `package` (required, supports scoped packages)

5.  **File paths**:

```python
{ "source": "file", "path": "/usr/local/share/claude/acme-marketplace.json" }
{ "source": "file", "path": "/opt/acme-corp/plugins/marketplace.json" }
```

Fields: `path` (required: absolute path to marketplace.json file)

6.  **Directory paths**:

```python
{ "source": "directory", "path": "/usr/local/share/claude/acme-plugins" }
{ "source": "directory", "path": "/opt/acme-corp/approved-marketplaces" }
```

Fields: `path` (required: absolute path to directory containing `.claude-plugin/marketplace.json`)

7.  **Host pattern matching**:

```python
{ "source": "hostPattern", "hostPattern": "^github\\.example\\.com$" }
{ "source": "hostPattern", "hostPattern": "^gitlab\\.internal\\.example\\.com$" }
```

Fields: `hostPattern` (required: regex pattern to match against the marketplace host) Use host pattern matching when you want to allow all marketplaces from a specific host without enumerating each repository individually. This is useful for organizations with internal GitHub Enterprise or GitLab servers where developers create their own marketplaces. Host extraction by source type:

- `github`: always matches against `github.com`
- `git`: extracts hostname from the URL (supports both HTTPS and SSH formats)
- `url`: extracts hostname from the URL
- `npm`, `file`, `directory`: not supported for host pattern matching

8.  **Path pattern matching**:

```python
{ "source": "pathPattern", "pathPattern": "^/opt/approved/" }
{ "source": "pathPattern", "pathPattern": ".*" }
```

Fields: `pathPattern` (required: regex pattern matched against the `path` field of `file` and `directory` sources) Use path pattern matching to allow filesystem-based marketplaces alongside `hostPattern` restrictions for network sources. Set `".*"` to allow all local paths, or a narrower pattern to restrict to specific directories. **Configuration examples**: Example: allow specific marketplaces only:

```python
{
  "strictKnownMarketplaces": [
    {
      "source": "github",
      "repo": "acme-corp/approved-plugins"
    },
    {
      "source": "github",
      "repo": "acme-corp/security-tools",
      "ref": "v2.0"
    },
    {
      "source": "url",
      "url": "https://plugins.example.com/marketplace.json"
    },
    {
      "source": "npm",
      "package": "@acme-corp/compliance-plugins"
    }
  ]
}
```

Example - Disable all marketplace additions:

```python
{
  "strictKnownMarketplaces": []
}
```

Example: allow all marketplaces from an internal git server:

```python
{
  "strictKnownMarketplaces": [
    {
      "source": "hostPattern",
      "hostPattern": "^github\\.example\\.com$"
    }
  ]
}
```

**Exact matching requirements**: Marketplace sources must match **exactly** for a user’s addition to be allowed. For git-based sources (`github` and `git`), this includes all optional fields:

- The `repo` or `url` must match exactly
- The `ref` field must match exactly (or both be undefined)
- The `path` field must match exactly (or both be undefined)

Examples of sources that **do NOT match**:

```python
// These are DIFFERENT sources:
{ "source": "github", "repo": "acme-corp/plugins" }
{ "source": "github", "repo": "acme-corp/plugins", "ref": "main" }

// These are also DIFFERENT:
{ "source": "github", "repo": "acme-corp/plugins", "path": "marketplace" }
{ "source": "github", "repo": "acme-corp/plugins" }
```

**Comparison with `extraKnownMarketplaces`**:

| Aspect                | `strictKnownMarketplaces`            | `extraKnownMarketplaces`             |
|-----------------------|--------------------------------------|--------------------------------------|
| **Purpose**           | Organizational policy enforcement    | Team convenience                     |
| **Settings file**     | `managed-settings.json` only         | Any settings file                    |
| **Behavior**          | Blocks non-allowlisted additions     | Auto-installs missing marketplaces   |
| **When enforced**     | Before network/filesystem operations | After user trust prompt              |
| **Can be overridden** | No (highest precedence)              | Yes (by higher precedence settings)  |
| **Source format**     | Direct source object                 | Named marketplace with nested source |
| **Use case**          | Compliance, security restrictions    | Onboarding, standardization          |

**Format difference**: `strictKnownMarketplaces` uses direct source objects:

```python
{
  "strictKnownMarketplaces": [
    { "source": "github", "repo": "acme-corp/plugins" }
  ]
}
```

`extraKnownMarketplaces` requires named marketplaces:

```python
{
  "extraKnownMarketplaces": {
    "acme-tools": {
      "source": { "source": "github", "repo": "acme-corp/plugins" }
    }
  }
}
```

**Using both together**: `strictKnownMarketplaces` is a policy gate: it controls what users may add but does not register any marketplaces. To both restrict and pre-register a marketplace for all users, set both in `managed-settings.json`:

```python
{
  "strictKnownMarketplaces": [
    { "source": "github", "repo": "acme-corp/plugins" }
  ],
  "extraKnownMarketplaces": {
    "acme-tools": {
      "source": { "source": "github", "repo": "acme-corp/plugins" }
    }
  }
}
```

With only `strictKnownMarketplaces` set, users can still add the allowed marketplace manually via `/plugin marketplace add`, but it is not available automatically. **Important notes**:

- Restrictions are checked BEFORE any network requests or filesystem operations
- When blocked, users see clear error messages indicating the source is blocked by managed policy
- The restriction is enforced on marketplace add and on plugin install, update, refresh, and auto-update. A marketplace added before the policy was set cannot be used to install or update plugins once its source no longer matches the allowlist
- Managed settings have the highest precedence and cannot be overridden

See [Managed marketplace restrictions](/docs/en/plugin-marketplaces#managed-marketplace-restrictions) for user-facing documentation.


Managing plugins

Use the `/plugin` command to manage plugins interactively:

- Browse available plugins from marketplaces
- Install/uninstall plugins
- Enable/disable plugins
- View plugin details (skills, agents, hooks provided)
- Add/remove marketplaces

Learn more about the plugin system in the [plugins documentation](/docs/en/plugins).


Environment variables

Environment variables let you control Claude Code behavior without editing settings files. Any variable can also be configured in [`settings.json`](#available-settings) under the `env` key to apply it to every session or roll it out to your team. See the [environment variables reference](/docs/en/env-vars) for the full list.


Tools available to Claude

Claude Code has access to a set of tools for reading, editing, searching, running commands, and orchestrating subagents. Tool names are the exact strings you use in permission rules and hook matchers. See the [tools reference](/docs/en/tools-reference) for the full list and Bash tool behavior details.


See also

- [Permissions](/docs/en/permissions): permission system, rule syntax, tool-specific patterns, and managed policies
- [Authentication](/docs/en/authentication): set up user access to Claude Code
- [Debug your configuration](/docs/en/debug-your-config): diagnose why a setting, hook, or MCP server isn’t taking effect
- [Troubleshoot installation and login](/docs/en/troubleshoot-install): installation, authentication, and platform issues


---
## claude-directory-06f83438fe.md

> ## Documentation Index
> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Explore the .claude directory

> Where Claude Code reads CLAUDE.md, settings.json, hooks, skills, commands, subagents, rules, and auto memory. Explore the .claude directory in your project and ~/.claude in your home directory.

export const ClaudeExplorer = () => {
  const A = useMemo(() => ({href, children}) => <a href={href} style={{
    color: 'var(--ce-accent)',
    textDecoration: 'none',
    borderBottom: '1px dotted var(--ce-accent)'
  }}>{children}</a>, []);
  const C = useMemo(() => ({children}) => <code style={{
    fontFamily: 'var(--ce-mono)',
    fontSize: '0.92em',
    padding: '1px 4px',
    borderRadius: '3px',
    background: 'var(--ce-surface)',
    border: '0.5px solid var(--ce-border-subtle)'
  }}>{children}</code>, []);
  const commandsNote = useMemo(() => <>Commands and skills are now the same mechanism. For new workflows, use <A href="/en/skills">skills/</A> instead: same <C>/name</C> invocation, plus you can bundle supporting files.</>, []);
  const FILE_TREE = useMemo(() => ({
    project: {
      label: 'your-project/',
      children: [{
        id: 'claude-md',
        label: 'CLAUDE.md',
        type: 'file',
        icon: 'md',
        color: '#6A9BCC',
        badge: 'committed',
        oneLiner: 'Project instructions Claude reads every session',
        when: 'Loaded into context at the start of every session',
        description: 'Project-specific instructions that shape how Claude works in this repository. Put your conventions, common commands, and architectural context here so Claude operates with the same assumptions your team does.',
        tips: ['Target under 200 lines. Longer files still load in full but may reduce adherence', <>CLAUDE.md loads into every session. If something only matters for specific tasks, move it to a <A href="/en/skills">skill</A> or a path-scoped <A href="/en/memory#organize-rules-with-claude/rules/">rule</A> so it loads only when needed</>, 'List the commands you run most, like build, test, and format, so Claude knows them without you spelling them out each time', <>Run <C>/memory</C> to open and edit CLAUDE.md from within a session</>, <>Also works at <C>.claude/CLAUDE.md</C> if you prefer to keep the project root clean</>],
        exampleIntro: 'This example is for a TypeScript and React project. It lists the build and test commands, the framework conventions Claude should follow, and project-specific rules like export style and file layout.',
        example: `# Project conventions

## Commands
- Build: \`npm run build\`
- Test: \`npm test\`
- Lint: \`npm run lint\`

## Stack
- TypeScript with strict mode
- React 19, functional components only

## Rules
- Named exports, never default exports
- Tests live next to source: \`foo.ts\` -> \`foo.test.ts\`
- All API routes return \`{ data, error }\` shape`,
        docsLink: '/en/memory'
      }, {
        id: 'mcp-json',
        label: '.mcp.json',
        type: 'file',
        icon: 'json',
        color: '#9B7BC4',
        badge: 'committed',
        oneLiner: 'Project-scoped MCP servers, shared with your team',
        when: <>Servers connect when the session begins. Tool schemas are deferred by default and load on demand via <A href="/en/mcp#scale-with-mcp-tool-search">tool search</A></>,
        description: <>Configures Model Context Protocol (MCP) servers that give Claude access to external tools: databases, APIs, browsers, and more. This file holds the project-scoped servers your whole team uses. Personal servers you want to keep to yourself go in <C>~/.claude.json</C> instead.</>,
        tips: [<>Use environment variable references for secrets: <C>{'${GITHUB_TOKEN}'}</C></>, <>Lives at the project root, not inside <C>.claude/</C></>, <>For servers only you need, run <C>claude mcp add --scope user</C>. This writes to <C>~/.claude.json</C> instead of <C>.mcp.json</C></>],
        exampleIntro: <>This example configures the GitHub MCP server so Claude can read issues and open pull requests. The <C>{'${GITHUB_TOKEN}'}</C> reference is read from your shell environment when Claude Code starts the server, so the token never lands in the file.</>,
        example: `{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_TOKEN": "\${GITHUB_TOKEN}"
      }
    }
  }
}`,
        docsLink: '/en/mcp'
      }, {
        id: 'worktreeinclude',
        label: '.worktreeinclude',
        type: 'file',
        icon: 'md',
        color: '#8FA876',
        badge: 'committed',
        oneLiner: 'Gitignored files to copy into new worktrees',
        when: <>Read when Claude creates a git worktree via <C>--worktree</C>, the <C>EnterWorktree</C> tool, or subagent <C>isolation: worktree</C></>,
        description: <>Lists gitignored files to copy from your main repository into each new worktree. Worktrees are fresh checkouts, so untracked files like <C>.env</C> are missing by default. Patterns here use <C>.gitignore</C> syntax. Only files that match a pattern and are also gitignored get copied, so tracked files are never duplicated.</>,
        tips: [<>Lives at the project root, not inside <C>.claude/</C></>, <>Git-only: if you configure a <A href="/en/hooks#worktreecreate">WorktreeCreate hook</A> for a different VCS, this file is not read. Copy files inside your hook script instead</>, <>Also applies to parallel sessions in the <A href="/en/desktop#work-in-parallel-with-sessions">desktop app</A></>],
        exampleIntro: 'This example copies your local environment files and a secrets config into every worktree Claude creates. Comments start with # and blank lines are ignored, same as .gitignore.',
        example: `# Local environment
.env
.env.local

# API credentials
config/secrets.json`,
        docsLink: '/en/common-workflows#copy-gitignored-files-to-worktrees'
      }, {
        id: 'dot-claude',
        label: '.claude/',
        type: 'folder',
        icon: 'folder',
        color: 'var(--ce-accent)',
        oneLiner: 'Project-level configuration, rules, and extensions',
        description: 'Everything Claude Code reads that is specific to this project. If you use git, commit most files here so your team shares them; a few, like settings.local.json, are automatically gitignored. Each file badge shows which.',
        children: [{
          id: 'settings-json',
          label: 'settings.json',
          type: 'file',
          icon: 'json',
          color: 'var(--ce-text-3)',
          badge: 'committed',
          oneLiner: 'Permissions, hooks, and configuration',
          when: <>Overrides global <C>~/.claude/settings.json</C>. Local settings, CLI flags, and managed settings override this</>,
          description: 'Settings that Claude Code applies directly. Permissions control which commands and tools Claude can use; hooks run your scripts at specific points in a session. Unlike CLAUDE.md, which Claude reads as guidance, these are enforced whether Claude follows them or not.',
          contains: [<><A href="/en/permissions">permissions</A>: allow, deny, or prompt before Claude uses specific tools or commands</>, <><A href="/en/hooks">hooks</A>: run your own scripts on events like before a tool call or after a file edit</>, <><A href="/en/statusline">statusLine</A>: customize the line shown at the bottom while Claude works</>, <><A href="/en/settings#available-settings">model</A>: pick a default model for this project</>, <><A href="/en/settings#environment-variables">env</A>: environment variables set in every session</>, <><A href="/en/output-styles">outputStyle</A>: select a custom system-prompt style from output-styles/</>],
          tips: [<>Bash permission patterns support wildcards: <C>Bash(npm test *)</C> matches any command starting with <C>npm test</C></>, <>Array settings like <C>permissions.allow</C> combine across all scopes; scalar settings like <C>model</C> use the most specific value</>],
          exampleIntro: <>This example allows <C>npm test</C> and <C>npm run</C> commands without prompting, blocks <C>rm -rf</C>, and runs Prettier on files after Claude edits or writes them.</>,
          example: `{
  "permissions": {
    "allow": [
      "Bash(npm test *)",
      "Bash(npm run *)"
    ],
    "deny": [
      "Bash(rm -rf *)"
    ]
  },
  "hooks": {
    "PostToolUse": [{
      "matcher": "Edit|Write",
      "hooks": [{
        "type": "command",
        "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write"
      }]
    }]
  }
}`,
          docsLink: '/en/settings'
        }, {
          id: 'settings-local-json',
          label: 'settings.local.json',
          type: 'file',
          icon: 'json',
          color: 'var(--ce-text-3)',
          badge: 'gitignored',
          oneLiner: 'Your personal settings overrides for this project',
          when: 'Highest of the user-editable settings files; CLI flags and managed settings still take precedence',
          description: 'Personal settings that take precedence over the project defaults. Same JSON format as settings.json, but not committed. Use this when you need different permissions or defaults than the team config.',
          tips: [<>Same schema as settings.json. Array settings like <C>permissions.allow</C> combine across scopes; scalar settings like <C>model</C> use the local value</>, <>Claude Code adds this file to <C>~/.config/git/ignore</C> the first time it writes one. If you use a custom <C>core.excludesFile</C>, add the pattern there too. To share the ignore rule with your team, also add it to the project <C>.gitignore</C></>],
          exampleIntro: 'This example adds Docker permissions on top of whatever the team settings.json allows.',
          example: `{
  "permissions": {
    "allow": [
      "Bash(docker *)"
    ]
  }
}`,
          docsLink: '/en/settings'
        }, {
          id: 'rules',
          label: 'rules/',
          type: 'folder',
          icon: 'folder',
          color: '#9B7BC4',
          oneLiner: 'Topic-scoped instructions, optionally gated by file paths',
          when: <>Rules without <C>paths:</C> load at session start. Rules with <C>paths:</C> load when a matching file enters context</>,
          description: [<>Project instructions split into topic files that can load conditionally based on file paths. A rule without <C>paths:</C> frontmatter loads at session start like CLAUDE.md; a rule with <C>paths:</C> loads only when Claude reads a matching file.</>, <>Like CLAUDE.md, rules are guidance Claude reads, not configuration Claude Code enforces. For guaranteed behavior use <A href="/en/hooks">hooks</A> or <A href="/en/permissions">permissions</A>.</>],
          tips: [<>Use <C>paths:</C> frontmatter with globs to scope rules to directories or file types</>, <>Subdirectories work: <C>.claude/rules/frontend/react.md</C> is discovered automatically</>, 'When CLAUDE.md approaches 200 lines, start splitting into rules'],
          docsLink: '/en/memory#organize-rules-with-claude/rules/',
          children: [{
            id: 'rule-testing',
            label: 'testing.md',
            type: 'file',
            icon: 'md',
            color: '#9B7BC4',
            badge: 'committed',
            oneLiner: 'Test conventions scoped to test files',
            when: <>Loaded when Claude reads a file matching the <C>paths:</C> globs below</>,
            description: <>An example rule that only loads when Claude is working on test files. The <C>paths:</C> globs in the frontmatter define which files trigger it; here, anything ending in .test.ts or .test.tsx. For other files, this rule is not loaded into context.</>,
            example: `---
paths:
  - "**/*.test.ts"
  - "**/*.test.tsx"
---

# Testing Rules

- Use descriptive test names: "should [expected] when [condition]"
- Mock external dependencies, not internal modules
- Clean up side effects in afterEach`
          }, {
            id: 'rule-api',
            label: 'api-design.md',
            type: 'file',
            icon: 'md',
            color: '#9B7BC4',
            badge: 'committed',
            oneLiner: 'API conventions scoped to backend code',
            when: <>Loaded when Claude reads a file matching the <C>paths:</C> glob below</>,
            description: <>A second example showing a rule scoped to backend code. The <C>paths:</C> glob matches files under src/api/, so these conventions load only when Claude is editing API routes.</>,
            example: `---
paths:
  - "src/api/**/*.ts"
---

# API Design Rules

- All endpoints must validate input with Zod schemas
- Return shape: { data: T } | { error: string }
- Rate limit all public endpoints`
          }]
        }, {
          id: 'skills',
          label: 'skills/',
          type: 'folder',
          icon: 'folder',
          color: '#D4A843',
          oneLiner: 'Reusable prompts you or Claude invoke by name',
          when: <>Invoked with <C>/skill-name</C> or when Claude matches the task to a skill</>,
          description: <>Each skill is a folder with a SKILL.md file plus any supporting files it needs. By default, both you and Claude can invoke a skill. Use frontmatter to control that: <C>disable-model-invocation: true</C> for user-only workflows like <C>/deploy</C>, or <C>user-invocable: false</C> to hide from the <C>/</C> menu while Claude can still invoke it.</>,
          tips: [<>Skills accept arguments: <C>/deploy staging</C> passes "staging" as <C>$ARGUMENTS</C>. Use <C>$0</C>, <C>$1</C>, and so on for positional access</>, <>The <C>description</C> frontmatter determines when Claude auto-invokes the skill</>, 'Bundle reference docs alongside SKILL.md. Claude knows the skill directory path and can read supporting files when you mention them'],
          docsLink: '/en/skills',
          children: [{
            id: 'skill-review',
            label: 'security-review/',
            type: 'folder',
            icon: 'folder',
            color: '#D4A843',
            oneLiner: 'A skill bundling SKILL.md with supporting files',
            children: [{
              id: 'skill-review-md',
              label: 'SKILL.md',
              type: 'file',
              icon: 'md',
              color: '#D4A843',
              badge: 'committed',
              oneLiner: 'Entrypoint: trigger, invocability, instructions',
              when: <>User types <C>/security-review &lt;target&gt;</C>; Claude cannot auto-invoke this skill</>,
              description: [<>This skill uses <C>disable-model-invocation: true</C> so only you can trigger it; Claude never invokes it on its own.</>, <>The <C>!`...`</C> line runs a shell command and injects its output into the prompt. <C>$ARGUMENTS</C> substitutes whatever you typed after the skill name. Claude sees the skill directory path, so mentioning a bundled file like checklist.md lets Claude read it.</>],
              example: `---
description: Reviews code changes for security vulnerabilities, authentication gaps, and injection risks
disable-model-invocation: true
argument-hint: <branch-or-path>
---

## Diff to review

!\`git diff $ARGUMENTS\`

Audit the changes above for:

1. Injection vulnerabilities (SQL, XSS, command)
2. Authentication and authorization gaps
3. Hardcoded secrets or credentials

Use checklist.md in this skill directory for the full review checklist.

Report findings with severity ratings and remediation steps.`
            }, {
              id: 'skill-checklist',
              label: 'checklist.md',
              type: 'file',
              icon: 'md',
              color: '#D4A843',
              badge: 'committed',
              oneLiner: 'Supporting file bundled with the skill',
              when: 'Claude reads it on demand while running the skill',
              description: <>Skills can bundle any supporting files: reference docs, templates, scripts. The skill directory path is prepended to SKILL.md, so Claude can read bundled files by name. For scripts in bash injection commands, use the <C>{'${CLAUDE_SKILL_DIR}'}</C> placeholder.</>,
              example: `# Security Review Checklist

## Input Validation
- [ ] All user input sanitized before DB queries
- [ ] File upload MIME types validated
- [ ] Path traversal prevented on file operations

## Authentication
- [ ] JWT tokens expire after 24 hours
- [ ] API keys stored in environment variables
- [ ] Passwords hashed with bcrypt or argon2`
            }]
          }]
        }, {
          id: 'commands',
          label: 'commands/',
          type: 'folder',
          icon: 'folder',
          color: '#788C5D',
          oneLiner: <>Single-file prompts invoked with <C>/name</C></>,
          note: commandsNote,
          when: <>User types <C>/command-name</C></>,
          description: <>A file at <C>commands/deploy.md</C> creates <C>/deploy</C> the same way a skill at <C>skills/deploy/SKILL.md</C> does, and both can be auto-invoked by Claude. Skills use a directory with SKILL.md, letting you bundle reference docs, templates, or scripts alongside the prompt.</>,
          tips: [<>Use <C>$ARGUMENTS</C> in the file to accept parameters: <C>/fix-issue 123</C></>, 'If a skill and command share a name, the skill takes precedence', 'New commands should usually be skills instead; commands remain supported'],
          docsLink: '/en/skills',
          children: [{
            id: 'cmd-example',
            label: 'fix-issue.md',
            type: 'file',
            icon: 'md',
            color: '#788C5D',
            badge: 'committed',
            oneLiner: <>Invoked as <C>/fix-issue &lt;number&gt;</C></>,
            note: commandsNote,
            description: [<>An example command for fixing a GitHub issue. Type <C>/fix-issue 123</C> and the <C>!`...`</C> line runs <C>gh issue view 123</C> in your shell, injecting the output into the prompt before Claude sees it.</>, <><C>$ARGUMENTS</C> substitutes whatever you typed after the command name. For positional access, use <C>$0</C> <C>$1</C> and so on.</>],
            example: `---
argument-hint: <issue-number>
---

!\`gh issue view $ARGUMENTS\`

Investigate and fix the issue above.

1. Trace the bug to its root cause
2. Implement the fix
3. Write or update tests
4. Summarize what you changed and why`
          }]
        }, {
          id: 'output-styles',
          label: 'output-styles/',
          type: 'folder',
          icon: 'folder',
          color: '#5AA7A7',
          oneLiner: 'Project-scoped output styles, if your team shares any',
          when: 'Applied at session start when selected via the outputStyle setting',
          description: <>Output styles are usually personal, so most live in <C>~/.claude/output-styles/</C>. Put one here if your team shares a style, like a review mode everyone uses. See <A href="#ce-global-output-styles">the Global tab</A> for the full explanation and example.</>,
          docsLink: '/en/output-styles',
          children: []
        }, {
          id: 'agents',
          label: 'agents/',
          type: 'folder',
          icon: 'folder',
          color: '#C46686',
          oneLiner: 'Specialized subagents with their own context window',
          when: 'Runs in its own context window when you or Claude invoke it',
          description: 'Each markdown file defines a subagent with its own system prompt, tool access, and optionally its own model. Subagents run in a fresh context window, keeping the main conversation clean. Useful for parallel work or isolated tasks.',
          tips: ['Each agent gets a fresh context window, separate from your main session', <>Restrict tool access per agent with the <C>tools:</C> frontmatter field</>, 'Type @ and pick an agent from the autocomplete to delegate directly'],
          docsLink: '/en/sub-agents',
          children: [{
            id: 'agent-reviewer',
            label: 'code-reviewer.md',
            type: 'file',
            icon: 'md',
            color: '#C46686',
            badge: 'committed',
            oneLiner: 'Subagent for isolated code review',
            when: 'Claude spawns it for review tasks, or you @-mention it from the autocomplete',
            description: <>An example subagent restricted to read-only tools. The <C>description</C> frontmatter tells Claude when to delegate to it automatically; <C>tools:</C> limits it to Read, Grep, and Glob so it can inspect code but never edit. The body becomes the subagent's system prompt.</>,
            example: `---
name: code-reviewer
description: Reviews code for correctness, security, and maintainability
tools: Read, Grep, Glob
---

You are a senior code reviewer. Review for:

1. Correctness: logic errors, edge cases, null handling
2. Security: injection, auth bypass, data exposure
3. Maintainability: naming, complexity, duplication

Every finding must include a concrete fix.`
          }]
        }, {
          id: 'agent-memory',
          label: 'agent-memory/',
          type: 'folder',
          icon: 'folder',
          color: '#C46686',
          badge: 'committed',
          autogen: true,
          oneLiner: 'Subagent persistent memory, separate from your main session auto memory',
          when: 'First 200 lines (capped at 25KB) of MEMORY.md loaded into the subagent system prompt when it runs',
          description: <>Subagents with <C>memory: project</C> in their frontmatter get a dedicated memory directory here. This is distinct from your <A href="/en/memory#auto-memory">main session auto memory</A> at <C>~/.claude/projects/</C>: each subagent reads and writes its own MEMORY.md, not yours.</>,
          tips: [<>Only created for subagents that set the <C>memory:</C> frontmatter field</>, <>This directory holds project-scoped subagent memory, meant to be shared with your team. To keep memory out of version control use <C>memory: local</C>, which writes to <C>.claude/agent-memory-local/</C> instead. For cross-project memory use <C>memory: user</C>, which writes to <C>~/.claude/agent-memory/</C></>, <>The main session auto memory is a different feature; see <C>~/.claude/projects/</C> in the Global tab</>],
          docsLink: '/en/sub-agents#enable-persistent-memory',
          children: [{
            id: 'agent-memory-sub',
            label: '<agent-name>/',
            type: 'folder',
            icon: 'folder',
            color: '#C46686',
            autogen: true,
            children: [{
              id: 'agent-memory-md',
              label: 'MEMORY.md',
              type: 'file',
              icon: 'md',
              color: '#C46686',
              badge: 'committed',
              autogen: true,
              oneLiner: 'The subagent writes and maintains this file automatically',
              when: 'Loaded into the subagent system prompt when the subagent starts',
              description: <>Works the same as your <A href="/en/memory#auto-memory">main auto memory</A>: the subagent creates and updates this file itself. You do not write it. The subagent reads it at the start of each task and writes back what it learns.</>,
              example: `# code-reviewer memory

## Patterns seen
- Project uses custom Result<T, E> type, not exceptions
- Auth middleware expects Bearer token in Authorization header
- Tests use factory functions in test/factories/

## Recurring issues
- Missing null checks on API responses (src/api/*)
- Unhandled promise rejections in background jobs`
            }]
          }]
        }]
      }]
    },
    global: {
      label: '~/',
      children: [{
        id: 'claude-json',
        label: '.claude.json',
        type: 'file',
        icon: 'json',
        color: 'var(--ce-text-3)',
        badge: 'local',
        oneLiner: 'App state and UI preferences',
        when: <>Read at session start for your preferences and MCP servers. Claude Code writes back to it when you change settings in <C>/config</C> or approve trust prompts</>,
        description: <>Holds state that does not belong in settings.json: theme, OAuth session, per-project trust decisions, your personal MCP servers, and UI toggles. Mostly managed through <C>/config</C> rather than editing directly.</>,
        tips: [<>IDE toggles like <C>autoConnectIde</C> and <C>externalEditorContext</C> live here, not in settings.json</>, <>The <C>projects</C> key tracks per-project state like trust-dialog acceptance and last-session metrics. Permission rules you approve in-session go to <C>.claude/settings.local.json</C> instead</>, <>MCP servers here are yours only: user scope applies across all projects, local scope is per-project but not committed. Team-shared servers go in <C>.mcp.json</C> at the project root instead</>],
        example: `{
  "autoConnectIde": true,
  "externalEditorContext": true,
  "mcpServers": {
    "my-tools": {
      "command": "npx",
      "args": ["-y", "@example/mcp-server"]
    }
  }
}`,
        docsLink: '/en/settings#global-config-settings'
      }, {
        id: 'global-dot-claude',
        label: '.claude/',
        type: 'folder',
        icon: 'folder',
        color: 'var(--ce-accent)',
        oneLiner: 'Your personal configuration across all projects',
        description: 'The global counterpart to your project .claude/ directory. Files here apply to every project you work in and are never committed to any repository.',
        children: [{
          id: 'global-claude-md',
          label: 'CLAUDE.md',
          type: 'file',
          icon: 'md',
          color: '#6A9BCC',
          badge: 'local',
          oneLiner: 'Personal preferences across every project',
          when: 'Loaded at the start of every session, in every project',
          description: 'Your global instruction file. Loaded alongside the project CLAUDE.md at session start, so both are in context together. When instructions conflict, project-level instructions take priority. Keep this to preferences that apply everywhere: response style, commit format, personal conventions.',
          tips: ['Keep it short since it loads into context for every project, alongside that project\'s own CLAUDE.md', 'Good for response style, commit format, and personal conventions'],
          example: `# Global preferences

- Keep explanations concise
- Use conventional commit format
- Show the terminal command to verify changes
- Prefer composition over inheritance`,
          docsLink: '/en/memory'
        }, {
          id: 'global-settings',
          label: 'settings.json',
          type: 'file',
          icon: 'json',
          color: 'var(--ce-text-3)',
          badge: 'local',
          oneLiner: 'Default settings for all projects',
          when: 'Your defaults. Project and local settings.json override any keys you also set there',
          description: [<>Same keys as project <C>settings.json</C>: permissions, hooks, model, environment variables, and the rest. Put settings here that you want in every project, like permissions you always allow, a preferred model, or a notification hook that runs regardless of which project you're in.</>, <>Settings follow a precedence order: project <C>settings.json</C> overrides any matching keys you set here. This is different from CLAUDE.md, where global and project files are both loaded into context rather than merged key by key.</>],
          example: `{
  "permissions": {
    "allow": [
      "Bash(git log *)",
      "Bash(git diff *)"
    ]
  }
}`,
          docsLink: '/en/settings'
        }, {
          id: 'keybindings',
          label: 'keybindings.json',
          type: 'file',
          icon: 'json',
          color: 'var(--ce-text-3)',
          badge: 'local',
          oneLiner: 'Custom keyboard shortcuts',
          when: 'Read at session start and hot-reloaded when you edit the file',
          description: <>Rebind keyboard shortcuts in the interactive CLI. Run <C>/keybindings</C> to create or open this file with a schema reference. Ctrl+C, Ctrl+D, and Ctrl+M are reserved and cannot be rebound.</>,
          exampleIntro: <>This example binds <C>Ctrl+E</C> to open your external editor and unbinds <C>Ctrl+U</C> by setting it to <C>null</C>. The <C>context</C> field scopes bindings to a specific part of the CLI, here the main chat input.</>,
          example: `{
  "$schema": "https://www.schemastore.org/claude-code-keybindings.json",
  "$docs": "https://code.claude.com/docs/en/keybindings",
  "bindings": [
    {
      "context": "Chat",
      "bindings": {
        "ctrl+e": "chat:externalEditor",
        "ctrl+u": null
      }
    }
  ]
}`,
          docsLink: '/en/keybindings'
        }, {
          id: 'themes',
          label: 'themes/',
          type: 'folder',
          icon: 'folder',
          color: '#5AA7A7',
          oneLiner: 'Custom color themes',
          when: <>Read at session start and hot-reloaded when files change. Listed in <C>/theme</C></>,
          description: <>Each <C>.json</C> file defines a custom color theme: a built-in <C>base</C> preset plus an <C>overrides</C> map of color tokens. Create one interactively with <C>/theme</C> or write the JSON by hand. Selecting a custom theme stores <C>custom:&lt;slug&gt;</C> as your theme preference.</>,
          example: `{
  "name": "Dracula",
  "base": "dark",
  "overrides": {
    "claude": "#bd93f9",
    "error": "#ff5555",
    "success": "#50fa7b"
  }
}`,
          docsLink: '/en/terminal-config#create-a-custom-theme',
          children: []
        }, {
          id: 'global-projects',
          label: 'projects/',
          type: 'folder',
          icon: 'folder',
          color: '#E8A45C',
          autogen: true,
          oneLiner: "Auto memory: Claude's notes to itself, per project",
          when: 'MEMORY.md loaded at session start; topic files read on demand',
          description: 'Auto memory lets Claude accumulate knowledge across sessions without you writing anything. Claude saves notes as it works: build commands, debugging insights, architecture notes. Each project gets its own memory directory keyed by the repository path.',
          tips: [<>On by default. Toggle with <C>/memory</C> or <C>autoMemoryEnabled</C> in settings</>, 'MEMORY.md is the index loaded each session. The first 200 lines, or 25KB, whichever comes first, are read', 'Topic files like debugging.md are read on demand, not at startup', 'These are plain markdown. Edit or delete them anytime'],
          docsLink: '/en/memory#auto-memory',
          children: [{
            id: 'memory-dir',
            label: '<project>/memory/',
            type: 'folder',
            icon: 'folder',
            color: '#E8A45C',
            autogen: true,
            oneLiner: "Claude's accumulated knowledge for one project",
            children: [{
              id: 'memory-md',
              label: 'MEMORY.md',
              type: 'file',
              icon: 'md',
              color: '#E8A45C',
              badge: 'local',
              autogen: true,
              oneLiner: 'Claude writes and maintains this file automatically',
              when: 'First 200 lines (capped at 25KB) loaded at session start',
              description: 'Claude creates and updates this file as it works; you do not write it yourself. It acts as an index that Claude reads at the start of every session, pointing to topic files for detail. You can edit or delete it, but Claude will keep updating it.',
              example: `# Memory Index

## Project
- [build-and-test.md](build-and-test.md): npm run build (~45s), Vitest, dev server on 3001
- [architecture.md](architecture.md): API client singleton, refresh-token auth

## Reference
- [debugging.md](debugging.md): auth token rotation and DB connection troubleshooting`,
              docsLink: '/en/memory'
            }, {
              id: 'memory-topic',
              label: 'debugging.md',
              type: 'file',
              icon: 'md',
              color: '#E8A45C',
              badge: 'local',
              autogen: true,
              oneLiner: 'Topic notes Claude writes when MEMORY.md gets long',
              when: 'Claude reads this when a related task comes up',
              description: 'An example of a topic file Claude creates when MEMORY.md grows too long. Claude picks the filename based on what it splits out: debugging.md, architecture.md, build-commands.md, or similar. You never create these yourself. Claude reads a topic file back only when the current task relates to it.',
              example: `---
name: Debugging patterns
description: Auth token rotation and database connection troubleshooting for this project
type: reference
---

## Auth Token Issues
- Refresh token rotation: old token invalidated immediately
- If 401 after refresh: check clock skew between client and server

## Database Connection Drops
- Connection pool: max 10 in dev, 50 in prod
- Always check \`docker compose ps\` first`
            }]
          }]
        }, {
          id: 'global-rules',
          label: 'rules/',
          type: 'folder',
          icon: 'folder',
          color: '#9B7BC4',
          oneLiner: 'User-level rules that apply to every project',
          when: <>Rules without <C>paths:</C> load at session start. Rules with <C>paths:</C> load when a matching file enters context</>,
          description: 'Same as project .claude/rules/ but applies everywhere. Use this for conventions you want across all your work, like personal code style or commit message format.',
          docsLink: '/en/memory#organize-rules-with-claude/rules/',
          children: []
        }, {
          id: 'global-skills',
          label: 'skills/',
          type: 'folder',
          icon: 'folder',
          color: '#D4A843',
          oneLiner: 'Personal skills available in every project',
          when: <>Invoked with <C>/skill-name</C> in any project</>,
          description: 'Skills you built for yourself that work everywhere. Same structure as project skills: each is a folder with SKILL.md, scoped to your user account instead of a single project.',
          docsLink: '/en/skills',
          children: []
        }, {
          id: 'global-commands',
          label: 'commands/',
          type: 'folder',
          icon: 'folder',
          color: '#788C5D',
          oneLiner: 'Personal single-file commands available in every project',
          note: commandsNote,
          when: <>User types <C>/command-name</C> in any project</>,
          description: 'Same as project commands/ but scoped to your user account. Each markdown file becomes a command available everywhere.',
          docsLink: '/en/skills',
          children: []
        }, {
          id: 'global-output-styles',
          label: 'output-styles/',
          type: 'folder',
          icon: 'folder',
          color: '#5AA7A7',
          oneLiner: 'Custom system-prompt sections that adjust how Claude works',
          when: 'Applied at session start when selected via the outputStyle setting',
          description: [<>Each markdown file defines an output style: a section appended to the system prompt that, by default, also drops the built-in software-engineering task instructions. Use this to adapt Claude Code for uses beyond coding, or to add teaching or review modes.</>, <>Select a built-in or custom style with <C>/config</C> or the <C>outputStyle</C> key in settings. Styles here are available in every project; project-level styles with the same name take precedence.</>],
          tips: ['Built-in styles Explanatory and Learning are included with Claude Code; custom styles go here', <>Set <C>keep-coding-instructions: true</C> in frontmatter to keep the default task instructions alongside your additions</>, 'Changes take effect on the next session since the system prompt is fixed at startup for caching'],
          docsLink: '/en/output-styles',
          children: [{
            id: 'output-style-example',
            label: 'teaching.md',
            type: 'file',
            icon: 'md',
            color: '#5AA7A7',
            badge: 'local',
            oneLiner: 'Example style that adds explanations and leaves small changes for you',
            when: <>Active when <C>outputStyle</C> in settings is set to <C>teaching</C></>,
            description: <>This style appends instructions to the system prompt: Claude adds a "Why this approach" note after each task and leaves TODO(human) markers for changes under 10 lines instead of writing them itself. Select it by setting <C>outputStyle</C> to the filename without .md, or to the <C>name</C> field if you set one in frontmatter.</>,
            example: `---
description: Explains reasoning and asks you to implement small pieces
keep-coding-instructions: true
---

After completing each task, add a brief "Why this approach" note
explaining the key design decision.

When a change is under 10 lines, ask the user to implement it
themselves by leaving a TODO(human) marker instead of writing it.`
          }]
        }, {
          id: 'global-agents',
          label: 'agents/',
          type: 'folder',
          icon: 'folder',
          color: '#C46686',
          oneLiner: 'Personal subagents available in every project',
          when: 'Claude delegates or you @-mention in any project',
          description: 'Subagents defined here are available across all your projects. Same format as project agents.',
          docsLink: '/en/sub-agents',
          children: []
        }, {
          id: 'global-agent-memory',
          label: 'agent-memory/',
          type: 'folder',
          icon: 'folder',
          color: '#C46686',
          autogen: true,
          oneLiner: <>Persistent memory for subagents with <C>memory: user</C></>,
          when: 'Loaded into the subagent system prompt when the subagent starts',
          description: <>Subagents with <C>memory: user</C> in their frontmatter store knowledge here that persists across all projects. For project-scoped subagent memory, see <C>.claude/agent-memory/</C> instead.</>,
          docsLink: '/en/sub-agents#enable-persistent-memory',
          children: []
        }]
      }]
    }
  }), []);
  const BADGE_STYLES = useMemo(() => ({
    committed: {
      bg: 'rgba(85,138,66,0.08)',
      color: 'var(--ce-badge-committed)',
      border: 'rgba(85,138,66,0.15)',
      label: 'committed'
    },
    gitignored: {
      bg: 'rgba(217,119,87,0.06)',
      color: 'var(--ce-badge-gitignored)',
      border: 'rgba(217,119,87,0.15)',
      label: 'gitignored'
    },
    local: {
      bg: 'rgba(115,114,108,0.06)',
      color: 'var(--ce-badge-local)',
      border: 'rgba(115,114,108,0.12)',
      label: 'local only'
    },
    autogen: {
      bg: 'rgba(232,164,92,0.1)',
      color: 'var(--ce-badge-autogen)',
      border: 'rgba(232,164,92,0.2)',
      label: 'Claude writes'
    }
  }), []);
  const allNodes = useMemo(() => {
    const flatten = (nodes, acc, path, parentId) => {
      for (const node of nodes) {
        const nextPath = [...path, node.label];
        acc[node.id] = {
          ...node,
          path: nextPath,
          parentId
        };
        if (node.children) flatten(node.children, acc, nextPath, node.id);
      }
      return acc;
    };
    const project = flatten(FILE_TREE.project.children, {}, [FILE_TREE.project.label]);
    const global = flatten(FILE_TREE.global.children, {}, [FILE_TREE.global.label]);
    for (const id in project) project[id].root = 'project';
    for (const id in global) global[id].root = 'global';
    return {
      ...project,
      ...global
    };
  }, [FILE_TREE]);
  const allFolderIds = useMemo(() => Object.keys(allNodes).filter(id => allNodes[id].type === 'folder'), [allNodes]);
  const DEFAULT_EXPANDED = ['dot-claude', 'rules', 'skills', 'skill-review', 'commands', 'agents', 'agent-memory', 'agent-memory-sub', 'global-dot-claude', 'global-output-styles', 'global-projects', 'memory-dir'];
  const [mounted, setMounted] = useState(false);
  const [activeRoot, setActiveRoot] = useState('project');
  const [selectedId, setSelectedId] = useState('claude-md');
  const [expandedFolders, setExpandedFolders] = useState(() => new Set(DEFAULT_EXPANDED));
  const [forceMobile, setForceMobile] = useState(false);
  const [copiedId, setCopiedId] = useState(null);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const copyTimeoutRef = useRef(null);
  const rootRef = useRef(null);
  useEffect(() => {
    setMounted(true);
    const applyHash = scroll => {
      const hash = window.location.hash.slice(1);
      if (!hash.startsWith('ce-')) return;
      const id = hash.slice(3);
      const node = allNodes[id];
      if (!node) return;
      setActiveRoot(node.root);
      setSelectedId(id);
      setExpandedFolders(new Set(allFolderIds));
      if (scroll && rootRef.current) rootRef.current.scrollIntoView({
        behavior: 'smooth',
        block: 'start'
      });
    };
    applyHash(false);
    const onHashChange = () => applyHash(true);
    const onFsChange = () => setIsFullscreen(!!document.fullscreenElement);
    window.addEventListener('hashchange', onHashChange);
    document.addEventListener('fullscreenchange', onFsChange);
    return () => {
      if (copyTimeoutRef.current) clearTimeout(copyTimeoutRef.current);
      window.removeEventListener('hashchange', onHashChange);
      document.removeEventListener('fullscreenchange', onFsChange);
    };
  }, []);
  useEffect(() => {
    if (!mounted || !rootRef.current) return;
    const hash = window.location.hash.slice(1);
    if (hash.startsWith('ce-') && allNodes[hash.slice(3)]) {
      rootRef.current.scrollIntoView({
        behavior: 'smooth',
        block: 'start'
      });
    }
  }, [mounted]);
  if (!mounted) return null;
  const selected = allNodes[selectedId];
  const tree = FILE_TREE[activeRoot];
  const isCopied = copiedId === selected.id;
  const toggleFolder = id => {
    const next = new Set(expandedFolders);
    next.has(id) ? next.delete(id) : next.add(id);
    setExpandedFolders(next);
  };
  const switchRoot = root => {
    if (root === activeRoot) return;
    setActiveRoot(root);
    const firstId = FILE_TREE[root].children[0].id;
    setSelectedId(firstId);
    try {
      history.replaceState(null, '', '#ce-' + firstId);
    } catch (e) {}
  };
  const toggleFullscreen = () => {
    if (!rootRef.current) return;
    if (document.fullscreenElement) document.exitFullscreen(); else rootRef.current.requestFullscreen().catch(() => {});
  };
  const selectNode = n => {
    setSelectedId(n.id);
    if (n.type === 'folder' && !expandedFolders.has(n.id)) toggleFolder(n.id);
    try {
      history.replaceState(null, '', '#ce-' + n.id);
    } catch (e) {}
  };
  const iconBtn = {
    width: 28,
    flexShrink: 0,
    borderRadius: '6px',
    border: 'none',
    cursor: 'pointer',
    background: 'transparent',
    color: 'var(--ce-text-4)',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center'
  };
  const visibleFolderIds = allFolderIds.filter(id => allNodes[id].root === activeRoot);
  const allExpanded = visibleFolderIds.every(id => expandedFolders.has(id));
  const toggleAllFolders = () => {
    const next = new Set(expandedFolders);
    visibleFolderIds.forEach(id => allExpanded ? next.delete(id) : next.add(id));
    setExpandedFolders(next);
  };
  const onTreeKeyDown = e => {
    if (!['ArrowDown', 'ArrowUp', 'ArrowRight', 'ArrowLeft'].includes(e.key)) return;
    const visible = [];
    const walk = nodes => {
      for (const n of nodes) {
        visible.push(n.id);
        if (n.children && expandedFolders.has(n.id)) walk(n.children);
      }
    };
    walk(tree.children);
    const i = visible.indexOf(selectedId);
    if (i === -1) return;
    e.preventDefault();
    if (e.key === 'ArrowDown' && i < visible.length - 1) selectNode(allNodes[visible[i + 1]]); else if (e.key === 'ArrowUp' && i > 0) selectNode(allNodes[visible[i - 1]]); else if (e.key === 'ArrowRight' && selected.type === 'folder') {
      if (!expandedFolders.has(selectedId)) toggleFolder(selectedId); else if (selected.children && selected.children.length) selectNode(allNodes[selected.children[0].id]);
    } else if (e.key === 'ArrowLeft') {
      if (selected.type === 'folder' && expandedFolders.has(selectedId)) toggleFolder(selectedId); else if (selected.parentId) selectNode(allNodes[selected.parentId]);
    }
  };
  const copyExample = (id, text) => {
    const done = () => {
      setCopiedId(id);
      if (copyTimeoutRef.current) clearTimeout(copyTimeoutRef.current);
      copyTimeoutRef.current = setTimeout(() => setCopiedId(null), 2000);
    };
    const fallback = () => {
      const ta = document.createElement('textarea');
      ta.value = text;
      ta.style.position = 'fixed';
      ta.style.opacity = '0';
      document.body.appendChild(ta);
      ta.select();
      try {
        if (document.execCommand('copy')) done();
      } catch (e) {}
      document.body.removeChild(ta);
    };
    if (navigator.clipboard) {
      navigator.clipboard.writeText(text).then(done, fallback);
    } else {
      fallback();
    }
  };
  const renderIcon = (icon, color, size) => {
    const sz = size || 14;
    if (icon === 'folder') {
      return <svg width={sz} height={sz} viewBox="0 0 14 14" fill="none">
          <path d="M1.5 3.5a1 1 0 0 1 1-1h2.6l1 1.2h5.4a1 1 0 0 1 1 1v5.8a1 1 0 0 1-1 1h-9a1 1 0 0 1-1-1V3.5z" fill={color} fillOpacity="0.15" stroke={color} strokeWidth="1" />
        </svg>;
    }
    if (icon === 'json') {
      return <svg width={sz} height={sz} viewBox="0 0 14 14" fill="none">
          <rect x="2" y="1.5" width="10" height="11" rx="1.5" fill={color} fillOpacity="0.15" stroke={color} strokeWidth="1" />
          <text x="7" y="9" fontSize="6" fontFamily="monospace" fill={color} textAnchor="middle" fontWeight="700">{'{}'}</text>
        </svg>;
    }
    return <svg width={sz} height={sz} viewBox="0 0 14 14" fill="none">
        <rect x="2" y="1.5" width="10" height="11" rx="1.5" fill={color} fillOpacity="0.15" stroke={color} strokeWidth="1" />
        <line x1="4.5" y1="5" x2="9.5" y2="5" stroke={color} strokeWidth="1" />
        <line x1="4.5" y1="7" x2="9.5" y2="7" stroke={color} strokeWidth="1" />
        <line x1="4.5" y1="9" x2="8" y2="9" stroke={color} strokeWidth="1" />
      </svg>;
  };
  const renderNode = (node, depth) => {
    const isFolder = node.type === 'folder';
    const isExpanded = expandedFolders.has(node.id);
    const isSelected = selectedId === node.id;
    return <div key={node.id}>
        <button role="treeitem" tabIndex={-1} onClick={() => selectNode(node)} aria-selected={isSelected} aria-expanded={isFolder ? isExpanded : undefined} style={{
      display: 'flex',
      alignItems: 'center',
      gap: '5px',
      width: '100%',
      padding: `4px 8px 4px ${8 + depth * 16}px`,
      background: isSelected ? 'var(--ce-accent-bg)' : 'transparent',
      borderTop: 'none',
      borderRight: 'none',
      borderBottom: 'none',
      borderLeft: isSelected ? '2px solid var(--ce-accent)' : '2px solid transparent',
      outline: 'none',
      cursor: 'pointer',
      textAlign: 'left',
      fontFamily: 'var(--ce-mono)',
      fontSize: '13.5px',
      color: isSelected ? 'var(--ce-accent)' : 'var(--ce-text-2)',
      fontWeight: isSelected ? 550 : 400,
      transition: 'all 0.1s'
    }}>
          {isFolder ? <span onClick={e => {
      e.stopPropagation();
      toggleFolder(node.id);
    }} style={{
      fontSize: '14px',
      color: 'var(--ce-text-4)',
      width: '20px',
      height: '20px',
      display: 'inline-flex',
      alignItems: 'center',
      justifyContent: 'center',
      cursor: 'pointer',
      borderRadius: '4px',
      marginLeft: '-6px',
      flexShrink: 0
    }} onMouseEnter={e => {
      e.currentTarget.style.background = 'var(--ce-arrow-hover)';
      e.currentTarget.style.color = 'var(--ce-text-2)';
    }} onMouseLeave={e => {
      e.currentTarget.style.background = 'transparent';
      e.currentTarget.style.color = 'var(--ce-text-4)';
    }}>{isExpanded ? '▾' : '▸'}</span> : <span style={{
      width: '14px',
      flexShrink: 0
    }} />}
          {renderIcon(node.icon, node.color)}
          <span style={{
      flex: 1,
      overflow: 'hidden',
      textOverflow: 'ellipsis',
      whiteSpace: 'nowrap'
    }}>{node.label}</span>
          {node.badge && BADGE_STYLES[node.badge] && <span title={BADGE_STYLES[node.badge].label} style={{
      width: 6,
      height: 6,
      borderRadius: '50%',
      background: BADGE_STYLES[node.badge].color,
      flexShrink: 0,
      opacity: 0.7
    }} />}
        </button>
        {isFolder && isExpanded && node.children && <div role="group">{node.children.map(child => renderNode(child, depth + 1))}</div>}
      </div>;
  };
  return <>
    <style>{`
      .ce-root {
        --ce-mono: var(--font-mono, ui-monospace, monospace);
        --ce-accent: #D97757;
        --ce-accent-bg: rgba(217,119,87,0.06);
        --ce-accent-border: rgba(217,119,87,0.12);
        --ce-bg: #fff;
        --ce-surface: #FAFAF7;
        --ce-surface-hover: #F0EEE6;
        --ce-border: #E8E6DC;
        --ce-border-subtle: #F0EEE6;
        --ce-text: #141413;
        --ce-text-2: #5E5D59;
        --ce-text-3: #73726C;
        --ce-text-4: #9C9A92;
        --ce-text-5: #B8B6AE;
        --ce-sep: #D1CFC5;
        --ce-code-header: #F5F4ED;
        --ce-code-bg: #1A1918;
        --ce-arrow-hover: rgba(0,0,0,0.08);
        --ce-badge-committed: #3d6b2e;
        --ce-badge-gitignored: #b85c3a;
        --ce-badge-local: #5e5d59;
        --ce-badge-autogen: #b07520;
        --ce-when-text: #4a7fb5;
      }
      .dark .ce-root {
        --ce-bg: #1a1918;
        --ce-surface: #232221;
        --ce-surface-hover: #2e2d2b;
        --ce-border: #3a3936;
        --ce-border-subtle: #2e2d2b;
        --ce-text: #e8e6dc;
        --ce-text-2: #c4c2b8;
        --ce-text-3: #9c9a92;
        --ce-text-4: #73726c;
        --ce-text-5: #5e5d59;
        --ce-sep: #4a4946;
        --ce-code-header: #2e2d2b;
        --ce-code-bg: #0d0d0c;
        --ce-arrow-hover: rgba(255,255,255,0.08);
        --ce-badge-committed: #6fa85c;
        --ce-badge-gitignored: #e08a60;
        --ce-badge-local: #9c9a92;
        --ce-badge-autogen: #e8a45c;
        --ce-when-text: #8bb4e0;
      }
      .ce-mobile-fallback { display: none; border: 1px solid rgba(0,0,0,0.1); background: rgba(0,0,0,0.03); }
      .dark .ce-mobile-fallback { border-color: rgba(255,255,255,0.15); background: rgba(255,255,255,0.04); }
      @media (max-width: 700px) {
        .ce-root:not(.ce-force) { display: none !important; }
        .ce-mobile-fallback { display: block; }
      }
    `}</style>
    {!forceMobile && <div className="ce-mobile-fallback" style={{
    padding: '14px 16px',
    borderRadius: '8px',
    fontSize: '14px'
  }}>
      The interactive explorer works best on a larger screen. See the <a href="#file-reference" style={{
    color: '#D97757'
  }}>file reference table</a> below, or <button onClick={() => setForceMobile(true)} style={{
    border: 'none',
    background: 'none',
    padding: 0,
    color: '#D97757',
    textDecoration: 'underline',
    cursor: 'pointer',
    font: 'inherit'
  }}>show the explorer anyway</button>.
    </div>}
    <div ref={rootRef} className={forceMobile ? 'ce-root ce-force' : 'ce-root'} style={{
    borderRadius: isFullscreen ? 0 : '12px',
    border: '1px solid var(--ce-border)',
    background: 'var(--ce-bg)',
    display: 'flex',
    alignItems: 'stretch',
    overflow: 'hidden',
    fontFamily: 'var(--font-sans, -apple-system, sans-serif)',
    ...isFullscreen && ({
      height: '100vh'
    })
  }}>
      {}
      <div style={{
    width: 'min(240px, 35%)',
    minWidth: '180px',
    flexShrink: 0,
    borderRight: '1px solid var(--ce-border-subtle)',
    background: 'var(--ce-surface)',
    display: 'flex',
    flexDirection: 'column'
  }}>
        <div style={{
    padding: '8px 8px 4px',
    borderBottom: '1px solid var(--ce-border-subtle)',
    display: 'flex',
    gap: '4px'
  }}>
          {['project', 'global'].map(root => <button key={root} onClick={() => switchRoot(root)} style={{
    flex: 1,
    padding: '6px 0',
    borderRadius: '6px',
    border: 'none',
    cursor: 'pointer',
    fontFamily: 'var(--ce-mono)',
    fontSize: '11.5px',
    background: activeRoot === root ? 'var(--ce-accent-bg)' : 'transparent',
    color: activeRoot === root ? 'var(--ce-accent)' : 'var(--ce-text-4)',
    fontWeight: activeRoot === root ? 600 : 430
  }}>
              {root === 'project' ? 'Project' : 'Global (~/)'}
            </button>)}
          <button onClick={toggleAllFolders} title={allExpanded ? 'Collapse all' : 'Expand all'} style={{
    ...iconBtn,
    fontSize: 11
  }}>
            {allExpanded ? '⊟' : '⊞'}
          </button>
          <button onClick={toggleFullscreen} title={isFullscreen ? 'Exit fullscreen' : 'Fullscreen'} style={{
    ...iconBtn,
    fontSize: 13
  }}>
            {isFullscreen ? '⤡' : '⛶'}
          </button>
        </div>
        <div role="tree" aria-label="Configuration files" tabIndex={0} onKeyDown={onTreeKeyDown} style={{
    padding: '6px 0',
    overflowY: 'auto',
    flex: 1,
    outline: 'none'
  }}>
          {tree.children.map(node => renderNode(node, 0))}
        </div>
      </div>

      {}
      <div style={{
    flex: 1,
    minWidth: 0,
    padding: '20px 24px',
    minHeight: '400px',
    overflowY: 'auto'
  }}>
            <span aria-live="polite" style={{
    position: 'absolute',
    width: 1,
    height: 1,
    overflow: 'hidden',
    clip: 'rect(0 0 0 0)'
  }}>{selected.label} selected</span>
            {}
            <div style={{
    fontFamily: 'var(--ce-mono)',
    fontSize: '11px',
    color: 'var(--ce-text-4)',
    marginBottom: '10px',
    cursor: 'default'
  }}>
              {selected.path.map((seg, i) => <span key={i}>
                  <span style={{
    color: i === selected.path.length - 1 ? 'var(--ce-accent)' : 'var(--ce-text-4)'
  }}>{seg.replace(/\/$/, '')}</span>
                  {i < selected.path.length - 1 && <span style={{
    color: 'var(--ce-sep)'
  }}> / </span>}
                </span>)}
            </div>

            {}
            <div style={{
    display: 'flex',
    alignItems: 'flex-start',
    gap: '10px',
    marginBottom: '10px'
  }}>
              <span style={{
    flexShrink: 0,
    display: 'flex'
  }}>{renderIcon(selected.icon, selected.color, 24)}</span>
              <div style={{
    flex: 1,
    minWidth: 0
  }}>
                <div style={{
    fontSize: '22px',
    fontWeight: 600,
    color: 'var(--ce-text)',
    letterSpacing: '-0.3px',
    lineHeight: '26px'
  }}>{selected.label}</div>
                {selected.oneLiner && <div style={{
    fontSize: '15px',
    color: 'var(--ce-text-3)',
    marginTop: '3px'
  }}>{selected.oneLiner}</div>}
              </div>
              <div style={{
    display: 'flex',
    gap: '4px',
    flexShrink: 0
  }}>
                {[selected.autogen && 'autogen', selected.badge].filter(Boolean).map(k => {
    const s = BADGE_STYLES[k];
    if (!s) return null;
    return <span key={k} style={{
      fontFamily: 'var(--ce-mono)',
      fontSize: '10px',
      fontWeight: 600,
      textTransform: 'uppercase',
      letterSpacing: '0.3px',
      padding: '2px 6px',
      borderRadius: '4px',
      background: s.bg,
      color: s.color,
      border: `0.5px solid ${s.border}`
    }}>{s.label}</span>;
  })}
              </div>
            </div>

            {}
            {selected.note && <div style={{
    padding: '10px 12px',
    borderRadius: '8px',
    marginBottom: '14px',
    background: 'rgba(217,119,87,0.06)',
    border: '1px solid rgba(217,119,87,0.2)',
    borderLeft: '3px solid var(--ce-accent)',
    fontSize: '15px',
    color: 'var(--ce-text-2)',
    lineHeight: 1.6
  }}>
                {selected.note}
              </div>}

            {}
            {selected.when && <div style={{
    padding: '8px 12px',
    borderRadius: '6px',
    background: 'rgba(106,155,204,0.06)',
    border: '0.5px solid rgba(106,155,204,0.12)',
    fontSize: '15px',
    color: 'var(--ce-when-text)',
    marginBottom: '16px'
  }}>
                <div style={{
    fontSize: '10px',
    fontWeight: 700,
    textTransform: 'uppercase',
    letterSpacing: '0.4px',
    opacity: 0.65,
    marginBottom: '3px'
  }}>When it loads</div>
                <div style={{
    fontWeight: 500
  }}>{selected.when}</div>
              </div>}

            {}
            {selected.description && <div style={{
    fontSize: '16px',
    color: 'var(--ce-text-2)',
    lineHeight: 1.65,
    marginBottom: '16px'
  }}>
                {Array.isArray(selected.description) ? selected.description.map((para, i) => <div key={i} style={{
    marginBottom: i < selected.description.length - 1 ? '12px' : 0
  }}>{para}</div>) : selected.description}
              </div>}

            {}
            {selected.contains && selected.contains.length > 0 && <div style={{
    marginBottom: '16px'
  }}>
                <div style={{
    fontSize: '11px',
    fontWeight: 700,
    color: 'var(--ce-text-4)',
    textTransform: 'uppercase',
    letterSpacing: '0.4px',
    marginBottom: '8px'
  }}>Common keys</div>
                {selected.contains.map((item, i) => <div key={i} style={{
    display: 'flex',
    gap: '7px',
    fontSize: '15px',
    color: 'var(--ce-text-2)',
    lineHeight: 1.5,
    marginBottom: '5px'
  }}>
                    <span style={{
    fontSize: '7px',
    color: 'var(--ce-text-4)',
    marginTop: '6px'
  }}>●</span>
                    <span>{item}</span>
                  </div>)}
              </div>}

            {}
            {selected.tips && selected.tips.length > 0 && <div style={{
    padding: '12px 14px',
    borderRadius: '8px',
    background: 'var(--ce-surface)',
    border: '1px solid var(--ce-border-subtle)',
    marginBottom: '16px'
  }}>
                <div style={{
    fontSize: '11px',
    fontWeight: 700,
    color: 'var(--ce-accent)',
    textTransform: 'uppercase',
    letterSpacing: '0.4px',
    marginBottom: '6px'
  }}>Tips</div>
                {selected.tips.map((tip, i) => <div key={i} style={{
    display: 'flex',
    gap: '7px',
    fontSize: '14.5px',
    color: 'var(--ce-text-2)',
    marginBottom: i < selected.tips.length - 1 ? '5px' : 0
  }}>
                    <span style={{
    fontSize: '7px',
    color: 'var(--ce-accent)',
    marginTop: '6px'
  }}>●</span>
                    <span>{tip}</span>
                  </div>)}
              </div>}

            {}
            {selected.example && <div style={{
    marginBottom: '16px'
  }}>
                {selected.exampleIntro && <div style={{
    fontSize: '15px',
    color: 'var(--ce-text-2)',
    lineHeight: 1.6,
    marginBottom: '10px'
  }}>
                    {selected.exampleIntro}
                  </div>}
                <div style={{
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: '6px 10px',
    background: 'var(--ce-code-header)',
    border: '1px solid var(--ce-border)',
    borderRadius: '8px 8px 0 0'
  }}>
                  <span style={{
    fontFamily: 'var(--ce-mono)',
    fontSize: '11px',
    fontWeight: 600,
    color: 'var(--ce-text-3)'
  }}>{selected.label}</span>
                  <button onClick={() => copyExample(selected.id, selected.example)} style={{
    padding: '3px 8px',
    borderRadius: '4px',
    fontSize: '11px',
    fontWeight: 600,
    cursor: 'pointer',
    transition: 'all 0.15s',
    background: isCopied ? 'rgba(85,138,66,0.08)' : 'var(--ce-code-header)',
    border: isCopied ? '0.5px solid rgba(85,138,66,0.2)' : '0.5px solid var(--ce-border)',
    color: isCopied ? '#558A42' : 'var(--ce-text-3)'
  }}>
                    {isCopied ? '✓ Copied' : 'Copy'}
                  </button>
                </div>
                <pre style={{
    margin: 0,
    padding: '12px 14px',
    background: 'var(--ce-code-bg)',
    color: '#E8E6DC',
    fontFamily: 'var(--ce-mono)',
    fontSize: '13px',
    lineHeight: 1.65,
    borderRadius: '0 0 8px 8px',
    overflowX: 'auto',
    whiteSpace: 'pre'
  }}>{selected.example}</pre>
              </div>}

            {}
            {selected.docsLink && <a href={selected.docsLink} style={{
    display: 'inline-flex',
    padding: '5px 12px',
    borderRadius: '6px',
    background: 'var(--ce-accent-bg)',
    border: '1px solid var(--ce-accent-border)',
    color: 'var(--ce-accent)',
    fontSize: '12px',
    fontWeight: 600,
    textDecoration: 'none'
  }}>Full docs →</a>}

            {}
            {selected.children && selected.children.length > 0 && <div style={{
    marginTop: '20px'
  }}>
                <div style={{
    fontSize: '11px',
    fontWeight: 700,
    color: 'var(--ce-text-4)',
    textTransform: 'uppercase',
    letterSpacing: '0.4px',
    marginBottom: '8px'
  }}>Contents</div>
                <div style={{
    display: 'flex',
    flexDirection: 'column',
    gap: '4px'
  }}>
                  {selected.children.map(child => <button key={child.id} onClick={() => selectNode(child)} style={{
    display: 'flex',
    alignItems: 'center',
    gap: '8px',
    padding: '6px 8px',
    width: '100%',
    background: 'var(--ce-surface)',
    borderRadius: '6px',
    border: 'none',
    cursor: 'pointer',
    textAlign: 'left',
    transition: 'background 0.1s'
  }} onMouseEnter={e => e.currentTarget.style.background = 'var(--ce-surface-hover)'} onMouseLeave={e => e.currentTarget.style.background = 'var(--ce-surface)'}>
                      {renderIcon(child.icon, child.color, 13)}
                      <span style={{
    fontFamily: 'var(--ce-mono)',
    fontSize: '12px',
    color: 'var(--ce-text-2)'
  }}>{child.label}</span>
                      {child.oneLiner && <span style={{
    fontSize: '11px',
    color: 'var(--ce-text-4)',
    overflow: 'hidden',
    textOverflow: 'ellipsis',
    whiteSpace: 'nowrap'
  }}>{child.oneLiner}</span>}
                    </button>)}
                </div>
              </div>}
      </div>
    </div>
    </>;
};

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`](env-vars-5c624d392b.md), every `~/.claude` path on this page lives under that directory instead.

Most users only edit `CLAUDE.md` and `settings.json`. The rest of the directory is optional: add skills, rules, or subagents as you need them.

## Explore the directory

Click files in the tree to see what each one does, when it loads, and an example.

<ClaudeExplorer />

## What's not shown

The explorer covers files you author and edit. A few related files live elsewhere:

| File                    | Location                   | Purpose                                                                                                                                                                                                                                                            |
| ----------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `managed-settings.json` | System-level, varies by OS | Enterprise-enforced settings that you can't override. See [server-managed settings](../13-Enterprise-Admin/configure-server-managed-settings-claude-code-docs-d6a169b0bf.md).                                                                                                                                                  |
| `CLAUDE.local.md`       | Project root               | Your private preferences for this project, loaded alongside CLAUDE.md. Create it manually and add it to `.gitignore`.                                                                                                                                              |
| Installed plugins       | `~/.claude/plugins`        | Cloned marketplaces, installed plugin versions, and per-plugin data, managed by `claude plugin` commands. Orphaned versions are deleted 7 days after a plugin update or uninstall. See [plugin caching](/en/plugins-reference#plugin-caching-and-file-resolution). |

`~/.claude` also holds data Claude Code writes as you work: transcripts, prompt history, file snapshots, caches, and logs. See [application data](#application-data) below.

## Choose the right file

Different kinds of customization live in different files. Use this table to find where a change belongs.

| You want to                                        | Edit                                     | Scope             | Reference                                          |
| :------------------------------------------------- | :--------------------------------------- | :---------------- | :------------------------------------------------- |
| Give Claude project context and conventions        | `CLAUDE.md`                              | project or global | [Memory](how-claude-remembers-your-project-claude-code-docs-f1c064262d.md)                               |
| Allow or block specific tool calls                 | `settings.json` `permissions` or `hooks` | project or global | [Permissions](configure-permissions-claude-code-docs-7b0e64d485.md), [Hooks](../07-Hooks/hooks-9168ed62a4.md) |
| Run a script before or after tool calls            | `settings.json` `hooks`                  | project or global | [Hooks](../07-Hooks/hooks-9168ed62a4.md)                                 |
| Set environment variables for the session          | `settings.json` `env`                    | project or global | [Settings](/en/settings#available-settings)        |
| Keep personal overrides out of git                 | `settings.local.json`                    | project only      | [Settings scopes](/en/settings#settings-files)     |
| Add a prompt or capability you invoke with `/name` | `skills/<name>/SKILL.md`                 | project or global | [Skills](../08-Plugins-Skills/extend-claude-with-skills-claude-code-docs.md)                               |
| Define a specialized subagent with its own tools   | `agents/*.md`                            | project or global | [Subagents](../09-Agents-Patterns/create-custom-subagents-claude-code-docs-7dc93e85c0.md)                        |
| Connect external tools over MCP                    | `.mcp.json`                              | project only      | [MCP](../06-MCP-Tools/mcp-208e742686.md)                                     |
| Change how Claude formats responses                | `output-styles/*.md`                     | project or global | [Output styles](output-styles-claude-code-docs-c315eeed32.md)                 |

## 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.

<Note>
  Several things can override what you put in these files:

  * [Managed settings](../13-Enterprise-Admin/configure-server-managed-settings-claude-code-docs-d6a169b0bf.md) deployed by your organization take precedence over everything
  * CLI flags like `--permission-mode` or `--settings` override `settings.json` for that session
  * Some environment variables take precedence over their equivalent setting, but this varies: check the [environment variables reference](env-vars-5c624d392b.md) for each one

  See [settings precedence](/en/settings#settings-precedence) for the full order.
</Note>

Click a filename to open that node in the explorer above.

| File                                                | Scope              | Commit | What it does                                          | Reference                                                            |
| --------------------------------------------------- | ------------------ | ------ | ----------------------------------------------------- | -------------------------------------------------------------------- |
| [`CLAUDE.md`](#ce-claude-md)                        | Project and global | ✓      | Instructions loaded every session                     | [Memory](how-claude-remembers-your-project-claude-code-docs-f1c064262d.md)                                                 |
| [`rules/*.md`](#ce-rules)                           | Project and global | ✓      | Topic-scoped instructions, optionally path-gated      | [Rules](/en/memory#organize-rules-with-claude/rules/)                |
| [`settings.json`](#ce-settings-json)                | Project and global | ✓      | Permissions, hooks, env vars, model defaults          | [Settings](claude-code-settings-claude-code-docs-d4420b4b52.md)                                             |
| [`settings.local.json`](#ce-settings-local-json)    | Project only       |        | Your personal overrides, auto-gitignored              | [Settings scopes](/en/settings#settings-files)                       |
| [`.mcp.json`](#ce-mcp-json)                         | Project only       | ✓      | Team-shared MCP servers                               | [MCP scopes](/en/mcp#mcp-installation-scopes)                        |
| [`.worktreeinclude`](#ce-worktreeinclude)           | Project only       | ✓      | Gitignored files to copy into new worktrees           | [Worktrees](/en/common-workflows#copy-gitignored-files-to-worktrees) |
| [`skills/<name>/SKILL.md`](#ce-skills)              | Project and global | ✓      | Reusable prompts invoked with `/name` or auto-invoked | [Skills](../08-Plugins-Skills/extend-claude-with-skills-claude-code-docs.md)                                                 |
| [`commands/*.md`](#ce-commands)                     | Project and global | ✓      | Single-file prompts; same mechanism as skills         | [Skills](../08-Plugins-Skills/extend-claude-with-skills-claude-code-docs.md)                                                 |
| [`output-styles/*.md`](#ce-output-styles)           | Project and global | ✓      | Custom system-prompt sections                         | [Output styles](output-styles-claude-code-docs-c315eeed32.md)                                   |
| [`agents/*.md`](#ce-agents)                         | Project and global | ✓      | Subagent definitions with their own prompt and tools  | [Subagents](../09-Agents-Patterns/create-custom-subagents-claude-code-docs-7dc93e85c0.md)                                          |
| [`agent-memory/<name>/`](#ce-agent-memory)          | Project and global | ✓      | Persistent memory for subagents                       | [Persistent memory](/en/sub-agents#enable-persistent-memory)         |
| [`~/.claude.json`](#ce-claude-json)                 | Global only        |        | App state, OAuth, UI toggles, personal MCP servers    | [Global config](/en/settings#global-config-settings)                 |
| [`projects/<project>/memory/`](#ce-global-projects) | Global only        |        | Auto memory: Claude's notes to itself across sessions | [Auto memory](/en/memory#auto-memory)                                |
| [`keybindings.json`](#ce-keybindings)               | Global only        |        | Custom keyboard shortcuts                             | [Keybindings](customize-keyboard-shortcuts-claude-code-docs-f23eb8cfd3.md)                                       |
| [`themes/*.json`](#ce-themes)                       | Global only        |        | Custom color themes                                   | [Custom themes](/en/terminal-config#create-a-custom-theme)           |

## Troubleshoot configuration

If a setting, hook, or file isn't taking effect, see [Debug your configuration](debug-your-config-615fc7cc73.md) for the inspection commands and a symptom-first lookup table.

## 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 lands in a transcript on disk: file contents, command output, pasted text.

### Cleaned up automatically

Files in the paths below are deleted on startup once they're older than [`cleanupPeriodDays`](/en/settings#available-settings). The default is 30 days.

| Path under `~/.claude/`                      | Contents                                                                                                          |
| -------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| `projects/<project>/<session>.jsonl`         | Full conversation transcript: every message, tool call, and tool result                                           |
| `projects/<project>/<session>/tool-results/` | Large tool outputs spilled to separate files                                                                      |
| `file-history/<session>/`                    | Pre-edit snapshots of files Claude changed, used for [checkpoint restore](checkpointing-94f7cd24eb.md)                      |
| `plans/`                                     | Plan files written during [plan mode](/en/permission-modes#analyze-before-you-edit-with-plan-mode)                |
| `debug/`                                     | Per-session debug logs, written only when you start with `--debug` or run `/debug`                                |
| `paste-cache/`, `image-cache/`               | Contents of large pastes and attached images                                                                      |
| `session-env/`                               | Per-session environment metadata                                                                                  |
| `tasks/`                                     | Per-session task lists written by the task tools                                                                  |
| `shell-snapshots/`                           | Captured shell environment used by the Bash tool. Removed on clean exit. The sweep clears any left after a crash. |
| `backups/`                                   | Timestamped copies of `~/.claude.json` taken before config migrations                                             |

### Kept until you delete them

The following paths are not covered by automatic cleanup and persist indefinitely.

| Path under `~/.claude/` | Contents                                                                              |
| ----------------------- | ------------------------------------------------------------------------------------- |
| `history.jsonl`         | Every prompt you've typed, with timestamp and project path. Used for up-arrow recall. |
| `stats-cache.json`      | Aggregated token and cost counts shown by `/usage`                                    |
| `todos/`                | Legacy per-session task lists. No longer written by current versions; safe to delete. |

Other small cache and lock files appear depending on which features you use and are safe to delete.

### 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:

* Lower `cleanupPeriodDays` to shorten how long transcripts are kept
* Set the [`CLAUDE_CODE_SKIP_PROMPT_HISTORY`](env-vars-5c624d392b.md) 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 Agent SDK.
* Use [permission rules](configure-permissions-claude-code-docs-7b0e64d485.md) to deny reads of credential files

### Clear local data

You can delete any of the application-data paths above at any time. New sessions are unaffected. The table below shows what you lose for past sessions.

| Delete                                                                                                                                                                                       | You lose                                                   |
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- |
| `~/.claude/projects/`                                                                                                                                                                        | Resume, continue, and rewind for past sessions             |
| `~/.claude/history.jsonl`                                                                                                                                                                    | Up-arrow prompt recall                                     |
| `~/.claude/file-history/`                                                                                                                                                                    | Checkpoint restore for past sessions                       |
| `~/.claude/stats-cache.json`                                                                                                                                                                 | Historical totals shown by `/usage`                        |
| `~/.claude/debug/`, `~/.claude/plans/`, `~/.claude/paste-cache/`, `~/.claude/image-cache/`, `~/.claude/session-env/`, `~/.claude/tasks/`, `~/.claude/shell-snapshots/`, `~/.claude/backups/` | Nothing user-facing                                        |
| `~/.claude/todos/`                                                                                                                                                                           | Nothing. Legacy directory not written by current versions. |

Don't delete `~/.claude.json`, `~/.claude/settings.json`, or `~/.claude/plugins/`: those hold your auth, preferences, and installed plugins.

## Related resources

* [Manage Claude's memory](how-claude-remembers-your-project-claude-code-docs-f1c064262d.md): write and organize CLAUDE.md, rules, and auto memory
* [Configure settings](claude-code-settings-claude-code-docs-d4420b4b52.md): set permissions, hooks, environment variables, and model defaults
* [Create skills](../08-Plugins-Skills/extend-claude-with-skills-claude-code-docs.md): build reusable prompts and workflows
* [Configure subagents](../09-Agents-Patterns/create-custom-subagents-claude-code-docs-7dc93e85c0.md): define specialized agents with their own context


---
## claude-for-financial-services-skills.md

- [](../15-Claude-AI-Features/claude-opus-4-6-anthropic.md)
    Opus
  - [](../15-Claude-AI-Features/claude-sonnet-4-6-anthropic.md)
    Sonnet
  - [](../15-Claude-AI-Features/claude-haiku-4-5-anthropic.md)
    Haiku

- Platform

  - [](/platform/api)
    Overview
  - [](https://platform.claude.com/docs)
    Developer docs
  - [](http://claude.com/pricing#api)
    Pricing

  - [](../04-API-Reference/Other/platform-claude-com.md)
    Console login

- Solutions

  Use cases

  - [](/solutions/agents)
    AI agents
  - [](/solutions/claude-code-security)
    Claude Code Security
  - [](/solutions/coding)
    Coding

  Industries

  - [](/solutions/customer-support)
    Customer support
  - [](/solutions/education)
    Education
  - [](/solutions/financial-services)
    Financial services
  - [](/solutions/government)
    Government
  - [](/solutions/healthcare)
    Healthcare
  - [](/solutions/life-sciences)
    Life sciences
  - [](/solutions/nonprofits)
    Nonprofits

- Pricing

  - [](/pricing)
    Overview
  - [](/pricing#api)
    API

  Pricing

  - [](/pricing/max)
    Max plan
  - [](/pricing/team)
    Team plan
  - [](/pricing/enterprise)
    Enterprise plan

- Resources

  Insights

  - [](/blog)
    Blog
  - [](/customers)
    Customer stories
  - [](https://www.anthropic.com/news)
    Anthropic news

  Learn

  - [](https://www.anthropic.com/learn)
    Anthropic Academy
  - [](/resources/courses)
    Courses
  - [](/resources/tutorials)
    Tutorials
  - [](/resources/use-cases)
    Use cases

  Tools

  - [](/connectors)
    Connectors
  - [](/plugins)
    Plugins

  Connect

  - [](https://www.anthropic.com/events)
    Events
  - [](/community)
    Community

- [](https://claude.ai/login)
  Login

&nbsp;

- 

  Contact sales

  [Contact sales](/contact-sales)
  Contact sales

- 

  Try Claude

  [Try Claude](https://claude.ai/)
  Try Claude

- 

  Contact sales

  [Contact sales](/contact-sales)
  Contact sales

- 

  Try Claude

  [Try Claude](https://claude.ai/)
  Try Claude

[](#)

- 

  Contact sales

  [Contact sales](/contact-sales)
  Contact sales

- 

  Try Claude

  [Try Claude](https://claude.ai/)
  Try Claude

- 

  Contact sales

  [Contact sales](/contact-sales)
  Contact sales

- 

  Try Claude

  [Try Claude](https://claude.ai/)
  Try Claude

- Meet Claude

  Products

  - [](/product/overview)
    Claude
  - [](/product/claude-code)
    Claude Code
  - [](/product/cowork)
    Claude Cowork

  Features

  - [](/claude-for-chrome)
    Claude for Chrome
  - [](/claude-for-slack)
    Claude for Slack
  - [](/claude-for-excel)
    Claude for Excel
  - [](/claude-for-powerpoint)
    Claude for PowerPoint
  - [](/skills)
    Skills

  Models

  - [](../15-Claude-AI-Features/claude-opus-4-6-anthropic.md)
    Opus
  - [](../15-Claude-AI-Features/claude-sonnet-4-6-anthropic.md)
    Sonnet
  - [](../15-Claude-AI-Features/claude-haiku-4-5-anthropic.md)
    Haiku

- Platform

  - [](/platform/api)
    Overview
  - [](https://platform.claude.com/docs)
    Developer docs
  - [](http://claude.com/pricing#api)
    Pricing

  - [](../04-API-Reference/Other/platform-claude-com.md)
    Console login

- Solutions

  Use cases

  - [](/solutions/agents)
    AI agents
  - [](/solutions/claude-code-security)
    Claude Code Security
  - [](/solutions/coding)
    Coding

  Industries

  - [](/solutions/customer-support)
    Customer support
  - [](/solutions/education)
    Education
  - [](/solutions/financial-services)
    Financial services
  - [](/solutions/government)
    Government
  - [](/solutions/healthcare)
    Healthcare
  - [](/solutions/life-sciences)
    Life sciences
  - [](/solutions/nonprofits)
    Nonprofits

- Pricing

  - [](/pricing)
    Overview
  - [](/pricing#api)
    API

  Pricing

  - [](/pricing/max)
    Max plan
  - [](/pricing/team)
    Team plan
  - [](/pricing/enterprise)
    Enterprise plan

- Resources

  Insights

  - [](/blog)
    Blog
  - [](/customers)
    Customer stories
  - [](https://www.anthropic.com/news)
    Anthropic news

  Learn

  - [](https://www.anthropic.com/learn)
    Anthropic Academy
  - [](/resources/courses)
    Courses
  - [](/resources/tutorials)
    Tutorials
  - [](/resources/use-cases)
    Use cases

  Tools

  - [](/connectors)
    Connectors
  - [](/plugins)
    Plugins

  Connect

  - [](https://www.anthropic.com/events)
    Events
  - [](/community)
    Community

- [](https://claude.ai/login)
  Login

- 

  Contact sales

  [Contact sales](/contact-sales)
  Contact sales

- 

  Try Claude

  [Try Claude](https://claude.ai/)
  Try Claude

- 

  Contact sales

  [Contact sales](/contact-sales)
  Contact sales

- 

  Try Claude

  [Try Claude](https://claude.ai/)
  Try Claude

1.  Tutorials

    [](/resources/tutorials)
    Tutorials

    /

2.  
    Six skills for financial service professionals

Explore here

- [](#)

  Ask questions about this page
- [](#)

  Copy as markdown

# Six skills for financial service professionals

Introduction to six specialized AI skills for financial professionals including valuation modeling, competitive analysis, research reports, and due diligence.

- 

  Category

  Finance

- 

  Product

  Claude.ai

- 

  Reading time

  Watch time

  5

  min

  min

- 

  Share

  [Copy link](#)
  https://claude.com/resources/tutorials/claude-for-financial-services-skills

Claude for Financial Services Skills are specialized tools designed to help financial services professionals with key workflows. These Skills provide Claude with targeted capabilities for common financial analysis, research, and document creation tasks, helping you work more efficiently and consistently.

These Skills are in research preview and available exclusively to Claude for Financial Services users who sign up on [our waitlist](https://docs.google.com/forms/d/1HuMMD2JnSXq0LvQ6Y-VUwAIZdNrg5sLXdCpF3CjmjUE/edit). We will periodically review this list and grant interested users access to this feature. If you have an Enterprise plan, you should contact your account manager to receive priority access.

This article provides an overview of six specialized Skills designed for financial services workflows. If you’re looking for information about Skills in general, see [What are Skills?](what-are-skills.md)

## Prerequisites

**For Enterprise plans:** Owners must first enable both **Code execution and file creation** and **Skills** in Admin settings \> Capabilities. Once enabled, individual members can toggle on example skills and upload their own in [Settings \> Capabilities](https://preview.claude.ai/settings/capabilities).

**How to enable Skills**

1.  Navigate to [Settings \> Capabilities](https://claude.ai/settings/capabilities).
2.  Ensure that **Code execution and file creation** is enabled.
3.  Scroll to the **Skills** section.
4.  Toggle individual skills on or off as needed.

Read more about [using Skills in Claude](https://support.claude.com/en/articles/12512180-using-skills-in-claude).

## Comps analysis with public/private peers

This Skill generates peer benchmarking tables with valuation multiples and operating metrics that auto-refresh with live data.

**What it does:** Creates comprehensive comparative analysis between a target company and selected peers using both public and private company data.

**Suggested data sources:**

- Public company fundamentals (FactSet/CapIQ/Daloopa)
- Private company fundamentals (PitchBook)
- M&A transactions data (PitchBook)

**Key outputs:**

- Excel spreadsheet with peer company financial data and valuation multiples
- Written analysis documenting peer selection rationale and key insights

## Discounted Cash Flow (DCF) modeling

This Skill builds discounted cash flow models with proper WACC calculations, scenario toggles, and sensitivity tables.

**What it does:** Constructs comprehensive DCF valuation models with detailed cash flow projections and scenario analysis.

**Suggested data sources:**

- Public company fundamentals (FactSet/CapIQ/Daloopa)
- Consensus estimates (FactSet)
- Broker research

**Key outputs:**

- Excel DCF model with detailed cash flow projections and valuation
- Sensitivity analysis showing impact of key assumptions
- Executive summary with valuation range and key drivers

## Initiating coverage research

This Skill helps conduct comprehensive company research for initiating coverage, including business model analysis, competitive positioning, and financial performance review.

**What it does:** Produces thorough research reports with investment recommendations, financial models, and valuation analysis for new coverage initiations.

**Suggest data sources:**

- Web search on key company developments
- SEC filings (EDGAR)
- Public company fundamentals (FactSet/CapIQ/Daloopa)
- Earnings transcripts (Aiera)

**Key outputs:**

- Comprehensive initiation report with investment recommendation and price target
- Detailed financial model with projections and valuation analysis
- Executive summary presentation for investment committee review

## Strip profile/business overview creation

This Skill creates concise 1-2 page company summaries for pitch books and buyer lists with key metrics and investment highlights.

**What it does:** Generates professional company profiles with executive summaries, business overviews, financial summaries, and supporting appendices.

**Suggested data sources:**

- Public company fundamentals (FactSet/CapIQ/Daloopa)
- Private company fundamentals & developments (Pitchbook)

**Key outputs:**

- Professional company profile presentation with executive summary
- Business overview document with key metrics and positioning
- Investment thesis summary with growth drivers and risks

## Due diligence data pack creation

This Skill processes data room documents into structured Excel data packs with financials, customer lists, and contract terms.

**What it does:** Extracts and organizes key information from CIMs, offering memorandums, and other due diligence materials into standardized formats.

**Suggested data sources:**

- Due diligence / CIM documents (SharePoint, Egnyte)

**Key outputs:**

- Standardized financial data pack with historical and projected financials
- Executive summary highlighting key investment metrics
- Normalized data for comps analysis and modeling

## Earnings Analysis

This Skill creates professional equity research earnings update reports analyzing quarterly results for companies already under coverage.

**What it does:** Creates fast-turnaround earnings analysis focusing on beat/miss analysis, key metrics, updated estimates, and revised thesis. Generates an 8-12 page document (3,000-5,000 words) including summary tables and charts.

**Suggested data sources:**

- Earnings call transcripts (Aiera)
- Investor presentations (Daloopa, Aiera)
- Public company fundamentals (FactSet/CapIQ/Daloopa)

## How to use these Skills

Claude for Financial Services Skills work automatically when relevant to your task. You don’t need to explicitly invoke them—Claude determines when each Skill is needed based on your request.

For example, if you ask Claude to “Create a DCF model for Company XYZ,” Claude will automatically use the DCF modeling Skill. Similarly, asking for “comps analysis for ABC Corp” will trigger the comps analysis Skill.

To guarantee Claude uses the skill, you are also welcome to explicitly instruct Claude to use the skill. For example, append “please use DCF skill” to the prompt.

## Best Practices

- **Be specific about your requirements:** Clearly state the company name, analysis type, and any specific parameters you need.****
- **Provide context:** Share relevant details like industry, time period, or specific metrics you want to focus on.****
- **Review and refine:** After Claude generates output using a Skill, you can ask for adjustments or additional analysis.****
- **Leverage multiple Skills:** Many workflows benefit from using several Skills together—for example, using the research Skill to initiate coverage, then the DCF Skill for valuation.

## Learn more about Skills

- [What are Skills?](what-are-skills.md)[](https://support.claude.com/en/articles/12512180-using-skills-in-claude)
- [Using Skills in Claude](https://support.claude.com/en/articles/12512180-using-skills-in-claude)[](how-to-create-custom-skills.md)
- [How to create custom Skills](how-to-create-custom-skills.md)

## Related tutorials

[How to build a plugin from scratch in Cowork](/resources/tutorials/how-to-build-a-plugin-from-scratch-in-cowork)

How to build a plugin from scratch in Cowork

How to build a plugin from scratch in Cowork

Tutorial

[Tutorial](/resources/tutorials/how-to-build-a-plugin-from-scratch-in-cowork)

Tutorial

[Getting started with Claude in Excel](/resources/tutorials/getting-started-with-claude-in-excel)

Getting started with Claude in Excel

Getting started with Claude in Excel

Tutorial

[Tutorial](/resources/tutorials/getting-started-with-claude-in-excel)

Tutorial

[How to use Claude in Excel for accounting: Revenue model validation](/resources/tutorials/how-to-use-claude-in-excel-for-accounting-revenue-model-validation)

How to use Claude in Excel for accounting: Revenue model validation

How to use Claude in Excel for accounting: Revenue model validation

Tutorial

[Tutorial](/resources/tutorials/how-to-use-claude-in-excel-for-accounting-revenue-model-validation)

Tutorial

[How to use Claude in Excel for HR: Headcount planning](/resources/tutorials/how-to-use-claude-in-excel-for-hr-headcount-planning)

How to use Claude in Excel for HR: Headcount planning

How to use Claude in Excel for HR: Headcount planning

Tutorial

[Tutorial](/resources/tutorials/how-to-use-claude-in-excel-for-hr-headcount-planning)

Tutorial

[Homepage](https://claude.com)

Homepage

[Next](#)

Next

Thank you! Your submission has been received!

Oops! Something went wrong while submitting the form.

Write

[Button Text](#)

Button Text

Learn

[Button Text](#)

Button Text

Code

[Button Text](#)

Button Text

Write

- Help me develop a unique voice for an audience

  [](#)

  Hi Claude! Could you help me develop a unique voice for an audience? If you need more information from me, ask me 1-2 key questions right away. If you think I should upload any documents that would help you do a better job, let me know. You can use the tools you have access to— like Google Drive, web search, etc.—if they’ll help you better accomplish this task. Do not use analysis tool. Please keep your responses friendly, brief and conversational.\
  \
  Please execute the task as soon as you can—an artifact would be great if it makes sense. If using an artifact, consider what kind of artifact (interactive, visual, checklist, etc.) might be most helpful for this specific task. Thanks for your help!

- Improve my writing style

  [](#)

  Hi Claude! Could you improve my writing style? If you need more information from me, ask me 1-2 key questions right away. If you think I should upload any documents that would help you do a better job, let me know. You can use the tools you have access to— like Google Drive, web search, etc.—if they’ll help you better accomplish this task. Do not use analysis tool. Please keep your responses friendly, brief and conversational.\
  \
  Please execute the task as soon as you can—an artifact would be great if it makes sense. If using an artifact, consider what kind of artifact (interactive, visual, checklist, etc.) might be most helpful for this specific task. Thanks for your help!

- Brainstorm creative ideas

  [](#)

  Hi Claude! Could you brainstorm creative ideas? If you need more information from me, ask me 1-2 key questions right away. If you think I should upload any documents that would help you do a better job, let me know. You can use the tools you have access to— like Google Drive, web search, etc.—if they’ll help you better accomplish this task. Do not use analysis tool. Please keep your responses friendly, brief and conversational.\
  \
  Please execute the task as soon as you can—an artifact would be great if it makes sense. If using an artifact, consider what kind of artifact (interactive, visual, checklist, etc.) might be most helpful for this specific task. Thanks for your help!

Learn

- Explain a complex topic simply

  [](#)

  Hi Claude! Could you explain a complex topic simply? If you need more information from me, ask me 1-2 key questions right away. If you think I should upload any documents that would help you do a better job, let me know. You can use the tools you have access to— like Google Drive, web search, etc.—if they’ll help you better accomplish this task. Do not use analysis tool. Please keep your responses friendly, brief and conversational.\
  \
  Please execute the task as soon as you can—an artifact would be great if it makes sense. If using an artifact, consider what kind of artifact (interactive, visual, checklist, etc.) might be most helpful for this specific task. Thanks for your help!

- Help me make sense of these ideas

  [](#)

  Hi Claude! Could you help me make sense of these ideas? If you need more information from me, ask me 1-2 key questions right away. If you think I should upload any documents that would help you do a better job, let me know. You can use the tools you have access to— like Google Drive, web search, etc.—if they’ll help you better accomplish this task. Do not use analysis tool. Please keep your responses friendly, brief and conversational.\
  \
  Please execute the task as soon as you can—an artifact would be great if it makes sense. If using an artifact, consider what kind of artifact (interactive, visual, checklist, etc.) might be most helpful for this specific task. Thanks for your help!

- Prepare for an exam or interview

  [](#)

  Hi Claude! Could you prepare for an exam or interview? If you need more information from me, ask me 1-2 key questions right away. If you think I should upload any documents that would help you do a better job, let me know. You can use the tools you have access to— like Google Drive, web search, etc.—if they’ll help you better accomplish this task. Do not use analysis tool. Please keep your responses friendly, brief and conversational.\
  \
  Please execute the task as soon as you can—an artifact would be great if it makes sense. If using an artifact, consider what kind of artifact (interactive, visual, checklist, etc.) might be most helpful for this specific task. Thanks for your help!

Code

- Explain a programming concept

  [](#)

  Hi Claude! Could you explain a programming concept? If you need more information from me, ask me 1-2 key questions right away. If you think I should upload any documents that would help you do a better job, let me know. You can use the tools you have access to— like Google Drive, web search, etc.—if they’ll help you better accomplish this task. Do not use analysis tool. Please keep your responses friendly, brief and conversational.\
  \
  Please execute the task as soon as you can—an artifact would be great if it makes sense. If using an artifact, consider what kind of artifact (interactive, visual, checklist, etc.) might be most helpful for this specific task. Thanks for your help!

- Look over my code and give me tips

  [](#)

  Hi Claude! Could you look over my code and give me tips? If you need more information from me, ask me 1-2 key questions right away. If you think I should upload any documents that would help you do a better job, let me know. You can use the tools you have access to— like Google Drive, web search, etc.—if they’ll help you better accomplish this task. Do not use analysis tool. Please keep your responses friendly, brief and conversational.\
  \
  Please execute the task as soon as you can—an artifact would be great if it makes sense. If using an artifact, consider what kind of artifact (interactive, visual, checklist, etc.) might be most helpful for this specific task. Thanks for your help!

- Vibe code with me

  [](#)

  Hi Claude! Could you vibe code with me? If you need more information from me, ask me 1-2 key questions right away. If you think I should upload any documents that would help you do a better job, let me know. You can use the tools you have access to— like Google Drive, web search, etc.—if they’ll help you better accomplish this task. Do not use analysis tool. Please keep your responses friendly, brief and conversational.\
  \
  Please execute the task as soon as you can—an artifact would be great if it makes sense. If using an artifact, consider what kind of artifact (interactive, visual, checklist, etc.) might be most helpful for this specific task. Thanks for your help!

More

- Write case studies

  [](#)

  This is another test

- Write grant proposals

  [](#)

  Hi Claude! Could you write grant proposals? If you need more information from me, ask me 1-2 key questions right away. If you think I should upload any documents that would help you do a better job, let me know. You can use the tools you have access to — like Google Drive, web search, etc. — if they’ll help you better accomplish this task. Do not use analysis tool. Please keep your responses friendly, brief and conversational.\
  \
  Please execute the task as soon as you can - an artifact would be great if it makes sense. If using an artifact, consider what kind of artifact (interactive, visual, checklist, etc.) might be most helpful for this specific task. Thanks for your help!

- Write video scripts

  [](#)

  this is a test

[Anthropic](https://www.anthropic.com/)

Anthropic

© \[year\] Anthropic PBC

Products

- Claude

  [Claude](/product/overview)
  Claude

- Claude Code

  [Claude Code](/product/claude-code)
  Claude Code

- Claude Code for Enterprise

  [Claude Code for Enterprise](/product/claude-code/enterprise)
  Claude Code for Enterprise

- Claude Cowork

  [Claude Cowork](/product/cowork)
  Claude Cowork

- Max plan

  [Max plan](/pricing/max)
  Max plan

- Team plan

  [Team plan](/pricing/team)
  Team plan

- Enterprise plan

  [Enterprise plan](/pricing/enterprise)
  Enterprise plan

- Download app

  [Download app](/download)
  Download app

- Pricing

  [Pricing](/pricing)
  Pricing

- Log in

  [Log in](https://claude.ai/login)
  Log in

Features

- Claude for Chrome

  [Claude for Chrome](/claude-for-chrome)
  Claude for Chrome

- Claude for Slack

  [Claude for Slack](/claude-for-slack)
  Claude for Slack

- Claude for Excel

  [Claude for Excel](/claude-for-excel)
  Claude for Excel

- Claude for PowerPoint

  [Claude for PowerPoint](/claude-for-powerpoint)
  Claude for PowerPoint

- Skills

  [Skills](/skills)
  Skills

Models

- Opus

  [Opus](../15-Claude-AI-Features/claude-opus-4-6-anthropic.md)
  Opus

- Sonnet

  [Sonnet](../15-Claude-AI-Features/claude-sonnet-4-6-anthropic.md)
  Sonnet

- Haiku

  [Haiku](../15-Claude-AI-Features/claude-haiku-4-5-anthropic.md)
  Haiku

Solutions

- AI agents

  [AI agents](/solutions/agents)
  AI agents

- Claude Code Security

  [Claude Code Security](/solutions/claude-code-security)
  Claude Code Security

- Code modernization

  [Code modernization](/solutions/code-modernization)
  Code modernization

- Coding

  [Coding](/solutions/coding)
  Coding

- Customer support

  [Customer support](/solutions/customer-support)
  Customer support

- Education

  [Education](/solutions/education)
  Education

- Financial services

  [Financial services](/solutions/financial-services)
  Financial services

- Government

  [Government](/solutions/government)
  Government

- Healthcare

  [Healthcare](/solutions/healthcare)
  Healthcare

- Life sciences

  [Life sciences](/solutions/life-sciences)
  Life sciences

- Nonprofits

  [Nonprofits](/solutions/nonprofits)
  Nonprofits

Claude Platform

- Overview

  [Overview](/platform/api)
  Overview

- Developer docs

  [Developer docs](https://platform.claude.com/docs)
  Developer docs

- Pricing

  [Pricing](https://claude.com/pricing#api)
  Pricing

- Marketplace

  [Marketplace](/platform/marketplace)
  Marketplace

- Amazon Bedrock

  [Amazon Bedrock](/partners/amazon-bedrock)
  Amazon Bedrock

- Google Cloud’s Vertex AI

  [Google Cloud’s Vertex AI](/partners/google-cloud-vertex-ai)
  Google Cloud’s Vertex AI

- Microsoft Foundry

  [Microsoft Foundry](/partners/microsoft-foundry)
  Microsoft Foundry

- Regional compliance

  [Regional compliance](/regional-compliance)
  Regional compliance

- Console login

  [Console login](../04-API-Reference/Other/platform-claude-com.md)
  Console login

Resources

- Blog

  [Blog](/blog)
  Blog

- Claude partner network

  [Claude partner network](/partners)
  Claude partner network

- Community

  [Community](/community)
  Community

- Connectors

  [Connectors](/connectors)
  Connectors

- Courses

  [Courses](https://www.anthropic.com/learn)
  Courses

- Customer stories

  [Customer stories](/customers)
  Customer stories

- Engineering at Anthropic

  [Engineering at Anthropic](https://www.anthropic.com/engineering)
  Engineering at Anthropic

- Events

  [Events](https://www.anthropic.com/events)
  Events

- Plugins

  [Plugins](/plugins)
  Plugins

- Powered by Claude

  [Powered by Claude](/partners/powered-by-claude)
  Powered by Claude

- Service partners

  [Service partners](/partners/services)
  Service partners

- Startups program

  [Startups program](/programs/startups)
  Startups program

- Tutorials

  [Tutorials](/resources/tutorials)
  Tutorials

- Use cases

  [Use cases](/resources/use-cases)
  Use cases

Company

- Anthropic

  [Anthropic](https://www.anthropic.com/)
  Anthropic

- Careers

  [Careers](https://www.anthropic.com/careers)
  Careers

- Economic Futures

  [Economic Futures](https://www.anthropic.com/economic-futures)
  Economic Futures

- Research

  [Research](https://www.anthropic.com/research)
  Research

- News

  [News](https://www.anthropic.com/news)
  News

- Responsible Scaling Policy

  [Responsible Scaling Policy](../19-Reference/announcing-our-updated-responsible-scaling-policy-anthropic.md)
  Responsible Scaling Policy

- Security and compliance

  [Security and compliance](https://trust.anthropic.com/)
  Security and compliance

- Transparency

  [Transparency](https://anthropic.com/transparency)
  Transparency

Help and security

- Availability

  [Availability](https://www.anthropic.com/supported-countries)
  Availability

- Status

  [Status](https://status.anthropic.com/)
  Status

- Support center

  [Support center](https://support.claude.com/en/)
  Support center

Terms and policies

Privacy choices

### Cookie settings

We use cookies to deliver and improve our services, analyze site usage, and if you agree, to customize or personalize your experience and market our services to you. You can read our Cookie Policy [here](https://www.anthropic.com/legal/cookies).

Customize cookie settings

Reject all cookies

Accept all cookies

###### Necessary

Enables security and basic functionality.

Required

###### Analytics

Enables tracking of site performance.

Off

###### Marketing

Enables ads personalization and tracking.

Off

Save preferences

Privacy policy

[Privacy policy](https://www.anthropic.com/legal/privacy)

Privacy policy

Responsible disclosure policy

[Responsible disclosure policy](https://www.anthropic.com/responsible-disclosure-policy)

Responsible disclosure policy

Terms of service: Commercial

[Terms of service: Commercial](https://www.anthropic.com/legal/commercial-terms)

Terms of service: Commercial

Terms of service: Consumer

[Terms of service: Consumer](https://www.anthropic.com/legal/consumer-terms)

Terms of service: Consumer

Usage policy

[Usage policy](https://www.anthropic.com/legal/aup)

Usage policy

[x.com](https://x.com/claudeai)

x.com

[LinkedIn](https://www.linkedin.com/showcase/claude/)

LinkedIn

[YouTube](https://www.youtube.com/@anthropic-ai)

YouTube

[Instagram](https://www.instagram.com/claudeai)

Instagram

English (US)

[English (US)](/resources/tutorials/claude-for-financial-services-skills)

[日本語 (Japan)](/ja-jp)

[Deutsch (Germany)](/de-de)

[Français (France)](/fr-fr)

[한국어 (South Korea)](/ko-kr)


---
## cli-reference-7bb98e3312.md

> ## Documentation Index
> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# CLI reference

> Complete reference for Claude Code command-line interface, including commands and flags.

## CLI commands

You can start sessions, pipe content, resume conversations, and manage updates with these commands:

| Command                         | Description                                                                                                                                                                                                                                 | Example                                                     |
| :------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :---------------------------------------------------------- |
| `claude`                        | Start interactive session                                                                                                                                                                                                                   | `claude`                                                    |
| `claude "query"`                | Start interactive session with initial prompt                                                                                                                                                                                               | `claude "explain this project"`                             |
| `claude -p "query"`             | Query via SDK, then exit                                                                                                                                                                                                                    | `claude -p "explain this function"`                         |
| `cat file \| claude -p "query"` | Process piped content                                                                                                                                                                                                                       | `cat logs.txt \| claude -p "explain"`                       |
| `claude -c`                     | Continue most recent conversation in current directory                                                                                                                                                                                      | `claude -c`                                                 |
| `claude -c -p "query"`          | Continue via SDK                                                                                                                                                                                                                            | `claude -c -p "Check for type errors"`                      |
| `claude -r "<session>" "query"` | Resume session by ID or name                                                                                                                                                                                                                | `claude -r "auth-refactor" "Finish this PR"`                |
| `claude update`                 | Update to latest version                                                                                                                                                                                                                    | `claude update`                                             |
| `claude install [version]`      | Install or reinstall the native binary. Accepts a version like `2.1.118`, or `stable` or `latest`. See [Install a specific version](/en/setup#install-a-specific-version)                                                                   | `claude install stable`                                     |
| `claude auth login`             | Sign in to your Anthropic account. Use `--email` to pre-fill your email address, `--sso` to force SSO authentication, and `--console` to sign in with Anthropic Console for API usage billing instead of a Claude subscription              | `claude auth login --console`                               |
| `claude auth logout`            | Log out from your Anthropic account                                                                                                                                                                                                         | `claude auth logout`                                        |
| `claude auth status`            | Show authentication status as JSON. Use `--text` for human-readable output. Exits with code 0 if logged in, 1 if not                                                                                                                        | `claude auth status`                                        |
| `claude agents`                 | List all configured [subagents](../09-Agents-Patterns/create-custom-subagents-claude-code-docs-7dc93e85c0.md), grouped by source                                                                                                                                                                          | `claude agents`                                             |
| `claude auto-mode defaults`     | Print the built-in [auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) classifier rules as JSON. Use `claude auto-mode config` to see your effective config with settings applied                                            | `claude auto-mode defaults > rules.json`                    |
| `claude mcp`                    | Configure Model Context Protocol (MCP) servers                                                                                                                                                                                              | See the [Claude Code MCP documentation](../06-MCP-Tools/mcp-208e742686.md).           |
| `claude plugin`                 | Manage Claude Code [plugins](../08-Plugins-Skills/create-plugins-claude-code-docs.md). Alias: `claude plugins`. See [plugin reference](/en/plugins-reference#cli-commands-reference) for subcommands                                                                                    | `claude plugin install code-review@claude-plugins-official` |
| `claude remote-control`         | Start a [Remote Control](continue-local-sessions-from-any-device-with-remote-control-claude-code-docs-c1c03fd914.md) server to control Claude Code from Claude.ai or the Claude app. Runs in server mode (no local interactive session). See [Server mode flags](/en/remote-control#start-a-remote-control-session) | `claude remote-control --name "My Project"`                 |
| `claude setup-token`            | Generate a long-lived OAuth token for CI and scripts. Prints the token to the terminal without saving it. Requires a Claude subscription. See [Generate a long-lived token](/en/authentication#generate-a-long-lived-token)                 | `claude setup-token`                                        |

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?`.

## 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.

| Flag                                            | Description                                                                                                                                                                                                                                                                                                                                                                                         | Example                                                                                            |
| :---------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------- |
| `--add-dir`                                     | Add additional working directories for Claude to read and edit files. Grants file access; most `.claude/` configuration is [not discovered](/en/permissions#additional-directories-grant-file-access-not-configuration) from these directories. Validates each path exists as a directory                                                                                                           | `claude --add-dir ../apps ../lib`                                                                  |
| `--agent`                                       | Specify an agent for the current session (overrides the `agent` setting)                                                                                                                                                                                                                                                                                                                            | `claude --agent my-custom-agent`                                                                   |
| `--agents`                                      | Define custom subagents dynamically via JSON. Uses the same field names as subagent [frontmatter](/en/sub-agents#supported-frontmatter-fields), plus a `prompt` field for the agent's instructions                                                                                                                                                                                                  | `claude --agents '{"reviewer":{"description":"Reviews code","prompt":"You are a code reviewer"}}'` |
| `--allow-dangerously-skip-permissions`          | Add `bypassPermissions` to the `Shift+Tab` mode cycle without starting in it. Lets you begin in a different mode like `plan` and switch to `bypassPermissions` later. See [permission modes](/en/permission-modes#skip-all-checks-with-bypasspermissions-mode)                                                                                                                                      | `claude --permission-mode plan --allow-dangerously-skip-permissions`                               |
| `--allowedTools`                                | Tools that execute without prompting for permission. See [permission rule syntax](/en/settings#permission-rule-syntax) for pattern matching. To restrict which tools are available, use `--tools` instead                                                                                                                                                                                           | `"Bash(git log *)" "Bash(git diff *)" "Read"`                                                      |
| `--append-system-prompt`                        | Append custom text to the end of the default system prompt                                                                                                                                                                                                                                                                                                                                          | `claude --append-system-prompt "Always use TypeScript"`                                            |
| `--append-system-prompt-file`                   | Load additional system prompt text from a file and append to the default prompt                                                                                                                                                                                                                                                                                                                     | `claude --append-system-prompt-file ./extra-rules.txt`                                             |
| `--bare`                                        | Minimal mode: skip auto-discovery of hooks, skills, plugins, MCP servers, auto memory, and CLAUDE.md so scripted calls start faster. Claude has access to Bash, file read, and file edit tools. Sets [`CLAUDE_CODE_SIMPLE`](env-vars-5c624d392b.md). See [bare mode](/en/headless#start-faster-with-bare-mode)                                                                                                | `claude --bare -p "query"`                                                                         |
| `--betas`                                       | Beta headers to include in API requests (API key users only)                                                                                                                                                                                                                                                                                                                                        | `claude --betas interleaved-thinking`                                                              |
| `--channels`                                    | (Research preview) MCP servers whose [channel](channels-00374ea787.md) notifications Claude should listen for in this session. Space-separated list of `plugin:<name>@<marketplace>` entries. Requires Claude.ai authentication                                                                                                                                                                               | `claude --channels plugin:my-notifier@my-marketplace`                                              |
| `--chrome`                                      | Enable [Chrome browser integration](../03-IDE-Integrations/use-claude-code-with-chrome-beta-claude-code-docs-4f2f5a5a96.md) for web automation and testing                                                                                                                                                                                                                                                                                                                      | `claude --chrome`                                                                                  |
| `--continue`, `-c`                              | Load the most recent conversation in the current directory. Includes sessions that added this directory with `/add-dir`                                                                                                                                                                                                                                                                             | `claude --continue`                                                                                |
| `--dangerously-load-development-channels`       | Enable [channels](/en/channels-reference#test-during-the-research-preview) that are not on the approved allowlist, for local development. Accepts `plugin:<name>@<marketplace>` and `server:<name>` entries. Prompts for confirmation                                                                                                                                                               | `claude --dangerously-load-development-channels server:webhook`                                    |
| `--dangerously-skip-permissions`                | Skip permission prompts. Equivalent to the admin-gated bypass permission mode. See [permission modes](/en/permission-modes#skip-all-checks-with-bypasspermissions-mode) for what this does and does not skip                                                                                                                                                                                         | `claude --dangerously-skip-permissions`                                                            |
| `--debug`                                       | Enable debug mode with optional category filtering (for example, `"api,hooks"` or `"!statsig,!file"`)                                                                                                                                                                                                                                                                                               | `claude --debug "api,mcp"`                                                                         |
| `--debug-file <path>`                           | Write debug logs to a specific file path. Implicitly enables debug mode. Takes precedence over `CLAUDE_CODE_DEBUG_LOGS_DIR`                                                                                                                                                                                                                                                                         | `claude --debug-file /tmp/claude-debug.log`                                                        |
| `--disable-slash-commands`                      | Disable all skills and commands for this session                                                                                                                                                                                                                                                                                                                                                    | `claude --disable-slash-commands`                                                                  |
| `--disallowedTools`                             | Tools that are removed from the model's context and cannot be used                                                                                                                                                                                                                                                                                                                                  | `"Bash(git log *)" "Bash(git diff *)" "Edit"`                                                      |
| `--effort`                                      | Set the [effort level](/en/model-config#adjust-effort-level) for the current session. Options: `low`, `medium`, `high`, `xhigh`, `max`; available levels depend on the model. Session-scoped and does not persist to settings                                                                                                                                                                       | `claude --effort high`                                                                             |
| `--enable-auto-mode`                            | {/* max-version: 2.1.110 */}Removed in v2.1.111. Auto mode is now in the `Shift+Tab` cycle by default; use `--permission-mode auto` to start in it                                                                                                                                                                                                                                                  | `claude --permission-mode auto`                                                                    |
| `--exclude-dynamic-system-prompt-sections`      | Move per-machine sections from the system prompt (working directory, environment info, memory paths, git status) into the first user message. Improves prompt-cache reuse across different users and machines running the same task. Only applies with the default system prompt; ignored when `--system-prompt` or `--system-prompt-file` is set. Use with `-p` for scripted, multi-user workloads | `claude -p --exclude-dynamic-system-prompt-sections "query"`                                       |
| `--fallback-model`                              | Enable automatic fallback to specified model when default model is overloaded (print mode only)                                                                                                                                                                                                                                                                                                     | `claude -p --fallback-model sonnet "query"`                                                        |
| `--fork-session`                                | When resuming, create a new session ID instead of reusing the original (use with `--resume` or `--continue`)                                                                                                                                                                                                                                                                                        | `claude --resume abc123 --fork-session`                                                            |
| `--from-pr`                                     | Resume sessions linked to a specific pull request. Accepts a PR number, a GitHub or GitHub Enterprise PR URL, a GitLab merge request URL, or a Bitbucket pull request URL. Sessions are linked automatically when Claude creates the pull request                                                                                                                                                   | `claude --from-pr 123`                                                                             |
| `--ide`                                         | Automatically connect to IDE on startup if exactly one valid IDE is available                                                                                                                                                                                                                                                                                                                       | `claude --ide`                                                                                     |
| `--init`                                        | Run initialization hooks and start interactive mode                                                                                                                                                                                                                                                                                                                                                 | `claude --init`                                                                                    |
| `--init-only`                                   | Run initialization hooks and exit (no interactive session)                                                                                                                                                                                                                                                                                                                                          | `claude --init-only`                                                                               |
| `--include-hook-events`                         | Include all hook lifecycle events in the output stream. Requires `--output-format stream-json`                                                                                                                                                                                                                                                                                                      | `claude -p --output-format stream-json --include-hook-events "query"`                              |
| `--include-partial-messages`                    | Include partial streaming events in output. Requires `--print` and `--output-format stream-json`                                                                                                                                                                                                                                                                                                    | `claude -p --output-format stream-json --include-partial-messages "query"`                         |
| `--input-format`                                | Specify input format for print mode (options: `text`, `stream-json`)                                                                                                                                                                                                                                                                                                                                | `claude -p --output-format json --input-format stream-json`                                        |
| `--json-schema`                                 | Get validated JSON output matching a JSON Schema after agent completes its workflow (print mode only, see [structured outputs](/en/agent-sdk/structured-outputs))                                                                                                                                                                                                                                   | `claude -p --json-schema '{"type":"object","properties":{...}}' "query"`                           |
| `--maintenance`                                 | Run maintenance hooks and start interactive mode                                                                                                                                                                                                                                                                                                                                                    | `claude --maintenance`                                                                             |
| `--max-budget-usd`                              | Maximum dollar amount to spend on API calls before stopping (print mode only)                                                                                                                                                                                                                                                                                                                       | `claude -p --max-budget-usd 5.00 "query"`                                                          |
| `--max-turns`                                   | Limit the number of agentic turns (print mode only). Exits with an error when the limit is reached. No limit by default                                                                                                                                                                                                                                                                             | `claude -p --max-turns 3 "query"`                                                                  |
| `--mcp-config`                                  | Load MCP servers from JSON files or strings (space-separated)                                                                                                                                                                                                                                                                                                                                       | `claude --mcp-config ./mcp.json`                                                                   |
| `--model`                                       | Sets the model for the current session with an alias for the latest model (`sonnet` or `opus`) or a model's full name                                                                                                                                                                                                                                                                               | `claude --model claude-sonnet-4-6`                                                                 |
| `--name`, `-n`                                  | Set a display name for the session, shown in `/resume` and the terminal title. You can resume a named session with `claude --resume <name>`. <br /><br />[`/rename`](built-in-commands-claude-code-docs.md) changes the name mid-session and also shows it on the prompt bar                                                                                                                                                 | `claude -n "my-feature-work"`                                                                      |
| `--no-chrome`                                   | Disable [Chrome browser integration](../03-IDE-Integrations/use-claude-code-with-chrome-beta-claude-code-docs-4f2f5a5a96.md) for this session                                                                                                                                                                                                                                                                                                                                   | `claude --no-chrome`                                                                               |
| `--no-session-persistence`                      | Disable session persistence so sessions are not saved to disk and cannot be resumed (print mode only)                                                                                                                                                                                                                                                                                               | `claude -p --no-session-persistence "query"`                                                       |
| `--output-format`                               | Specify output format for print mode (options: `text`, `json`, `stream-json`)                                                                                                                                                                                                                                                                                                                       | `claude -p "query" --output-format json`                                                           |
| `--permission-mode`                             | Begin in a specified [permission mode](permission-modes-c83d6eff7e.md). Accepts `default`, `acceptEdits`, `plan`, `auto`, `dontAsk`, or `bypassPermissions`. Overrides `defaultMode` from settings files                                                                                                                                                                                                      | `claude --permission-mode plan`                                                                    |
| `--permission-prompt-tool`                      | Specify an MCP tool to handle permission prompts in non-interactive mode                                                                                                                                                                                                                                                                                                                            | `claude -p --permission-prompt-tool mcp_auth_tool "query"`                                         |
| `--plugin-dir`                                  | Load plugins from a directory for this session only. Each flag takes one path. Repeat the flag for multiple directories: `--plugin-dir A --plugin-dir B`                                                                                                                                                                                                                                            | `claude --plugin-dir ./my-plugins`                                                                 |
| `--print`, `-p`                                 | Print response without interactive mode (see [Agent SDK documentation](/en/agent-sdk/overview) for programmatic usage details)                                                                                                                                                                                                                                                                      | `claude -p "query"`                                                                                |
| `--remote`                                      | Create a new [web session](claude-code-on-the-web-69d53821d4.md) on claude.ai with the provided task description                                                                                                                                                                                                                                                                                              | `claude --remote "Fix the login bug"`                                                              |
| `--remote-control`, `--rc`                      | Start an interactive session with [Remote Control](/en/remote-control#start-a-remote-control-session) enabled so you can also control it from claude.ai or the Claude app. Optionally pass a name for the session                                                                                                                                                                                   | `claude --remote-control "My Project"`                                                             |
| `--remote-control-session-name-prefix <prefix>` | Prefix for auto-generated [Remote Control](continue-local-sessions-from-any-device-with-remote-control-claude-code-docs-c1c03fd914.md) session names when no explicit name is set. Defaults to your machine's hostname, producing names like `myhost-graceful-unicorn`. Set `CLAUDE_REMOTE_CONTROL_SESSION_NAME_PREFIX` for the same effect                                                                                                                                 | `claude remote-control --remote-control-session-name-prefix dev-box`                               |
| `--replay-user-messages`                        | Re-emit user messages from stdin back on stdout for acknowledgment. Requires `--input-format stream-json` and `--output-format stream-json`                                                                                                                                                                                                                                                         | `claude -p --input-format stream-json --output-format stream-json --replay-user-messages`          |
| `--resume`, `-r`                                | Resume a specific session by ID or name, or show an interactive picker to choose a session. Includes sessions that added this directory with `/add-dir`                                                                                                                                                                                                                                             | `claude --resume auth-refactor`                                                                    |
| `--session-id`                                  | Use a specific session ID for the conversation (must be a valid UUID)                                                                                                                                                                                                                                                                                                                               | `claude --session-id "550e8400-e29b-41d4-a716-446655440000"`                                       |
| `--setting-sources`                             | Comma-separated list of setting sources to load (`user`, `project`, `local`)                                                                                                                                                                                                                                                                                                                        | `claude --setting-sources user,project`                                                            |
| `--settings`                                    | Path to a settings JSON file or a JSON string to load additional settings from                                                                                                                                                                                                                                                                                                                      | `claude --settings ./settings.json`                                                                |
| `--strict-mcp-config`                           | Only use MCP servers from `--mcp-config`, ignoring all other MCP configurations                                                                                                                                                                                                                                                                                                                     | `claude --strict-mcp-config --mcp-config ./mcp.json`                                               |
| `--system-prompt`                               | Replace the entire system prompt with custom text                                                                                                                                                                                                                                                                                                                                                   | `claude --system-prompt "You are a Python expert"`                                                 |
| `--system-prompt-file`                          | Load system prompt from a file, replacing the default prompt                                                                                                                                                                                                                                                                                                                                        | `claude --system-prompt-file ./custom-prompt.txt`                                                  |
| `--teleport`                                    | Resume a [web session](claude-code-on-the-web-69d53821d4.md) in your local terminal                                                                                                                                                                                                                                                                                                                           | `claude --teleport`                                                                                |
| `--teammate-mode`                               | Set how [agent team](../09-Agents-Patterns/agent-teams-e29da6ed1b.md) teammates display: `auto` (default), `in-process`, or `tmux`. See [Choose a display mode](/en/agent-teams#choose-a-display-mode)                                                                                                                                                                                                                              | `claude --teammate-mode in-process`                                                                |
| `--tmux`                                        | Create a tmux session for the worktree. Requires `--worktree`. Uses iTerm2 native panes when available; pass `--tmux=classic` for traditional tmux                                                                                                                                                                                                                                                  | `claude -w feature-auth --tmux`                                                                    |
| `--tools`                                       | Restrict which built-in tools Claude can use. Use `""` to disable all, `"default"` for all, or tool names like `"Bash,Edit,Read"`                                                                                                                                                                                                                                                                   | `claude --tools "Bash,Edit,Read"`                                                                  |
| `--verbose`                                     | Enable verbose logging, shows full turn-by-turn output                                                                                                                                                                                                                                                                                                                                              | `claude --verbose`                                                                                 |
| `--version`, `-v`                               | Output the version number                                                                                                                                                                                                                                                                                                                                                                           | `claude -v`                                                                                        |
| `--worktree`, `-w`                              | Start Claude in an isolated [git worktree](/en/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees) at `<repo>/.claude/worktrees/<name>`. If no name is given, one is auto-generated                                                                                                                                                                                              | `claude -w feature-auth`                                                                           |

### System prompt flags

Claude Code provides four flags for customizing the system prompt. All four work in both interactive and non-interactive modes.

| Flag                          | Behavior                                    | Example                                                 |
| :---------------------------- | :------------------------------------------ | :------------------------------------------------------ |
| `--system-prompt`             | Replaces the entire default prompt          | `claude --system-prompt "You are a Python expert"`      |
| `--system-prompt-file`        | Replaces with file contents                 | `claude --system-prompt-file ./prompts/review.txt`      |
| `--append-system-prompt`      | Appends to the default prompt               | `claude --append-system-prompt "Always use TypeScript"` |
| `--append-system-prompt-file` | Appends file contents to the default prompt | `claude --append-system-prompt-file ./style-rules.txt`  |

`--system-prompt` and `--system-prompt-file` are mutually exclusive. The append flags can be combined with either replacement flag.

For most use cases, use an append flag. Appending preserves Claude Code's built-in capabilities while adding your requirements. Use a replacement flag only when you need complete control over the system prompt.

## See also

* [Chrome extension](../03-IDE-Integrations/use-claude-code-with-chrome-beta-claude-code-docs-4f2f5a5a96.md) - Browser automation and web testing
* [Interactive mode](interactive-mode-c5c4efb32c.md) - Shortcuts, input modes, and interactive features
* [Quickstart guide](../01-Getting-Started/quickstart-claude-code-docs-a21b84bdea.md) - Getting started with Claude Code
* [Common workflows](common-workflows-c909406123.md) - Advanced workflows and patterns
* [Settings](claude-code-settings-claude-code-docs-d4420b4b52.md) - Configuration options
* [Agent SDK documentation](/en/agent-sdk/overview) - Programmatic usage and integrations


---
## cli-reference-claude-code-docs-3b3cc92a63.md

# CLI reference


Complete reference for Claude Code command-line interface, including commands and flags.


> ## Documentation Index
>
> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt>
>
> Use this file to discover all available pages before exploring further.


CLI commands

You can start sessions, pipe content, resume conversations, and manage updates with these commands:

| Command                         | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                         | Example                                                     |
|:--------------------------------|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:------------------------------------------------------------|
| `claude`                        | Start interactive session                                                                                                                                                                                                                                                                                                                                                                                                                                           | `claude`                                                    |
| `claude "query"`                | Start interactive session with initial prompt                                                                                                                                                                                                                                                                                                                                                                                                                       | `claude "explain this project"`                             |
| `claude -p "query"`             | Query via SDK, then exit                                                                                                                                                                                                                                                                                                                                                                                                                                            | `claude -p "explain this function"`                         |
| `cat file | claude -p "query"`  | Process piped content                                                                                                                                                                                                                                                                                                                                                                                                                                               | `cat logs.txt | claude -p "explain"`                        |
| `claude -c`                     | Continue most recent conversation in current directory                                                                                                                                                                                                                                                                                                                                                                                                              | `claude -c`                                                 |
| `claude -c -p "query"`          | Continue via SDK                                                                                                                                                                                                                                                                                                                                                                                                                                                    | `claude -c -p "Check for type errors"`                      |
| `claude -r "<session>" "query"` | Resume session by ID or name                                                                                                                                                                                                                                                                                                                                                                                                                                        | `claude -r "auth-refactor" "Finish this PR"`                |
| `claude update`                 | Update to latest version                                                                                                                                                                                                                                                                                                                                                                                                                                            | `claude update`                                             |
| `claude install [version]`      | Install or reinstall the native binary. Accepts a version like `2.1.118`, or `stable` or `latest`. See [Install a specific version](/docs/en/setup#install-a-specific-version)                                                                                                                                                                                                                                                                                      | `claude install stable`                                     |
| `claude auth login`             | Sign in to your Anthropic account. Use `--email` to pre-fill your email address, `--sso` to force SSO authentication, and `--console` to sign in with Anthropic Console for API usage billing instead of a Claude subscription                                                                                                                                                                                                                                      | `claude auth login --console`                               |
| `claude auth logout`            | Log out from your Anthropic account                                                                                                                                                                                                                                                                                                                                                                                                                                 | `claude auth logout`                                        |
| `claude auth status`            | Show authentication status as JSON. Use `--text` for human-readable output. Exits with code 0 if logged in, 1 if not                                                                                                                                                                                                                                                                                                                                                | `claude auth status`                                        |
| `claude agents`                 | Open [agent view](/docs/en/agent-view) to monitor and dispatch parallel background sessions. Use `--cwd <path>` to show only sessions started under that directory. Pass `--permission-mode`, `--model`, or `--effort` to set [defaults for dispatched sessions](/docs/en/agent-view#permission-mode-model-and-effort). Accepts `--settings`, `--add-dir`, `--plugin-dir`, and `--mcp-config` like the top-level `claude` command. Requires an interactive terminal | `claude agents --cwd ~/projects/my-app`                     |
| `claude attach <id>`            | Attach to a [background session](/docs/en/agent-view#manage-sessions-from-the-shell) in this terminal                                                                                                                                                                                                                                                                                                                                                               | `claude attach 7c5dcf5d`                                    |
| `claude auto-mode defaults`     | Print the built-in [auto mode](/docs/en/permission-modes#eliminate-prompts-with-auto-mode) classifier rules as JSON. Use `claude auto-mode config` to see your effective config with settings applied                                                                                                                                                                                                                                                               | `claude auto-mode defaults > rules.json`                    |
| `claude daemon status`          | Print the background-session [supervisor’s](/docs/en/agent-view#the-supervisor-process) state, version, socket directory, and worker count for diagnostics. Exits 1 if the supervisor isn’t running                                                                                                                                                                                                                                                                 | `claude daemon status`                                      |
| `claude logs <id>`              | Print recent output from a [background session](/docs/en/agent-view#manage-sessions-from-the-shell)                                                                                                                                                                                                                                                                                                                                                                 | `claude logs 7c5dcf5d`                                      |
| `claude mcp`                    | Configure Model Context Protocol (MCP) servers                                                                                                                                                                                                                                                                                                                                                                                                                      | See the [Claude Code MCP documentation](/docs/en/mcp).      |
| `claude plugin`                 | Manage Claude Code [plugins](/docs/en/plugins). Alias: `claude plugins`. See [plugin reference](/docs/en/plugins-reference#cli-commands-reference) for subcommands                                                                                                                                                                                                                                                                                                  | `claude plugin install code-review@claude-plugins-official` |
| `claude project purge [path]`   | Delete all local Claude Code state for a project: transcripts, task lists, debug logs, file-edit history, prompt history lines, and the project’s entry in `~/.claude.json`. Omit `[path]` to pick from an interactive list. Flags: `--dry-run` to preview, `-y`/`--yes` to skip confirmation, `-i`/`--interactive` to confirm each item, `--all` for every project. See [Clear local data](/docs/en/claude-directory#clear-local-data)                             | `claude project purge ~/work/repo --dry-run`                |
| `claude remote-control`         | Start a [Remote Control](/docs/en/remote-control) server to control Claude Code from Claude.ai or the Claude app. Runs in server mode (no local interactive session). See [Server mode flags](/docs/en/remote-control#start-a-remote-control-session)                                                                                                                                                                                                               | `claude remote-control --name "My Project"`                 |
| `claude respawn <id>`           | Restart a [background session](/docs/en/agent-view#manage-sessions-from-the-shell), running or stopped, with its conversation intact. Use `--all` to restart every running session, e.g. to pick up an updated Claude Code binary                                                                                                                                                                                                                                   | `claude respawn 7c5dcf5d`                                   |
| `claude rm <id>`                | Remove a [background session](/docs/en/agent-view#manage-sessions-from-the-shell) from the list. The conversation transcript stays on your local machine, available through `claude --resume`                                                                                                                                                                                                                                                                       | `claude rm 7c5dcf5d`                                        |
| `claude setup-token`            | Generate a long-lived OAuth token for CI and scripts. Prints the token to the terminal without saving it. Requires a Claude subscription. See [Generate a long-lived token](/docs/en/authentication#generate-a-long-lived-token)                                                                                                                                                                                                                                    | `claude setup-token`                                        |
| `claude stop <id>`              | Stop a [background session](/docs/en/agent-view#manage-sessions-from-the-shell). Also accepts `claude kill`                                                                                                                                                                                                                                                                                                                                                         | `claude stop 7c5dcf5d`                                      |
| `claude ultrareview [target]`   | Run [ultrareview](/docs/en/ultrareview#run-ultrareview-non-interactively) non-interactively. Prints findings to stdout and exits 0 on success or 1 on failure. Use `--json` for the raw payload and `--timeout <minutes>` to override the 30-minute default                                                                                                                                                                                                         | `claude ultrareview 1234 --json`                            |

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?`.


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.

[TABLE]


System prompt flags

Claude Code provides four flags for customizing the system prompt. All four work in both interactive and non-interactive modes.

| Flag                          | Behavior                                    | Example                                                 |
|:------------------------------|:--------------------------------------------|:--------------------------------------------------------|
| `--system-prompt`             | Replaces the entire default prompt          | `claude --system-prompt "You are a Python expert"`      |
| `--system-prompt-file`        | Replaces with file contents                 | `claude --system-prompt-file ./prompts/review.txt`      |
| `--append-system-prompt`      | Appends to the default prompt               | `claude --append-system-prompt "Always use TypeScript"` |
| `--append-system-prompt-file` | Appends file contents to the default prompt | `claude --append-system-prompt-file ./style-rules.txt`  |

`--system-prompt` and `--system-prompt-file` are mutually exclusive. The append flags can be combined with either replacement flag. 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. These flags apply only to the current invocation. 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.


See also

- [Chrome extension](/docs/en/chrome) - Browser automation and web testing
- [Interactive mode](/docs/en/interactive-mode) - Shortcuts, input modes, and interactive features
- [Quickstart guide](/docs/en/quickstart) - Getting started with Claude Code
- [Common workflows](/docs/en/common-workflows) - Advanced workflows and patterns
- [Settings](/docs/en/settings) - Configuration options
- [Agent SDK documentation](/docs/en/agent-sdk/overview) - Programmatic usage and integrations


---
## cli-reference.md

> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# CLI reference

> Complete reference for Claude Code command-line interface, including commands and flags.

## CLI commands

| Command                         | Description                                            | Example                                           |
| :------------------------------ | :----------------------------------------------------- | :------------------------------------------------ |
| `claude`                        | Start interactive REPL                                 | `claude`                                          |
| `claude "query"`                | Start REPL with initial prompt                         | `claude "explain this project"`                   |
| `claude -p "query"`             | Query via SDK, then exit                               | `claude -p "explain this function"`               |
| `cat file \| claude -p "query"` | Process piped content                                  | `cat logs.txt \| claude -p "explain"`             |
| `claude -c`                     | Continue most recent conversation in current directory | `claude -c`                                       |
| `claude -c -p "query"`          | Continue via SDK                                       | `claude -c -p "Check for type errors"`            |
| `claude -r "<session>" "query"` | Resume session by ID or name                           | `claude -r "auth-refactor" "Finish this PR"`      |
| `claude update`                 | Update to latest version                               | `claude update`                                   |
| `claude mcp`                    | Configure Model Context Protocol (MCP) servers         | See the [Claude Code MCP documentation](../06-MCP-Tools/General/connect-claude-code-to-tools-via-mcp-claude-code-docs.md). |

## CLI flags

Customize Claude Code's behavior with these command-line flags:

| Flag                                   | Description                                                                                                                                                                                               | Example                                                                                            |
| :------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------- |
| `--add-dir`                            | Add additional working directories for Claude to access (validates each path exists as a directory)                                                                                                       | `claude --add-dir ../apps ../lib`                                                                  |
| `--agent`                              | Specify an agent for the current session (overrides the `agent` setting)                                                                                                                                  | `claude --agent my-custom-agent`                                                                   |
| `--agents`                             | Define custom [subagents](../09-Agents-Patterns/create-custom-subagents-claude-code-docs-7dc93e85c0.md) dynamically via JSON (see below for format)                                                                                                                     | `claude --agents '{"reviewer":{"description":"Reviews code","prompt":"You are a code reviewer"}}'` |
| `--allow-dangerously-skip-permissions` | Enable permission bypassing as an option without immediately activating it. Allows composing with `--permission-mode` (use with caution)                                                                  | `claude --permission-mode plan --allow-dangerously-skip-permissions`                               |
| `--allowedTools`                       | Tools that execute without prompting for permission. See [permission rule syntax](/en/settings#permission-rule-syntax) for pattern matching. To restrict which tools are available, use `--tools` instead | `"Bash(git log *)" "Bash(git diff *)" "Read"`                                                      |
| `--append-system-prompt`               | Append custom text to the end of the default system prompt (works in both interactive and print modes)                                                                                                    | `claude --append-system-prompt "Always use TypeScript"`                                            |
| `--append-system-prompt-file`          | Load additional system prompt text from a file and append to the default prompt (print mode only)                                                                                                         | `claude -p --append-system-prompt-file ./extra-rules.txt "query"`                                  |
| `--betas`                              | Beta headers to include in API requests (API key users only)                                                                                                                                              | `claude --betas interleaved-thinking`                                                              |
| `--chrome`                             | Enable [Chrome browser integration](chrome.md) for web automation and testing                                                                                                                            | `claude --chrome`                                                                                  |
| `--continue`, `-c`                     | Load the most recent conversation in the current directory                                                                                                                                                | `claude --continue`                                                                                |
| `--dangerously-skip-permissions`       | Skip all permission prompts (use with caution)                                                                                                                                                            | `claude --dangerously-skip-permissions`                                                            |
| `--debug`                              | Enable debug mode with optional category filtering (for example, `"api,hooks"` or `"!statsig,!file"`)                                                                                                     | `claude --debug "api,mcp"`                                                                         |
| `--disable-slash-commands`             | Disable all skills and slash commands for this session                                                                                                                                                    | `claude --disable-slash-commands`                                                                  |
| `--disallowedTools`                    | Tools that are removed from the model's context and cannot be used                                                                                                                                        | `"Bash(git log *)" "Bash(git diff *)" "Edit"`                                                      |
| `--fallback-model`                     | Enable automatic fallback to specified model when default model is overloaded (print mode only)                                                                                                           | `claude -p --fallback-model sonnet "query"`                                                        |
| `--fork-session`                       | When resuming, create a new session ID instead of reusing the original (use with `--resume` or `--continue`)                                                                                              | `claude --resume abc123 --fork-session`                                                            |
| `--from-pr`                            | Resume sessions linked to a specific GitHub PR. Accepts a PR number or URL. Sessions are automatically linked when created via `gh pr create`                                                             | `claude --from-pr 123`                                                                             |
| `--ide`                                | Automatically connect to IDE on startup if exactly one valid IDE is available                                                                                                                             | `claude --ide`                                                                                     |
| `--init`                               | Run initialization hooks and start interactive mode                                                                                                                                                       | `claude --init`                                                                                    |
| `--init-only`                          | Run initialization hooks and exit (no interactive session)                                                                                                                                                | `claude --init-only`                                                                               |
| `--include-partial-messages`           | Include partial streaming events in output (requires `--print` and `--output-format=stream-json`)                                                                                                         | `claude -p --output-format stream-json --include-partial-messages "query"`                         |
| `--input-format`                       | Specify input format for print mode (options: `text`, `stream-json`)                                                                                                                                      | `claude -p --output-format json --input-format stream-json`                                        |
| `--json-schema`                        | Get validated JSON output matching a JSON Schema after agent completes its workflow (print mode only, see [Agent SDK Structured Outputs](https://docs.claude.com/en/docs/agent-sdk/structured-outputs))   | `claude -p --json-schema '{"type":"object","properties":{...}}' "query"`                           |
| `--maintenance`                        | Run maintenance hooks and exit                                                                                                                                                                            | `claude --maintenance`                                                                             |
| `--max-budget-usd`                     | Maximum dollar amount to spend on API calls before stopping (print mode only)                                                                                                                             | `claude -p --max-budget-usd 5.00 "query"`                                                          |
| `--max-turns`                          | Limit the number of agentic turns (print mode only). Exits with an error when the limit is reached. No limit by default                                                                                   | `claude -p --max-turns 3 "query"`                                                                  |
| `--mcp-config`                         | Load MCP servers from JSON files or strings (space-separated)                                                                                                                                             | `claude --mcp-config ./mcp.json`                                                                   |
| `--model`                              | Sets the model for the current session with an alias for the latest model (`sonnet` or `opus`) or a model's full name                                                                                     | `claude --model claude-sonnet-4-5-20250929`                                                        |
| `--no-chrome`                          | Disable [Chrome browser integration](chrome.md) for this session                                                                                                                                         | `claude --no-chrome`                                                                               |
| `--no-session-persistence`             | Disable session persistence so sessions are not saved to disk and cannot be resumed (print mode only)                                                                                                     | `claude -p --no-session-persistence "query"`                                                       |
| `--output-format`                      | Specify output format for print mode (options: `text`, `json`, `stream-json`)                                                                                                                             | `claude -p "query" --output-format json`                                                           |
| `--permission-mode`                    | Begin in a specified [permission mode](/en/iam#permission-modes)                                                                                                                                          | `claude --permission-mode plan`                                                                    |
| `--permission-prompt-tool`             | Specify an MCP tool to handle permission prompts in non-interactive mode                                                                                                                                  | `claude -p --permission-prompt-tool mcp_auth_tool "query"`                                         |
| `--plugin-dir`                         | Load plugins from directories for this session only (repeatable)                                                                                                                                          | `claude --plugin-dir ./my-plugins`                                                                 |
| `--print`, `-p`                        | Print response without interactive mode (see [SDK documentation](https://docs.claude.com/en/docs/agent-sdk) for programmatic usage details)                                                               | `claude -p "query"`                                                                                |
| `--remote`                             | Create a new [web session](claude-code-on-the-web-69d53821d4.md) on claude.ai with the provided task description                                                                                                    | `claude --remote "Fix the login bug"`                                                              |
| `--resume`, `-r`                       | Resume a specific session by ID or name, or show an interactive picker to choose a session                                                                                                                | `claude --resume auth-refactor`                                                                    |
| `--session-id`                         | Use a specific session ID for the conversation (must be a valid UUID)                                                                                                                                     | `claude --session-id "550e8400-e29b-41d4-a716-446655440000"`                                       |
| `--setting-sources`                    | Comma-separated list of setting sources to load (`user`, `project`, `local`)                                                                                                                              | `claude --setting-sources user,project`                                                            |
| `--settings`                           | Path to a settings JSON file or a JSON string to load additional settings from                                                                                                                            | `claude --settings ./settings.json`                                                                |
| `--strict-mcp-config`                  | Only use MCP servers from `--mcp-config`, ignoring all other MCP configurations                                                                                                                           | `claude --strict-mcp-config --mcp-config ./mcp.json`                                               |
| `--system-prompt`                      | Replace the entire system prompt with custom text (works in both interactive and print modes)                                                                                                             | `claude --system-prompt "You are a Python expert"`                                                 |
| `--system-prompt-file`                 | Load system prompt from a file, replacing the default prompt (print mode only)                                                                                                                            | `claude -p --system-prompt-file ./custom-prompt.txt "query"`                                       |
| `--teleport`                           | Resume a [web session](claude-code-on-the-web-69d53821d4.md) in your local terminal                                                                                                                                 | `claude --teleport`                                                                                |
| `--tools`                              | Restrict which built-in tools Claude can use (works in both interactive and print modes). Use `""` to disable all, `"default"` for all, or tool names like `"Bash,Edit,Read"`                             | `claude --tools "Bash,Edit,Read"`                                                                  |
| `--verbose`                            | Enable verbose logging, shows full turn-by-turn output (helpful for debugging in both print and interactive modes)                                                                                        | `claude --verbose`                                                                                 |
| `--version`, `-v`                      | Output the version number                                                                                                                                                                                 | `claude -v`                                                                                        |

<Tip>
  The `--output-format json` flag is particularly useful for scripting and
  automation, allowing you to parse Claude's responses programmatically.
</Tip>

### Agents flag format

The `--agents` flag accepts a JSON object that defines one or more custom subagents. Each subagent requires a unique name (as the key) and a definition object with the following fields:

| Field         | Required | Description                                                                                                                         |
| :------------ | :------- | :---------------------------------------------------------------------------------------------------------------------------------- |
| `description` | Yes      | Natural language description of when the subagent should be invoked                                                                 |
| `prompt`      | Yes      | The system prompt that guides the subagent's behavior                                                                               |
| `tools`       | No       | Array of specific tools the subagent can use (for example, `["Read", "Edit", "Bash"]`). If omitted, inherits all tools              |
| `model`       | No       | Model alias to use: `sonnet`, `opus`, `haiku`, or `inherit`. If omitted, defaults to `inherit` (uses the main conversation's model) |

Example:

```bash  theme={null}
claude --agents '{
  "code-reviewer": {
    "description": "Expert code reviewer. Use proactively after code changes.",
    "prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",
    "tools": ["Read", "Grep", "Glob", "Bash"],
    "model": "sonnet"
  },
  "debugger": {
    "description": "Debugging specialist for errors and test failures.",
    "prompt": "You are an expert debugger. Analyze errors, identify root causes, and provide fixes."
  }
}'
```

For more details on creating and using subagents, see the [subagents documentation](../09-Agents-Patterns/create-custom-subagents-claude-code-docs-7dc93e85c0.md).

### System prompt flags

Claude Code provides four flags for customizing the system prompt, each serving a different purpose:

| Flag                          | Behavior                                    | Modes               | Use Case                                                             |
| :---------------------------- | :------------------------------------------ | :------------------ | :------------------------------------------------------------------- |
| `--system-prompt`             | **Replaces** entire default prompt          | Interactive + Print | Complete control over Claude's behavior and instructions             |
| `--system-prompt-file`        | **Replaces** with file contents             | Print only          | Load prompts from files for reproducibility and version control      |
| `--append-system-prompt`      | **Appends** to default prompt               | Interactive + Print | Add specific instructions while keeping default Claude Code behavior |
| `--append-system-prompt-file` | **Appends** file contents to default prompt | Print only          | Load additional instructions from files while keeping defaults       |

**When to use each:**

* **`--system-prompt`**: Use when you need complete control over Claude's system prompt. This removes all default Claude Code instructions, giving you a blank slate.
  ```bash  theme={null}
  claude --system-prompt "You are a Python expert who only writes type-annotated code"
  ```

* **`--system-prompt-file`**: Use when you want to load a custom prompt from a file, useful for team consistency or version-controlled prompt templates.
  ```bash  theme={null}
  claude -p --system-prompt-file ./prompts/code-review.txt "Review this PR"
  ```

* **`--append-system-prompt`**: Use when you want to add specific instructions while keeping Claude Code's default capabilities intact. This is the safest option for most use cases.
  ```bash  theme={null}
  claude --append-system-prompt "Always use TypeScript and include JSDoc comments"
  ```

* **`--append-system-prompt-file`**: Use when you want to append instructions from a file while keeping Claude Code's defaults. Useful for version-controlled additions.
  ```bash  theme={null}
  claude -p --append-system-prompt-file ./prompts/style-rules.txt "Review this PR"
  ```

`--system-prompt` and `--system-prompt-file` are mutually exclusive. The append flags can be used together with either replacement flag.

For most use cases, `--append-system-prompt` or `--append-system-prompt-file` is recommended as they preserve Claude Code's built-in capabilities while adding your custom requirements. Use `--system-prompt` or `--system-prompt-file` only when you need complete control over the system prompt.

## See also

* [Chrome extension](chrome.md) - Browser automation and web testing
* [Interactive mode](interactive-mode-claude-code-docs.md) - Shortcuts, input modes, and interactive features
* [Quickstart guide](../01-Getting-Started/quickstart-claude-code-docs-a21b84bdea.md) - Getting started with Claude Code
* [Common workflows](common-workflows-c909406123.md) - Advanced workflows and patterns
* [Settings](claude-code-settings-claude-code-docs-d4420b4b52.md) - Configuration options
* [SDK documentation](https://docs.claude.com/en/docs/agent-sdk) - Programmatic usage and integrations


---
## clients.md

# Example Clients

> A list of applications that support MCP integrations

export const FEATURES = ["Resources", "Prompts", "Tools", "Discovery", "Sampling", "Roots", "Elicitation", "Instructions", "Tasks", "Apps"];


export const filterStore = {
  state: {
    selectedFeatures: [],
    searchText: "",
    visibleCount: 0,
    totalCount: 0
  },
  listeners: new Set(),
  setState(updater) {
    if (typeof updater === "function") {
      this.state = {
        ...this.state,
        ...updater(this.state)
      };
    } else {
      this.state = {
        ...this.state,
        ...updater
      };
    }
    this.listeners.forEach(fn => fn(this.state));
  },
  subscribe(fn) {
    this.listeners.add(fn);
    return () => this.listeners.delete(fn);
  }
};


export const useFilterStore = () => {
  const [state, setState] = useState(filterStore.state);
  useEffect(() => filterStore.subscribe(setState), []);
  return state;
};


export const useFilter = ({name, supports}) => {
  const {selectedFeatures, searchText} = useFilterStore();
  const isVisible = name.toLowerCase().includes(searchText.toLowerCase()) && selectedFeatures.every(feature => supports?.includes(feature));
  useEffect(() => {
    filterStore.setState(s => ({
      totalCount: s.totalCount + 1
    }));
    return () => filterStore.setState(s => ({
      totalCount: s.totalCount - 1
    }));
  }, []);
  useEffect(() => {
    if (isVisible) {
      filterStore.setState(s => ({
        visibleCount: s.visibleCount + 1
      }));
      return () => filterStore.setState(s => ({
        visibleCount: s.visibleCount - 1
      }));
    }
  }, [isVisible]);
  return isVisible;
};


export const ClientFilter = () => {
  const {selectedFeatures, searchText, visibleCount, totalCount} = useFilterStore();
  useEffect(() => {
    filterStore.setState({
      selectedFeatures: [],
      searchText: ""
    });
  }, []);
  const toggleFeature = feature => {
    const newFeatures = selectedFeatures.includes(feature) ? selectedFeatures.filter(f => f !== feature) : [...selectedFeatures, feature];
    filterStore.setState({
      selectedFeatures: newFeatures
    });
  };
  const clearFilters = () => {
    filterStore.setState({
      selectedFeatures: [],
      searchText: ""
    });
  };
  const hasFilters = selectedFeatures.length > 0 || searchText.length > 0;
  return <div className="p-4 border border-gray-200 dark:border-gray-700 rounded-lg bg-gray-50 dark:bg-gray-800/50">
      <div className="flex items-center justify-between">
        <span className="font-bold text-gray-700 dark:text-gray-300">
          Showing {visibleCount} of {totalCount} clients
        </span>
        {hasFilters && <button onClick={clearFilters} className="text-sm cursor-pointer px-3 py-1 rounded-full bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-600 transition-colors">
            <Icon icon="xmark" iconType="solid" size={16} /> Clear filters
          </button>}
      </div>
      <div className="mt-3">
        <input type="text" placeholder="Search clients by name..." value={searchText} onChange={e => filterStore.setState({
    searchText: e.target.value
  })} className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 placeholder-gray-500 dark:placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" />
      </div>
      <div className="mt-4">
        <div className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
          Filter by features:
        </div>
        <div className="flex flex-wrap gap-2">
          {FEATURES.map(feature => <button key={feature} onClick={() => toggleFeature(feature)} className={`flex items-center gap-1.5 px-2 py-1 rounded text-sm transition-colors cursor-pointer ${selectedFeatures.includes(feature) ? 'bg-primary/10 text-primary dark:bg-gray-700 dark:text-gray-100' : 'text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-800'}`}>
              <Icon icon={selectedFeatures.includes(feature) ? "square-check" : "square"} iconType={selectedFeatures.includes(feature) ? "solid" : "regular"} size={16} />
              {feature}
            </button>)}
        </div>
      </div>
    </div>;
};


export const McpClient = ({name, homepage, supports, sourceCode, instructions, children}) => {
  const slug = name.toLowerCase().replace(/[().\s-]+/g, "-").replace(/^-|-$/g, "");
  if (homepage?.match(/^https:\/\/github\.com\/[^/]+\/[^/]+/)) {
    sourceCode ??= homepage;
  }
  const instructionsLinks = Array.isArray(instructions) ? <>
        <strong>Configuration instructions:</strong>{" "}
        {instructions.map(([text, url], i) => [i > 0 && ", ", <a href={url} target="_blank" rel="noopener noreferrer">{text}</a>])}
      </> : <a href={instructions} target="_blank" rel="noopener noreferrer">
        Configuration instructions
      </a>;
  const [expanded, setExpanded] = useState(false);
  const [hasOverflow, setHasOverflow] = useState(false);
  const contentRef = useRef(null);
  const isVisible = useFilter({
    name,
    supports
  });
  useEffect(() => {
    const el = contentRef.current;
    if (el) {
      setHasOverflow(el.scrollHeight > el.clientHeight);
    }
  }, []);
  if (!isVisible) return null;
  return <div id={slug} className="group mt-8 scroll-mt-32">
      <div className="border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
        <div className="px-4 py-3 border-b border-gray-200 dark:border-gray-700">
          <div className="flex items-center gap-2">
            <a href={homepage} className="border-0 text-xl font-semibold text-primary underline" target="_blank" rel="noopener noreferrer">
              {name}
            </a>
            <a href={`#${slug}`} className="ml-auto border-0 opacity-0 group-hover:opacity-100 text-xl text-gray-400 hover:text-gray-600" aria-label={`Link to ${name}`}>
              #
            </a>
          </div>
          {supports && <div className="flex items-start gap-1.5 mt-2 text-base">
              <span className="flex items-center h-[1lh]">
                <Icon icon="check" iconType="solid" size={18} />
              </span>
              <span><strong>Supports:</strong> {supports}</span>
            </div>}
          {sourceCode && <div className="flex items-start gap-1.5 mt-2 text-base">
              <span className="flex items-center h-[1lh]">
                <Icon icon="code" iconType="solid" size={18} />
              </span>
              <span>
                <a href={sourceCode} target="_blank" rel="noopener noreferrer">
                  Open source
                </a>
              </span>
            </div>}
          {instructions && <div className="flex items-start gap-1.5 mt-2 text-base">
              <span className="flex items-center h-[1lh]">
                <Icon icon="gear" iconType="solid" size={18} />
              </span>
              <span>
                {instructionsLinks}
              </span>
            </div>}
        </div>
        <div className="relative">
          <div ref={contentRef} className={`px-4 py-4 prose ${!expanded ? "max-h-[7rem] overflow-hidden" : "pb-8"}`}>
            {children}
          </div>
          {hasOverflow && <button onClick={() => setExpanded(!expanded)} className={`absolute bottom-0 left-0 right-0 flex justify-center items-end pb-1 cursor-pointer text-gray-400 hover:text-gray-600 ${!expanded ? "h-16 bg-gradient-to-t from-white dark:from-gray-900 to-transparent" : "h-8"}`}>
              <span className={`${expanded ? "rotate-180" : ""} bg-white/60 dark:bg-gray-900/60 rounded-full`}>
                <Icon icon="chevron-down" iconType="solid" size={18} />
              </span>
            </button>}
        </div>
      </div>
    </div>;
};


This page provides an overview of applications that support the Model Context Protocol (MCP). Each client may support different MCP features, allowing for varying levels of integration with MCP servers.

<Note>
  This list is maintained by the community. If you notice any inaccuracies or would like to add or update information about MCP support in your application, please [submit a pull request](https://github.com/modelcontextprotocol/modelcontextprotocol/pulls).
</Note>

[Content continues with all client details as fetched...]


---
## code-review-09694cae75.md

> ## Documentation Index
> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Code Review

> Set up automated PR reviews that catch logic errors, security vulnerabilities, and regressions using multi-agent analysis of your full codebase

<Note>
  Code Review is in research preview, available for [Team and Enterprise](https://claude.ai/admin-settings/claude-code) subscriptions. It is not available for organizations with [Zero Data Retention](../22-Safety-Policy/zero-data-retention-claude-code-docs-6ec9ee63f1.md) enabled.
</Note>

Code Review analyzes your GitHub pull requests and posts findings as inline comments on the lines of code where it found issues. A fleet of specialized agents examine the code changes in the context of your full codebase, looking for logic errors, security vulnerabilities, broken edge cases, and subtle regressions.

Findings are tagged by severity and don't approve or block your PR, so existing review workflows stay intact. You can tune what Claude flags by adding a `CLAUDE.md` or `REVIEW.md` file to your repository.

To run Claude in your own CI infrastructure instead of this managed service, see [GitHub Actions](claude-code-github-actions-claude-code-docs-0d633fbd8a.md) or [GitLab CI/CD](claude-code-gitlab-ci-cd-claude-code-docs-fbcd915fee.md). For repositories on a self-hosted GitHub instance, see [GitHub Enterprise Server](../03-IDE-Integrations/github-enterprise-server.md).

This page covers:

* [How reviews work](#how-reviews-work)
* [Setup](#set-up-code-review)
* [Triggering reviews manually](#manually-trigger-reviews) with `@claude review` and `@claude review once`
* [Customizing reviews](#customize-reviews) with `CLAUDE.md` and `REVIEW.md`
* [Pricing](#pricing)
* [Troubleshooting](#troubleshooting) failed runs and missing comments

## How reviews work

Once an admin [enables Code Review](#set-up-code-review) for your organization, reviews trigger when a PR opens, on every push, or when manually requested, depending on the repository's configured behavior. Commenting `@claude review` [starts reviews on a PR](#manually-trigger-reviews) in any mode.

When a review runs, multiple agents analyze the diff and surrounding code in parallel on Anthropic infrastructure. Each agent looks for a different class of issue, then a verification step checks candidates against actual code behavior to filter out false positives. The results are deduplicated, ranked by severity, and posted as inline comments on the specific lines where issues were found, with a summary in the review body. If no issues are found, Claude posts a short confirmation comment on the PR.

Reviews scale in cost with PR size and complexity, completing in 20 minutes on average. Admins can monitor review activity and spend via the [analytics dashboard](#view-usage).

### Severity levels

Each finding is tagged with a severity level:

| Marker | Severity     | Meaning                                                             |
| :----- | :----------- | :------------------------------------------------------------------ |
| 🔴     | Important    | A bug that should be fixed before merging                           |
| 🟡     | Nit          | A minor issue, worth fixing but not blocking                        |
| 🟣     | Pre-existing | A bug that exists in the codebase but was not introduced by this PR |

Findings include a collapsible extended reasoning section you can expand to understand why Claude flagged the issue and how it verified the problem.

### Rate and reply to findings

Each review comment from Claude arrives with 👍 and 👎 already attached so both buttons appear in the GitHub UI for one-click rating. Click 👍 if the finding was useful or 👎 if it was wrong or noisy. Anthropic collects reaction counts after the PR merges and uses them to tune the reviewer. Reactions do not trigger a re-review or change anything on the PR.

Replying to an inline comment does not prompt Claude to respond or update the PR. To act on a finding, fix the code and push. If the PR is subscribed to push-triggered reviews, the next run resolves the thread when the issue is fixed. To request a fresh review without pushing, comment `@claude review once` as a [top-level PR comment](#manually-trigger-reviews).

### Check run output

Beyond the inline review comments, each review populates the **Claude Code Review** check run that appears alongside your CI checks. Expand its **Details** link to see a summary of every finding in one place, sorted by severity:

| Severity     | File:Line                 | Issue                                                          |
| ------------ | ------------------------- | -------------------------------------------------------------- |
| 🔴 Important | `src/auth/session.ts:142` | Token refresh races with logout, leaving stale sessions active |
| 🟡 Nit       | `src/auth/session.ts:88`  | `parseExpiry` silently returns 0 on malformed input            |

Each finding also appears as an annotation in the **Files changed** tab, marked directly on the relevant diff lines. Important findings render with a red marker, nits with a yellow warning, and pre-existing bugs with a gray notice. Annotations and the severity table are written to the check run independently of inline review comments, so they remain available even if GitHub rejects an inline comment on a line that moved.

The check run always completes with a neutral conclusion so it never blocks merging through branch protection rules. If you want to gate merges on Code Review findings, read the severity breakdown from the check run output in your own CI. The last line of the Details text is a machine-readable comment your workflow can parse with `gh` and jq:

```bash theme={null}
gh api repos/OWNER/REPO/check-runs/CHECK_RUN_ID \
  --jq '.output.text | split("bughunter-severity: ")[1] | split(" -->")[0] | fromjson'
```

This returns a JSON object with counts per severity, for example `{"normal": 2, "nit": 1, "pre_existing": 0}`. The `normal` key holds the count of Important findings; a non-zero value means Claude found at least one bug worth fixing before merge.

### What Code Review checks

By default, Code Review focuses on correctness: bugs that would break production, not formatting preferences or missing test coverage. You can expand what it checks by [adding guidance files](#customize-reviews) to your repository.

## Set up Code Review

An admin enables Code Review once for the organization and selects which repositories to include.

<Steps>
  <Step title="Open Claude Code admin settings">
    Go to [claude.ai/admin-settings/claude-code](https://claude.ai/admin-settings/claude-code) and find the Code Review section. You need admin access to your Claude organization and permission to install GitHub Apps in your GitHub organization.
  </Step>

  <Step title="Start setup">
    Click **Setup**. This begins the GitHub App installation flow.
  </Step>

  <Step title="Install the Claude GitHub App">
    Follow the prompts to install the Claude GitHub App to your GitHub organization. The app requests these repository permissions:

    * **Contents**: read and write
    * **Issues**: read and write
    * **Pull requests**: read and write

    Code Review uses read access to contents and write access to pull requests. The broader permission set also supports [GitHub Actions](claude-code-github-actions-claude-code-docs-0d633fbd8a.md) if you enable that later.
  </Step>

  <Step title="Select repositories">
    Choose which repositories to enable for Code Review. If you don't see a repository, make sure you gave the Claude GitHub App access to it during installation. You can add more repositories later.
  </Step>

  <Step title="Set review triggers per repo">
    After setup completes, the Code Review section shows your repositories in a table. For each repository, use the **Review Behavior** dropdown to choose when reviews run:

    * **Once after PR creation**: review runs once when a PR is opened or marked ready for review
    * **After every push**: review runs on every push to the PR branch, catching new issues as the PR evolves and auto-resolving threads when you fix flagged issues
    * **Manual**: reviews start only when someone [comments `@claude review` or `@claude review once` on a PR](#manually-trigger-reviews); `@claude review` also subscribes the PR to reviews on subsequent pushes

    Reviewing on every push runs the most reviews and costs the most. Manual mode is useful for high-traffic repos where you want to opt specific PRs into review, or to only start reviewing your PRs once they're ready.
  </Step>
</Steps>

The repositories table also shows the average cost per review for each repo based on recent activity. Use the row actions menu to turn Code Review on or off per repository, or to remove a repository entirely.

To verify setup, open a test PR. If you chose an automatic trigger, a check run named **Claude Code Review** appears within a few minutes. If you chose Manual, comment `@claude review` on the PR to start the first review. If no check run appears, confirm the repository is listed in your admin settings and the Claude GitHub App has access to it.

## Manually trigger reviews

Two comment commands start a review on demand. Both work regardless of the repository's configured trigger, so you can use them to opt specific PRs into review in Manual mode or to get an immediate re-review in other modes.

| Command               | What it does                                                                  |
| :-------------------- | :---------------------------------------------------------------------------- |
| `@claude review`      | Starts a review and subscribes the PR to push-triggered reviews going forward |
| `@claude review once` | Starts a single review without subscribing the PR to future pushes            |

Use `@claude review once` when you want feedback on the current state of a PR but don't want every subsequent push to incur a review. This is useful for long-running PRs with frequent pushes, or when you want a one-off second opinion without changing the PR's review behavior.

For either command to trigger a review:

* Post it as a top-level PR comment, not an inline comment on a diff line
* Put the command at the start of the comment, with `once` on the same line if you're using the one-shot form
* You must have owner, member, or collaborator access to the repository
* The PR must be open

Unlike automatic triggers, manual triggers run on draft PRs, since an explicit request signals you want the review now regardless of draft status.

If a review is already running on that PR, the request is queued until the in-progress review completes. You can monitor progress via the check run on the PR.

## Customize reviews

Code Review reads two files from your repository to guide what it flags. They differ in how strongly they influence the review:

* **`CLAUDE.md`**: shared project instructions that Claude Code uses for all tasks, not just reviews. Code Review reads it as project context and flags newly introduced violations as nits.
* **`REVIEW.md`**: review-only instructions, injected directly into every agent in the review pipeline as highest priority. Use it to change what gets flagged, at what severity, and how findings are reported.

### CLAUDE.md

Code Review reads your repository's `CLAUDE.md` files and treats newly introduced violations as [nit-level](#severity-levels) findings. This works bidirectionally: if your PR changes code in a way that makes a `CLAUDE.md` statement outdated, Claude flags that the docs need updating too.

Claude reads `CLAUDE.md` files at every level of your directory hierarchy, so rules in a subdirectory's `CLAUDE.md` apply only to files under that path. See the [memory documentation](how-claude-remembers-your-project-claude-code-docs-f1c064262d.md) for more on how `CLAUDE.md` works.

For review-specific guidance that you don't want applied to general Claude Code sessions, use [`REVIEW.md`](#review-md) instead.

### REVIEW\.md

`REVIEW.md` is a file at your repository root that overrides how Code Review behaves on your repo. Its contents are injected into the system prompt of every agent in the review pipeline as the highest-priority instruction block, taking precedence over the default review guidance.

Because it's pasted verbatim, `REVIEW.md` is plain instructions: [`@` import syntax](/en/memory#import-additional-files) is not expanded, and referenced files are not read into the prompt. Put the rules you want enforced directly in the file.

#### What you can tune

`REVIEW.md` is freeform markdown, so anything you can express as a review instruction is in scope. The patterns below have the most impact in practice.

**Severity**: redefine what 🔴 Important means for your repo. The default calibration targets production code; a docs repo, a config repo, or a prototype might want a much narrower definition. State explicitly which classes of finding are Important and which are Nit at most. You can also escalate in the other direction, for example treating any `CLAUDE.md` violation as Important rather than the default nit.

**Nit volume**: cap how many 🟡 Nit comments a single review posts. Prose and config files can be polished forever. A cap like "report at most five nits, mention the rest as a count in the summary" keeps reviews actionable.

**Skip rules**: list paths, branch patterns, and finding categories where Claude should post no findings. Common candidates are generated code, lockfiles, vendored dependencies, and machine-authored branches, along with anything your CI already enforces like linting or spellcheck. For paths that warrant some review but not full scrutiny, set a higher bar instead of skipping entirely: "in `scripts/`, only report if near-certain and severe."

**Repo-specific checks**: add rules you want flagged on every PR, like "new API routes must have an integration test." Because `REVIEW.md` is injected as highest priority, these land more reliably than the same rules in a long `CLAUDE.md`.

**Verification bar**: require evidence before a class of finding is posted. For example, "behavior claims need a `file:line` citation in the source, not an inference from naming" cuts false positives that would otherwise cost the author a round trip.

**Re-review convergence**: tell Claude how to behave when a PR has already been reviewed. A rule like "after the first review, suppress new nits and post Important findings only" stops a one-line fix from reaching round seven on style alone.

**Summary shape**: ask for the review body to open with a one-line tally such as `2 factual, 4 style`, and to lead with "no factual issues" when that's the case. The author wants to know the shape of the work before the details.

#### Example

This `REVIEW.md` recalibrates severity for a backend service, caps nits, skips generated files, and adds repo-specific checks.

```markdown theme={null}
# Review instructions

## What Important means here

Reserve Important for findings that would break behavior, leak data,
or block a rollback: incorrect logic, unscoped database queries, PII
in logs or error messages, and migrations that aren't backward
compatible. Style, naming, and refactoring suggestions are Nit at
most.

## Cap the nits

Report at most five Nits per review. If you found more, say "plus N
similar items" in the summary instead of posting them inline. If
everything you found is a Nit, lead the summary with "No blocking
issues."

## Do not report

- Anything CI already enforces: lint, formatting, type errors
- Generated files under `src/gen/` and any `*.lock` file
- Test-only code that intentionally violates production rules

## Always check

- New API routes have an integration test
- Log lines don't include email addresses, user IDs, or request bodies
- Database queries are scoped to the caller's tenant
```

#### Keep it focused

Length has a cost: a long `REVIEW.md` dilutes the rules that matter most. Keep it to instructions that change review behavior, and leave general project context in `CLAUDE.md`.

## View usage

Go to [claude.ai/analytics/code-review](https://claude.ai/analytics/code-review) to see Code Review activity across your organization. The dashboard shows:

| Section              | What it shows                                                                            |
| :------------------- | :--------------------------------------------------------------------------------------- |
| PRs reviewed         | Daily count of pull requests reviewed over the selected time range                       |
| Cost weekly          | Weekly spend on Code Review                                                              |
| Feedback             | Count of review comments that were auto-resolved because a developer addressed the issue |
| Repository breakdown | Per-repo counts of PRs reviewed and comments resolved                                    |

The repositories table in admin settings also shows average cost per review for each repo. Dashboard cost figures are estimates for monitoring activity; for invoice-accurate spend, refer to your Anthropic bill.

## Pricing

Code Review is billed based on token usage. Each review averages \$15-25 in cost, scaling with PR size, codebase complexity, and how many issues require verification. Code Review usage is billed separately through [extra usage](../17-Billing-Plans/extra-usage-for-paid-claude-plans.md) and does not count against your plan's included usage.

The review trigger you choose affects total cost:

* **Once after PR creation**: runs once per PR
* **After every push**: runs on each push, multiplying cost by the number of pushes
* **Manual**: no reviews until someone comments `@claude review` on a PR

In any mode, commenting `@claude review` [opts the PR into push-triggered reviews](#manually-trigger-reviews), so additional cost accrues per push after that comment. To run a single review without subscribing to future pushes, comment `@claude review once` instead.

Costs appear on your Anthropic bill regardless of whether your organization uses AWS Bedrock or Google Vertex AI for other Claude Code features. To set a monthly spend cap 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.

Monitor spend via the weekly cost chart in [analytics](#view-usage) or the per-repo average cost column in admin settings.

## Troubleshooting

Review runs are best-effort. A failed run never blocks your PR, but it also doesn't retry on its own. This section covers how to recover from a failed run and where to look when the check run reports issues you can't find.

### Retrigger a failed or timed-out review

When the review infrastructure hits an internal error or exceeds its time limit, the check run completes with a title of **Code review encountered an error** or **Code review timed out**. The conclusion is still neutral, so nothing blocks your merge, but no findings are posted.

To run the review again, comment `@claude review once` on the PR. This starts a fresh review without subscribing the PR to future pushes. If the PR is already subscribed to push-triggered reviews, pushing a new commit also starts a new review.

The **Re-run** button in GitHub's Checks tab does not retrigger Code Review. Use the comment command or a new push instead.

### Review didn't run and the PR shows a spend-cap message

When your organization's monthly spend cap is reached, Code Review posts a single comment on the PR explaining that the review was skipped. Reviews resume automatically at the start of the next billing period, or immediately when an admin raises the cap at [claude.ai/admin-settings/usage](https://claude.ai/admin-settings/usage).

### 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:

* **Check run Details**: click **Details** next to the Claude Code Review check in the Checks tab. The severity table lists every finding with its file, line, and summary regardless of whether the inline comment was accepted.
* **Files changed annotations**: open the **Files changed** tab on the PR. Findings render as annotations attached directly to the diff lines, separate from review comments.
* **Review body**: if you pushed to the PR while a review was running, some findings may reference lines that no longer exist in the current diff. Those appear under an **Additional findings** heading in the review body text rather than as inline comments.

## Related resources

Code Review is designed to work alongside the rest of Claude Code. If you want to run reviews locally before opening a PR, need a self-hosted setup, or want to go deeper on how `CLAUDE.md` shapes Claude's behavior across tools, these pages are good next stops:

* [Plugins](../08-Plugins-Skills/discover-and-install-prebuilt-plugins-through-marketplaces-claude-code-docs-fe3568ee5c.md): browse the plugin marketplace, including a `code-review` plugin for running on-demand reviews locally before pushing
* [GitHub Actions](claude-code-github-actions-claude-code-docs-0d633fbd8a.md): run Claude in your own GitHub Actions workflows for custom automation beyond code review
* [GitLab CI/CD](claude-code-gitlab-ci-cd-claude-code-docs-fbcd915fee.md): self-hosted Claude integration for GitLab pipelines
* [Memory](how-claude-remembers-your-project-claude-code-docs-f1c064262d.md): how `CLAUDE.md` files work across Claude Code
* [Analytics](../13-Enterprise-Admin/track-team-usage-with-analytics-claude-code-docs-35e754aabf.md): track Claude Code usage beyond code review


---
## code-review-claude-code-docs-d5ca97ed20.md

# Code Review


Set up automated PR reviews that catch logic errors, security vulnerabilities, and regressions using multi-agent analysis of your full codebase


> ## Documentation Index
>
> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt>
>
> Use this file to discover all available pages before exploring further.

Code Review is in research preview, available for [Team and Enterprise](https://claude.ai/admin-settings/claude-code) subscriptions. It is not available for organizations with [Zero Data Retention](/docs/en/zero-data-retention) enabled.

Code Review analyzes your GitHub pull requests and posts findings as inline comments on the lines of code where it found issues. A fleet of specialized agents examine the code changes in the context of your full codebase, looking for logic errors, security vulnerabilities, broken edge cases, and subtle regressions. Findings are tagged by severity and don’t approve or block your PR, so existing review workflows stay intact. You can tune what Claude flags by adding a `CLAUDE.md` or `REVIEW.md` file to your repository. To run Claude in your own CI infrastructure instead of this managed service, see [GitHub Actions](/docs/en/github-actions) or [GitLab CI/CD](/docs/en/gitlab-ci-cd). For repositories on a self-hosted GitHub instance, see [GitHub Enterprise Server](/docs/en/github-enterprise-server). This page covers:

- [How reviews work](#how-reviews-work)
- [Setup](#set-up-code-review)
- [Triggering reviews manually](#manually-trigger-reviews) with `@claude review` and `@claude review once`
- [Customizing reviews](#customize-reviews) with `CLAUDE.md` and `REVIEW.md`
- [Pricing](#pricing)
- [Troubleshooting](#troubleshooting) failed runs and missing comments


How reviews work

Once an admin [enables Code Review](#set-up-code-review) for your organization, reviews trigger when a PR opens, on every push, or when manually requested, depending on the repository’s configured behavior. Commenting `@claude review` [starts reviews on a PR](#manually-trigger-reviews) in any mode. When a review runs, multiple agents analyze the diff and surrounding code in parallel on Anthropic infrastructure. Each agent looks for a different class of issue, then a verification step checks candidates against actual code behavior to filter out false positives. The results are deduplicated, ranked by severity, and posted as inline comments on the specific lines where issues were found, with a summary in the review body. If no issues are found, Code Review updates the GitHub check run to show that no issues were detected. Claude may also post a short confirmation comment on the PR. Reviews scale in cost with PR size and complexity, completing in 20 minutes on average. Admins can monitor review activity and spend via the [analytics dashboard](#view-usage).


Severity levels

Each finding is tagged with a severity level:

| Marker | Severity     | Meaning                                                             |
|:-------|:-------------|:--------------------------------------------------------------------|
| 🔴     | Important    | A bug that should be fixed before merging                           |
| 🟡     | Nit          | A minor issue, worth fixing but not blocking                        |
| 🟣     | Pre-existing | A bug that exists in the codebase but was not introduced by this PR |

Findings include a collapsible extended reasoning section you can expand to understand why Claude flagged the issue and how it verified the problem.


Rate and reply to findings

Each review comment from Claude arrives with 👍 and 👎 already attached so both buttons appear in the GitHub UI for one-click rating. Click 👍 if the finding was useful or 👎 if it was wrong or noisy. Anthropic collects reaction counts after the PR merges and uses them to tune the reviewer. Reactions do not trigger a re-review or change anything on the PR. Replying to an inline comment does not prompt Claude to respond or update the PR. To act on a finding, fix the code and push. If the PR is subscribed to push-triggered reviews, the next run resolves the thread when the issue is fixed. To request a fresh review without pushing, comment `@claude review once` as a [top-level PR comment](#manually-trigger-reviews).


Check run output

Beyond the inline review comments, each review populates the **Claude Code Review** check run that appears alongside your CI checks. Expand its **Details** link to see a summary of every finding in one place, sorted by severity:

| Severity     | File:Line                 | Issue                                                          |
|--------------|---------------------------|----------------------------------------------------------------|
| 🔴 Important | `src/auth/session.ts:142` | Token refresh races with logout, leaving stale sessions active |
| 🟡 Nit       | `src/auth/session.ts:88`  | `parseExpiry` silently returns 0 on malformed input            |

Each finding also appears as an annotation in the **Files changed** tab, marked directly on the relevant diff lines. Important findings render with a red marker, nits with a yellow warning, and pre-existing bugs with a gray notice. Annotations and the severity table are written to the check run independently of inline review comments, so they remain available even if GitHub rejects an inline comment on a line that moved. The check run always completes with a neutral conclusion so it never blocks merging through branch protection rules. If you want to gate merges on Code Review findings, read the severity breakdown from the check run output in your own CI. The last line of the Details text is a machine-readable comment your workflow can parse with `gh` and jq:

```python
gh api repos/OWNER/REPO/check-runs/CHECK_RUN_ID \
  --jq '.output.text | split("bughunter-severity: ")[1] | split(" -->")[0] | fromjson'
```

This returns a JSON object with counts per severity, for example `{"normal": 2, "nit": 1, "pre_existing": 0}`. The `normal` key holds the count of Important findings; a non-zero value means Claude found at least one bug worth fixing before merge.


What Code Review checks

By default, Code Review focuses on correctness: bugs that would break production, not formatting preferences or missing test coverage. You can expand what it checks by [adding guidance files](#customize-reviews) to your repository.


Set up Code Review

An admin enables Code Review once for the organization and selects which repositories to include.

1


Open Claude Code admin settings

Go to [claude.ai/admin-settings/claude-code](https://claude.ai/admin-settings/claude-code) and find the Code Review section. You need admin access to your Claude organization and permission to install GitHub Apps in your GitHub organization.

2


Start setup

Click **Setup**. This begins the GitHub App installation flow.

3


Install the Claude GitHub App

Follow the prompts to install the Claude GitHub App to your GitHub organization. The app requests these repository permissions:

- **Contents**: read and write
- **Issues**: read and write
- **Pull requests**: read and write

Code Review uses read access to contents and write access to pull requests. The broader permission set also supports [GitHub Actions](/docs/en/github-actions) if you enable that later.

4


Select repositories

Choose which repositories to enable for Code Review. If you don’t see a repository, make sure you gave the Claude GitHub App access to it during installation. You can add more repositories later.

5


Set review triggers per repo

After setup completes, the Code Review section shows your repositories in a table. For each repository, use the **Review Behavior** dropdown to choose when reviews run:

- **Once after PR creation**: review runs once when a PR is opened or marked ready for review
- **After every push**: review runs on every push to the PR branch, catching new issues as the PR evolves and auto-resolving threads when you fix flagged issues
- **Manual**: reviews start only when someone [comments `@claude review` or `@claude review once` on a PR](#manually-trigger-reviews); `@claude review` also subscribes the PR to reviews on subsequent pushes

Reviewing on every push runs the most reviews and costs the most. Manual mode is useful for high-traffic repos where you want to opt specific PRs into review, or to only start reviewing your PRs once they’re ready.

The repositories table also shows the average cost per review for each repo based on recent activity. Use the row actions menu to turn Code Review on or off per repository, or to remove a repository entirely. To verify setup, open a test PR. If you chose an automatic trigger, a check run named **Claude Code Review** appears within a few minutes. If you chose Manual, comment `@claude review` on the PR to start the first review. If no check run appears, confirm the repository is listed in your admin settings and the Claude GitHub App has access to it.


Manually trigger reviews

Two comment commands start a review on demand. Both work regardless of the repository’s configured trigger, so you can use them to opt specific PRs into review in Manual mode or to get an immediate re-review in other modes.

| Command               | What it does                                                                  |
|:----------------------|:------------------------------------------------------------------------------|
| `@claude review`      | Starts a review and subscribes the PR to push-triggered reviews going forward |
| `@claude review once` | Starts a single review without subscribing the PR to future pushes            |

Use `@claude review once` when you want feedback on the current state of a PR but don’t want every subsequent push to incur a review. This is useful for long-running PRs with frequent pushes, or when you want a one-off second opinion without changing the PR’s review behavior. For either command to trigger a review:

- Post it as a top-level PR comment, not an inline comment on a diff line
- Put the command at the start of the comment, with `once` on the same line if you’re using the one-shot form
- You must have owner, member, or collaborator access to the repository
- The PR must be open

Unlike automatic triggers, manual triggers run on draft PRs, since an explicit request signals you want the review now regardless of draft status. If a review is already running on that PR, the request is queued until the in-progress review completes. You can monitor progress via the check run on the PR.


Customize reviews

Code Review reads two files from your repository to guide what it flags. They differ in how strongly they influence the review:

- **`CLAUDE.md`**: shared project instructions that Claude Code uses for all tasks, not just reviews. Code Review reads it as project context and flags newly introduced violations as nits.
- **`REVIEW.md`**: review-only instructions, injected directly into every agent in the review pipeline as highest priority. Use it to change what gets flagged, at what severity, and how findings are reported.


CLAUDE.md

Code Review reads your repository’s `CLAUDE.md` files and treats newly introduced violations as [nit-level](#severity-levels) findings. This works bidirectionally: if your PR changes code in a way that makes a `CLAUDE.md` statement outdated, Claude flags that the docs need updating too. Claude reads `CLAUDE.md` files at every level of your directory hierarchy, so rules in a subdirectory’s `CLAUDE.md` apply only to files under that path. See the [memory documentation](/docs/en/memory) for more on how `CLAUDE.md` works. For review-specific guidance that you don’t want applied to general Claude Code sessions, use [`REVIEW.md`](#review-md) instead.


REVIEW.md

`REVIEW.md` is a file at your repository root that overrides how Code Review behaves on your repo. Its contents are injected into the system prompt of every agent in the review pipeline as the highest-priority instruction block, taking precedence over the default review guidance. Because it’s pasted verbatim, `REVIEW.md` is plain instructions: [`@` import syntax](/docs/en/memory#import-additional-files) is not expanded, and referenced files are not read into the prompt. Put the rules you want enforced directly in the file.


What you can tune

`REVIEW.md` is freeform markdown, so anything you can express as a review instruction is in scope. The patterns below have the most impact in practice. **Severity**: redefine what 🔴 Important means for your repo. The default calibration targets production code; a docs repo, a config repo, or a prototype might want a much narrower definition. State explicitly which classes of finding are Important and which are Nit at most. You can also escalate in the other direction, for example treating any `CLAUDE.md` violation as Important rather than the default nit. **Nit volume**: cap how many 🟡 Nit comments a single review posts. Prose and config files can be polished forever. A cap like “report at most five nits, mention the rest as a count in the summary” keeps reviews actionable. **Skip rules**: list paths, branch patterns, and finding categories where Claude should post no findings. Common candidates are generated code, lockfiles, vendored dependencies, and machine-authored branches, along with anything your CI already enforces like linting or spellcheck. For paths that warrant some review but not full scrutiny, set a higher bar instead of skipping entirely: “in `scripts/`, only report if near-certain and severe.” **Repo-specific checks**: add rules you want flagged on every PR, like “new API routes must have an integration test.” Because `REVIEW.md` is injected as highest priority, these land more reliably than the same rules in a long `CLAUDE.md`. **Verification bar**: require evidence before a class of finding is posted. For example, “behavior claims need a `file:line` citation in the source, not an inference from naming” cuts false positives that would otherwise cost the author a round trip. **Re-review convergence**: tell Claude how to behave when a PR has already been reviewed. A rule like “after the first review, suppress new nits and post Important findings only” stops a one-line fix from reaching round seven on style alone. **Summary shape**: ask for the review body to open with a one-line tally such as `2 factual, 4 style`, and to lead with “no factual issues” when that’s the case. The author wants to know the shape of the work before the details.


Example

This `REVIEW.md` recalibrates severity for a backend service, caps nits, skips generated files, and adds repo-specific checks.

```python
# Review instructions

## What Important means here

Reserve Important for findings that would break behavior, leak data,
or block a rollback: incorrect logic, unscoped database queries, PII
in logs or error messages, and migrations that aren't backward
compatible. Style, naming, and refactoring suggestions are Nit at
most.

## Cap the nits

Report at most five Nits per review. If you found more, say "plus N
similar items" in the summary instead of posting them inline. If
everything you found is a Nit, lead the summary with "No blocking
issues."

## Do not report

- Anything CI already enforces: lint, formatting, type errors
- Generated files under `src/gen/` and any `*.lock` file
- Test-only code that intentionally violates production rules

## Always check

- New API routes have an integration test
- Log lines don't include email addresses, user IDs, or request bodies
- Database queries are scoped to the caller's tenant
```


Keep it focused

Length has a cost: a long `REVIEW.md` dilutes the rules that matter most. Keep it to instructions that change review behavior, and leave general project context in `CLAUDE.md`.


View usage

Go to [claude.ai/analytics/code-review](https://claude.ai/analytics/code-review) to see Code Review activity across your organization. The dashboard shows:

| Section              | What it shows                                                                            |
|:---------------------|:-----------------------------------------------------------------------------------------|
| PRs reviewed         | Daily count of pull requests reviewed over the selected time range                       |
| Cost weekly          | Weekly spend on Code Review                                                              |
| Feedback             | Count of review comments that were auto-resolved because a developer addressed the issue |
| Repository breakdown | Per-repo counts of PRs reviewed and comments resolved                                    |

The repositories table in admin settings also shows average cost per review for each repo. Dashboard cost figures are estimates for monitoring activity; for invoice-accurate spend, refer to your Anthropic bill.


Pricing

Code Review is billed based on token usage. Each review averages \$15-25 in cost, scaling with PR size, codebase complexity, and how many issues require verification. Code Review usage is billed separately through [usage credits](../17-Billing-Plans/extra-usage-for-paid-claude-plans.md) and does not count against your plan’s included usage. The review trigger you choose affects total cost:

- **Once after PR creation**: runs once per PR
- **After every push**: runs on each push, multiplying cost by the number of pushes
- **Manual**: no reviews until someone comments `@claude review` on a PR

In any mode, commenting `@claude review` [opts the PR into push-triggered reviews](#manually-trigger-reviews), so additional cost accrues per push after that comment. To run a single review without subscribing to future pushes, comment `@claude review once` instead. Costs appear on your Anthropic bill regardless of whether your organization uses Amazon Bedrock or Google Vertex AI for other Claude Code features. To set a monthly spend cap 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. Monitor spend via the weekly cost chart in [analytics](#view-usage) or the per-repo average cost column in admin settings.


Troubleshooting

Review runs are best-effort. A failed run never blocks your PR, but it also doesn’t retry on its own. This section covers how to recover from a failed run and where to look when the check run reports issues you can’t find.


Retrigger a failed or timed-out review

When the review infrastructure hits an internal error or exceeds its time limit, the check run completes with a title of **Code review encountered an error** or **Code review timed out**. The conclusion is still neutral, so nothing blocks your merge, but no findings are posted. To run the review again, comment `@claude review once` on the PR. This starts a fresh review without subscribing the PR to future pushes. If the PR is already subscribed to push-triggered reviews, pushing a new commit also starts a new review. The **Re-run** button in GitHub’s Checks tab does not retrigger Code Review. Use the comment command or a new push instead.


Review didn’t run and the PR shows a spend-cap message

When your organization’s monthly spend cap is reached, Code Review posts a single comment on the PR explaining that the review was skipped. Reviews resume automatically at the start of the next billing period, or immediately when an admin raises the cap at [claude.ai/admin-settings/usage](https://claude.ai/admin-settings/usage).


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:

- **Check run Details**: click **Details** next to the Claude Code Review check in the Checks tab. The severity table lists every finding with its file, line, and summary regardless of whether the inline comment was accepted.
- **Files changed annotations**: open the **Files changed** tab on the PR. Findings render as annotations attached directly to the diff lines, separate from review comments.
- **Review body**: if you pushed to the PR while a review was running, some findings may reference lines that no longer exist in the current diff. Those appear under an **Additional findings** heading in the review body text rather than as inline comments.


Related resources

Code Review is designed to work alongside the rest of Claude Code. If you want to run reviews locally before opening a PR, need a self-hosted setup, or want to go deeper on how `CLAUDE.md` shapes Claude’s behavior across tools, these pages are good next stops:

- [Plugins](/docs/en/discover-plugins): browse the plugin marketplace, including a `code-review` plugin for running on-demand reviews locally before pushing
- [GitHub Actions](/docs/en/github-actions): run Claude in your own GitHub Actions workflows for custom automation beyond code review
- [GitLab CI/CD](/docs/en/gitlab-ci-cd): self-hosted Claude integration for GitLab pipelines
- [Memory](/docs/en/memory): how `CLAUDE.md` files work across Claude Code
- [Analytics](/docs/en/analytics): track Claude Code usage beyond code review


---
## code-review.md

# Code Review

Set up automated PR reviews that catch logic errors, security vulnerabilities, and regressions using multi-agent analysis of your full codebase.

> Code Review is in research preview, available for Team and Enterprise subscriptions. Not available for organizations with Zero Data Retention enabled.

Code Review analyzes your GitHub pull requests and posts findings as inline comments on the lines of code where it found issues. A fleet of specialized agents examine the code changes in the context of your full codebase, looking for logic errors, security vulnerabilities, broken edge cases, and subtle regressions.

Findings are tagged by severity and don't approve or block your PR, so existing review workflows stay intact.

## How reviews work

Reviews trigger when a PR opens, on every push, or when manually requested. When a review runs, multiple agents analyze the diff and surrounding code in parallel on Anthropic infrastructure. Results are deduplicated, ranked by severity, and posted as inline comments.

### Severity levels

| Marker | Severity     | Meaning                                                |
| :----- | :----------- | :----------------------------------------------------- |
| 🔴     | Important    | A bug that should be fixed before merging              |
| 🟡     | Nit          | A minor issue, worth fixing but not blocking           |
| 🟣     | Pre-existing | A bug in the codebase not introduced by this PR        |

### Rate and reply to findings

Each comment arrives with 👍 and 👎 already attached for one-click rating. Anthropic collects reactions after merge to tune the reviewer. Replying to an inline comment does not prompt Claude to respond.

### Check run output

Each review populates the **Claude Code Review** check run. The check run always completes with a neutral conclusion so it never blocks merging.

Machine-readable severity data:

```bash
gh api repos/OWNER/REPO/check-runs/CHECK_RUN_ID \
  --jq '.output.text | split("bughunter-severity: ")[1] | split(" -->")[0] | fromjson'
```

## Set up Code Review

1. Go to claude.ai/admin-settings/claude-code → Code Review section
2. Click **Setup** → Install Claude GitHub App
3. Select repositories to enable
4. Set review triggers per repo:
   - **Once after PR creation**: review runs once when PR opens
   - **After every push**: review runs on every push
   - **Manual**: reviews start only with `@claude review`

## Manually trigger reviews

| Command               | What it does                                                    |
| :-------------------- | :-------------------------------------------------------------- |
| `@claude review`      | Starts review and subscribes PR to push-triggered reviews       |
| `@claude review once` | Starts a single review without subscribing to future pushes     |

Post as a top-level PR comment. Requires owner, member, or collaborator access.

## Customize reviews

### CLAUDE.md

Code Review reads your repository's `CLAUDE.md` files and treats newly-introduced violations as nit-level findings.

### REVIEW.md

Add a `REVIEW.md` file to your repository root for review-specific rules:

```markdown
# Code Review Guidelines

## Always check
- New API endpoints have corresponding integration tests
- Database migrations are backward-compatible
- Error messages don't leak internal details to users

## Skip
- Generated files under `src/gen/`
- Formatting-only changes in `*.lock` files
```

## Pricing

Each review averages $15-25 in cost, scaling with PR size and complexity. Billed separately through extra usage.

## Troubleshooting

### Retrigger a failed review

Comment `@claude review once` on the PR. The **Re-run** button in GitHub's Checks tab does not retrigger Code Review.

### Find issues not showing as inline comments

Check: Details in the check run, Files changed annotations, or Review body under "Additional findings".

## See Also

- [GitHub Actions](claude-code-github-actions-claude-code-docs-0d633fbd8a.md)
- [GitLab CI/CD](claude-code-gitlab-ci-cd-claude-code-docs-fbcd915fee.md)
- [Memory](how-claude-remembers-your-project-claude-code-docs-f1c064262d.md) — How `CLAUDE.md` files work


---
## commands-976c970187.md

> ## Documentation Index
> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Commands

> Complete reference for commands available in Claude Code, including built-in commands and bundled skills.

Commands control Claude Code from inside a session. They provide a quick way to switch models, manage permissions, clear context, run a workflow, and more.

Type `/` to see every command available to you, or type `/` followed by letters to filter.

The table below lists all the commands included in Claude Code. Entries marked **[Skill](/en/skills#bundled-skills)** are bundled skills. They use the same mechanism as skills you write yourself: a prompt handed to Claude, which Claude can also invoke automatically when relevant. Everything else is a built-in command whose behavior is coded into the CLI. To add your own commands, see [skills](../08-Plugins-Skills/extend-claude-with-skills-claude-code-docs.md).

Not every command appears for every user. Availability depends on your platform, plan, and environment. For example, `/desktop` only shows on macOS and Windows, and `/upgrade` only shows on Pro and Max plans.

In the table below, `<arg>` indicates a required argument and `[arg]` indicates an optional one.

| Command                                         | Purpose                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| :---------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `/add-dir <path>`                               | Add a working directory for file access during the current session. Most `.claude/` configuration is [not discovered](/en/permissions#additional-directories-grant-file-access-not-configuration) from the added directory. You can later resume the session from the added directory with `--continue` or `--resume`                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `/agents`                                       | Manage [agent](../09-Agents-Patterns/create-custom-subagents-claude-code-docs-7dc93e85c0.md) configurations                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `/autofix-pr [prompt]`                          | Spawn a [Claude Code on the web](/en/claude-code-on-the-web#auto-fix-pull-requests) session that watches the current branch's PR and pushes fixes when CI fails or reviewers leave comments. Detects the open PR from your checked-out branch with `gh pr view`; to watch a different PR, check out its branch first. By default the remote session is told to fix every CI failure and review comment; pass a prompt to give it different instructions, for example `/autofix-pr only fix lint and type errors`. Requires the `gh` CLI and access to [Claude Code on the web](/en/claude-code-on-the-web#who-can-use-claude-code-on-the-web)                                                                                          |
| `/batch <instruction>`                          | **[Skill](/en/skills#bundled-skills).** Orchestrate large-scale changes across a codebase in parallel. Researches the codebase, decomposes the work into 5 to 30 independent units, and presents a plan. Once approved, spawns one background agent per unit in an isolated [git worktree](/en/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees). Each agent implements its unit, runs tests, and opens a pull request. Requires a git repository. Example: `/batch migrate src/ from Solid to React`                                                                                                                                                                                                             |
| `/branch [name]`                                | Create a branch of the current conversation at this point. Switches you into the branch and preserves the original, which you can return to with `/resume`. Alias: `/fork`. When [`CLAUDE_CODE_FORK_SUBAGENT`](env-vars-5c624d392b.md) is set, `/fork` instead spawns a [forked subagent](/en/sub-agents#fork-the-current-conversation) and is no longer an alias for this command                                                                                                                                                                                                                                                                                                                                                               |
| `/btw <question>`                               | Ask a quick [side question](/en/interactive-mode#side-questions-with-%2Fbtw) without adding to the conversation                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `/chrome`                                       | Configure [Claude in Chrome](../03-IDE-Integrations/use-claude-code-with-chrome-beta-claude-code-docs-4f2f5a5a96.md) settings                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `/claude-api [migrate\|managed-agents-onboard]` | **[Skill](/en/skills#bundled-skills).** Load Claude API reference material for your project's language (Python, TypeScript, Java, Go, Ruby, C#, PHP, or cURL) and Managed Agents reference. Covers tool use, streaming, batches, structured outputs, and common pitfalls. Also activates automatically when your code imports `anthropic` or `@anthropic-ai/sdk`. Run `/claude-api migrate` to upgrade existing Claude API code to a newer model: Claude asks which files to scan and which model to target, then updates model IDs, thinking configuration, and other parameters that changed between versions. Run `/claude-api managed-agents-onboard` for an interactive walkthrough that creates a new Managed Agent from scratch |
| `/clear`                                        | Start a new conversation with empty context. The previous conversation stays available in `/resume`. To free up context while continuing the same conversation, use `/compact` instead. Aliases: `/reset`, `/new`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `/color [color\|default]`                       | Set the prompt bar color for the current session. Available colors: `red`, `blue`, `green`, `yellow`, `purple`, `orange`, `pink`, `cyan`. Use `default` to reset. When [Remote Control](continue-local-sessions-from-any-device-with-remote-control-claude-code-docs-c1c03fd914.md) is connected, the color syncs to claude.ai/code                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `/compact [instructions]`                       | Free up context by summarizing the conversation so far. Optionally pass focus instructions for the summary. See [how compaction handles rules, skills, and memory files](/en/context-window#what-survives-compaction)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `/config`                                       | Open the [Settings](claude-code-settings-claude-code-docs-d4420b4b52.md) interface to adjust theme, model, [output style](output-styles-claude-code-docs-c315eeed32.md), and other preferences. Alias: `/settings`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `/context`                                      | Visualize current context usage as a colored grid. Shows optimization suggestions for context-heavy tools, memory bloat, and capacity warnings                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `/copy [N]`                                     | Copy the last assistant response to clipboard. Pass a number `N` to copy the Nth-latest response: `/copy 2` copies the second-to-last. When code blocks are present, shows an interactive picker to select individual blocks or the full response. Press `w` in the picker to write the selection to a file instead of the clipboard, which is useful over SSH                                                                                                                                                                                                                                                                                                                                                                         |
| `/cost`                                         | Alias for `/usage`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `/debug [description]`                          | **[Skill](/en/skills#bundled-skills).** Enable debug logging for the current session and troubleshoot issues by reading the session debug log. Debug logging is off by default unless you started with `claude --debug`, so running `/debug` mid-session starts capturing logs from that point forward. Optionally describe the issue to focus the analysis                                                                                                                                                                                                                                                                                                                                                                            |
| `/desktop`                                      | Continue the current session in the Claude Code Desktop app. macOS and Windows only. Alias: `/app`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `/diff`                                         | Open an interactive diff viewer showing uncommitted changes and per-turn diffs. Use left/right arrows to switch between the current git diff and individual Claude turns, and up/down to browse files                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `/doctor`                                       | Diagnose and verify your Claude Code installation and settings. Results show with status icons. Press `f` to have Claude fix any reported issues                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `/effort [level\|auto]`                         | Set the model [effort level](/en/model-config#adjust-effort-level). Accepts `low`, `medium`, `high`, `xhigh`, or `max`; available levels depend on the model and `max` is session-only. `auto` resets to the model default. Without an argument, opens an interactive slider; use left and right arrows to pick a level and `Enter` to apply. Takes effect immediately without waiting for the current response to finish                                                                                                                                                                                                                                                                                                              |
| `/exit`                                         | Exit the CLI. Alias: `/quit`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `/export [filename]`                            | Export the current conversation as plain text. With a filename, writes directly to that file. Without, opens a dialog to copy to clipboard or save to a file                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `/extra-usage`                                  | Configure extra usage to keep working when rate limits are hit                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `/fast [on\|off]`                               | Toggle [fast mode](fast-mode-847ef2d690.md) on or off                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `/feedback [report]`                            | Submit feedback about Claude Code. Alias: `/bug`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `/fewer-permission-prompts`                     | **[Skill](/en/skills#bundled-skills).** Scan your transcripts for common read-only Bash and MCP tool calls, then add a prioritized allowlist to project `.claude/settings.json` to reduce permission prompts                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `/focus`                                        | Toggle the focus view, which shows only your last prompt, a one-line tool-call summary with edit diffstats, and the final response. The selection persists across sessions. Only available in [fullscreen rendering](fullscreen-34ba4558ad.md)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `/heapdump`                                     | Write a JavaScript heap snapshot and a memory breakdown to `~/Desktop` for diagnosing high memory usage. See [troubleshooting](/en/troubleshooting#high-cpu-or-memory-usage)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `/help`                                         | Show help and available commands                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `/hooks`                                        | View [hook](../07-Hooks/hooks-9168ed62a4.md) configurations for tool events                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `/ide`                                          | Manage IDE integrations and show status                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `/init`                                         | Initialize project with a `CLAUDE.md` guide. Set `CLAUDE_CODE_NEW_INIT=1` for an interactive flow that also walks through skills, hooks, and personal memory files                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `/insights`                                     | Generate a report analyzing your Claude Code sessions, including project areas, interaction patterns, and friction points                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `/install-github-app`                           | Set up the [Claude GitHub Actions](claude-code-github-actions-claude-code-docs-0d633fbd8a.md) app for a repository. Walks you through selecting a repo and configuring the integration                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `/install-slack-app`                            | Install the Claude Slack app. Opens a browser to complete the OAuth flow                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `/keybindings`                                  | Open or create your keybindings configuration file                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `/login`                                        | Sign in to your Anthropic account                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `/logout`                                       | Sign out from your Anthropic account                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `/loop [interval] [prompt]`                     | **[Skill](/en/skills#bundled-skills).** Run a prompt repeatedly while the session stays open. Omit the interval and Claude self-paces between iterations. Omit the prompt and Claude runs an autonomous maintenance check, or the prompt in `.claude/loop.md` if present. Example: `/loop 5m check if the deploy finished`. See [Run prompts on a schedule](run-prompts-on-a-schedule-claude-code-docs.md). Alias: `/proactive`                                                                                                                                                                                                                                                                                                                                  |
| `/mcp`                                          | Manage MCP server connections and OAuth authentication                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `/memory`                                       | Edit `CLAUDE.md` memory files, enable or disable [auto-memory](/en/memory#auto-memory), and view auto-memory entries                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `/mobile`                                       | Show QR code to download the Claude mobile app. Aliases: `/ios`, `/android`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `/model [model]`                                | Select or change the AI model. For models that support it, use left/right arrows to [adjust effort level](/en/model-config#adjust-effort-level). With no argument, opens a picker that asks for confirmation when the conversation has prior output, since the next response re-reads the full history without cached context. Once confirmed, the change applies without waiting for the current response to finish                                                                                                                                                                                                                                                                                                                   |
| `/passes`                                       | Share a free week of Claude Code with friends. Only visible if your account is eligible                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `/permissions`                                  | Manage allow, ask, and deny rules for tool permissions. Opens an interactive dialog where you can view rules by scope, add or remove rules, manage working directories, and review [recent auto mode denials](/en/auto-mode-config#review-denials). Alias: `/allowed-tools`                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `/plan [description]`                           | Enter plan mode directly from the prompt. Pass an optional description to enter plan mode and immediately start with that task, for example `/plan fix the auth bug`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `/plugin`                                       | Manage Claude Code [plugins](../08-Plugins-Skills/create-plugins-claude-code-docs.md)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `/powerup`                                      | Discover Claude Code features through quick interactive lessons with animated demos                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `/pr-comments [PR]`                             | {/* max-version: 2.1.90 */}Removed in v2.1.91. Ask Claude directly to view pull request comments instead. On earlier versions, fetches and displays comments from a GitHub pull request; automatically detects the PR for the current branch, or pass a PR URL or number. Requires the `gh` CLI                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `/privacy-settings`                             | View and update your privacy settings. Only available for Pro and Max plan subscribers                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `/recap`                                        | Generate a one-line summary of the current session on demand. See [Session recap](/en/interactive-mode#session-recap) for the automatic recap that appears after you've been away                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `/release-notes`                                | View the changelog in an interactive version picker. Select a specific version to see its release notes, or choose to show all versions                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `/reload-plugins`                               | Reload all active [plugins](../08-Plugins-Skills/create-plugins-claude-code-docs.md) to apply pending changes without restarting. Reports counts for each reloaded component and flags any load errors                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `/remote-control`                               | Make this session available for [remote control](continue-local-sessions-from-any-device-with-remote-control-claude-code-docs-c1c03fd914.md) from claude.ai. Alias: `/rc`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `/remote-env`                                   | Configure the default remote environment for [web sessions started with `--remote`](/en/claude-code-on-the-web#configure-your-environment)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `/rename [name]`                                | Rename the current session and show the name on the prompt bar. Without a name, auto-generates one from conversation history                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `/resume [session]`                             | Resume a conversation by ID or name, or open the session picker. Alias: `/continue`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `/review [PR]`                                  | Review a pull request locally in your current session. For a deeper cloud-based review, see [`/ultrareview`](ultrareview-78bb971406.md)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `/rewind`                                       | Rewind the conversation and/or code to a previous point, or summarize from a selected message. See [checkpointing](checkpointing-94f7cd24eb.md). Aliases: `/checkpoint`, `/undo`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `/sandbox`                                      | Toggle [sandbox mode](../22-Safety-Policy/sandboxing-claude-code-docs-5f97cd27c4.md). Available on supported platforms only                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `/schedule [description]`                       | Create, update, list, or run [routines](routines-3111c7bd3a.md). Claude walks you through the setup conversationally. Alias: `/routines`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `/security-review`                              | Analyze pending changes on the current branch for security vulnerabilities. Reviews the git diff and identifies risks like injection, auth issues, and data exposure                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `/setup-bedrock`                                | Configure [Amazon Bedrock](../20-Models/claude-code-on-amazon-bedrock-claude-code-docs-435e92efd0.md) authentication, region, and model pins through an interactive wizard. Only visible when `CLAUDE_CODE_USE_BEDROCK=1` is set. First-time Bedrock users can also access this wizard from the login screen                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `/setup-vertex`                                 | Configure [Google Vertex AI](../20-Models/claude-code-on-google-vertex-ai-claude-code-docs-2acd050a7a.md) authentication, project, region, and model pins through an interactive wizard. Only visible when `CLAUDE_CODE_USE_VERTEX=1` is set. First-time Vertex AI users can also access this wizard from the login screen                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `/simplify [focus]`                             | **[Skill](/en/skills#bundled-skills).** Review your recently changed files for code reuse, quality, and efficiency issues, then fix them. Spawns three review agents in parallel, aggregates their findings, and applies fixes. Pass text to focus on specific concerns: `/simplify focus on memory efficiency`                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `/skills`                                       | List available [skills](../08-Plugins-Skills/extend-claude-with-skills-claude-code-docs.md). Press `t` to sort by token count                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `/stats`                                        | Alias for `/usage`. Opens on the Stats tab                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `/status`                                       | Open the Settings interface (Status tab) showing version, model, account, and connectivity. Works while Claude is responding, without waiting for the current response to finish                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `/statusline`                                   | Configure Claude Code's [status line](customize-your-status-line-claude-code-docs-8a9fc80be1.md). Describe what you want, or run without arguments to auto-configure from your shell prompt                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `/stickers`                                     | Order Claude Code stickers                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `/tasks`                                        | List and manage background tasks. Also available as `/bashes`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `/team-onboarding`                              | Generate a team onboarding guide from your Claude Code usage history. Claude analyzes your sessions, commands, and MCP server usage from the past 30 days and produces a markdown guide a teammate can paste as a first message to get set up quickly                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `/teleport`                                     | Pull a [Claude Code on the web](/en/claude-code-on-the-web#from-web-to-terminal) session into this terminal: opens a picker, then fetches the branch and conversation. Also available as `/tp`. Requires a claude.ai subscription                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `/terminal-setup`                               | Configure terminal keybindings for Shift+Enter and other shortcuts. Only visible in terminals that need it, like VS Code, Cursor, Windsurf, Alacritty, or Zed                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `/theme`                                        | Change the color theme. Includes an `auto` option that matches your terminal's light or dark background, light and dark variants, colorblind-accessible (daltonized) themes, ANSI themes that use your terminal's color palette, and any [custom themes](/en/terminal-config#create-a-custom-theme) from `~/.claude/themes/` or plugins. Select **New custom theme…** to create one                                                                                                                                                                                                                                                                                                                                                    |
| `/tui [default\|fullscreen]`                    | Set the terminal UI renderer and relaunch into it with your conversation intact. `fullscreen` enables the [flicker-free alt-screen renderer](fullscreen-34ba4558ad.md). With no argument, prints the active renderer                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `/ultraplan <prompt>`                           | Draft a plan in an [ultraplan](ultraplan-14dfb476fe.md) session, review it in your browser, then execute remotely or send it back to your terminal                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `/ultrareview [PR]`                             | Run a deep, multi-agent code review in a cloud sandbox with [ultrareview](ultrareview-78bb971406.md). Includes 3 free runs on Pro and Max through May 5, 2026, then requires [extra usage](../17-Billing-Plans/extra-usage-for-paid-claude-plans.md)                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `/upgrade`                                      | Open the upgrade page to switch to a higher plan tier                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `/usage`                                        | Show session cost, plan usage limits, and activity stats. See the [cost tracking guide](/en/costs#using-the-%2Fusage-command) for subscription-specific details. `/cost` and `/stats` are aliases                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `/vim`                                          | {/* max-version: 2.1.91 */}Removed in v2.1.92. To toggle between Vim and Normal editing modes, use `/config` → Editor mode                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `/voice [hold\|tap\|off]`                       | Toggle [voice dictation](voice-dictation-0555c38d5c.md), or enable it in a specific mode. Requires a Claude.ai account                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `/web-setup`                                    | Connect your GitHub account to [Claude Code on the web](/en/web-quickstart#connect-from-your-terminal) using your local `gh` CLI credentials. `/schedule` prompts for this automatically if GitHub isn't connected                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |

## MCP prompts

MCP servers can expose prompts that appear as commands. These use the format `/mcp__<server>__<prompt>` and are dynamically discovered from connected servers. See [MCP prompts](/en/mcp#use-mcp-prompts-as-commands) for details.

## See also

* [Skills](../08-Plugins-Skills/extend-claude-with-skills-claude-code-docs.md): create your own commands
* [Interactive mode](interactive-mode-c5c4efb32c.md): keyboard shortcuts, Vim mode, and command history
* [CLI reference](cli-reference-7bb98e3312.md): launch-time flags


---
## commands-claude-code-docs-1ce67529b6.md

# Commands


Complete reference for commands available in Claude Code, including built-in commands and bundled skills.


> ## Documentation Index
>
> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt>
>
> Use this file to discover all available pages before exploring further.

Commands control Claude Code from inside a session. They provide a quick way to switch models, manage permissions, clear context, run a workflow, and more. Type `/` to see every command available to you, or type `/` followed by letters to filter. A command is only recognized at the start of your message. Text that follows the command name is passed to it as arguments.


Commands across a typical workflow

Most commands are useful at a specific point in a session, from setting up a project to shipping a change. **First session in a repo.** Run `/init` to generate a starter `CLAUDE.md`, then `/memory` to refine it. Use `/mcp` and `/agents` to set up any servers or subagents the project needs, and `/permissions` to set the approval rules you want. **During a task.** `/plan` switches into plan mode before a large change. `/model` and `/effort` adjust how much reasoning you’re spending. When the conversation gets long, `/context` shows where the window is going and `/compact` summarizes it down; use `/btw` for a quick aside that shouldn’t bloat history. **Running work in parallel.** `/agents` opens the manager for the [subagents](/docs/en/sub-agents) Claude can delegate side tasks to, and `/tasks` lists what’s running in the background of the current session. `/background` detaches the whole session to keep running as a [background agent](/docs/en/agent-view) and frees your terminal. For a large change that spans the codebase, `/batch` decomposes it into independent units and runs each in its own [worktree](/docs/en/worktrees). See [Run agents in parallel](/docs/en/agents) for how these approaches relate. **Before you ship.** `/diff` shows what changed, `/simplify` reviews recent files and applies quality and efficiency fixes, and `/review` or `/security-review` give a deeper read-only pass. **Between sessions.** `/clear` starts fresh on a new task while keeping project memory. `/resume` and `/branch` let you return to or fork an earlier conversation. `/teleport` pulls a web session into this terminal, and `/remote-control` lets you continue this local session from another device. **When something is wrong.** `/rewind` rolls code and conversation back to a checkpoint, or summarizes part of the conversation. `/doctor` and `/debug` diagnose install and runtime issues, and `/feedback` reports a bug with session context attached.


All commands

The table below lists all the commands included in Claude Code. Entries marked **[Skill](/docs/en/skills#bundled-skills)** are bundled skills. They use the same mechanism as skills you write yourself: a prompt handed to Claude, which Claude can also invoke automatically when relevant. Everything else is a built-in command whose behavior is coded into the CLI. 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.

Not every command appears for every user. Availability depends on your platform, plan, and environment. For example, `/desktop` only shows on macOS and Windows, and `/upgrade` only shows on Pro and Max plans.

| Command                                        | Purpose                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
|:-----------------------------------------------|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `/add-dir <path>`                              | Add a working directory for file access during the current session. Most `.claude/` configuration is [not discovered](/docs/en/permissions#additional-directories-grant-file-access-not-configuration) from the added directory. You can later resume the session from the added directory with `--continue` or `--resume`                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `/agents`                                      | Manage [agent](/docs/en/sub-agents) configurations                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `/autofix-pr [prompt]`                         | Spawn a [Claude Code on the web](/docs/en/claude-code-on-the-web#auto-fix-pull-requests) session that watches the current branch’s PR and pushes fixes when CI fails or reviewers leave comments. Detects the open PR from your checked-out branch with `gh pr view`; to watch a different PR, check out its branch first. By default the remote session is told to fix every CI failure and review comment; pass a prompt to give it different instructions, for example `/autofix-pr only fix lint and type errors`. Requires the `gh` CLI and access to [Claude Code on the web](/docs/en/claude-code-on-the-web#who-can-use-claude-code-on-the-web)                                                                                     |
| `/background [prompt]`                         | Detach the current session to run as a [background agent](/docs/en/agent-view) and free this terminal. Pass a prompt to send one more instruction before detaching. Monitor the session with `claude agents`. Alias: `/bg`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `/batch <instruction>`                         | **[Skill](/docs/en/skills#bundled-skills).** Orchestrate large-scale changes across a codebase in parallel. Researches the codebase, decomposes the work into 5 to 30 independent units, and presents a plan. Once approved, spawns one [background subagent](/docs/en/sub-agents#run-subagents-in-foreground-or-background) per unit in an isolated [git worktree](/docs/en/worktrees). Each subagent implements its unit, runs tests, and opens a pull request. Requires a git repository. Example: `/batch migrate src/ from Solid to React`                                                                                                                                                                                             |
| `/branch [name]`                               | Create a branch of the current conversation at this point. Switches you into the branch and preserves the original, which you can return to with `/resume`. Alias: `/fork`. When [`CLAUDE_CODE_FORK_SUBAGENT`](/docs/en/env-vars) is set, `/fork` instead spawns a [forked subagent](/docs/en/sub-agents#fork-the-current-conversation) and is no longer an alias for this command                                                                                                                                                                                                                                                                                                                                                          |
| `/btw <question>`                              | Ask a quick [side question](/docs/en/interactive-mode#side-questions-with-%2Fbtw) without adding to the conversation                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `/chrome`                                      | Configure [Claude in Chrome](/docs/en/chrome) settings                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `/claude-api [migrate|managed-agents-onboard]` | **[Skill](/docs/en/skills#bundled-skills).** Load Claude API reference material for your project’s language (Python, TypeScript, Java, Go, Ruby, C#, PHP, or cURL) and Managed Agents reference. Covers tool use, streaming, batches, structured outputs, and common pitfalls. Also activates automatically when your code imports `anthropic` or `@anthropic-ai/sdk`. Run `/claude-api migrate` to upgrade existing Claude API code to a newer model: Claude asks which files to scan and which model to target, then updates model IDs, thinking configuration, and other parameters that changed between versions. Run `/claude-api managed-agents-onboard` for an interactive walkthrough that creates a new Managed Agent from scratch |
| `/clear [name]`                                | Start a new conversation with empty context. The previous conversation stays available in `/resume`. Pass a name to label the previous conversation in the `/resume` picker. To free up context while continuing the same conversation, use `/compact` instead. Aliases: `/reset`, `/new`                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `/color [color|default]`                       | Set the prompt bar color for the current session. Available colors: `red`, `blue`, `green`, `yellow`, `purple`, `orange`, `pink`, `cyan`. Use `default` to reset, or run with no argument to pick a random color. When [Remote Control](/docs/en/remote-control) is connected, the color syncs to claude.ai/code                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `/compact [instructions]`                      | Free up context by summarizing the conversation so far. Optionally pass focus instructions for the summary. See [how compaction handles rules, skills, and memory files](/docs/en/context-window#what-survives-compaction)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `/config`                                      | Open the [Settings](/docs/en/settings) interface to adjust theme, model, [output style](/docs/en/output-styles), and other preferences. Alias: `/settings`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `/context [all]`                               | Visualize current context usage as a colored grid. Shows optimization suggestions for context-heavy tools, memory bloat, and capacity warnings. In [fullscreen mode](/docs/en/fullscreen) the per-item breakdown is collapsed to keep the grid visible. Pass `all` to expand it                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `/copy [N]`                                    | Copy the last assistant response to clipboard. Pass a number `N` to copy the Nth-latest response: `/copy 2` copies the second-to-last. When code blocks are present, shows an interactive picker to select individual blocks or the full response. Press `w` in the picker to write the selection to a file instead of the clipboard, which is useful over SSH                                                                                                                                                                                                                                                                                                                                                                              |
| `/cost`                                        | Alias for `/usage`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `/debug [description]`                         | **[Skill](/docs/en/skills#bundled-skills).** Enable debug logging for the current session and troubleshoot issues by reading the session debug log. Debug logging is off by default unless you started with `claude --debug`, so running `/debug` mid-session starts capturing logs from that point forward. Optionally describe the issue to focus the analysis                                                                                                                                                                                                                                                                                                                                                                            |
| `/desktop`                                     | Continue the current session in the Claude Code Desktop app. macOS and Windows only. Alias: `/app`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `/diff`                                        | Open an interactive diff viewer showing uncommitted changes and per-turn diffs. Use left/right arrows to switch between the current git diff and individual Claude turns, and up/down to browse files                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `/doctor`                                      | Diagnose and verify your Claude Code installation and settings. Results show with status icons. Press `f` to have Claude fix any reported issues                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `/effort [level|auto]`                         | Set the model [effort level](/docs/en/model-config#adjust-effort-level). Accepts `low`, `medium`, `high`, `xhigh`, or `max`; available levels depend on the model and `max` is session-only. `auto` resets to the model default. Without an argument, opens an interactive slider; use left and right arrows to pick a level and `Enter` to apply. Takes effect immediately without waiting for the current response to finish                                                                                                                                                                                                                                                                                                              |
| `/exit`                                        | Exit the CLI. In an attached [background session](/docs/en/agent-view#attach-to-a-session), this detaches and the session keeps running. Alias: `/quit`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `/export [filename]`                           | Export the current conversation as plain text. With a filename, writes directly to that file. Without, opens a dialog to copy to clipboard or save to a file                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `/fast [on|off]`                               | Toggle [fast mode](/docs/en/fast-mode) on or off                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `/feedback [report]`                           | Submit feedback, report a bug, or share your conversation. Aliases: `/bug`, `/share`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `/fewer-permission-prompts`                    | **[Skill](/docs/en/skills#bundled-skills).** Scan your transcripts for common read-only Bash and MCP tool calls, then add a prioritized allowlist to project `.claude/settings.json` to reduce permission prompts                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `/focus`                                       | Toggle the focus view, which shows only your last prompt, a one-line tool-call summary with edit diffstats, and the final response. The selection persists across sessions; set [`viewMode`](/docs/en/settings#available-settings) in settings to override it. Only available in [fullscreen rendering](/docs/en/fullscreen)                                                                                                                                                                                                                                                                                                                                                                                                                |
| `/goal [condition|clear]`                      | Set a [goal](/docs/en/goal): Claude keeps working across turns until the condition is met. With no argument, shows the current or most recently achieved goal. `clear`, `stop`, `off`, `reset`, `none`, or `cancel` removes an active goal early                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `/heapdump`                                    | Write a JavaScript heap snapshot and a memory breakdown to `~/Desktop`, or your home directory on Linux without a Desktop folder, for diagnosing high memory usage. See [troubleshooting](/docs/en/troubleshooting#high-cpu-or-memory-usage)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `/help`                                        | Show help and available commands                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `/hooks`                                       | View [hook](/docs/en/hooks) configurations for tool events                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `/ide`                                         | Manage IDE integrations and show status                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `/init`                                        | Initialize project with a `CLAUDE.md` guide. Set `CLAUDE_CODE_NEW_INIT=1` for an interactive flow that also walks through skills, hooks, and personal memory files                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `/insights`                                    | Generate a report analyzing your Claude Code sessions, including project areas, interaction patterns, and friction points                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `/install-github-app`                          | Set up the [Claude GitHub Actions](/docs/en/github-actions) app for a repository. Walks you through selecting a repo and configuring the integration                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `/install-slack-app`                           | Install the Claude Slack app. Opens a browser to complete the OAuth flow                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `/keybindings`                                 | Open or create your keybindings configuration file                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `/login`                                       | Sign in to your Anthropic account                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `/logout`                                      | Sign out from your Anthropic account                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `/loop [interval] [prompt]`                    | **[Skill](/docs/en/skills#bundled-skills).** Run a prompt repeatedly while the session stays open. Omit the interval and Claude self-paces between iterations. Omit the prompt and Claude runs an autonomous maintenance check, or the prompt in `.claude/loop.md` if present. Example: `/loop 5m check if the deploy finished`. See [Run prompts on a schedule](/docs/en/scheduled-tasks). Alias: `/proactive`                                                                                                                                                                                                                                                                                                                             |
| `/mcp`                                         | Manage MCP server connections and OAuth authentication                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `/memory`                                      | Edit `CLAUDE.md` memory files, enable or disable [auto-memory](/docs/en/memory#auto-memory), and view auto-memory entries                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `/mobile`                                      | Show QR code to download the Claude mobile app. Aliases: `/ios`, `/android`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `/model [model]`                               | Set the AI model for the current session. For models that support it, use left/right arrows to [adjust effort level](/docs/en/model-config#adjust-effort-level). With no argument, opens a picker; press `d` on a row to also save that model as the default for new sessions. The picker asks for confirmation when the conversation has prior output, since the next response re-reads the full history without cached context. Once confirmed, the change applies without waiting for the current response to finish                                                                                                                                                                                                                     |
| `/passes`                                      | Share a free week of Claude Code with friends. Only visible if your account is eligible                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `/permissions`                                 | Manage allow, ask, and deny rules for tool permissions. Opens an interactive dialog where you can view rules by scope, add or remove rules, manage working directories, and review [recent auto mode denials](/docs/en/auto-mode-config#review-denials). Alias: `/allowed-tools`                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `/plan [description]`                          | Enter plan mode directly from the prompt. Pass an optional description to enter plan mode and immediately start with that task, for example `/plan fix the auth bug`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `/plugin`                                      | Manage Claude Code [plugins](/docs/en/plugins)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `/powerup`                                     | Discover Claude Code features through quick interactive lessons with animated demos                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `/pr-comments [PR]`                            | Removed in v2.1.91. Ask Claude directly to view pull request comments instead. On earlier versions, fetches and displays comments from a GitHub pull request; automatically detects the PR for the current branch, or pass a PR URL or number. Requires the `gh` CLI                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `/privacy-settings`                            | View and update your privacy settings. Only available for Pro and Max plan subscribers                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `/radio`                                       | Open Claude FM lo-fi radio in your browser. Prints the stream URL when no browser is available. Not available on Bedrock, Vertex, or Foundry                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `/recap`                                       | Generate a one-line summary of the current session on demand. See [Session recap](/docs/en/interactive-mode#session-recap) for the automatic recap that appears after you’ve been away                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `/release-notes`                               | View the changelog in an interactive version picker. Select a specific version to see its release notes, or choose to show all versions                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `/reload-plugins`                              | Reload all active [plugins](/docs/en/plugins) to apply pending changes without restarting. Reports counts for each reloaded component and flags any load errors                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `/remote-control`                              | Make this session available for [remote control](/docs/en/remote-control) from claude.ai. Alias: `/rc`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `/remote-env`                                  | Configure the default remote environment for [web sessions started with `--remote`](/docs/en/claude-code-on-the-web#configure-your-environment)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `/rename [name]`                               | Rename the current session and show the name on the prompt bar. Without a name, auto-generates one from conversation history                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `/resume [session]`                            | Resume a conversation by ID or name, or open the session picker. As of v2.1.144, [background sessions](/docs/en/agent-view) appear in the picker marked with `bg`. Alias: `/continue`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `/review [PR]`                                 | Review a pull request locally in your current session. For a deeper cloud-based review, see [`/ultrareview`](/docs/en/ultrareview)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `/rewind`                                      | Rewind the conversation and/or code to a previous point, or summarize from a selected message. See [checkpointing](/docs/en/checkpointing). Aliases: `/checkpoint`, `/undo`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `/sandbox`                                     | Toggle [sandbox mode](/docs/en/sandboxing). Available on supported platforms only                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `/schedule [description]`                      | Create, update, list, or run [routines](/docs/en/routines), which execute on Anthropic-managed cloud infrastructure. Claude walks you through the setup conversationally. Alias: `/routines`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `/scroll-speed`                                | Adjust mouse wheel [scroll speed](/docs/en/fullscreen#mouse-wheel-scrolling) interactively, with a ruler you can scroll while the dialog is open to preview the change. Available in [fullscreen rendering](/docs/en/fullscreen) only and not in the JetBrains IDE terminal                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `/security-review`                             | Analyze pending changes on the current branch for security vulnerabilities. Reviews the git diff and identifies risks like injection, auth issues, and data exposure                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `/setup-bedrock`                               | Configure [Amazon Bedrock](/docs/en/amazon-bedrock) authentication, region, and model pins through an interactive wizard. Only visible when `CLAUDE_CODE_USE_BEDROCK=1` is set. First-time Bedrock users can also access this wizard from the login screen                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `/setup-vertex`                                | Configure [Google Vertex AI](/docs/en/google-vertex-ai) authentication, project, region, and model pins through an interactive wizard. Only visible when `CLAUDE_CODE_USE_VERTEX=1` is set. First-time Vertex AI users can also access this wizard from the login screen                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `/simplify [focus]`                            | **[Skill](/docs/en/skills#bundled-skills).** Review your recently changed files for code reuse, quality, and efficiency issues, then fix them. Spawns three review agents in parallel, aggregates their findings, and applies fixes. Pass text to focus on specific concerns: `/simplify focus on memory efficiency`                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `/skills`                                      | List available [skills](/docs/en/skills). Press `t` to sort by token count. Press `Space` to [hide a skill from Claude or the `/` menu](/docs/en/skills#override-skill-visibility-from-settings), then `Enter` to save                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `/stats`                                       | Alias for `/usage`. Opens on the Stats tab                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `/status`                                      | Open the Settings interface (Status tab) showing version, model, account, and connectivity. Works while Claude is responding, without waiting for the current response to finish                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `/statusline`                                  | Configure Claude Code’s [status line](/docs/en/statusline). Describe what you want, or run without arguments to auto-configure from your shell prompt                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `/stickers`                                    | Order Claude Code stickers                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `/stop`                                        | Stop the current [background session](/docs/en/agent-view). Only available while attached to a background session; the transcript and any worktree are kept. To detach without stopping, use `/exit` or press `←`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `/tasks`                                       | List and manage background tasks. Also available as `/bashes`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `/team-onboarding`                             | Generate a team onboarding guide from your Claude Code usage history. Claude analyzes your sessions, commands, and MCP server usage from the past 30 days and produces a markdown guide a teammate can paste as a first message to get set up quickly. For claude.ai subscribers on Pro, Max, Team, and Enterprise plans, also returns a share link teammates can open directly in Claude Code                                                                                                                                                                                                                                                                                                                                              |
| `/teleport`                                    | Pull a [Claude Code on the web](/docs/en/claude-code-on-the-web#from-web-to-terminal) session into this terminal: opens a picker, then fetches the branch and conversation. Also available as `/tp`. Requires a claude.ai subscription                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `/terminal-setup`                              | Configure terminal keybindings for Shift+Enter and other shortcuts. Only visible in terminals that need it, like VS Code, Cursor, Windsurf, Alacritty, or Zed                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `/theme`                                       | Change the color theme. Includes an `auto` option that matches your terminal’s light or dark background, light and dark variants, colorblind-accessible (daltonized) themes, ANSI themes that use your terminal’s color palette, and any [custom themes](/docs/en/terminal-config#create-a-custom-theme) from `~/.claude/themes/` or plugins. Select **New custom theme…** to create one                                                                                                                                                                                                                                                                                                                                                    |
| `/tui [default|fullscreen]`                    | Set the terminal UI renderer and relaunch into it with your conversation intact. `fullscreen` enables the [flicker-free alt-screen renderer](/docs/en/fullscreen). With no argument, prints the active renderer                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `/ultraplan <prompt>`                          | Draft a plan in an [ultraplan](/docs/en/ultraplan) session, review it in your browser, then execute remotely or send it back to your terminal                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `/ultrareview [PR]`                            | Run a deep, multi-agent code review in a cloud sandbox with [ultrareview](/docs/en/ultrareview). Includes 3 free runs on Pro and Max, then requires [usage credits](../17-Billing-Plans/extra-usage-for-paid-claude-plans.md)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `/upgrade`                                     | Open the upgrade page to switch to a higher plan tier                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `/usage`                                       | Show session cost, plan usage limits, and activity stats. See the [cost tracking guide](/docs/en/costs#using-the-%2Fusage-command) for subscription-specific details. `/cost` and `/stats` are aliases                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `/usage-credits`                               | Configure usage credits to keep working when you hit a limit. Previously `/extra-usage`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `/vim`                                         | Removed in v2.1.92. To toggle between Vim and Normal editing modes, use `/config` → Editor mode                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `/voice [hold|tap|off]`                        | Toggle [voice dictation](/docs/en/voice-dictation), or enable it in a specific mode. Requires a Claude.ai account                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `/web-setup`                                   | Connect your GitHub account to [Claude Code on the web](/docs/en/web-quickstart#connect-from-your-terminal) using your local `gh` CLI credentials. `/schedule` prompts for this automatically if GitHub isn’t connected                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |


MCP prompts

MCP servers can expose prompts that appear as commands. These use the format `/mcp__<server>__<prompt>` and are dynamically discovered from connected servers. See [MCP prompts](/docs/en/mcp#use-mcp-prompts-as-commands) for details.


See also

- [Skills](/docs/en/skills): create your own commands
- [Interactive mode](/docs/en/interactive-mode): keyboard shortcuts, Vim mode, and command history
- [CLI reference](/docs/en/cli-reference): launch-time flags


---
## common-workflows-c909406123.md

> ## Documentation Index
> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Common workflows

> Step-by-step guides for exploring codebases, fixing bugs, refactoring, testing, and other everyday tasks with Claude Code.

This page covers practical workflows for everyday development: exploring unfamiliar code, debugging, refactoring, writing tests, creating PRs, and managing sessions. Each section includes example prompts you can adapt to your own projects. For higher-level patterns and tips, see [Best practices](../10-Prompting-Guides/best-practices-for-claude-code-claude-code-docs-9686dc1633.md).

## Understand new codebases

### Get a quick codebase overview

Suppose you've just joined a new project and need to understand its structure quickly.

<Steps>
  <Step title="Navigate to the project root directory">
    ```bash theme={null}
    cd /path/to/project 
    ```
  </Step>

  <Step title="Start Claude Code">
    ```bash theme={null}
    claude 
    ```
  </Step>

  <Step title="Ask for a high-level overview">
    ```text theme={null}
    give me an overview of this codebase
    ```
  </Step>

  <Step title="Dive deeper into specific components">
    ```text theme={null}
    explain the main architecture patterns used here
    ```

    ```text theme={null}
    what are the key data models?
    ```

    ```text theme={null}
    how is authentication handled?
    ```
  </Step>
</Steps>

<Tip>
  Tips:

  * Start with broad questions, then narrow down to specific areas
  * Ask about coding conventions and patterns used in the project
  * Request a glossary of project-specific terms
</Tip>

### Find relevant code

Suppose you need to locate code related to a specific feature or functionality.

<Steps>
  <Step title="Ask Claude to find relevant files">
    ```text theme={null}
    find the files that handle user authentication
    ```
  </Step>

  <Step title="Get context on how components interact">
    ```text theme={null}
    how do these authentication files work together?
    ```
  </Step>

  <Step title="Understand the execution flow">
    ```text theme={null}
    trace the login process from front-end to database
    ```
  </Step>
</Steps>

<Tip>
  Tips:

  * Be specific about what you're looking for
  * Use domain language from the project
  * Install a [code intelligence plugin](/en/discover-plugins#code-intelligence) for your language to give Claude precise "go to definition" and "find references" navigation
</Tip>

***

## Fix bugs efficiently

Suppose you've encountered an error message and need to find and fix its source.

<Steps>
  <Step title="Share the error with Claude">
    ```text theme={null}
    I'm seeing an error when I run npm test
    ```
  </Step>

  <Step title="Ask for fix recommendations">
    ```text theme={null}
    suggest a few ways to fix the @ts-ignore in user.ts
    ```
  </Step>

  <Step title="Apply the fix">
    ```text theme={null}
    update user.ts to add the null check you suggested
    ```
  </Step>
</Steps>

<Tip>
  Tips:

  * Tell Claude the command to reproduce the issue and get a stack trace
  * Mention any steps to reproduce the error
  * Let Claude know if the error is intermittent or consistent
</Tip>

***

## Refactor code

Suppose you need to update old code to use modern patterns and practices.

<Steps>
  <Step title="Identify legacy code for refactoring">
    ```text theme={null}
    find deprecated API usage in our codebase
    ```
  </Step>

  <Step title="Get refactoring recommendations">
    ```text theme={null}
    suggest how to refactor utils.js to use modern JavaScript features
    ```
  </Step>

  <Step title="Apply the changes safely">
    ```text theme={null}
    refactor utils.js to use ES2024 features while maintaining the same behavior
    ```
  </Step>

  <Step title="Verify the refactoring">
    ```text theme={null}
    run tests for the refactored code
    ```
  </Step>
</Steps>

<Tip>
  Tips:

  * Ask Claude to explain the benefits of the modern approach
  * Request that changes maintain backward compatibility when needed
  * Do refactoring in small, testable increments
</Tip>

***

## Use specialized subagents

Suppose you want to use specialized AI subagents to handle specific tasks more effectively.

<Steps>
  <Step title="View available subagents">
    ```text theme={null}
    /agents
    ```

    This shows all available subagents and lets you create new ones.
  </Step>

  <Step title="Use subagents automatically">
    Claude Code automatically delegates appropriate tasks to specialized subagents:

    ```text theme={null}
    review my recent code changes for security issues
    ```

    ```text theme={null}
    run all tests and fix any failures
    ```
  </Step>

  <Step title="Explicitly request specific subagents">
    ```text theme={null}
    use the code-reviewer subagent to check the auth module
    ```

    ```text theme={null}
    have the debugger subagent investigate why users can't log in
    ```
  </Step>

  <Step title="Create custom subagents for your workflow">
    ```text theme={null}
    /agents
    ```

    Then select "Create New subagent" and follow the prompts to define:

    * A unique identifier that describes the subagent's purpose (for example, `code-reviewer`, `api-designer`).
    * When Claude should use this agent
    * Which tools it can access
    * A system prompt describing the agent's role and behavior
  </Step>
</Steps>

<Tip>
  Tips:

  * Create project-specific subagents in `.claude/agents/` for team sharing
  * Use descriptive `description` fields to enable automatic delegation
  * Limit tool access to what each subagent actually needs
  * Check the [subagents documentation](../09-Agents-Patterns/create-custom-subagents-claude-code-docs-7dc93e85c0.md) for detailed examples
</Tip>

***

## Use Plan Mode for safe code analysis

Plan Mode instructs Claude to create a plan by analyzing the codebase with read-only operations, perfect for exploring codebases, planning complex changes, or reviewing code safely. In Plan Mode, Claude uses [`AskUserQuestion`](../04-API-Reference/tools-reference-claude-code-docs-d21fdcb4c5.md) to gather requirements and clarify your goals before proposing a plan.

### When to use Plan Mode

* **Multi-step implementation**: When your feature requires making edits to many files
* **Code exploration**: When you want to research the codebase thoroughly before changing anything
* **Interactive development**: When you want to iterate on the direction with Claude

### How to use Plan Mode

**Turn on Plan Mode during a session**

You can switch into Plan Mode during a session using **Shift+Tab** to cycle through permission modes.

If you are in Normal Mode, **Shift+Tab** first switches into Auto-Accept Mode, indicated by `⏵⏵ accept edits on` at the bottom of the terminal. A subsequent **Shift+Tab** will switch into Plan Mode, indicated by `⏸ plan mode on`.

**Start a new session in Plan Mode**

To start a new session in Plan Mode, use the `--permission-mode plan` flag:

```bash theme={null}
claude --permission-mode plan
```

**Run "headless" queries in Plan Mode**

You can also run a query in Plan Mode directly with `-p` (that is, in ["headless mode"](headless-b99e3140ec.md)):

```bash theme={null}
claude --permission-mode plan -p "Analyze the authentication system and suggest improvements"
```

### Example: Planning a complex refactor

```bash theme={null}
claude --permission-mode plan
```

```text theme={null}
I need to refactor our authentication system to use OAuth2. Create a detailed migration plan.
```

Claude analyzes the current implementation and create a comprehensive plan. Refine with follow-ups:

```text theme={null}
What about backward compatibility?
```

```text theme={null}
How should we handle database migration?
```

<Tip>Press `Ctrl+G` to open the plan in your default text editor, where you can edit it directly before Claude proceeds.</Tip>

When you accept a plan, Claude automatically names the session from the plan content. The name appears on the prompt bar and in the session picker. If you've already set a name with `--name` or `/rename`, accepting a plan won't overwrite it.

### Configure Plan Mode as default

```json theme={null}
// .claude/settings.json
{
  "permissions": {
    "defaultMode": "plan"
  }
}
```

See [settings documentation](/en/settings#available-settings) for more configuration options.

***

## Work with tests

Suppose you need to add tests for uncovered code.

<Steps>
  <Step title="Identify untested code">
    ```text theme={null}
    find functions in NotificationsService.swift that are not covered by tests
    ```
  </Step>

  <Step title="Generate test scaffolding">
    ```text theme={null}
    add tests for the notification service
    ```
  </Step>

  <Step title="Add meaningful test cases">
    ```text theme={null}
    add test cases for edge conditions in the notification service
    ```
  </Step>

  <Step title="Run and verify tests">
    ```text theme={null}
    run the new tests and fix any failures
    ```
  </Step>
</Steps>

Claude can generate tests that follow your project's existing patterns and conventions. When asking for tests, be specific about what behavior you want to verify. Claude examines your existing test files to match the style, frameworks, and assertion patterns already in use.

For comprehensive coverage, ask Claude to identify edge cases you might have missed. Claude can analyze your code paths and suggest tests for error conditions, boundary values, and unexpected inputs that are easy to overlook.

***

## 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:

<Steps>
  <Step title="Summarize your changes">
    ```text theme={null}
    summarize the changes I've made to the authentication module
    ```
  </Step>

  <Step title="Generate a pull request">
    ```text theme={null}
    create a pr
    ```
  </Step>

  <Step title="Review and refine">
    ```text theme={null}
    enhance the PR description with more context about the security improvements
    ```
  </Step>
</Steps>

When you create a PR using `gh pr create`, the session is automatically linked to that PR. You can resume it later with `claude --from-pr <number>`.

<Tip>
  Review Claude's generated PR before submitting and ask Claude to highlight potential risks or considerations.
</Tip>

## Handle documentation

Suppose you need to add or update documentation for your code.

<Steps>
  <Step title="Identify undocumented code">
    ```text theme={null}
    find functions without proper JSDoc comments in the auth module
    ```
  </Step>

  <Step title="Generate documentation">
    ```text theme={null}
    add JSDoc comments to the undocumented functions in auth.js
    ```
  </Step>

  <Step title="Review and enhance">
    ```text theme={null}
    improve the generated documentation with more context and examples
    ```
  </Step>

  <Step title="Verify documentation">
    ```text theme={null}
    check if the documentation follows our project standards
    ```
  </Step>
</Steps>

<Tip>
  Tips:

  * Specify the documentation style you want (JSDoc, docstrings, etc.)
  * Ask for examples in the documentation
  * Request documentation for public APIs, interfaces, and complex logic
</Tip>

***

## 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

Suppose you need to work with images in your codebase, and you want Claude's help analyzing image content.

<Steps>
  <Step title="Add an image to the conversation">
    You can use any of these methods:

    1. Drag and drop an image into the Claude Code window
    2. Copy an image and paste it into the CLI with ctrl+v (Do not use cmd+v)
    3. Provide an image path to Claude. E.g., "Analyze this image: /path/to/your/image.png"
  </Step>

  <Step title="Ask Claude to analyze the image">
    ```text theme={null}
    What does this image show?
    ```

    ```text theme={null}
    Describe the UI elements in this screenshot
    ```

    ```text theme={null}
    Are there any problematic elements in this diagram?
    ```
  </Step>

  <Step title="Use images for context">
    ```text theme={null}
    Here's a screenshot of the error. What's causing it?
    ```

    ```text theme={null}
    This is our current database schema. How should we modify it for the new feature?
    ```
  </Step>

  <Step title="Get code suggestions from visual content">
    ```text theme={null}
    Generate CSS to match this design mockup
    ```

    ```text theme={null}
    What HTML structure would recreate this component?
    ```
  </Step>
</Steps>

<Tip>
  Tips:

  * Use images when text descriptions would be unclear or cumbersome
  * Include screenshots of errors, UI designs, or diagrams for better context
  * You can work with multiple images in a conversation
  * Image analysis works with diagrams, screenshots, mockups, and more
  * When Claude references images (for example, `[Image #1]`), `Cmd+Click` (Mac) or `Ctrl+Click` (Windows/Linux) the link to open the image in your default viewer
</Tip>

***

## Reference files and directories

Use @ to quickly include files or directories without waiting for Claude to read them.

<Steps>
  <Step title="Reference a single file">
    ```text theme={null}
    Explain the logic in @src/utils/auth.js
    ```

    This includes the full content of the file in the conversation.
  </Step>

  <Step title="Reference a directory">
    ```text theme={null}
    What's the structure of @src/components?
    ```

    This provides a directory listing with file information.
  </Step>

  <Step title="Reference MCP resources">
    ```text theme={null}
    Show me the data from @github:repos/owner/repo/issues
    ```

    This fetches data from connected MCP servers using the format @server:resource. See [MCP resources](/en/mcp#use-mcp-resources) for details.
  </Step>
</Steps>

<Tip>
  Tips:

  * File paths can be relative or absolute
  * @ file references add `CLAUDE.md` in the file's directory and parent directories to context
  * Directory references show file listings, not contents
  * You can reference multiple files in a single message (for example, "@file1.js and @file2.js")
</Tip>

***

## Use extended thinking (thinking mode)

[Extended thinking](../04-API-Reference/Guides/build-with-claude-extended-thinking-dd12780e6a.md) is enabled by default, giving Claude space to reason through complex problems step-by-step before responding. This reasoning is visible in verbose mode, which you can toggle on with `Ctrl+O`. During extended thinking, the spinner shows inline progress hints such as "still thinking" and "almost done thinking" to indicate Claude is actively working.

Additionally, [models that support effort](/en/model-config#adjust-effort-level) use adaptive reasoning: instead of a fixed thinking token budget, the model dynamically decides whether and how much to think based on your effort level setting and the task at hand. Adaptive reasoning lets Claude respond faster to routine prompts and reserve deeper thinking for steps that benefit from it.

Extended thinking is particularly valuable for complex architectural decisions, challenging bugs, multi-step implementation planning, and evaluating tradeoffs between different approaches.

<Note>
  Phrases like "think", "think hard", and "think more" are interpreted as regular prompt instructions and don't allocate thinking tokens.
</Note>

### Configure thinking mode

Thinking is enabled by default, but you can adjust or disable it.

| Scope                    | How to configure                                                                     | Details                                                                                                                                                                                          |
| ------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Effort level**         | Run `/effort`, adjust in `/model`, or set [`CLAUDE_CODE_EFFORT_LEVEL`](env-vars-5c624d392b.md) | Control thinking depth on [supported models](/en/model-config#adjust-effort-level)                                                                                                               |
| **`ultrathink` keyword** | Include "ultrathink" anywhere in your prompt                                         | Adds an in-context instruction telling the model to reason more on that turn. Does not change the effort level itself; see [Adjust effort level](/en/model-config#adjust-effort-level) for that  |
| **Toggle shortcut**      | Press `Option+T` (macOS) or `Alt+T` (Windows/Linux)                                  | Toggle thinking on/off for the current session (all models). May require [terminal configuration](configure-your-terminal-for-claude-code-claude-code-docs-6f181483c1.md) to enable Option key shortcuts                                            |
| **Global default**       | Use `/config` to toggle thinking mode                                                | Sets your default across all projects (all models).<br />Saved as `alwaysThinkingEnabled` in `~/.claude/settings.json`                                                                           |
| **Limit token budget**   | Set [`MAX_THINKING_TOKENS`](env-vars-5c624d392b.md) environment variable                       | Limit the thinking budget to a specific number of tokens. On models with adaptive reasoning, only `0` applies unless adaptive reasoning is disabled. Example: `export MAX_THINKING_TOKENS=10000` |

To view Claude's thinking process, press `Ctrl+O` to toggle verbose mode and see the internal reasoning displayed as gray italic text.

### How extended thinking works

Extended thinking controls how much internal reasoning Claude performs before responding. More thinking provides more space to explore solutions, analyze edge cases, and self-correct mistakes.

On [models that support effort](/en/model-config#adjust-effort-level), thinking uses adaptive reasoning: the model dynamically allocates thinking tokens based on the effort level you select. This is the recommended way to tune the tradeoff between speed and reasoning depth. If you want Claude to think more or less often than your effort level would otherwise produce, you can also say so directly in your prompt or in `CLAUDE.md`.

With older models, thinking uses a fixed token budget drawn from your output allocation. The budget varies by model; see [`MAX_THINKING_TOKENS`](env-vars-5c624d392b.md) for per-model ceilings. You can limit the budget with that environment variable, or disable thinking entirely via `/config` or the `Option+T`/`Alt+T` toggle.

On models with adaptive reasoning, `MAX_THINKING_TOKENS` only applies when set to `0` to disable thinking, or when `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING=1` reverts the model to the fixed budget. `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING` applies to Opus 4.6 and Sonnet 4.6 only. Opus 4.7 always uses adaptive reasoning and does not support a fixed thinking budget. See [environment variables](env-vars-5c624d392b.md).

<Warning>
  You're charged for all thinking tokens used even when thinking summaries are redacted. In interactive mode, thinking appears as a collapsed stub by default. Set `showThinkingSummaries: true` in `settings.json` to show full summaries.
</Warning>

***

## Resume previous conversations

When starting Claude Code, you can resume a previous session:

* `claude --continue` continues the most recent conversation in the current directory
* `claude --resume` opens a conversation picker or resumes by name
* `claude --from-pr 123` resumes sessions linked to a specific pull request

From inside an active session, use `/resume` to switch to a different conversation.

When the selected session is old and large enough that re-reading it would consume a substantial share of your usage limits, `--resume`, `--continue`, and `/resume` offer to resume from a summary instead of loading the full transcript. This prompt is not available on Amazon Bedrock, Google Cloud Vertex AI, or Microsoft Foundry.

Sessions are stored per project directory. By default, the `/resume` picker shows interactive sessions from the current worktree, with keyboard shortcuts to widen the list to other worktrees or projects, search, preview, and rename. Sessions started elsewhere that added the current directory with `/add-dir` are also included by default. See [Use the session picker](#use-the-session-picker) below for the full shortcut reference.

When you select a session from another worktree of the same repository, Claude Code resumes it directly without requiring you to switch directories first. Selecting a session from an unrelated project copies a `cd` and resume command to your clipboard instead.

Resuming by name resolves across the current repository and its worktrees. Both `claude --resume <name>` and `/resume <name>` look for an exact match and resume it directly, even if the session lives in a different worktree.

When the name is ambiguous, `claude --resume <name>` opens the picker with the name pre-filled as a search term. `/resume <name>` from inside a session reports an error instead, so run `/resume` with no argument to open the picker and choose.

Sessions created by `claude -p` or SDK invocations do not appear in the picker, but you can still resume one by passing its session ID directly to `claude --resume <session-id>`.

### Name your sessions

Give sessions descriptive names to find them later. This is a best practice when working on multiple tasks or features.

<Steps>
  <Step title="Name the session">
    Name a session at startup with `-n`:

    ```bash theme={null}
    claude -n auth-refactor
    ```

    Or use `/rename` during a session, which also shows the name on the prompt bar:

    ```text theme={null}
    /rename auth-refactor
    ```

    You can also rename any session from the picker: run `/resume`, navigate to a session, and press `Ctrl+R`.
  </Step>

  <Step title="Resume by name later">
    From the command line:

    ```bash theme={null}
    claude --resume auth-refactor
    ```

    Or from inside an active session:

    ```text theme={null}
    /resume auth-refactor
    ```
  </Step>
</Steps>

### Use the session picker

The `/resume` command (or `claude --resume` without arguments) opens an interactive session picker with these features:

**Keyboard shortcuts in the picker:**

| Shortcut                                          | Action                                                                                                                                             |
| :------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------- |
| `↑` / `↓`                                         | Navigate between sessions                                                                                                                          |
| `→` / `←`                                         | Expand or collapse grouped sessions                                                                                                                |
| `Enter`                                           | Select and resume the highlighted session                                                                                                          |
| `Space`                                           | Preview the session content. `Ctrl+V` also works on terminals that do not capture it as paste                                                      |
| `Ctrl+R`                                          | Rename the highlighted session                                                                                                                     |
| `/` or any printable character other than `Space` | Enter search mode and filter sessions                                                                                                              |
| `Ctrl+A`                                          | Show sessions from all projects on this machine. Press again to restore the current repository                                                     |
| `Ctrl+W`                                          | Show sessions from all worktrees of the current repository. Press again to restore the current worktree. Only shown in multi-worktree repositories |
| `Ctrl+B`                                          | Filter to sessions from your current git branch. Press again to show sessions from all branches                                                    |
| `Esc`                                             | Exit the picker or search mode                                                                                                                     |

**Session organization:**

The picker displays sessions with helpful metadata:

* Session name if set, otherwise the conversation summary or first user prompt
* Time elapsed since last activity
* Message count
* Git branch (if applicable)
* Project path, shown after widening to all projects with `Ctrl+A`

Forked sessions (created with `/branch`, `/rewind`, or `--fork-session`) are grouped together under their root session, making it easier to find related conversations.

<Tip>
  Tips:

  * **Name sessions early**: Use `/rename` when starting work on a distinct task: it's much easier to find "payment-integration" than "explain this function" later
  * Use `--continue` for quick access to your most recent conversation in the current directory
  * Use `--resume session-name` when you know which session you need
  * Use `--resume` (without a name) when you need to browse and select
  * For scripts, use `claude --continue --print "prompt"` to resume in non-interactive mode
  * Press `Space` in the picker to preview a session before resuming it
  * The resumed conversation starts with the same model and configuration as the original

  How it works:

  1. **Conversation Storage**: All conversations are automatically saved locally with their full message history
  2. **Message Deserialization**: When resuming, the entire message history is restored to maintain context
  3. **Tool State**: Tool usage and results from the previous conversation are preserved
  4. **Context Restoration**: The conversation resumes with all previous context intact
</Tip>

***

## Run parallel Claude Code sessions with Git worktrees

When working on multiple tasks at once, you need each Claude session to have its own copy of the codebase so changes don't collide. Git worktrees solve this by creating separate working directories that each have their own files and branch, while sharing the same repository history and remote connections. This means you can have Claude working on a feature in one worktree while fixing a bug in another, without either session interfering with the other.

Use the `--worktree` (`-w`) flag to create an isolated worktree and start Claude in it. The value you pass becomes the worktree directory name and branch name:

```bash theme={null}
# Start Claude in a worktree named "feature-auth"
# Creates .claude/worktrees/feature-auth/ with a new branch
claude --worktree feature-auth

# Start another session in a separate worktree
claude --worktree bugfix-123
```

If you omit the name, Claude generates a random one automatically:

```bash theme={null}
# Auto-generates a name like "bright-running-fox"
claude --worktree
```

Worktrees are created at `<repo>/.claude/worktrees/<name>` and branch from the default remote branch, which is where `origin/HEAD` points. The worktree branch is named `worktree-<name>`.

The base branch is not configurable through a Claude Code flag or setting. `origin/HEAD` is a reference stored in your local `.git` directory that Git set once when you cloned. If the repository's default branch later changes on GitHub or GitLab, your local `origin/HEAD` keeps pointing at the old one, and worktrees will branch from there. To re-sync your local reference with whatever the remote currently considers its default:

```bash theme={null}
git remote set-head origin -a
```

This is a standard Git command that only updates your local `.git` directory. Nothing on the remote server changes. If you want worktrees to base off a specific branch rather than the remote's default, set it explicitly with `git remote set-head origin your-branch-name`.

For full control over how worktrees are created, including choosing a different base per invocation, configure a [WorktreeCreate hook](/en/hooks#worktreecreate). The hook replaces Claude Code's default `git worktree` logic entirely, so you can fetch and branch from whatever ref you need.

You can also ask Claude to "work in a worktree" or "start a worktree" during a session, and it will create one automatically.

### Subagent worktrees

Subagents can also use worktree isolation to work in parallel without conflicts. Ask Claude to "use worktrees for your agents" or configure it in a [custom subagent](/en/sub-agents#supported-frontmatter-fields) by adding `isolation: worktree` to the agent's frontmatter. Each subagent gets its own worktree that is automatically cleaned up when the subagent finishes without changes.

### Worktree cleanup

When you exit a worktree session, Claude handles cleanup based on whether you made changes:

* **No changes**: the worktree and its branch are removed automatically
* **Changes or commits exist**: Claude prompts you to keep or remove the worktree. Keeping preserves the directory and branch so you can return later. Removing deletes the worktree directory and its branch, discarding all uncommitted changes and commits

Subagent worktrees orphaned by a crash or an interrupted parallel run are removed automatically at startup once they are older than your [`cleanupPeriodDays`](/en/settings#available-settings) setting, provided they have no uncommitted changes, no untracked files, and no unpushed commits. Worktrees you create with `--worktree` are never removed by this sweep.

To clean up worktrees outside of a Claude session, use [manual worktree management](#manage-worktrees-manually).

<Tip>
  Add `.claude/worktrees/` to your `.gitignore` to prevent worktree contents from appearing as untracked files in your main repository.
</Tip>

### Copy gitignored files to worktrees

Git worktrees are fresh checkouts, so they don't include untracked files like `.env` or `.env.local` from your main repository. To automatically copy these files when Claude creates a worktree, add a `.worktreeinclude` file to your project root.

The file uses `.gitignore` syntax to list which files to copy. Only files that match a pattern and are also gitignored get copied, so tracked files are never duplicated.

```text .worktreeinclude theme={null}
.env
.env.local
config/secrets.json
```

This applies to worktrees created with `--worktree`, subagent worktrees, and parallel sessions in the [desktop app](/en/desktop#work-in-parallel-with-sessions).

### Manage worktrees manually

For more control over worktree location and branch configuration, create worktrees with Git directly. This is useful when you need to check out a specific existing branch or place the worktree outside the repository.

```bash theme={null}
# Create a worktree with a new branch
git worktree add ../project-feature-a -b feature-a

# Create a worktree with an existing branch
git worktree add ../project-bugfix bugfix-123

# Start Claude in the worktree
cd ../project-feature-a && claude

# Clean up when done
git worktree list
git worktree remove ../project-feature-a
```

Learn more in the [official Git worktree documentation](https://git-scm.com/docs/git-worktree).

<Tip>
  Remember to initialize your development environment in each new worktree according to your project's setup. Depending on your stack, this might include running dependency installation (`npm install`, `yarn`), setting up virtual environments, or following your project's standard setup process.
</Tip>

### Non-git version control

Worktree isolation works with git by default. For other version control systems like SVN, Perforce, or Mercurial, configure [WorktreeCreate and WorktreeRemove hooks](/en/hooks#worktreecreate) to provide custom worktree creation and cleanup logic. When configured, these hooks replace the default git behavior when you use `--worktree`, so [`.worktreeinclude`](#copy-gitignored-files-to-worktrees) is not processed. Copy any local configuration files inside your hook script instead.

For automated coordination of parallel sessions with shared tasks and messaging, see [agent teams](../09-Agents-Patterns/agent-teams-e29da6ed1b.md).

***

## Get notified when Claude needs your attention

When you kick off a long-running task and switch to another window, you can set up desktop notifications so you know when Claude finishes or needs your input. This uses the `Notification` [hook event](/en/hooks-guide#get-notified-when-claude-needs-input), which fires whenever Claude is waiting for permission, idle and ready for a new prompt, or completing authentication.

<Steps>
  <Step title="Add the hook to your settings">
    Open `~/.claude/settings.json` and add a `Notification` hook that calls your platform's native notification command:

    <Tabs>
      <Tab title="macOS">
        ```json theme={null}
        {
          "hooks": {
            "Notification": [
              {
                "matcher": "",
                "hooks": [
                  {
                    "type": "command",
                    "command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"
                  }
                ]
              }
            ]
          }
        }
        ```
      </Tab>

      <Tab title="Linux">
        ```json theme={null}
        {
          "hooks": {
            "Notification": [
              {
                "matcher": "",
                "hooks": [
                  {
                    "type": "command",
                    "command": "notify-send 'Claude Code' 'Claude Code needs your attention'"
                  }
                ]
              }
            ]
          }
        }
        ```
      </Tab>

      <Tab title="Windows">
        ```json theme={null}
        {
          "hooks": {
            "Notification": [
              {
                "matcher": "",
                "hooks": [
                  {
                    "type": "command",
                    "command": "powershell.exe -Command \"[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); [System.Windows.Forms.MessageBox]::Show('Claude Code needs your attention', 'Claude Code')\""
                  }
                ]
              }
            ]
          }
        }
        ```
      </Tab>
    </Tabs>

    If your settings file already has a `hooks` key, merge the `Notification` entry into it rather than overwriting. You can also ask Claude to write the hook for you by describing what you want in the CLI.
  </Step>

  <Step title="Optionally narrow the matcher">
    By default the hook fires on all notification types. To fire only for specific events, set the `matcher` field to one of these values:

    | Matcher              | Fires when                                      |
    | :------------------- | :---------------------------------------------- |
    | `permission_prompt`  | Claude needs you to approve a tool use          |
    | `idle_prompt`        | Claude is done and waiting for your next prompt |
    | `auth_success`       | Authentication completes                        |
    | `elicitation_dialog` | Claude is asking you a question                 |
  </Step>

  <Step title="Verify the hook">
    Type `/hooks` and select `Notification` to confirm the hook appears. Selecting it shows the command that will run. To test it end-to-end, ask Claude to run a command that requires permission and switch away from the terminal, or ask Claude to trigger a notification directly.
  </Step>
</Steps>

For the complete event schema and notification types, see the [Notification reference](/en/hooks#notification).

***

## Use Claude as a unix-style utility

### Add Claude to your verification process

Suppose you want to use Claude Code as a linter or code reviewer.

**Add Claude to your build script:**

```json theme={null}
// package.json
{
    ...
    "scripts": {
        ...
        "lint:claude": "claude -p 'you are a linter. please look at the changes vs. main and report any issues related to typos. report the filename and line number on one line, and a description of the issue on the second line. do not return any other text.'"
    }
}
```

<Tip>
  Tips:

  * Use Claude for automated code review in your CI/CD pipeline
  * Customize the prompt to check for specific issues relevant to your project
  * Consider creating multiple scripts for different types of verification
</Tip>

### Pipe in, pipe out

Suppose you want to pipe data into Claude, and get back data in a structured format.

**Pipe data through Claude:**

```bash theme={null}
cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > output.txt
```

<Tip>
  Tips:

  * Use pipes to integrate Claude into existing shell scripts
  * Combine with other Unix tools for powerful workflows
  * Consider using `--output-format` for structured output
</Tip>

### Control output format

Suppose you need Claude's output in a specific format, especially when integrating Claude Code into scripts or other tools.

<Steps>
  <Step title="Use text format (default)">
    ```bash theme={null}
    cat data.txt | claude -p 'summarize this data' --output-format text > summary.txt
    ```

    This outputs just Claude's plain text response (default behavior).
  </Step>

  <Step title="Use JSON format">
    ```bash theme={null}
    cat code.py | claude -p 'analyze this code for bugs' --output-format json > analysis.json
    ```

    This outputs a JSON array of messages with metadata including cost and duration.
  </Step>

  <Step title="Use streaming JSON format">
    ```bash theme={null}
    cat log.txt | claude -p 'parse this log file for errors' --output-format stream-json
    ```

    This outputs a series of JSON objects in real-time as Claude processes the request. Each message is a valid JSON object, but the entire output is not valid JSON if concatenated.
  </Step>
</Steps>

<Tip>
  Tips:

  * Use `--output-format text` for simple integrations where you just need Claude's response
  * Use `--output-format json` when you need the full conversation log
  * Use `--output-format stream-json` for real-time output of each conversation turn
</Tip>

***

## 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:

| Option                                                 | Where it runs                     | Best for                                                                                                                                                                                                 |
| :----------------------------------------------------- | :-------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Routines](routines-3111c7bd3a.md)                               | Anthropic-managed infrastructure  | Tasks that should run even when your computer is off. Can also trigger on API calls or GitHub events in addition to a schedule. Configure at [claude.ai/code/routines](https://claude.ai/code/routines). |
| [Desktop scheduled tasks](../16-Mobile-Desktop/desktop-scheduled-tasks.md) | Your machine, via the desktop app | Tasks that need direct access to local files, tools, or uncommitted changes.                                                                                                                             |
| [GitHub Actions](claude-code-github-actions-claude-code-docs-0d633fbd8a.md)                   | Your CI pipeline                  | Tasks tied to repo events like opened PRs, or cron schedules that should live alongside your workflow config.                                                                                            |
| [`/loop`](run-prompts-on-a-schedule-claude-code-docs.md)                         | The current CLI session           | Quick polling while a session is open. Tasks stop when you start a new conversation; `--resume` and `--continue` restore unexpired ones.                                                                 |

<Tip>
  When writing prompts for scheduled tasks, be explicit about what success looks like and what to do with results. The task runs autonomously, so it can't ask clarifying questions. For example: "Review open PRs labeled `needs-review`, leave inline comments on any issues, and post a summary in the `#eng-reviews` Slack channel."
</Tip>

***

## Ask Claude about its capabilities

Claude has built-in access to its documentation and can answer questions about its own features and limitations.

### Example questions

```text theme={null}
can Claude Code create pull requests?
```

```text theme={null}
how does Claude Code handle permissions?
```

```text theme={null}
what skills are available?
```

```text theme={null}
how do I use MCP with Claude Code?
```

```text theme={null}
how do I configure Claude Code for Amazon Bedrock?
```

```text theme={null}
what are the limitations of Claude Code?
```

<Note>
  Claude provides documentation-based answers to these questions. For hands-on demonstrations, run `/powerup` for interactive lessons with animated demos, or refer to the specific workflow sections above.
</Note>

<Tip>
  Tips:

  * Claude always has access to the latest Claude Code documentation, regardless of the version you're using
  * Ask specific questions to get detailed answers
  * Claude can explain complex features like MCP integration, enterprise configurations, and advanced workflows
</Tip>

***

## Next steps

<CardGroup cols={2}>
  <Card title="Best practices" icon="lightbulb" href="/en/best-practices">
    Patterns for getting the most out of Claude Code
  </Card>

  <Card title="How Claude Code works" icon="gear" href="/en/how-claude-code-works">
    Understand the agentic loop and context management
  </Card>

  <Card title="Extend Claude Code" icon="puzzle-piece" href="/en/features-overview">
    Add skills, hooks, MCP, subagents, and plugins
  </Card>

  <Card title="Reference implementation" icon="code" href="https://github.com/anthropics/claude-code/tree/main/.devcontainer">
    Clone the development container reference implementation
  </Card>
</CardGroup>


---
## common-workflows-claude-code-docs-0630c9a5f8.md

# Common workflows


Step-by-step guides for exploring codebases, fixing bugs, refactoring, testing, and other everyday tasks with Claude Code.


> ## Documentation Index
>
> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt>
>
> Use this file to discover all available pages before exploring further.

This page collects short recipes for everyday development. For higher-level guidance on prompting and context management, see [Best practices](/docs/en/best-practices). This page covers:

- [Prompt recipes](#prompt-recipes) for exploring code, fixing bugs, refactoring, testing, PRs, and documentation
- [Resume previous conversations](#resume-previous-conversations) so a task can span multiple sittings
- [Run parallel sessions with worktrees](#run-parallel-sessions-with-worktrees) so concurrent edits don’t collide
- [Plan before editing](#plan-before-editing) to review changes before they touch disk
- [Delegate research to subagents](#delegate-research-to-subagents) to keep your main context clean
- [Pipe Claude into scripts](#pipe-claude-into-scripts) for CI and batch processing


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


Get a quick codebase overview

Suppose you’ve just joined a new project and need to understand its structure quickly.

1


Navigate to the project root directory

```python
cd /path/to/project 
```

2


Start Claude Code

```python
claude 
```

3


Ask for a high-level overview

```python
give me an overview of this codebase
```

4


Dive deeper into specific components

```python
explain the main architecture patterns used here
```

```python
what are the key data models?
```

```python
how is authentication handled?
```

Tips:

- Start with broad questions, then narrow down to specific areas
- Ask about coding conventions and patterns used in the project
- Request a glossary of project-specific terms


Find relevant code

Suppose you need to locate code related to a specific feature or functionality.

1


Ask Claude to find relevant files

```python
find the files that handle user authentication
```

2


Get context on how components interact

```python
how do these authentication files work together?
```

3


Understand the execution flow

```python
trace the login process from front-end to database
```

Tips:

- Be specific about what you’re looking for
- Use domain language from the project
- Install a [code intelligence plugin](/docs/en/discover-plugins#code-intelligence) for your language to give Claude precise “go to definition” and “find references” navigation

------------------------------------------------------------------------


Fix bugs efficiently

Suppose you’ve encountered an error message and need to find and fix its source.

1


Share the error with Claude

```python
I'm seeing an error when I run npm test
```

2


Ask for fix recommendations

```python
suggest a few ways to fix the @ts-ignore in user.ts
```

3


Apply the fix

```python
update user.ts to add the null check you suggested
```

Tips:

- Tell Claude the command to reproduce the issue and get a stack trace
- Mention any steps to reproduce the error
- Let Claude know if the error is intermittent or consistent

------------------------------------------------------------------------


Refactor code

Suppose you need to update old code to use modern patterns and practices.

1


Identify legacy code for refactoring

```python
find deprecated API usage in our codebase
```

2


Get refactoring recommendations

```python
suggest how to refactor utils.js to use modern JavaScript features
```

3


Apply the changes safely

```python
refactor utils.js to use ES2024 features while maintaining the same behavior
```

4


Verify the refactoring

```python
run tests for the refactored code
```

Tips:

- Ask Claude to explain the benefits of the modern approach
- Request that changes maintain backward compatibility when needed
- Do refactoring in small, testable increments

------------------------------------------------------------------------


Work with tests

Suppose you need to add tests for uncovered code.

1


Identify untested code

```python
find functions in NotificationsService.swift that are not covered by tests
```

2


Generate test scaffolding

```python
add tests for the notification service
```

3


Add meaningful test cases

```python
add test cases for edge conditions in the notification service
```

4


Run and verify tests

```python
run the new tests and fix any failures
```

Claude can generate tests that follow your project’s existing patterns and conventions. When asking for tests, be specific about what behavior you want to verify. Claude examines your existing test files to match the style, frameworks, and assertion patterns already in use. For comprehensive coverage, ask Claude to identify edge cases you might have missed. Claude can analyze your code paths and suggest tests for error conditions, boundary values, and unexpected inputs that are easy to overlook.

------------------------------------------------------------------------


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:

1


Summarize your changes

```python
summarize the changes I've made to the authentication module
```

2


Generate a pull request

```python
create a pr
```

3


Review and refine

```python
enhance the PR description with more context about the security improvements
```

When you create a PR using `gh pr create`, the session is automatically linked to that PR. To return to it later, run `claude --from-pr <number>` or paste the PR URL into the [`/resume` picker](/docs/en/sessions#use-the-session-picker) search.

Review Claude’s generated PR before submitting and ask Claude to highlight potential risks or considerations.


Handle documentation

Suppose you need to add or update documentation for your code.

1


Identify undocumented code

```python
find functions without proper JSDoc comments in the auth module
```

2


Generate documentation

```python
add JSDoc comments to the undocumented functions in auth.js
```

3


Review and enhance

```python
improve the generated documentation with more context and examples
```

4


Verify documentation

```python
check if the documentation follows our project standards
```

Tips:

- Specify the documentation style you want (JSDoc, docstrings, etc.)
- Ask for examples in the documentation
- Request documentation for public APIs, interfaces, and complex logic

------------------------------------------------------------------------


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

Suppose you need to work with images in your codebase, and you want Claude’s help analyzing image content.

1


Add an image to the conversation

You can use any of these methods:

1.  Drag and drop an image into the Claude Code window
2.  Copy an image and paste it into the CLI with ctrl+v (Do not use cmd+v)
3.  Provide an image path to Claude. E.g., “Analyze this image: /path/to/your/image.png”

2


Ask Claude to analyze the image

```python
What does this image show?
```

```python
Describe the UI elements in this screenshot
```

```python
Are there any problematic elements in this diagram?
```

3


Use images for context

```python
Here's a screenshot of the error. What's causing it?
```

```python
This is our current database schema. How should we modify it for the new feature?
```

4


Get code suggestions from visual content

```python
Generate CSS to match this design mockup
```

```python
What HTML structure would recreate this component?
```

Tips:

- Use images when text descriptions would be unclear or cumbersome
- Include screenshots of errors, UI designs, or diagrams for better context
- You can work with multiple images in a conversation
- Image analysis works with diagrams, screenshots, mockups, and more
- When Claude references images (for example, `[Image #1]`), `Cmd+Click` (Mac) or `Ctrl+Click` (Windows/Linux) the link to open the image in your default viewer

------------------------------------------------------------------------


Reference files and directories

Use @ to quickly include files or directories without waiting for Claude to read them.

1


Reference a single file

```python
Explain the logic in @src/utils/auth.js
```

This includes the full content of the file in the conversation.

2


Reference a directory

```python
What's the structure of @src/components?
```

This provides a directory listing with file information.

3


Reference MCP resources

```python
Show me the data from @github:repos/owner/repo/issues
```

This fetches data from connected MCP servers using the format @server:resource. See [MCP resources](/docs/en/mcp#use-mcp-resources) for details.

Tips:

- File paths can be relative or absolute
- @ file references add `CLAUDE.md` in the file’s directory and parent directories to context
- Directory references show file listings, not contents
- You can reference multiple files in a single message (for example, “@file1.js and @file2.js”)

------------------------------------------------------------------------


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:

| Option                                                      | Where it runs                     | Best for                                                                                                                                                                                                 |
|:------------------------------------------------------------|:----------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [Routines](/docs/en/routines)                               | Anthropic-managed infrastructure  | Tasks that should run even when your computer is off. Can also trigger on API calls or GitHub events in addition to a schedule. Configure at [claude.ai/code/routines](https://claude.ai/code/routines). |
| [Desktop scheduled tasks](/docs/en/desktop-scheduled-tasks) | Your machine, via the desktop app | Tasks that need direct access to local files, tools, or uncommitted changes.                                                                                                                             |
| [GitHub Actions](/docs/en/github-actions)                   | Your CI pipeline                  | Tasks tied to repo events like opened PRs, or cron schedules that should live alongside your workflow config.                                                                                            |
| [`/loop`](/docs/en/scheduled-tasks)                         | The current CLI session           | Quick polling while a session is open. Tasks stop when you start a new conversation; `--resume` and `--continue` restore unexpired ones.                                                                 |

When writing prompts for scheduled tasks, be explicit about what success looks like and what to do with results. The task runs autonomously, so it can’t ask clarifying questions. For example: “Review open PRs labeled `needs-review`, leave inline comments on any issues, and post a summary in the `#eng-reviews` Slack channel.”

------------------------------------------------------------------------


Ask Claude about its capabilities

Claude has built-in access to its documentation and can answer questions about its own features and limitations.


Example questions

```python
can Claude Code create pull requests?
```

```python
how does Claude Code handle permissions?
```

```python
what skills are available?
```

```python
how do I use MCP with Claude Code?
```

```python
how do I configure Claude Code for Amazon Bedrock?
```

```python
what are the limitations of Claude Code?
```

Claude provides documentation-based answers to these questions. For hands-on demonstrations, run `/powerup` for interactive lessons with animated demos, or refer to the specific workflow sections above.

Tips:

- Claude always has access to the latest Claude Code documentation, regardless of the version you’re using
- Ask specific questions to get detailed answers
- Claude can explain complex features like MCP integration, enterprise configurations, and advanced workflows

------------------------------------------------------------------------


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.

```python
claude --continue
```

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

Work on a feature in one terminal while Claude fixes a bug in another, without the edits colliding. Each worktree is a separate checkout on its own branch.

```python
claude --worktree feature-auth
```

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

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.

```python
claude --permission-mode plan
```

You can also press `Shift+Tab` mid-session to toggle into plan mode. 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

Exploring a large codebase fills your context with file reads. Delegate the exploration so only the findings come back.

```python
use a subagent to investigate how our auth system handles token refresh
```

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

Run Claude non-interactively for CI, pre-commit hooks, or batch processing. Stdin and stdout work like any Unix tool.

```python
git log --oneline -20 | claude -p "summarize these recent commits"
```

See [Non-interactive mode](/docs/en/headless) for output formats, permission flags, and fan-out patterns.


Next steps

## Best practices

Patterns for getting the most out of Claude Code

## Manage sessions

Resume, name, and branch conversations

## Worktrees

Run isolated parallel sessions

## Extend Claude Code

Add skills, hooks, MCP, subagents, and plugins


---
## computer-use-427032da98.md

> ## Documentation Index
> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Let Claude use your computer from the CLI

> Enable computer use in the Claude Code CLI so Claude can open apps, click, type, and see your screen on macOS. Test native apps, debug visual issues, and automate GUI-only tools without leaving your terminal.

<Note>
  {/* plan-availability: feature=computer-use plans=pro,max */}

  Computer use is a research preview on macOS that requires a Pro or Max plan. It is not available on Team or Enterprise plans. It requires Claude Code v2.1.85 or later and an interactive session, so it is not available in non-interactive mode with the `-p` flag.
</Note>

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](/en/desktop#let-claude-use-your-computer).

## 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.

* **Build and validate native apps**: ask Claude to build a macOS menu bar app. Claude writes the Swift, compiles it, launches it, and clicks through every control to verify it works before you ever open it.
* **End-to-end UI testing**: point Claude at a local Electron app and say "test the onboarding flow." Claude opens the app, clicks through signup, and screenshots each step. No Playwright config, no test harness.
* **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

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:

* If you have an [MCP server](../06-MCP-Tools/mcp-208e742686.md) for the service, Claude uses that.
* If the task is a shell command, Claude uses Bash.
* If the task is browser work and you have [Claude in Chrome](../03-IDE-Integrations/use-claude-code-with-chrome-beta-claude-code-docs-4f2f5a5a96.md) set up, Claude uses that.
* If none of those apply, Claude uses computer use.

Screen control is reserved for things nothing else can reach: native apps, simulators, and tools without an API.

## 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.

<Steps>
  <Step title="Open the MCP menu">
    In an interactive Claude Code session, run:

    ```text theme={null}
    /mcp
    ```

    Find `computer-use` in the server list. It shows as disabled.
  </Step>

  <Step title="Enable the server">
    Select `computer-use` and choose **Enable**. The setting persists per project, so you only do this once for each project where you want computer use.
  </Step>

  <Step title="Grant macOS permissions">
    The first time Claude tries to use your computer, you'll see a prompt to grant two macOS permissions:

    * **Accessibility**: lets Claude click, type, and scroll
    * **Screen Recording**: lets Claude see what's on your screen

    The prompt includes links to open the relevant System Settings pane. Grant both, then select **Try again** in the prompt. macOS may require you to restart Claude Code after granting Screen Recording.
  </Step>
</Steps>

After setup, ask Claude to do something that needs the GUI:

```text theme={null}
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

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:

* Which apps Claude wants to control
* Any extra permissions requested, such as clipboard access
* How many other apps will be hidden while Claude works

Choose **Allow for this session** or **Deny**. Approvals last for the current session. You can approve multiple apps at once when Claude requests them together.

Apps with broad reach show an extra warning in the prompt so you know what approving them grants:

| Warning                    | Applies to                                                   |
| :------------------------- | :----------------------------------------------------------- |
| Equivalent to shell access | Terminal, iTerm, VS Code, Warp, and other terminals and IDEs |
| Can read or write any file | Finder                                                       |
| Can change system settings | System Settings                                              |

These apps aren't blocked. The warning lets you decide whether the task warrants that level of access.

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](/en/desktop#app-permissions) for the complete tier breakdown.

## 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

Computer use holds a machine-wide lock while active. If another Claude Code session is already using your computer, new attempts fail with a message telling you which session holds the lock. Finish or exit that session first.

### 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

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

When Claude acquires the lock, 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 releases the lock, unhides your apps, and returns control to you.

A second notification appears when Claude is done.

## Safety and the trust boundary

<Warning>
  Unlike the [sandboxed Bash tool](../22-Safety-Policy/sandboxing-claude-code-docs-5f97cd27c4.md), 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.
</Warning>

The built-in guardrails reduce risk without requiring configuration:

* **Per-app approval**: Claude can only control apps you've approved in the current session.
* **Sentinel warnings**: apps that grant shell, filesystem, or system settings access are flagged before you approve.
* **Terminal excluded from screenshots**: Claude never sees your terminal window, so on-screen prompts in your session can't feed back into the model.
* **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

These examples show common ways to combine computer use with coding tasks.

### Validate a native build

After making changes to a macOS or iOS app, have Claude compile and verify in one pass:

```text theme={null}
Build the MenuBarStats target, launch it, open the preferences window,
and verify the interval slider updates the label. Screenshot the
preferences window when you're done.
```

Claude runs `xcodebuild`, launches the app, interacts with the UI, and reports what it finds.

### Reproduce a layout bug

When a visual bug only appears at certain window sizes, let Claude find it:

```text theme={null}
The settings modal clips its footer on narrow windows. Resize the app
window down until you can reproduce it, screenshot the clipped state,
then check the CSS for the modal container.
```

Claude resizes the window, captures the broken state, and reads the relevant stylesheets.

### Test a simulator flow

Drive the iOS Simulator without writing XCTest:

```text theme={null}
Open the iOS Simulator, launch the app, tap through the onboarding
screens, and tell me if any screen takes more than a second to load.
```

Claude controls the simulator the same way you would with a mouse.

## Differences from the Desktop app

The CLI and Desktop surfaces share the same computer use engine, with a few differences:

| Feature              | Desktop                                                  | CLI                             |
| :------------------- | :------------------------------------------------------- | :------------------------------ |
| Platforms            | macOS and Windows                                        | macOS only                      |
| Enable               | Toggle in **Settings > General** (under **Desktop app**) | Enable `computer-use` in `/mcp` |
| Denied apps list     | Configurable in Settings                                 | Not yet available               |
| Auto-unhide toggle   | Optional                                                 | Always on                       |
| Dispatch integration | Dispatch-spawned sessions can use computer use           | Not applicable                  |

## Troubleshooting

### "Computer use is in use by another Claude session"

Another Claude Code session holds the lock. Finish the task in that session or exit it. 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 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`

The server only appears on eligible setups. Check that:

* You're on macOS. Computer use in the CLI is not available on Linux or Windows. On Windows, use [computer use in Desktop](/en/desktop#let-claude-use-your-computer) instead.
* You're running Claude Code v2.1.85 or later. Run `claude --version` to check.
* You're on a Pro or Max plan. Run `/status` to confirm your subscription.
* You're authenticated through claude.ai. Computer use is not available with third-party providers like Amazon Bedrock, Google Cloud Vertex AI, 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

* [Computer use in Desktop](/en/desktop#let-claude-use-your-computer): the same capability with a graphical settings page
* [Claude in Chrome](../03-IDE-Integrations/use-claude-code-with-chrome-beta-claude-code-docs-4f2f5a5a96.md): browser automation for web-based tasks
* [MCP](../06-MCP-Tools/mcp-208e742686.md): connect Claude to structured tools and APIs
* [Sandboxing](../22-Safety-Policy/sandboxing-claude-code-docs-5f97cd27c4.md): how Claude's Bash tool isolates filesystem and network access
* [Computer use safety guide](https://support.claude.com/en/articles/14128542): best practices for safe computer use


---
## computer-use.md

# Let Claude use your computer from the CLI

Enable computer use in the Claude Code CLI so Claude can open apps, click, type, and see your screen on macOS. Test native apps, debug visual issues, and automate GUI-only tools without leaving your terminal.

> Computer use is a research preview on macOS that requires a Pro or Max plan. It requires Claude Code v2.1.85 or later and an interactive session (not available with `-p` flag).

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.

## What you can do

- **Build and validate native apps**: write Swift, compile, launch, and click through controls to verify
- **End-to-end UI testing**: open an Electron app, click through signup, screenshot each step
- **Debug visual and layout issues**: resize windows, reproduce bugs, patch CSS, verify fixes
- **Drive GUI-only tools**: interact with design tools, hardware control panels, iOS Simulator

## When computer use applies

Claude tries the most precise tool first:

1. MCP server for the service
2. Bash for shell commands
3. Claude in Chrome for browser work
4. Computer use for everything else (native apps, simulators, tools without APIs)

## Enable computer use

1. Run `/mcp` in an interactive session
2. Find `computer-use` and select **Enable**
3. Grant macOS permissions:
   - **Accessibility**: lets Claude click, type, and scroll
   - **Screen Recording**: lets Claude see your screen

## Approve apps per session

The first time Claude needs a specific app in a session, a prompt appears showing which apps Claude wants to control. Choose **Allow for this session** or **Deny**.

Apps with broad reach show extra warnings:

| Warning                    | Applies to                           |
| :------------------------- | :----------------------------------- |
| Equivalent to shell access | Terminal, iTerm, VS Code, Warp       |
| Can read or write any file | Finder                               |
| Can change system settings | System Settings                      |

## How Claude works on your screen

- **One session at a time**: machine-wide lock while active
- **Apps hidden during use**: other apps are hidden so Claude interacts only with approved apps
- **Terminal excluded from screenshots**: Claude never sees its own output
- **Stop at any time**: press `Esc` anywhere or `Ctrl+C` in terminal

## Safety

- **Per-app approval**: Claude only controls approved apps
- **Sentinel warnings**: apps with shell/filesystem/system access are flagged
- **Global escape**: `Esc` key aborts computer use immediately
- **Lock file**: only one session can control your machine at a time

## Differences from Desktop app

| Feature              | Desktop                                       | CLI                             |
| :------------------- | :-------------------------------------------- | :------------------------------ |
| Platforms            | macOS and Windows                             | macOS only                      |
| Enable               | Toggle in Settings > General                  | Enable `computer-use` in `/mcp` |
| Denied apps list     | Configurable in Settings                      | Not yet available               |

## Troubleshooting

- **"Computer use is in use by another session"**: finish or exit the other session
- **macOS permissions prompt keeps reappearing**: quit Claude Code completely and restart
- **`computer-use` doesn't appear in `/mcp`**: check macOS, v2.1.85+, Pro/Max plan, claude.ai auth

## See Also

- [Computer use in Desktop](/en/desktop#let-claude-use-your-computer)
- [Claude in Chrome](chrome.md)
- [MCP](../06-MCP-Tools/General/connect-claude-code-to-tools-via-mcp-claude-code-docs.md)
- [Sandboxing](../22-Safety-Policy/sandboxing-claude-code-docs-5f97cd27c4.md)


---
## configure-permissions-claude-code-docs-7b0e64d485.md

# Configure permissions


Control what Claude Code can access and do with fine-grained permission rules, modes, and managed policies.


> ## Documentation Index
>
> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt>
>
> Use this file to discover all available pages before exploring further.

Claude Code supports fine-grained permissions so that you can specify exactly what the agent is allowed to do and what it cannot. Permission settings can be checked into version control and distributed to all developers in your organization, as well as customized by individual developers.


Permission system

Claude Code uses a tiered permission system to balance power and safety:

| Tool type         | Example          | Approval required | ”Yes, don’t ask again” behavior               |
|:------------------|:-----------------|:------------------|:----------------------------------------------|
| Read-only         | File reads, Grep | No                | N/A                                           |
| Bash commands     | Shell execution  | Yes               | Permanently per project directory and command |
| File modification | Edit/write files | Yes               | Until session end                             |


Manage permissions

You can view and manage Claude Code’s tool permissions with `/permissions`. This UI lists all permission rules and the settings.json file they are sourced from.

- **Allow** rules let Claude Code use the specified tool without manual approval.
- **Ask** rules prompt for confirmation whenever Claude Code tries to use the specified tool.
- **Deny** rules prevent Claude Code from using the specified tool.

Rules are evaluated in order: **deny -\> ask -\> allow**. The first matching rule wins, so deny rules always take precedence. Deny rules behave differently depending on whether they name a tool or scope a pattern within one. A bare tool name like `Bash` removes the tool from Claude’s context entirely, so Claude never sees it. A scoped rule like `Bash(rm *)` leaves the tool available and blocks matching calls when Claude attempts them.

Permission rules are enforced by Claude Code, not by the model. Instructions in your prompt or `CLAUDE.md` shape what Claude tries to do, but they don’t change what Claude Code allows. To grant or revoke access, use `/permissions`, the rules described here, a [permission mode](/docs/en/permission-modes), or a [PreToolUse hook](#extend-permissions-with-hooks).


Permission modes

Claude Code supports several permission modes that control how tools are approved. See [Permission modes](/docs/en/permission-modes) for when to use each one. Set the `defaultMode` in your [settings files](/docs/en/settings#settings-files):

| Mode                | Description                                                                                                                                                        |
|:--------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `default`           | Standard behavior: prompts for permission on first use of each tool                                                                                                |
| `acceptEdits`       | Automatically accepts file edits and common filesystem commands (`mkdir`, `touch`, `mv`, `cp`, etc.) for paths in the working directory or `additionalDirectories` |
| `plan`              | Plan Mode: Claude reads files and runs read-only shell commands to explore but does not edit your source files                                                     |
| `auto`              | Auto-approves tool calls with background safety checks that verify actions align with your request. Currently a research preview                                   |
| `dontAsk`           | Auto-denies tools unless pre-approved via `/permissions` or `permissions.allow` rules                                                                              |
| `bypassPermissions` | Skips all permission prompts. Root and home directory removals such as `rm -rf /` still prompt as a circuit breaker                                                |

`bypassPermissions` mode skips all permission prompts, including writes to common configuration directories. Removals targeting the filesystem root or home directory, such as `rm -rf /` and `rm -rf ~`, still prompt as a circuit breaker against model error. Only use this mode in isolated environments like containers or VMs where Claude Code cannot cause damage. Administrators can prevent this mode by setting `permissions.disableBypassPermissionsMode` to `"disable"` in [managed settings](#managed-settings).

To prevent `bypassPermissions` or `auto` mode from being used, set `permissions.disableBypassPermissionsMode` or `permissions.disableAutoMode` to `"disable"` in any [settings file](/docs/en/settings#settings-files). These are most useful in [managed settings](#managed-settings) where they cannot be overridden.


Permission rule syntax

Permission rules follow the format `Tool` or `Tool(specifier)`.


Match all uses of a tool

To match all uses of a tool, use just the tool name without parentheses:

| Rule       | Effect                         |
|:-----------|:-------------------------------|
| `Bash`     | Matches all Bash commands      |
| `WebFetch` | Matches all web fetch requests |
| `Read`     | Matches all file reads         |

`Bash(*)` is equivalent to `Bash` and matches all Bash commands. As a deny rule, both forms remove the tool from Claude’s context.


Use specifiers for fine-grained control

Add a specifier in parentheses to match specific tool uses:

| Rule                           | Effect                                                   |
|:-------------------------------|:---------------------------------------------------------|
| `Bash(npm run build)`          | Matches the exact command `npm run build`                |
| `Read(./.env)`                 | Matches reading the `.env` file in the current directory |
| `WebFetch(domain:example.com)` | Matches fetch requests to example.com                    |


Wildcard patterns

Bash rules support glob patterns with `*`. Wildcards can appear at any position in the command. This configuration allows npm and git commit commands while blocking git push:

```python
{
  "permissions": {
    "allow": [
      "Bash(npm run *)",
      "Bash(git commit *)",
      "Bash(git * main)",
      "Bash(* --version)",
      "Bash(* --help *)"
    ],
    "deny": [
      "Bash(git push *)"
    ]
  }
}
```

The space before `*` matters: `Bash(ls *)` matches `ls -la` but not `lsof`, while `Bash(ls*)` matches both. The `:*` suffix is an equivalent way to write a trailing wildcard, so `Bash(ls:*)` matches the same commands as `Bash(ls *)`. The permission dialog writes the space-separated form when you select “Yes, don’t ask again” for a command prefix. The `:*` form is only recognized at the end of a pattern. In a pattern like `Bash(git:* push)`, the colon is treated as a literal character and won’t match git commands.


Tool-specific permission rules


Bash

Bash permission rules support wildcard matching with `*`. Wildcards can appear at any position in the command, including at the beginning, middle, or end:

- `Bash(npm run build)` matches the exact Bash command `npm run build`
- `Bash(npm run test *)` matches Bash commands starting with `npm run test`
- `Bash(npm *)` matches any command starting with `npm `
- `Bash(* install)` matches any command ending with ` install`
- `Bash(git * main)` matches commands like `git checkout main` and `git log --oneline main`

A single `*` matches any sequence of characters including spaces, so one wildcard can span multiple arguments. `Bash(git *)` matches `git log --oneline --all`, and `Bash(git * main)` matches `git push origin main` as well as `git merge main`. When `*` appears at the end with a space before it (like `Bash(ls *)`), it enforces a word boundary, requiring the prefix to be followed by a space or end-of-string. For example, `Bash(ls *)` matches `ls -la` but not `lsof`. In contrast, `Bash(ls*)` without a space matches both `ls -la` and `lsof` because there’s no word boundary constraint.


Compound commands

Claude Code is aware of shell operators, so a rule like `Bash(safe-cmd *)` won’t give it permission to run the command `safe-cmd && other-cmd`. The recognized command separators are `&&`, `||`, `;`, `|`, `|&`, `&`, and newlines. A rule must match each subcommand independently.

When you approve a compound command with “Yes, don’t ask again”, Claude Code saves a separate rule for each subcommand that requires approval, rather than a single rule for the full compound string. For example, approving `git status && npm test` saves a rule for `npm test`, so future `npm test` invocations are recognized regardless of what precedes the `&&`. Subcommands like `cd` into a subdirectory generate their own Read rule for that path. Up to 5 rules may be saved for a single compound command.


Process wrappers

Before matching Bash rules, Claude Code strips a fixed set of process wrappers so a rule like `Bash(npm test *)` also matches `timeout 30 npm test`. The recognized wrappers are `timeout`, `time`, `nice`, `nohup`, and `stdbuf`. Bare `xargs` is also stripped, so `Bash(grep *)` matches `xargs grep pattern`. Stripping applies only when `xargs` has no flags: an invocation like `xargs -n1 grep pattern` is matched as an `xargs` command, so rules written for the inner command do not cover it. This wrapper list is built in and is not configurable. Development environment runners such as `direnv exec`, `devbox run`, `mise exec`, `npx`, and `docker exec` are not in the list. Because these tools execute their arguments as a command, a rule like `Bash(devbox run *)` matches whatever comes after `run`, including `devbox run rm -rf .`. To approve work inside an environment runner, write a specific rule that includes both the runner and the inner command, such as `Bash(devbox run npm test)`. Add one rule per inner command you want to allow. Exec wrappers such as `watch`, `setsid`, `ionice`, and `flock` always prompt and cannot be auto-approved by a prefix rule like `Bash(watch *)`. The same applies to `find` with `-exec` or `-delete`: a `Bash(find *)` rule does not cover these forms. To approve a specific invocation, write an exact-match rule for the full command string.


Read-only commands

Claude Code recognizes a built-in set of Bash commands as read-only and runs them without a permission prompt in every mode. These include `ls`, `cat`, `echo`, `pwd`, `head`, `tail`, `grep`, `find`, `wc`, `which`, `diff`, `stat`, `du`, `cd`, and read-only forms of `git`. The set is not configurable; to require a prompt for one of these commands, add an `ask` or `deny` rule for it. Unquoted glob patterns are permitted for commands whose every flag is read-only, so `ls *.ts` and `wc -l src/*.py` run without a prompt. Commands with write-capable or exec-capable flags, such as `find`, `sort`, `sed`, and `git`, still prompt when an unquoted glob is present because the glob could expand to a flag like `-delete`. A `cd` into a path inside your working directory or an [additional directory](#working-directories) is also read-only. A compound command like `cd packages/api && ls` runs without a prompt when each part qualifies on its own. Combining `cd` with `git` in one compound command always prompts, regardless of the target directory.

Bash permission patterns that try to constrain command arguments are fragile. For example, `Bash(curl http://github.com/ *)` intends to restrict curl to GitHub URLs, but won’t match variations like:

- Options before URL: `curl -X GET http://github.com/...`
- Different protocol: `curl https://github.com/...`
- Redirects: `curl -L http://bit.ly/xyz` (redirects to github)
- Variables: `URL=http://github.com && curl $URL`
- Extra spaces: `curl http://github.com`

For more reliable URL filtering, consider:

- **Restrict Bash network tools**: use deny rules to block `curl`, `wget`, and similar commands, then use the WebFetch tool with `WebFetch(domain:github.com)` permission for allowed domains
- **Use PreToolUse hooks**: implement a hook that validates URLs in Bash commands and blocks disallowed domains
- **Add CLAUDE.md guidance**: describe your allowed curl patterns in `CLAUDE.md`. This shapes what Claude tries but doesn’t enforce a boundary, so pair it with one of the options above

Note that using WebFetch alone does not prevent network access. If Bash is allowed, Claude can still use `curl`, `wget`, or other tools to reach any URL.


PowerShell

PowerShell permission rules use the same shape as Bash rules. Wildcards with `*` match at any position, the `:*` suffix is equivalent to a trailing ` *`, and a bare `PowerShell` or `PowerShell(*)` matches every command. This configuration allows `Get-ChildItem` and `git commit` commands while blocking `Remove-Item`:

```python
{
  "permissions": {
    "allow": [
      "PowerShell(Get-ChildItem *)",
      "PowerShell(git commit *)"
    ],
    "deny": [
      "PowerShell(Remove-Item *)"
    ]
  }
}
```

Common aliases are canonicalized before matching. A rule written for the cmdlet name also matches its aliases, so `PowerShell(Get-ChildItem *)` matches `gci`, `ls`, and `dir` as well. Matching is case-insensitive. Claude Code parses the PowerShell AST and checks each command in a compound command independently. Pipeline operators `|`, statement separators `;`, and on PowerShell 7+ the chain operators `&&` and `||` split a compound command into subcommands. A rule must match every subcommand for the compound command to be allowed.


Read and Edit

`Edit` rules apply to all built-in tools that edit files. Claude makes a best-effort attempt to apply `Read` rules to all built-in tools that read files like Grep and Glob, to `@file` mentions in your prompts, and to the selection and open-file context that a connected [IDE](/docs/en/vs-code#the-built-in-ide-mcp-server) shares with Claude.

Read and Edit deny rules apply to Claude’s built-in file tools and to file commands Claude Code recognizes in Bash, such as `cat`, `head`, `tail`, and `sed`. They do not apply to arbitrary subprocesses that read or write files indirectly, like a Python or Node script that opens files itself. For OS-level enforcement that blocks all processes from accessing a path, [enable the sandbox](/docs/en/sandboxing).

Read and Edit rules both follow the [gitignore](https://git-scm.com/docs/gitignore) specification with four distinct pattern types:

| Pattern            | Meaning                                | Example                          | Matches                        |
|--------------------|----------------------------------------|----------------------------------|--------------------------------|
| `//path`           | **Absolute** path from filesystem root | `Read(//Users/alice/secrets/**)` | `/Users/alice/secrets/**`      |
| `~/path`           | Path from **home** directory           | `Read(~/Documents/*.pdf)`        | `/Users/alice/Documents/*.pdf` |
| `/path`            | Path **relative to project root**      | `Edit(/src/**/*.ts)`             | `<project root>/src/**/*.ts`   |
| `path` or `./path` | Path **relative to current directory** | `Read(*.env)`                    | `<cwd>/*.env`                  |

A pattern like `/Users/alice/file` is NOT an absolute path. It’s relative to the project root. Use `//Users/alice/file` for absolute paths.

On Windows, paths are normalized to POSIX form before matching. `C:\Users\alice` becomes `/c/Users/alice`, so use `//c/**/.env` to match `.env` files anywhere on that drive. To match across all drives, use `//**/.env`. Examples:

- `Edit(/docs/**)`: edits in `<project>/docs/` (NOT `/docs/` and NOT `<project>/.claude/docs/`)
- `Read(~/.zshrc)`: reads your home directory’s `.zshrc`
- `Edit(//tmp/scratch.txt)`: edits the absolute path `/tmp/scratch.txt`
- `Read(src/**)`: reads from `<current-directory>/src/`

A rule only matches files under its anchor, so the anchor determines how far a deny rule reaches. Bare filenames follow gitignore semantics and match at any depth, so `Read(.env)` and `Read(**/.env)` are equivalent:

| Deny rule                       | Blocks                                       | Does not block                                       |
|---------------------------------|----------------------------------------------|------------------------------------------------------|
| `Read(.env)` or `Read(**/.env)` | any `.env` at or under the current directory | `.env` in a parent directory or another project      |
| `Read(//**/.env)`               | any `.env` anywhere on the filesystem        | nothing; the rule is anchored at the filesystem root |

In gitignore patterns, `*` matches files in a single directory while `**` matches recursively across directories. To allow all file access, use just the tool name without parentheses: `Read`, `Edit`, or `Write`.

When Claude accesses a symlink, permission rules check two paths: the symlink itself and the file it resolves to. Allow and deny rules treat that pair differently: allow rules fall back to prompting you, while deny rules block outright.

- **Allow rules**: apply only when both the symlink path and its target match. A symlink inside an allowed directory that points outside it still prompts you.
- **Deny rules**: apply when either the symlink path or its target matches. A symlink that points to a denied file is itself denied.

For example, with `Read(./project/**)` allowed and `Read(~/.ssh/**)` denied, a symlink at `./project/key` pointing to `~/.ssh/id_rsa` is blocked: the target fails the allow rule and matches the deny rule.


WebFetch

- `WebFetch(domain:example.com)` matches fetch requests to example.com


MCP

- `mcp__puppeteer` matches any tool provided by the `puppeteer` server (name configured in Claude Code)
- `mcp__puppeteer__*` wildcard syntax that also matches all tools from the `puppeteer` server
- `mcp__puppeteer__puppeteer_navigate` matches the `puppeteer_navigate` tool provided by the `puppeteer` server


Agent (subagents)

Use `Agent(AgentName)` rules to control which [subagents](/docs/en/sub-agents) Claude can use:

- `Agent(Explore)` matches the Explore subagent
- `Agent(Plan)` matches the Plan subagent
- `Agent(my-custom-agent)` matches a custom subagent named `my-custom-agent`

Add these rules to the `deny` array in your settings or use the `--disallowedTools` CLI flag to disable specific agents. To disable the Explore agent:

```python
{
  "permissions": {
    "deny": ["Agent(Explore)"]
  }
}
```


Extend permissions with hooks

[Claude Code hooks](/docs/en/hooks-guide) provide a way to register custom shell commands to perform permission evaluation at runtime. When Claude Code makes a tool call, PreToolUse hooks run before the permission prompt. The hook output can deny the tool call, force a prompt, or skip the prompt to let the call proceed. Hook decisions do not bypass permission rules. Deny and ask rules are evaluated regardless of what a PreToolUse hook returns, so a matching deny rule blocks the call and a matching ask rule still prompts even when the hook returned `"allow"` or `"ask"`. This preserves the deny-first precedence described in [Manage permissions](#manage-permissions), including deny rules set in managed settings. A blocking hook also takes precedence over allow rules. A hook that exits with code 2 stops the tool call before permission rules are evaluated, so the block applies even when an allow rule would otherwise let the call proceed. To run all Bash commands without prompts except for a few you want blocked, add `"Bash"` to your allow list and register a PreToolUse hook that rejects those specific commands. See [Block edits to protected files](/docs/en/hooks-guide#block-edits-to-protected-files) for a hook script you can adapt.


Working directories

By default, Claude has access to files in the directory where it was launched. You can extend this access:

- **During startup**: use `--add-dir <path>` CLI argument
- **During session**: use `/add-dir` command
- **Persistent configuration**: add to `additionalDirectories` in [settings files](/docs/en/settings#settings-files)

Files in additional directories follow the same permission rules as the original working directory: they become readable without prompts, and file editing permissions follow the current permission mode.


Additional directories grant file access, not configuration

Adding a directory extends where Claude can read and edit files. It does not make that directory a full configuration root: most `.claude/` configuration is not discovered from additional directories, though a few types are loaded as exceptions. The following configuration types are loaded from `--add-dir` directories:

| Configuration                                                               | Loaded from `--add-dir`                                                                                                                                            |
|:----------------------------------------------------------------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [Skills](/docs/en/skills) in `.claude/skills/`                              | Yes, with live reload                                                                                                                                              |
| Plugin settings in `.claude/settings.json`                                  | `enabledPlugins` and `extraKnownMarketplaces` only                                                                                                                 |
| [CLAUDE.md](/docs/en/memory) files, `.claude/rules/`, and `CLAUDE.local.md` | Only when `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1` is set. `CLAUDE.local.md` additionally requires the `local` setting source, which is enabled by default |

Subagents, commands, and output styles are discovered from the current working directory and its parents, your user directory at `~/.claude/`, and managed settings. Hooks and other `settings.json` keys load from the current working directory’s `.claude/` folder with no parent-directory fallback, alongside your user `~/.claude/settings.json` and managed settings. To share that configuration across projects, use one of these approaches:

- **User-level configuration**: place files in `~/.claude/agents/`, `~/.claude/output-styles/`, or `~/.claude/settings.json` to make them available in every project
- **Plugins**: package and distribute configuration as a [plugin](/docs/en/plugins) that teams can install
- **Launch from the config directory**: run Claude Code from the directory containing the `.claude/` configuration you want


How permissions interact with sandboxing

Permissions and [sandboxing](/docs/en/sandboxing) are complementary security layers:

- **Permissions** control which tools Claude Code can use and which files or domains it can access. They apply to all tools (Bash, Read, Edit, WebFetch, MCP, and others).
- **Sandboxing** provides OS-level enforcement that restricts the Bash tool’s filesystem and network access. It applies only to Bash commands and their child processes.

Use both for defense-in-depth:

- Permission deny rules block Claude from even attempting to access restricted resources
- Sandbox restrictions prevent Bash commands from reaching resources outside defined boundaries, even if a prompt injection bypasses Claude’s decision-making
- Filesystem restrictions in the sandbox combine the [`sandbox.filesystem`](/docs/en/sandboxing) settings with Read and Edit deny rules; both are merged into the final sandbox boundary
- Network restrictions combine WebFetch permission rules with the sandbox’s `allowedDomains` and `deniedDomains` lists

When sandboxing is enabled with `autoAllowBashIfSandboxed: true`, which is the default, sandboxed Bash commands run without prompting even if your permissions include `ask: Bash(*)`. The sandbox boundary substitutes for the per-command prompt. Explicit deny rules still apply, and `rm` or `rmdir` commands that target `/`, your home directory, or other critical system paths still trigger a prompt. See [sandbox modes](/docs/en/sandboxing#sandbox-modes) to change this behavior.


Managed settings

For organizations that need centralized control over Claude Code configuration, administrators can deploy managed settings that cannot be overridden by user or project settings. These policy settings follow the same format as regular settings files and can be delivered through MDM/OS-level policies, managed settings files, or [server-managed settings](/docs/en/server-managed-settings). See [settings files](/docs/en/settings#settings-files) for delivery mechanisms and file locations.


Managed-only settings

The following settings are only read from managed settings. Placing them in user or project settings files has no effect.

| Setting                                        | Description                                                                                                                                                                                                                                             |
|:-----------------------------------------------|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `allowedChannelPlugins`                        | Allowlist of channel plugins that may push messages. Replaces the default Anthropic allowlist when set. Requires `channelsEnabled: true`. See [Restrict which channel plugins can run](/docs/en/channels#restrict-which-channel-plugins-can-run)        |
| `allowManagedHooksOnly`                        | When `true`, only managed hooks, SDK hooks, and hooks from plugins force-enabled in managed settings `enabledPlugins` are loaded. User, project, and all other plugin hooks are blocked                                                                 |
| `allowManagedMcpServersOnly`                   | When `true`, only `allowedMcpServers` from managed settings are respected. `deniedMcpServers` still merges from all sources. See [Managed MCP configuration](/docs/en/mcp#managed-mcp-configuration)                                                    |
| `allowManagedPermissionRulesOnly`              | When `true`, prevents user and project settings from defining `allow`, `ask`, or `deny` permission rules. Only rules in managed settings apply                                                                                                          |
| `blockedMarketplaces`                          | Blocklist of marketplace sources. Blocked sources are checked before downloading, so they never touch the filesystem. See [managed marketplace restrictions](/docs/en/plugin-marketplaces#managed-marketplace-restrictions)                             |
| `channelsEnabled`                              | Allow [channels](/docs/en/channels) for the organization. See [enterprise controls](/docs/en/channels#enterprise-controls) for the default on each plan                                                                                                 |
| `forceRemoteSettingsRefresh`                   | When `true`, blocks CLI startup until remote managed settings are freshly fetched and exits if the fetch fails. See [fail-closed enforcement](/docs/en/server-managed-settings#enforce-fail-closed-startup)                                             |
| `pluginTrustMessage`                           | Custom message appended to the plugin trust warning shown before installation                                                                                                                                                                           |
| `sandbox.filesystem.allowManagedReadPathsOnly` | When `true`, only `filesystem.allowRead` paths from managed settings are respected. `denyRead` still merges from all sources                                                                                                                            |
| `sandbox.network.allowManagedDomainsOnly`      | When `true`, only `allowedDomains` and `WebFetch(domain:...)` allow rules from managed settings are respected. Non-allowed domains are blocked automatically without prompting the user. Denied domains still merge from all sources                    |
| `strictKnownMarketplaces`                      | Controls which plugin marketplace sources users can add and install plugins from. See [managed marketplace restrictions](/docs/en/plugin-marketplaces#managed-marketplace-restrictions)                                                                 |
| `wslInheritsWindowsSettings`                   | When `true` in the Windows HKLM registry key or `C:\Program Files\ClaudeCode\managed-settings.json`, WSL reads managed settings from the Windows policy chain in addition to `/etc/claude-code`. See [Settings files](/docs/en/settings#settings-files) |

`disableBypassPermissionsMode` is typically placed in managed settings to enforce organizational policy, but it works from any scope. A user can set it in their own settings to lock themselves out of bypass mode.

On Team and Enterprise plans, an admin enables or disables [Remote Control](/docs/en/remote-control) and [web sessions](/docs/en/claude-code-on-the-web) organization-wide in [Claude Code admin settings](https://claude.ai/admin-settings/claude-code). Remote Control can additionally be disabled per device with the [`disableRemoteControl`](/docs/en/settings#available-settings) managed setting. Web sessions have no per-device managed settings key.


Settings precedence

Permission rules follow the same [settings precedence](/docs/en/settings#settings-precedence) as all other Claude Code settings:

1.  **Managed settings**: cannot be overridden by any other level, including command line arguments
2.  **Command line arguments**: temporary session overrides
3.  **Local project settings** (`.claude/settings.local.json`)
4.  **Shared project settings** (`.claude/settings.json`)
5.  **User settings** (`~/.claude/settings.json`)

If a tool is denied at any level, no other level can allow it. For example, a managed settings deny cannot be overridden by `--allowedTools`, and `--disallowedTools` can add restrictions beyond what managed settings define. Embedding hosts can supply additional managed policy via the SDK `managedSettings` option when [`parentSettingsBehavior`](/docs/en/settings#settings-precedence) is set to `"merge"`; embedder values can tighten policy but not loosen it. For example, if user settings allow a permission and project settings deny it, the deny rule blocks it. The reverse is also true: a user-level deny blocks a project-level allow, because deny rules from any scope are evaluated before allow rules.


Example configurations

This [repository](https://github.com/anthropics/claude-code/tree/main/examples/settings) includes starter settings configurations for common deployment scenarios. Use these as starting points and adjust them to fit your needs.


See also

- [Settings](/docs/en/settings): complete configuration reference including the permission settings table
- [Configure auto mode](/docs/en/auto-mode-config): tell the auto mode classifier which infrastructure your organization trusts
- [Sandboxing](/docs/en/sandboxing): OS-level filesystem and network isolation for Bash commands
- [Authentication](/docs/en/authentication): set up user access to Claude Code
- [Security](/docs/en/security): security safeguards and best practices
- [Hooks](/docs/en/hooks-guide): automate workflows and extend permission evaluation


---
## configure-server-managed-settings-public-beta-claude-code-docs.md

# Configure server-managed settings (public beta)


Centrally configure Claude Code for your organization through server-delivered settings, without requiring device management infrastructure.


Server-managed settings allow administrators to centrally configure Claude Code through a web-based interface on Claude.ai. Claude Code clients automatically receive these settings when users authenticate with their organization credentials. This approach is designed for organizations that do not have device management infrastructure in place, or need to manage settings for users on unmanaged devices.

Server-managed settings are in public beta and 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. Features may evolve before general availability.

## 

Requirements

To use server-managed settings, you need:

- Claude for Teams or Claude for Enterprise plan
- Claude Code version 2.1.38 or later for Claude for Teams, or version 2.1.30 or later for Claude for Enterprise
- Network access to `api.anthropic.com`

## 

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/settings#settings-files) are deployed directly to devices through native OS policies (macOS managed preferences, Windows registry) or managed settings files.

| Approach | Best for | Security model |
|:---|:---|:---|
| **Server-managed settings** | Organizations without MDM, or users on unmanaged devices | Settings delivered from Anthropic’s servers at authentication time |
| **[Endpoint-managed settings](/docs/en/settings#settings-files)** | Organizations with MDM or endpoint management | Settings deployed to devices via MDM configuration profiles, registry policies, or managed settings files |

If your devices are enrolled in an MDM or endpoint management solution, endpoint-managed settings provide stronger security guarantees because the settings file can be protected from user modification at the OS level.

## 

Configure server-managed settings

1

[](#)

Open the admin console

In [Claude.ai](https://claude.ai), navigate to **Admin Settings \> Claude Code \> Managed settings**.

2

[](#)

Define your settings

Add your configuration as JSON. All [settings available in `settings.json`](/docs/en/settings#available-settings) are supported, including [managed-only settings](/docs/en/permissions#managed-only-settings) like `disableBypassPermissionsMode`.This example enforces a permission deny list and prevents users from bypassing permissions:

Report incorrect code

Copy


``` shiki
{
  "permissions": {
    "deny": [
      "Bash(curl *)",
      "Read(./.env)",
      "Read(./.env.*)",
      "Read(./secrets/**)"
    ]
  },
  "disableBypassPermissionsMode": "disable"
}
```

3

[](#)

Save and deploy

Save your changes. Claude Code clients receive the updated settings on their next startup or hourly polling cycle.

### 

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](#security-approval-dialogs), the user sees a prompt describing the managed settings on startup. You can also verify that managed permission rules are active by having a user run `/permissions` to view their effective permission rules.

### 

Access control

The following roles can manage server-managed settings:

- **Primary Owner**
- **Owner**

Restrict access to trusted personnel, as settings changes apply to all users in the organization.

### 

Current limitations

Server-managed settings have the following limitations during the beta period:

- Settings apply uniformly to all users in the organization. Per-group configurations are not yet supported.
- [MCP server configurations](/docs/en/mcp#managed-mcp-configuration) cannot be distributed through server-managed settings.

## 

Settings delivery

### 

Settings precedence

Server-managed settings and [endpoint-managed settings](/docs/en/settings#settings-files) both occupy the highest tier in the Claude Code [settings hierarchy](/docs/en/settings#settings-precedence). No other settings level can override them, including command line arguments. When both are present, server-managed settings take precedence and endpoint-managed settings are not used.

### 

Fetch and caching behavior

Claude Code fetches settings from Anthropic’s servers at startup and polls for updates hourly during active sessions. **First launch without cached settings:**

- Claude Code fetches settings asynchronously
- If the fetch fails, Claude Code continues without managed settings
- There is a brief window before settings load where restrictions are not yet enforced

**Subsequent launches with cached settings:**

- Cached settings apply immediately at startup
- Claude Code fetches fresh settings in the background
- Cached settings persist through network failures

Claude Code applies settings updates automatically without a restart, except for advanced settings like OpenTelemetry configuration, which require a full restart to take effect.

### 

Security approval dialogs

Certain settings that could pose security risks require explicit user approval before being applied:

- **Shell command settings**: settings that execute shell commands
- **Custom environment variables**: variables not in the known safe allowlist
- **Hook configurations**: any hook definition

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.

In non-interactive mode with the `-p` flag, Claude Code skips security dialogs and applies settings without user approval.

## 

Platform availability

Server-managed settings require a direct connection to `api.anthropic.com` and are not available when using third-party model providers:

- Amazon Bedrock
- Google Vertex AI
- Microsoft Foundry
- Custom API endpoints via `ANTHROPIC_BASE_URL` or [LLM gateways](/docs/en/llm-gateway)

## 

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

Server-managed settings provide centralized policy enforcement, but they operate as a client-side control. On unmanaged devices, users with admin or sudo access can modify the Claude Code binary, filesystem, or network configuration.

| Scenario | Behavior |
|:---|:---|
| User edits the cached settings file | Tampered file applies at startup, but correct settings restore on the next server fetch |
| User deletes the cached settings file | First-launch behavior occurs: settings fetch asynchronously with a brief unenforced window |
| API is unavailable | Cached settings apply if available, otherwise managed settings are not enforced until the next successful fetch |
| User authenticates with a different organization | Settings are not delivered for accounts outside the managed organization |
| User sets a non-default `ANTHROPIC_BASE_URL` | Server-managed settings are bypassed when using third-party API providers |

To detect runtime configuration changes, use [`ConfigChange` hooks](/docs/en/hooks#configchange) to log modifications or block unauthorized changes before they take effect. For stronger enforcement guarantees, use [endpoint-managed settings](/docs/en/settings#settings-files) on devices enrolled in an MDM solution.

## 

See also

Related pages for managing Claude Code configuration:

- [Settings](/docs/en/settings): complete configuration reference including all available settings
- [Endpoint-managed settings](/docs/en/settings#settings-files): managed settings deployed to devices by IT
- [Authentication](/docs/en/authentication): set up user access to Claude Code
- [Security](/docs/en/security): security safeguards and best practices


---
## configure-your-terminal-for-claude-code-claude-code-docs-6f181483c1.md

# Configure your terminal for Claude Code


Fix Shift+Enter for newlines, get a terminal bell when Claude finishes, configure tmux, match the color theme, and enable Vim mode in the Claude Code CLI.


> ## Documentation Index
>
> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt>
>
> Use this file to discover all available pages before exploring further.

Claude Code works in any terminal without configuration. This page is for when something specific is not behaving the way you expect. Find your symptom below. If everything already feels right, you do not need this page.

- [Shift+Enter submits instead of inserting a newline](#enter-multiline-prompts)
- [Option-key shortcuts do nothing on macOS](#enable-option-key-shortcuts-on-macos)
- [No sound or alert when Claude finishes](#get-a-terminal-bell-or-notification)
- [You run Claude Code inside tmux](#configure-tmux)
- [Display flickers or scrollback jumps](#switch-to-fullscreen-rendering)
- [You want Vim keys in the prompt](#edit-prompts-with-vim-keybindings)

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

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                         |
| VS Code, Cursor, Windsurf, Alacritty, Zed                               | Run `/terminal-setup` once                  |
| gnome-terminal, JetBrains IDEs such as PyCharm and Android Studio       | Not available; use Ctrl+J or `\` then Enter |

For VS Code, Cursor, Windsurf, Alacritty, and Zed, `/terminal-setup` writes Shift+Enter and other keybindings into the terminal’s configuration file. In VS Code, Cursor, and Windsurf it also sets `terminal.integrated.mouseWheelScrollSensitivity` in the editor settings for smoother scrolling in [fullscreen mode](/docs/en/fullscreen). Existing bindings and settings are left in place; if you see a message such as `VSCode terminal Shift+Enter key binding already configured`, no change was made. Run `/terminal-setup` directly in the host terminal rather than inside tmux or screen, since it needs to write to the host terminal’s configuration. If you are running inside tmux, Shift+Enter also requires the [tmux configuration below](#configure-tmux) 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

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.

- Apple Terminal

- iTerm2

- VS Code

Open Settings → Profiles → Keyboard and check “Use Option as Meta Key”.If you accepted Claude Code’s first-run prompt that offered “Option+Enter for newlines and visual bell”, this is already done. That prompt runs `/terminal-setup` for you, which enables Option as Meta and switches the audio bell to a visual screen flash in your Apple Terminal profile.

Open Settings → Profiles → Keys → General and set Left Option key and Right Option key to “Esc+”.Running `/terminal-setup` in iTerm2 enables “Applications in terminal may access clipboard” under Settings → General → Selection so the `/copy` command can write to your system clipboard. The command detects iTerm2 even when run from inside tmux. Restart iTerm2 for the change to take effect.

Add `"terminal.integrated.macOptionIsMeta": true` to your VS Code settings.

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

When Claude finishes a task or pauses for a permission prompt, it fires a notification event. 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 only in Ghostty, Kitty, and iTerm2. In other terminals, set [`preferredNotifChannel`](/docs/en/settings#available-settings) to `"terminal_bell"` to ring the terminal bell instead, or configure a [Notification hook](#play-a-sound-with-a-notification-hook) for a custom sound or command. The desktop notification reaches your local machine over SSH, so a remote session can still alert you. Ghostty and Kitty forward it to your OS notification center without further setup. iTerm2 requires you to enable forwarding:

1


Open iTerm2 notification settings

Go to Settings → Profiles → Terminal.

2


Enable alerts

Check “Notification Center Alerts”, then click “Filter Alerts” and enable “Send escape sequence-generated alerts”.

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](#configure-tmux).


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.

~/.claude/settings.json

```python
{
  "hooks": {
    "Notification": [
      {
        "hooks": [{ "type": "command", "command": "afplay /System/Library/Sounds/Glass.aiff" }]
      }
    ]
  }
}
```


Configure tmux

When Claude Code runs inside tmux, two things break by default: Shift+Enter submits instead of inserting a newline, and desktop notifications and the [progress bar](/docs/en/settings#available-settings) never reach the outer terminal. Add these lines to `~/.tmux.conf`, then run `tmux source-file ~/.tmux.conf` to apply them to the running server:

~/.tmux.conf

```python
set -g allow-passthrough on
set -s extended-keys on
set -as terminal-features 'xterm*:extkeys'
```

The `allow-passthrough` line lets notifications and progress updates reach the outer terminal instead of being swallowed by tmux. The `extended-keys` lines let tmux distinguish Shift+Enter from plain Enter so the newline shortcut works.


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

Custom themes require Claude Code v2.1.118 or later.

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-reference#themes). 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:

| Field       | Type   | Description                                                                                                                                     |
|:------------|:-------|:------------------------------------------------------------------------------------------------------------------------------------------------|
| `name`      | string | Display label shown in `/theme`. Defaults to the filename slug                                                                                  |
| `base`      | string | Built-in preset the theme starts from: `dark`, `light`, `dark-daltonized`, `light-daltonized`, `dark-ansi`, or `light-ansi`. Defaults to `dark` |
| `overrides` | object | Map of color token names to color values. Tokens not listed here fall through to the base preset                                                |

Color values accept `#rrggbb`, `#rgb`, `rgb(r,g,b)`, `ansi256(n)`, or `ansi:<name>` where `<name>` is one of the 16 standard ANSI color names such as `red` or `cyanBright`. Unknown tokens and invalid color values are ignored, so a typo cannot break rendering. The following example defines a theme that keeps the dark preset but recolors the prompt accent, error text, and success text:

~/.claude/themes/dracula.json

```python
{
  "name": "Dracula",
  "base": "dark",
  "overrides": {
    "claude": "#bd93f9",
    "error": "#ff5555",
    "success": "#50fa7b"
  }
}
```

Claude Code watches `~/.claude/themes/` and reloads when a file changes, so edits made in your editor apply to a running session without a restart. The reference below covers the tokens you can set in `overrides`. The interactive editor in `/theme` shows the same tokens with a live preview, plus a few single-purpose accents such as onboarding screen colors that are omitted here.

Color token reference

The following example combines tokens from several of the groups below: the brand accent, the plan mode border, the diff backgrounds, and the fullscreen message background.

~/.claude/themes/midnight.json

```python
{
  "name": "Midnight",
  "base": "dark",
  "overrides": {
    "claude": "#a78bfa",
    "planMode": "#38bdf8",
    "diffAdded": "#14532d",
    "diffRemoved": "#7f1d1d",
    "userMessageBackground": "#1e1b4b"
  }
}
```


Text and accent colors

Control the primary brand accent and the foreground text shades used throughout the interface.

| Token         | Controls                                                         |
|:--------------|:-----------------------------------------------------------------|
| `claude`      | Primary brand accent, used for the spinner and assistant label   |
| `text`        | Default foreground text                                          |
| `inverseText` | Text drawn on top of a colored background, such as status badges |
| `inactive`    | Secondary text such as hints, timestamps, and disabled items     |
| `subtle`      | Faint borders and de-emphasized secondary text                   |
| `suggestion`  | Autocomplete suggestions and selection highlight in pickers      |
| `permission`  | Dialog borders, including permission prompts and pickers         |
| `remember`    | Memory and `CLAUDE.md` indicators                                |


Status colors

Signal success, failure, and warning states across messages and indicators.

| Token     | Controls                                             |
|:----------|:-----------------------------------------------------|
| `success` | Success messages and passing checks                  |
| `error`   | Error messages and failures                          |
| `warning` | Warnings, caution messages, and the auto mode border |
| `merged`  | Merged pull request status                           |


Input box and mode indicators

Set the input box border color and the accent shown while a permission mode or indicator is active.

| Token          | Controls                                           |
|:---------------|:---------------------------------------------------|
| `promptBorder` | Input box border in the default permission mode    |
| `planMode`     | Plan mode accent and border                        |
| `autoAccept`   | Accept-edits mode accent and border                |
| `bashBorder`   | Input box border when entering a `!` shell command |
| `ide`          | IDE connection indicator                           |
| `fastMode`     | Fast mode indicator                                |


Diff rendering

Color added and removed code in file edits and reviews.

| Token               | Controls                                           |
|:--------------------|:---------------------------------------------------|
| `diffAdded`         | Background of added lines                          |
| `diffRemoved`       | Background of removed lines                        |
| `diffAddedDimmed`   | Background of unchanged context near added lines   |
| `diffRemovedDimmed` | Background of unchanged context near removed lines |
| `diffAddedWord`     | Word-level highlight within an added line          |
| `diffRemovedWord`   | Word-level highlight within a removed line         |


Fullscreen mode

Apply only in [fullscreen rendering mode](/docs/en/fullscreen), where messages have a background fill.

| Token                        | Controls                                                           |
|:-----------------------------|:-------------------------------------------------------------------|
| `userMessageBackground`      | Background behind your messages in the transcript                  |
| `userMessageBackgroundHover` | Background behind a message while hovered or expanded              |
| `messageActionsBackground`   | Background behind the selected message when the action bar is open |
| `bashMessageBackgroundColor` | Background behind `!` shell command entries in the transcript      |
| `memoryBackgroundColor`      | Background behind `#` memory entries in the transcript             |
| `selectionBg`                | Background of text selected with the mouse                         |


Usage meter and speaker labels

Adjust the bar shown in the `/usage` view and the labels that distinguish your messages from Claude’s.

| Token              | Controls                                          |
|:-------------------|:--------------------------------------------------|
| `rate_limit_fill`  | Filled portion of the usage meter                 |
| `rate_limit_empty` | Unfilled portion of the usage meter               |
| `briefLabelYou`    | Color of the `You` label on your messages         |
| `briefLabelClaude` | Color of the `Claude` label on assistant messages |


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.

- `claude` and `claudeShimmer`
- `warning` and `warningShimmer`
- `permission` and `permissionShimmer`
- `promptBorder` and `promptBorderShimmer`
- `inactive` and `inactiveShimmer`
- `fastMode` and `fastModeShimmer`

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.The [`ultrathink`](/docs/en/model-config#use-ultrathink-for-one-off-deep-reasoning) and [`ultraplan`](/docs/en/ultraplan) keywords in the prompt input are rendered 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

If the display flickers or the scroll position jumps while Claude is working, switch to [fullscreen rendering mode](/docs/en/fullscreen). It draws to a separate screen the terminal reserves for full-screen apps instead of appending to your normal scrollback, which keeps memory usage flat and adds mouse support for scrolling and selection. In this mode you scroll with the mouse or PageUp inside Claude Code rather than with your terminal’s native scrollback; see the [fullscreen page](/docs/en/fullscreen#search-and-review-the-conversation) for how to search and copy. Run `/tui fullscreen` to switch in the current session with your conversation intact. To make it the default, set the `CLAUDE_CODE_NO_FLICKER` environment variable before starting Claude Code:

Bash and Zsh

PowerShell

~/.claude/settings.json

```python
CLAUDE_CODE_NO_FLICKER=1 claude
```


Paste large content

When you paste more than 10,000 characters into the prompt, Claude Code collapses the input to a `[Pasted text]` placeholder so the input box stays usable. The full content is still sent to Claude when you submit. The VS Code integrated terminal can drop characters from very large pastes before they reach Claude Code, so prefer file-based workflows there. 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. This keeps the conversation transcript readable and lets Claude reference the file by path in later turns.


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#available-settings) 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 are not remappable through the keybindings file. 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

- [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
- [Fullscreen rendering](/docs/en/fullscreen): details on scrolling, search, and copy in fullscreen mode
- [Hooks guide](/docs/en/hooks-guide): more Notification hook examples for Linux and Windows
- [Troubleshooting](/docs/en/troubleshooting): fixes for issues outside terminal configuration


---
## configure.md

# Configure Hookify Rules

**Load hookify:writing-rules skill first** to understand rule format.

Enable or disable existing hookify rules using an interactive interface.

## Steps

### 1. Find Existing Rules

Use Glob tool to find all hookify rule files:
```
pattern: ".claude/hookify.*.local.md"
```

If no rules found, inform user:
```
No hookify rules configured yet. Use `/hookify` to create your first rule.
```

### 2. Read Current State

For each rule file:
- Read the file
- Extract `name` and `enabled` fields from frontmatter
- Build list of rules with current state

### 3. Ask User Which Rules to Toggle

Use AskUserQuestion to let user select rules:

```json
{
  "questions": [
    {
      "question": "Which rules would you like to enable or disable?",
      "header": "Configure",
      "multiSelect": true,
      "options": [
        {
          "label": "warn-dangerous-rm (currently enabled)",
          "description": "Warns about rm -rf commands"
        },
        {
          "label": "warn-console-log (currently disabled)",
          "description": "Warns about console.log in code"
        },
        {
          "label": "require-tests (currently enabled)",
          "description": "Requires tests before stopping"
        }
      ]
    }
  ]
}
```

**Option format:**
- Label: `{rule-name} (currently {enabled|disabled})`
- Description: Brief description from rule's message or pattern

### 4. Parse User Selection

For each selected rule:
- Determine current state from label (enabled/disabled)
- Toggle state: enabled → disabled, disabled → enabled

### 5. Update Rule Files

For each rule to toggle:
- Use Read tool to read current content
- Use Edit tool to change `enabled: true` to `enabled: false` (or vice versa)
- Handle both with and without quotes

**Edit pattern for enabling:**
```
old_string: "enabled: false"
new_string: "enabled: true"
```

**Edit pattern for disabling:**
```
old_string: "enabled: true"
new_string: "enabled: false"
```

### 6. Confirm Changes

Show user what was changed:

```
## Hookify Rules Updated

**Enabled:**
- warn-console-log

**Disabled:**
- warn-dangerous-rm

**Unchanged:**
- require-tests

Changes apply immediately - no restart needed
```

## Important Notes

- Changes take effect immediately on next tool use
- You can also manually edit .claude/hookify.*.local.md files
- To permanently remove a rule, delete its .local.md file
- Use `/hookify:list` to see all configured rules

## Edge Cases

**No rules to configure:**
- Show message about using `/hookify` to create rules first

**User selects no rules:**
- Inform that no changes were made

**File read/write errors:**
- Inform user of specific error
- Suggest manual editing as fallback


---
## context-window-d266068204.md

> ## Documentation Index
> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Explore the context window

> An interactive simulation of how Claude Code's context window fills during a session. See what loads automatically, what each file read costs, and when rules and hooks fire.

export const ContextWindow = () => {
  const MAX = 200000;
  const STARTUP_END = 0.2;
  {}
  const EVENTS = useMemo(() => [{}, {
    t: 0.015,
    kind: 'auto',
    label: 'System prompt',
    tokens: 4200,
    color: '#6B6964',
    vis: 'hidden',
    desc: 'Core instructions for behavior, tool use, and response formatting. Always loaded first. You never see it.',
    link: null
  }, {
    t: 0.035,
    kind: 'auto',
    label: 'Auto memory (MEMORY.md)',
    tokens: 680,
    color: '#E8A45C',
    vis: 'hidden',
    desc: "Claude's notes to itself from previous sessions: build commands it learned, patterns it noticed, mistakes to avoid. The first 200 lines or 25KB, whichever comes first, are loaded into the conversation context.",
    link: '/en/memory#auto-memory'
  }, {
    t: 0.06,
    kind: 'auto',
    label: 'Environment info',
    tokens: 280,
    color: '#6B6964',
    vis: 'hidden',
    desc: 'Working directory, platform, shell, OS version, and whether this is a git repo. Git branch, status, and recent commits load as a separate block at the very end of the system prompt.',
    link: null
  }, {
    t: 0.08,
    kind: 'auto',
    label: 'MCP tools (deferred)',
    tokens: 120,
    color: '#9B7BC4',
    vis: 'hidden',
    desc: 'MCP tool names listed so Claude knows what is available. By default, full schemas stay deferred and Claude loads specific ones on demand via tool search when a task needs them. Set `ENABLE_TOOL_SEARCH=auto` to load schemas upfront when they fit within 10% of the context window, or `ENABLE_TOOL_SEARCH=false` to load everything.',
    link: '/en/mcp#scale-with-mcp-tool-search'
  }, {
    t: 0.1,
    kind: 'auto',
    label: 'Skill descriptions',
    tokens: 450,
    color: '#D4A843',
    vis: 'hidden',
    noSurviveCompact: true,
    desc: 'One-line descriptions of available skills so Claude knows what it can invoke. Full skill content loads only when Claude actually uses one. Skills with `disable-model-invocation: true` are not in this list. They stay completely out of context until you invoke them with `/name`. Unlike the rest of the startup content, this listing is not re-injected after `/compact`. Only skills you actually invoked get preserved.',
    link: '/en/skills'
  }, {
    t: 0.12,
    kind: 'auto',
    label: '~/.claude/CLAUDE.md',
    tokens: 320,
    color: '#6A9BCC',
    vis: 'hidden',
    desc: 'Your global preferences. Applies to every project. Loaded alongside project instructions at the start of every conversation.',
    link: '/en/memory#choose-where-to-put-claude-md-files'
  }, {
    t: 0.14,
    kind: 'auto',
    label: 'Project CLAUDE.md',
    tokens: 1800,
    color: '#6A9BCC',
    vis: 'hidden',
    desc: 'Project conventions, build commands, architecture notes. The most important file you can create. Lives in your project root, so your whole team gets the same instructions.',
    tip: 'Keep it under 200 lines. Move reference content to skills or path-scoped rules so it only loads when needed.',
    link: '/en/memory'
  }, {}, {
    t: 0.22,
    kind: 'user',
    label: 'Your prompt',
    tokens: 45,
    color: '#558A42',
    vis: 'full',
    desc: '"Fix the auth bug where users get 401 after token refresh"',
    link: null
  }, {}, {
    t: 0.28,
    kind: 'claude',
    label: 'Read src/api/auth.ts',
    tokens: 2400,
    color: '#8A8880',
    vis: 'brief',
    desc: 'Main auth file. You see "Read auth.ts" in your terminal, but the 2,400 tokens of file content only Claude sees.',
    tip: 'File reads dominate context usage. Be specific in prompts ("fix the bug in auth.ts") so Claude reads fewer files. For research-heavy tasks, use a subagent.',
    link: null
  }, {
    t: 0.32,
    kind: 'claude',
    label: 'Read src/lib/tokens.ts',
    tokens: 1100,
    color: '#8A8880',
    vis: 'brief',
    desc: 'Following imports to the token module. Shown as a one-liner in your terminal.',
    link: null
  }, {
    t: 0.35,
    kind: 'auto',
    label: 'Rule: api-conventions.md',
    tokens: 380,
    color: '#4A9B8E',
    vis: 'brief',
    desc: 'This rule in `.claude/rules/` has a `paths:` pattern matching `src/api/**`. It loaded automatically when Claude read a file in that directory. You see "Loaded .claude/rules/api-conventions.md" in your terminal, but not the rule content.',
    link: '/en/memory#path-specific-rules'
  }, {
    t: 0.38,
    kind: 'claude',
    label: 'Read middleware.ts',
    tokens: 1800,
    color: '#8A8880',
    vis: 'brief',
    desc: 'Tracing the auth flow deeper.',
    link: null
  }, {
    t: 0.41,
    kind: 'claude',
    label: 'Read auth.test.ts',
    tokens: 1600,
    color: '#8A8880',
    vis: 'brief',
    desc: 'Checking existing tests for expected behavior.',
    link: null
  }, {
    t: 0.44,
    kind: 'auto',
    label: 'Rule: testing.md',
    tokens: 290,
    color: '#4A9B8E',
    vis: 'brief',
    desc: 'Another path-scoped rule, this one matching `*.test.ts` files. Triggered when Claude read auth.test.ts. Shown as a one-line "Loaded" notice.',
    link: '/en/memory#path-specific-rules'
  }, {
    t: 0.47,
    kind: 'claude',
    label: 'grep "refreshToken"',
    tokens: 600,
    color: '#A09E96',
    vis: 'brief',
    desc: 'Search results across the codebase. You see the command ran, not the full output.',
    link: null
  }, {}, {
    t: 0.53,
    kind: 'claude',
    label: "Claude's analysis",
    tokens: 800,
    color: '#D97757',
    vis: 'full',
    desc: 'Explains the bug: token invalidated too early in the rotation. This text appears in your terminal.',
    link: null
  }, {
    t: 0.57,
    kind: 'claude',
    label: 'Edit auth.ts',
    tokens: 400,
    color: '#D97757',
    vis: 'full',
    desc: 'Fixes the token rotation order. The diff appears in your terminal.',
    link: null
  }, {
    t: 0.59,
    kind: 'hook',
    label: 'Hook: prettier',
    tokens: 120,
    color: '#B8860B',
    vis: 'hidden',
    desc: 'A PostToolUse hook in `settings.json` runs prettier after every file edit and reports back via `hookSpecificOutput.additionalContext`. That field enters Claude\'s context. Plain stdout on exit 0 does not. It is written to the debug log only.',
    tip: 'Output JSON with `additionalContext` to send info to Claude. For PostToolUse hooks, exit code 2 surfaces stderr as an error but cannot block since the tool already ran. Keep output concise since it enters context without truncation.',
    link: '/en/hooks-guide'
  }, {
    t: 0.62,
    kind: 'claude',
    label: 'Edit auth.test.ts',
    tokens: 600,
    color: '#D97757',
    vis: 'full',
    desc: 'Adds a regression test for the fix. The diff appears in your terminal.',
    link: null
  }, {
    t: 0.64,
    kind: 'hook',
    label: 'Hook: prettier',
    tokens: 100,
    color: '#B8860B',
    vis: 'hidden',
    desc: 'The same hook fires again for the test file. Every matching tool event triggers it.',
    link: '/en/hooks-guide'
  }, {
    t: 0.67,
    kind: 'claude',
    label: 'npm test output',
    tokens: 1200,
    color: '#A09E96',
    vis: 'brief',
    desc: 'Runs the test suite. You see "Running npm test..." and the pass count, not the full 1,200 tokens of output.',
    link: null
  }, {
    t: 0.70,
    kind: 'claude',
    label: 'Summary',
    tokens: 400,
    color: '#D97757',
    vis: 'full',
    desc: '"Fixed token rotation. Added regression test. All tests pass."',
    link: null
  }, {}, {
    t: 0.72,
    kind: 'user',
    label: 'Your follow-up',
    tokens: 40,
    color: '#558A42',
    vis: 'full',
    desc: '"Use a subagent to research session timeout handling, then fix it"',
    tip: 'Follow-ups add to the same context. Delegating research to a subagent keeps large file reads out of your main window.',
    link: null
  }, {
    t: 0.79,
    kind: 'claude',
    label: 'Spawn research subagent',
    tokens: 80,
    color: '#D97757',
    vis: 'brief',
    desc: "Claude delegates the research to a subagent with a fresh, separate context window. It loads CLAUDE.md and the same MCP and skill setup, but starts without your conversation history or the main session's auto memory.",
    link: '/en/sub-agents'
  }, {
    t: 0.795,
    kind: 'sub',
    label: 'System prompt',
    tokens: 0,
    subTokens: 900,
    color: '#6B6964',
    vis: 'hidden',
    desc: "The subagent gets its own system prompt, shorter than the main session's. For the general-purpose agent, it's a brief prompt plus environment details. The main session's auto memory is not included. If a custom agent has memory: in its frontmatter, it loads its own separate MEMORY.md here instead.",
    link: '/en/sub-agents#enable-persistent-memory'
  }, {
    t: 0.80,
    kind: 'sub',
    label: 'Project CLAUDE.md (own copy)',
    tokens: 0,
    subTokens: 1800,
    color: '#6A9BCC',
    vis: 'hidden',
    desc: "The subagent loads CLAUDE.md too. Same file, same content, but it counts against the subagent's context, not yours. The built-in Explore and Plan agents skip this for a smaller context.",
    link: '/en/sub-agents'
  }, {
    t: 0.805,
    kind: 'sub',
    label: 'MCP tools + skills',
    tokens: 0,
    subTokens: 970,
    color: '#9B7BC4',
    vis: 'hidden',
    desc: "The subagent has access to the same MCP servers and skills. It gets most of the parent's tools, minus several that don't apply in a nested context, including plan-mode controls, background-task tools, and by default the Agent tool itself to prevent recursion.",
    link: '/en/sub-agents'
  }, {
    t: 0.81,
    kind: 'sub',
    label: 'Task prompt from main',
    tokens: 0,
    subTokens: 120,
    color: '#558A42',
    vis: 'hidden',
    desc: "Instead of a user prompt, the subagent receives the task Claude wrote for it: 'Research session timeout handling in this codebase.'",
    link: '/en/sub-agents'
  }, {
    t: 0.82,
    kind: 'sub',
    label: 'Read session.ts',
    tokens: 0,
    subTokens: 2200,
    color: '#8A8880',
    vis: 'hidden',
    desc: "Now the subagent does its work. This file read fills the subagent's context, not yours.",
    link: '/en/sub-agents'
  }, {
    t: 0.825,
    kind: 'sub',
    label: 'Read timeouts.ts',
    tokens: 0,
    subTokens: 800,
    color: '#8A8880',
    vis: 'hidden',
    desc: "Another file read in the subagent's separate context.",
    link: '/en/sub-agents'
  }, {
    t: 0.83,
    kind: 'sub',
    label: 'Read config/*.ts',
    tokens: 0,
    subTokens: 3100,
    color: '#8A8880',
    vis: 'hidden',
    desc: "The subagent can read as many files as it needs. None of this touches your main context.",
    link: '/en/sub-agents'
  }, {
    t: 0.85,
    kind: 'claude',
    label: 'Subagent returns summary',
    tokens: 420,
    color: '#D97757',
    vis: 'brief',
    desc: "Only the subagent's final text response comes back to your context, plus a small metadata trailer with token counts and duration. The subagent read 6,100 tokens of files. You got a 420-token result. That's the context savings.",
    link: '/en/sub-agents'
  }, {
    t: 0.86,
    kind: 'claude',
    label: "Claude's response",
    tokens: 1200,
    color: '#D97757',
    vis: 'full',
    desc: 'Analysis and fix for session timeouts. This text appears in your terminal.',
    link: null
  }, {}, {
    t: 0.875,
    kind: 'user',
    label: '!git status',
    tokens: 180,
    color: '#558A42',
    vis: 'full',
    desc: "You ran a shell command with the ! prefix to see which files Claude modified. The command and its output both enter context as part of your message. Useful for grounding Claude in command output without Claude running it.",
    link: '/en/interactive-mode#bash-mode-with-prefix'
  }, {
    t: 0.89,
    kind: 'user',
    label: '/commit-push',
    tokens: 620,
    color: '#558A42',
    vis: 'brief',
    desc: 'You invoked a skill that has `disable-model-invocation: true`. Its description was not in the skill index at startup, so it cost zero context until this moment. Now the full skill content loads and Claude follows its instructions to stage, commit, and push your changes.',
    tip: 'Set `disable-model-invocation: true` on skills with side effects like committing, deploying, or sending messages. They stay out of context entirely until you need them.',
    link: '/en/skills#control-who-invokes-a-skill'
  }, {}, {
    t: 0.93,
    kind: 'compact',
    label: '/compact',
    tokens: 0,
    color: '#D97757',
    vis: 'brief',
    desc: 'Replaces the conversation with a structured summary. You see a "Conversation compacted" message. The summarization happens without appearing in your terminal.',
    link: '/en/how-claude-code-works#the-context-window'
  }].filter(e => e.t !== undefined), []);
  const VIS_META = {
    hidden: {
      label: 'Invisible in your terminal',
      sub: 'This content does not appear in your terminal.'
    },
    brief: {
      label: 'One-liner in your terminal',
      sub: 'You see a brief mention, not the full content.'
    },
    full: {
      label: 'Shown in your terminal',
      sub: 'The actual content appears in your terminal.'
    }
  };
  {}
  const GATES = [{
    at: 0.18,
    kind: 'prompt',
    text: 'Fix the auth bug where users get 401 after token refresh',
    resumeTo: 0.22
  }, {
    at: 0.705,
    kind: 'prompt',
    text: 'Use a subagent to research session timeout handling, then fix it',
    resumeTo: 0.72
  }, {
    at: 0.865,
    kind: 'bang',
    text: '!git status',
    resumeTo: 0.875
  }, {
    at: 0.88,
    kind: 'slash',
    text: '/commit-push',
    resumeTo: 0.89
  }, {
    at: 0.90,
    kind: 'compact',
    text: '/compact',
    resumeTo: 1
  }];
  const KIND_META = {
    auto: {
      badge: 'auto',
      detail: 'Auto-loaded',
      badgeBg: 'rgba(94,93,89,0.15)',
      badgeColor: '#8A8880'
    },
    user: {
      badge: 'you',
      detail: 'You typed this',
      badgeBg: 'rgba(85,138,66,0.15)',
      badgeColor: '#6BA656'
    },
    claude: {
      badge: 'claude',
      detail: "Claude's work",
      badgeBg: 'rgba(217,119,87,0.12)',
      badgeColor: '#D97757'
    },
    hook: {
      badge: 'hook',
      detail: 'Hook (automatic)',
      badgeBg: 'rgba(184,134,11,0.15)',
      badgeColor: '#CCA020'
    },
    compact: {
      badge: 'compact',
      detail: 'Compaction',
      badgeBg: 'rgba(217,119,87,0.12)',
      badgeColor: '#D97757'
    },
    sub: {
      badge: 'subagent',
      detail: "In subagent's context",
      badgeBg: 'rgba(155,123,196,0.12)',
      badgeColor: '#9B7BC4'
    }
  };
  const LEGEND = [{
    c: '#6B6964',
    l: 'System'
  }, {
    c: '#6A9BCC',
    l: 'CLAUDE.md'
  }, {
    c: '#E8A45C',
    l: 'Memory'
  }, {
    c: '#D4A843',
    l: 'Skills'
  }, {
    c: '#9B7BC4',
    l: 'MCP'
  }, {
    c: '#4A9B8E',
    l: 'Rules'
  }, {
    c: '#558A42',
    l: 'You'
  }, {
    c: '#8A8880',
    l: 'Files'
  }, {
    c: '#A09E96',
    l: 'Output'
  }, {
    c: '#D97757',
    l: 'Claude'
  }, {
    c: '#B8860B',
    l: 'Hooks'
  }];
  const fmt = n => n >= 1000 ? (n / 1000).toFixed(1).replace(/\.0$/, '') + 'K' : n + '';
  const [time, setTime] = useState(0);
  const [playing, setPlaying] = useState(false);
  const [hovIdx, setHovIdx] = useState(null);
  const [selIdx, setSelIdx] = useState(null);
  const [hovCat, setHovCat] = useState(null);
  const [gatesPassed, setGatesPassed] = useState(0);
  const [mounted, setMounted] = useState(false);
  const [hasInteracted, setHasInteracted] = useState(false);
  const lastRef = useRef(null);
  const scrollRef = useRef(null);
  const detailRef = useRef(null);
  useEffect(() => setMounted(true), []);
  const activeGate = GATES.find((g, i) => i >= gatesPassed && time >= g.at && time < g.resumeTo);
  useEffect(() => {
    if (!playing) return;
    let raf;
    let stopped = false;
    const tick = ts => {
      if (stopped) return;
      if (!lastRef.current) lastRef.current = ts;
      const dt = (ts - lastRef.current) / 1000;
      lastRef.current = ts;
      setTime(prev => {
        const next = prev + dt * 0.032;
        const gate = GATES.find((g, i) => i >= gatesPassed && next >= g.at && prev < g.resumeTo);
        if (gate) {
          stopped = true;
          setPlaying(false);
          return gate.at;
        }
        if (next >= 1) {
          stopped = true;
          setPlaying(false);
          return 1;
        }
        return next;
      });
      if (!stopped) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => {
      stopped = true;
      cancelAnimationFrame(raf);
      lastRef.current = null;
    };
  }, [playing, gatesPassed]);
  const sendPrompt = () => {
    if (!activeGate) return;
    const isCompact = activeGate.kind === 'compact';
    setGatesPassed(n => n + 1);
    setTime(activeGate.resumeTo);
    setSelIdx(null);
    setHovIdx(null);
    if (!isCompact) setPlaying(true);
  };
  const visibleCount = EVENTS.filter(e => e.t <= time).length;
  const preCompactVisible = useMemo(() => EVENTS.slice(0, visibleCount), [EVENTS, visibleCount]);
  const compactGateIdx = GATES.length - 1;
  const isCompacted = gatesPassed > compactGateIdx && preCompactVisible.some(e => e.kind === 'compact');
  const {visible, preCompactTotal} = useMemo(() => {
    const nonCompact = preCompactVisible.filter(e => e.kind !== 'compact');
    if (!isCompacted) {
      return {
        visible: preCompactVisible,
        preCompactTotal: 0
      };
    }
    {}
    const autoLoads = nonCompact.filter(e => e.kind === 'auto' && e.t < STARTUP_END && !e.noSurviveCompact);
    const summarized = nonCompact.filter(e => e.t >= STARTUP_END && e.kind !== 'sub');
    const sumTokens = summarized.reduce((s, e) => s + e.tokens, 0);
    const summaryBlock = {
      t: STARTUP_END,
      kind: 'compact',
      label: 'Conversation summary',
      tokens: Math.round(sumTokens * 0.12),
      color: '#A09E96',
      vis: 'hidden',
      desc: `All ${summarized.length} conversation events condensed into one structured summary. The summary keeps: your requests and intent, key technical concepts, files examined or modified with important code snippets, errors and how they were fixed, pending tasks, and current work. It replaces the verbatim conversation: full tool outputs and intermediate reasoning are gone. Claude can still reference the work but won't have the exact code it read earlier.`,
      link: '/en/how-claude-code-works#the-context-window'
    };
    return {
      visible: [...autoLoads, summaryBlock],
      preCompactTotal: nonCompact.reduce((s, e) => s + e.tokens, 0)
    };
  }, [preCompactVisible, isCompacted]);
  const {blocks, totalTokens} = useMemo(() => {
    const bl = visible.map((e, visIdx) => ({
      ...e,
      id: e.label + e.t,
      visIdx
    })).filter(e => e.tokens > 0 || e.label === 'Conversation summary');
    return {
      blocks: bl,
      totalTokens: bl.reduce((s, b) => s + b.tokens, 0)
    };
  }, [visible]);
  const subTotal = useMemo(() => visible.filter(e => e.kind === 'sub').reduce((s, e) => s + (e.subTokens || 0), 0), [visible]);
  useEffect(() => {
    if (!scrollRef.current) return;
    if (isCompacted) scrollRef.current.scrollTo({
      top: 0,
      behavior: 'smooth'
    }); else if (playing || activeGate) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [visible.length, !!activeGate, isCompacted]);
  const rootRef = useRef(null);
  const keyStateRef = useRef({});
  const [isFullscreen, setIsFullscreen] = useState(false);
  keyStateRef.current = {
    time,
    activeGate,
    sendPrompt,
    hasInteracted
  };
  useEffect(() => {
    const onFsChange = () => setIsFullscreen(!!document.fullscreenElement);
    document.addEventListener('fullscreenchange', onFsChange);
    return () => document.removeEventListener('fullscreenchange', onFsChange);
  }, []);
  const toggleFullscreen = () => {
    if (!rootRef.current) return;
    if (document.fullscreenElement) document.exitFullscreen(); else rootRef.current.requestFullscreen().catch(() => {});
  };
  useEffect(() => {
    const onKey = e => {
      const tag = e.target.tagName;
      if (tag === 'INPUT' || tag === 'BUTTON' || tag === 'TEXTAREA' || tag === 'SELECT' || e.target.isContentEditable) return;
      if (!rootRef.current) return;
      const rect = rootRef.current.getBoundingClientRect();
      if (rect.width === 0 && rect.height === 0) return;
      if (rect.bottom < 0 || rect.top > window.innerHeight) return;
      if (e.code === 'Space') {
        const {time: t, activeGate: g, sendPrompt: send, hasInteracted: hi} = keyStateRef.current;
        if (!hi) return;
        e.preventDefault();
        if (t === 0) setPlaying(true); else if (g) send(); else if (t >= 1) {
          setTime(0);
          setGatesPassed(0);
          setSelIdx(null);
          setHovIdx(null);
          setPlaying(true);
        } else setPlaying(p => !p);
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);
  const pct = totalTokens / MAX * 100;
  const barColor = pct > 75 ? '#D97757' : pct > 50 ? '#B8860B' : '#558A42';
  const activeIdx = selIdx !== null ? selIdx : hovIdx;
  const hovEvent = activeIdx !== null ? visible[activeIdx] : null;
  useEffect(() => {
    if (detailRef.current) detailRef.current.scrollTop = 0;
  }, [hovEvent]);
  const focusT = hovEvent ? hovEvent.t : time;
  const takeaway = isCompacted ? 'Compaction replaces the conversation with a structured summary. System prompt, CLAUDE.md, memory, and MCP tools reload automatically. The skill listing is the one exception. Only skills you actually invoked are preserved.' : focusT < STARTUP_END ? 'A lot loads before you type anything. CLAUDE.md, memory, skills, and MCP tools are all in context before your first prompt.' : focusT < 0.28 ? "Your prompt is tiny compared to what's already loaded. Most of Claude's context is project knowledge, not your words." : focusT < 0.50 ? 'Each file Claude reads grows the context. Path-scoped rules load automatically alongside matching files.' : focusT < 0.71 ? 'Hooks fire automatically on tool events. Output reaches Claude via additionalContext JSON. Exit code 2 surfaces stderr to Claude. Plain stdout on exit 0 goes to the debug log, not the transcript.' : focusT < 0.79 ? 'Follow-up questions keep building on the same context. Everything from earlier is still there.' : focusT < 0.87 ? "The subagent works in its own separate context window. None of its file reads touch yours. Only the final summary comes back." : focusT < 0.88 ? 'Bang commands run in your shell and prefix the output to your next message. Useful for grounding Claude in command results without it running them.' : focusT < 0.90 ? 'User-only skills stay out of context entirely until you invoke them. The skill index at startup only lists skills Claude can call on its own.' : '/compact summarizes the conversation to free space while keeping key information. In a real session, run it when context starts affecting performance or before a long new task.';
  const terminalView = isCompacted ? 'A "Conversation compacted" message. The summarization happens silently.' : focusT < STARTUP_END ? 'The input box, waiting for your first message. Everything above loads silently before you type anything.' : focusT < 0.28 ? 'Your prompt. Claude hasn\'t started working yet.' : focusT < 0.52 ? 'Your prompt and "Reading files...". Rules show as one-line "Loaded" notices, not their content.' : focusT < 0.72 ? "Claude's response and file diffs. Hooks fire silently. Tool output like npm test shows as a brief summary, not the full content." : focusT < 0.79 ? 'Your follow-up prompt.' : focusT < 0.86 ? "A brief notice that a subagent is working, then its result. You don't see the subagent's individual file reads." : focusT < 0.90 ? "Claude's response, your git status output, and the commit-push skill running." : 'Your full conversation. /compact is available to run.';
  const mono = 'var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace)';
  const renderWithCode = s => s.split('`').map((part, i) => i % 2 === 1 ? <code key={i} style={{
    fontFamily: mono,
    fontSize: '0.92em',
    background: 'var(--cw-track)',
    padding: '1px 4px',
    borderRadius: 3
  }}>{part}</code> : part);
  if (!mounted) return null;
  return <>
    <div className="cw-mobile-fallback">
      This interactive timeline works best on a larger screen. See <a href="#what-the-timeline-shows" style={{
    color: '#D97757'
  }}>the written breakdown below</a> for the same concepts.
    </div>
    <div className="cw-root" ref={rootRef} onClickCapture={() => setHasInteracted(true)} style={isFullscreen ? {
    height: '100vh',
    borderRadius: 0,
    display: 'flex',
    flexDirection: 'column'
  } : {}}>
      <style>{`
        .cw-root {
          --cw-bg: #FAFAF8;
          --cw-text: #1A1918;
          --cw-text-2: #3D3C38;
          --cw-text-3: #5E5D59;
          --cw-text-dim: #6E6C64;
          --cw-text-faint: #8A8880;
          --cw-surface: rgba(0,0,0,0.025);
          --cw-surface-2: rgba(0,0,0,0.04);
          --cw-border: rgba(0,0,0,0.08);
          --cw-track: rgba(0,0,0,0.04);
          --cw-hover: rgba(0,0,0,0.04);
          --cw-rail: rgba(0,0,0,0.08);
          --cw-scrollbar: rgba(0,0,0,0.22);
          background: var(--cw-bg);
          border-radius: 12px;
          overflow: hidden;
          font-family: var(--font-sans, -apple-system, BlinkMacSystemFont, sans-serif);
          color: var(--cw-text);
          border: 1px solid var(--cw-border);
        }
        .dark .cw-root {
          --cw-bg: #111110;
          --cw-text: #E8E6DC;
          --cw-text-2: #B8B6AE;
          --cw-text-3: #9C9A92;
          --cw-text-dim: #8A8880;
          --cw-text-faint: #6E6C64;
          --cw-surface: rgba(255,255,255,0.02);
          --cw-surface-2: rgba(255,255,255,0.015);
          --cw-border: rgba(255,255,255,0.06);
          --cw-track: rgba(255,255,255,0.03);
          --cw-hover: rgba(255,255,255,0.04);
          --cw-rail: rgba(255,255,255,0.04);
          --cw-scrollbar: rgba(255,255,255,0.18);
        }
        .cw-scroll::-webkit-scrollbar { width: 6px; }
        .cw-scroll::-webkit-scrollbar-track { background: transparent; }
        .cw-scroll::-webkit-scrollbar-thumb { background: var(--cw-scrollbar); border-radius: 3px; }
        @keyframes cw-blink { 50% { opacity: 0; } }
        @keyframes cw-fadein { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: translateY(0); } }
        .cw-compacted-row { animation: cw-fadein 0.3s ease-out backwards; }
        .cw-mobile-fallback { display: none; padding: 14px 16px; border-radius: 8px; font-size: 14px; border: 1px solid rgba(0,0,0,0.1); background: rgba(0,0,0,0.03); }
        .dark .cw-mobile-fallback { border-color: rgba(255,255,255,0.15); background: rgba(255,255,255,0.04); }
        @media (max-width: 700px) {
          .cw-root { display: none !important; }
          .cw-mobile-fallback { display: block; }
        }
      `}</style>

      {}
      <div style={{
    padding: '16px 20px 12px',
    display: 'flex',
    alignItems: 'flex-end',
    gap: 24
  }}>
        <div style={{
    flex: 1,
    minWidth: 0
  }}>
          <div style={{
    fontSize: 18,
    fontWeight: 600,
    letterSpacing: -0.3,
    lineHeight: 1
  }}>
            Explore the context window
          </div>
          <div style={{
    fontSize: 14,
    color: 'var(--cw-text-dim)',
    marginTop: 4
  }}>
            A simulated session showing what enters context and what it costs
          </div>
        </div>
        <div style={{
    textAlign: 'right',
    flexShrink: 0
  }}>
          <div style={{
    fontFamily: mono,
    fontSize: 20,
    fontWeight: 600,
    color: barColor,
    letterSpacing: -0.5,
    lineHeight: 1
  }}>
            ~{fmt(totalTokens)}<span style={{
    fontSize: 15,
    fontWeight: 500,
    marginLeft: 4
  }}>tokens</span>
          </div>
          <div style={{
    fontFamily: mono,
    fontSize: 13,
    color: 'var(--cw-text-dim)',
    marginTop: 2
  }} title="Token counts are illustrative. Actual values vary with your CLAUDE.md size, MCP servers, and file lengths.">
            / {fmt(MAX)} · illustrative
          </div>
        </div>
      </div>

      {}
      <div style={{
    padding: '0 20px'
  }}>
        <div style={{
    height: 4,
    borderRadius: 2,
    background: 'var(--cw-track)',
    overflow: 'hidden',
    marginBottom: 6
  }}>
          <div style={{
    width: pct + '%',
    height: '100%',
    background: barColor,
    transition: 'width 0.6s cubic-bezier(0.4, 0, 0.2, 1), background 0.3s'
  }} />
        </div>
        <div style={{
    height: 28,
    borderRadius: 5,
    background: 'var(--cw-track)',
    border: '1px solid var(--cw-border)',
    overflow: 'hidden',
    display: 'flex'
  }}>
          {blocks.map((b, i) => {
    const w = Math.max(b.tokens / MAX * 100, 0.15);
    const isHov = b.visIdx === activeIdx;
    const catMatch = hovCat && b.color === hovCat;
    const dimmed = hovCat ? !catMatch : activeIdx !== null && !isHov;
    return <div key={b.id} onMouseEnter={() => setHovIdx(b.visIdx)} onMouseLeave={() => setHovIdx(null)} onClick={() => setSelIdx(selIdx === b.visIdx ? null : b.visIdx)} style={{
      width: w + '%',
      height: '100%',
      background: b.color,
      opacity: isHov || catMatch ? 1 : dimmed ? 0.25 : 0.65,
      borderRight: i < blocks.length - 1 ? '0.5px solid var(--cw-border)' : 'none',
      transition: 'opacity 0.15s',
      cursor: 'pointer'
    }} />;
  })}
        </div>
        <div style={{
    display: 'flex',
    gap: 12,
    marginTop: 6,
    flexWrap: 'wrap',
    justifyContent: 'space-between'
  }}>
          <div style={{
    display: 'flex',
    gap: 12,
    flexWrap: 'wrap'
  }}>
            {LEGEND.map(x => {
    const active = hovCat === x.c;
    return <div key={x.l} onMouseEnter={() => setHovCat(x.c)} onMouseLeave={() => setHovCat(null)} style={{
      display: 'flex',
      alignItems: 'center',
      gap: 4,
      padding: '2px 6px',
      borderRadius: 4,
      cursor: 'pointer',
      background: active ? 'var(--cw-hover)' : 'transparent',
      transition: 'background 0.1s'
    }}>
                  <div style={{
      width: 6,
      height: 6,
      borderRadius: 1.5,
      background: x.c,
      opacity: active ? 1 : 0.7
    }} />
                  <span style={{
      fontSize: 12,
      color: active ? 'var(--cw-text)' : 'var(--cw-text-dim)'
    }}>{x.l}</span>
                </div>;
  })}
          </div>
          <div style={{
    display: 'flex',
    gap: 6,
    alignItems: 'center',
    fontSize: 12,
    color: 'var(--cw-text-dim)'
  }}>
            <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#558A42" strokeWidth="2.5">
              <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" /><circle cx="12" cy="12" r="3" />
            </svg>
            <span>= appears in your terminal</span>
          </div>
        </div>
      </div>

      {}
      <div style={{
    display: 'flex',
    padding: '14px 20px 0',
    gap: 16,
    height: isFullscreen ? 'calc(100vh - 240px)' : 420
  }}>

        {}
        <div ref={scrollRef} className="cw-scroll" style={{
    flex: 1,
    minWidth: 0,
    overflowY: 'auto',
    paddingRight: 8,
    scrollBehavior: 'smooth'
  }}>
          {visible.length === 0 && !playing && <div style={{
    height: '100%',
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    gap: 16
  }}>
              <div style={{
    fontFamily: mono,
    fontSize: 16,
    color: 'var(--cw-text-dim)',
    display: 'flex',
    alignItems: 'center',
    gap: 8
  }}>
                <span style={{
    color: 'var(--cw-text-faint)'
  }}>$</span>
                <span>claude</span>
                <span style={{
    display: 'inline-block',
    width: 8,
    height: 16,
    background: 'var(--cw-text-dim)',
    opacity: 0.5,
    animation: 'cw-blink 1s step-end infinite'
  }} />
              </div>
              <button onClick={() => setPlaying(true)} style={{
    padding: '10px 20px',
    borderRadius: 8,
    border: '1px solid rgba(217,119,87,0.3)',
    background: 'rgba(217,119,87,0.08)',
    color: '#D97757',
    fontSize: 15,
    fontWeight: 600,
    cursor: 'pointer',
    display: 'flex',
    alignItems: 'center',
    gap: 8
  }}>
                <span>▶</span>
                <span>Start session</span>
              </button>
              <div style={{
    fontSize: 13,
    color: 'var(--cw-text-faint)',
    maxWidth: 280,
    textAlign: 'center',
    lineHeight: 1.5
  }}>
                Watch what loads into context, from the moment you run <code style={{
    fontFamily: mono
  }}>claude</code> through a full conversation.
              </div>
            </div>}
          {isCompacted && <div style={{
    marginBottom: 10,
    padding: '10px 12px',
    borderRadius: 6,
    background: 'rgba(217,119,87,0.05)',
    border: '1px solid rgba(217,119,87,0.15)'
  }}>
              <div style={{
    fontSize: 13,
    fontWeight: 600,
    color: '#D97757',
    marginBottom: 3
  }}>
                After /compact
              </div>
              <div style={{
    fontSize: 13,
    color: 'var(--cw-text-3)',
    lineHeight: 1.5,
    fontFamily: mono
  }}>
                {fmt(preCompactTotal)} → {fmt(totalTokens)} tokens · freed {fmt(preCompactTotal - totalTokens)}
              </div>
              <div style={{
    fontSize: 13,
    color: 'var(--cw-text-dim)',
    lineHeight: 1.5,
    marginTop: 4
  }}>
                This is what's left in context: startup content, which lives outside the message history and reloads after compaction, plus a structured summary of the entire conversation. Skill descriptions don't reload.
              </div>
            </div>}
          {time > 0 && visible.length > 0 && <div style={{
    fontSize: 12,
    fontWeight: 700,
    color: 'var(--cw-text-faint)',
    textTransform: 'uppercase',
    letterSpacing: 0.6,
    marginBottom: 6,
    paddingLeft: 28
  }}>
              {isCompacted ? 'Reloaded after compact' : 'Before you type anything'}
            </div>}

          {time > 0 && visible.map((evt, i) => {
    const meta = KIND_META[evt.kind];
    const isHov = hovIdx === i;
    const prevKind = i > 0 ? visible[i - 1].kind : null;
    const isSub = evt.kind === 'sub';
    const enteringSubagent = isSub && prevKind !== 'sub';
    const leavingSubagent = prevKind === 'sub' && !isSub;
    let showPhase = null;
    if (evt.kind === 'user' && prevKind !== 'user') showPhase = 'You'; else if (evt.kind === 'claude' && prevKind === 'user') showPhase = 'Claude works'; else if (evt.label === 'Conversation summary') showPhase = 'Summarized by /compact';
    const isNewRow = isCompacted && !(evt.kind === 'auto' && evt.t < STARTUP_END);
    return <div key={evt.label + evt.t} className={isNewRow ? 'cw-compacted-row' : ''} style={isNewRow ? {
      animationDelay: `${i * 60}ms`
    } : {}}>
                {showPhase && <div style={{
      fontSize: 12,
      fontWeight: 700,
      color: 'var(--cw-text-faint)',
      textTransform: 'uppercase',
      letterSpacing: 0.6,
      marginTop: 14,
      marginBottom: 6,
      paddingLeft: 28
    }}>
                    {showPhase}
                  </div>}
                {enteringSubagent && <div style={{
      marginLeft: 28,
      marginTop: 6,
      marginBottom: 2,
      paddingLeft: 10,
      borderLeft: '2px solid rgba(155,123,196,0.4)',
      fontSize: 12,
      fontWeight: 600,
      color: '#9B7BC4',
      textTransform: 'uppercase',
      letterSpacing: 0.5
    }}>
                    Subagent's separate context window
                  </div>}
                {leavingSubagent && <div style={{
      marginLeft: 28,
      marginBottom: 6,
      paddingLeft: 10,
      paddingBottom: 6,
      borderLeft: '2px solid rgba(155,123,196,0.4)',
      fontSize: 12,
      color: 'var(--cw-text-dim)',
      fontFamily: mono
    }}>
                    ↓ {fmt(subTotal)} tokens stayed in subagent's context · only the summary returns
                  </div>}
                <div onMouseEnter={() => setHovIdx(i)} onMouseLeave={() => setHovIdx(null)} onClick={() => setSelIdx(selIdx === i ? null : i)} style={{
      display: 'flex',
      alignItems: 'flex-start',
      borderRadius: 6,
      cursor: 'pointer',
      background: selIdx === i || isHov ? 'var(--cw-hover)' : 'transparent',
      outline: selIdx === i ? '1px solid rgba(217,119,87,0.4)' : 'none',
      opacity: hovCat && evt.color !== hovCat ? 0.35 : 1,
      transition: 'background 0.1s, opacity 0.15s',
      marginLeft: isSub ? 28 : 0,
      paddingLeft: isSub ? 10 : 0,
      borderLeft: isSub ? '2px solid rgba(155,123,196,0.4)' : 'none'
    }}>
                  <div style={{
      width: 28,
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      paddingTop: 8,
      flexShrink: 0
    }}>
                    <div style={{
      width: evt.kind === 'user' || evt.kind === 'compact' ? 10 : 7,
      height: evt.kind === 'user' || evt.kind === 'compact' ? 10 : 7,
      borderRadius: '50%',
      background: evt.color,
      opacity: isHov ? 1 : 0.6,
      transition: 'opacity 0.15s',
      boxShadow: isHov ? `0 0 8px ${evt.color}40` : 'none'
    }} />
                    {i < visible.length - 1 && <div style={{
      width: 1.5,
      flex: 1,
      background: 'var(--cw-rail)',
      marginTop: 2,
      minHeight: 6
    }} />}
                  </div>
                  <div style={{
      flex: 1,
      minWidth: 0,
      padding: '5px 10px 5px 4px',
      display: 'flex',
      alignItems: 'center',
      gap: 8
    }}>
                    <span style={{
      fontSize: 12,
      fontWeight: 600,
      padding: '1px 5px',
      borderRadius: 3,
      background: meta.badgeBg,
      color: meta.badgeColor,
      flexShrink: 0,
      fontFamily: mono
    }}>
                      {meta.badge}
                    </span>
                    <span style={{
      fontSize: 15,
      fontFamily: mono,
      color: isHov ? 'var(--cw-text)' : evt.kind === 'user' ? '#558A42' : evt.kind === 'auto' ? 'var(--cw-text-dim)' : 'var(--cw-text-2)',
      flex: 1,
      minWidth: 0,
      overflow: 'hidden',
      textOverflow: 'ellipsis',
      whiteSpace: 'nowrap',
      fontWeight: evt.kind === 'user' ? 550 : 400
    }}>
                      {evt.label}
                    </span>
                    {evt.tokens > 0 && <span style={{
      fontSize: 12,
      fontFamily: mono,
      color: 'var(--cw-text-faint)',
      flexShrink: 0
    }}>
                        +{fmt(evt.tokens)}
                      </span>}
                    {evt.subTokens > 0 && <span style={{
      fontSize: 12,
      fontFamily: mono,
      color: '#9B7BC4',
      flexShrink: 0,
      opacity: 0.6
    }}>
                        +{fmt(evt.subTokens)}
                      </span>}
                    {evt.tokens > 0 && <div style={{
      width: 50,
      height: 5,
      borderRadius: 2,
      background: 'var(--cw-track)',
      flexShrink: 0,
      overflow: 'hidden'
    }}>
                        <div style={{
      width: Math.min(evt.tokens / 5000 * 100, 100) + '%',
      height: '100%',
      background: evt.color,
      opacity: isHov ? 0.8 : 0.4,
      transition: 'opacity 0.15s'
    }} />
                      </div>}
                    <span style={{
      width: 14,
      flexShrink: 0,
      display: 'flex',
      justifyContent: 'center'
    }} title={VIS_META[evt.vis].label}>
                      {evt.vis !== 'hidden' && <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke={evt.vis === 'full' ? '#558A42' : 'currentColor'} style={{
      color: 'var(--cw-text-faint)',
      opacity: evt.vis === 'full' ? 1 : 0.5
    }} strokeWidth="2">
                          <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" /><circle cx="12" cy="12" r="3" />
                        </svg>}
                    </span>
                  </div>
                </div>
              </div>;
  })}

          {activeGate && (activeGate.kind === 'prompt' || activeGate.kind === 'bang' || activeGate.kind === 'slash') && <div style={{
    paddingLeft: 28,
    marginTop: 12,
    paddingRight: 8
  }}>
              <div style={{
    fontSize: 11,
    fontWeight: 600,
    color: '#6BA656',
    fontFamily: mono,
    textTransform: 'uppercase',
    letterSpacing: 0.5,
    marginBottom: 4,
    paddingLeft: 2
  }}>
                You type in your terminal
              </div>
              <div style={{
    display: 'flex',
    alignItems: 'flex-start',
    gap: 8,
    padding: '10px 12px',
    borderRadius: 6,
    background: 'rgba(85,138,66,0.06)',
    border: '1px solid rgba(85,138,66,0.2)'
  }}>
                <span style={{
    color: '#558A42',
    fontSize: 15,
    fontFamily: mono,
    flexShrink: 0
  }}>❯</span>
                <span style={{
    fontSize: 15,
    fontFamily: mono,
    color: 'var(--cw-text-2)',
    flex: 1,
    lineHeight: 1.5
  }}>
                  {activeGate.text}
                  <span style={{
    display: 'inline-block',
    width: 7,
    height: 13,
    marginLeft: 2,
    background: '#558A42',
    opacity: 0.5,
    verticalAlign: 'middle',
    animation: 'cw-blink 1s step-end infinite'
  }} />
                </span>
                <button onClick={sendPrompt} style={{
    padding: '5px 12px',
    borderRadius: 5,
    border: 'none',
    background: '#558A42',
    color: '#fff',
    fontSize: 13,
    fontWeight: 600,
    cursor: 'pointer',
    flexShrink: 0
  }}>
                  {activeGate.kind === 'prompt' ? 'Send ↵' : 'Run ↵'}
                </button>
              </div>
            </div>}
          {activeGate && activeGate.kind === 'compact' && <div style={{
    paddingLeft: 28,
    marginTop: 12,
    paddingRight: 8
  }}>
              <div style={{
    padding: '12px 14px',
    borderRadius: 6,
    background: 'rgba(217,119,87,0.06)',
    border: '1px solid rgba(217,119,87,0.25)'
  }}>
                <div style={{
    fontSize: 13,
    color: 'var(--cw-text-3)',
    marginBottom: 8,
    lineHeight: 1.5
  }}>
                  Context is at <span style={{
    fontFamily: mono,
    fontWeight: 600,
    color: barColor
  }}>{fmt(totalTokens)} tokens</span>.
                  Run <code style={{
    fontFamily: mono,
    background: 'var(--cw-track)',
    padding: '1px 4px',
    borderRadius: 3
  }}>/compact</code> to
                  summarize older exchanges and free space for more work.
                </div>
                <div style={{
    display: 'flex',
    alignItems: 'center',
    gap: 8
  }}>
                  <span style={{
    color: '#D97757',
    fontSize: 15,
    fontFamily: mono
  }}>❯</span>
                  <span style={{
    fontSize: 15,
    fontFamily: mono,
    color: 'var(--cw-text-2)',
    flex: 1
  }}>
                    {activeGate.text}
                  </span>
                  <button onClick={sendPrompt} style={{
    padding: '5px 12px',
    borderRadius: 5,
    border: 'none',
    background: '#D97757',
    color: '#fff',
    fontSize: 13,
    fontWeight: 600,
    cursor: 'pointer',
    flexShrink: 0
  }}>
                    Run ↵
                  </button>
                </div>
              </div>
            </div>}
        </div>

        {}
        <div style={{
    width: 300,
    flexShrink: 0,
    display: 'flex',
    flexDirection: 'column'
  }}>
          <div ref={detailRef} className="cw-scroll" style={{
    padding: '14px 16px',
    borderRadius: 10,
    background: 'var(--cw-surface)',
    border: '1px solid var(--cw-border)',
    flex: 1,
    minHeight: 0,
    overflowY: 'auto',
    display: 'flex',
    flexDirection: 'column',
    gap: 10
  }}>
            {hovEvent ? <div>
                <div style={{
    display: 'flex',
    alignItems: 'center',
    gap: 8,
    marginBottom: 8
  }}>
                  <div style={{
    width: 10,
    height: 10,
    borderRadius: 3,
    background: hovEvent.color,
    opacity: 0.8
  }} />
                  <span style={{
    fontSize: 16,
    fontWeight: 600
  }}>{hovEvent.label}</span>
                </div>
                <div style={{
    display: 'flex',
    width: 'fit-content',
    padding: '3px 8px',
    borderRadius: 4,
    marginBottom: 8,
    background: KIND_META[hovEvent.kind].badgeBg
  }}>
                  <span style={{
    fontSize: 12,
    fontWeight: 600,
    color: KIND_META[hovEvent.kind].badgeColor
  }}>
                    {KIND_META[hovEvent.kind].detail}
                  </span>
                </div>
                {hovEvent.tokens > 0 && <div style={{
    fontSize: 14,
    fontFamily: mono,
    color: 'var(--cw-text-dim)',
    marginBottom: 6
  }}>
                    {fmt(hovEvent.tokens)} tokens
                  </div>}
                {hovEvent.subTokens > 0 && <div style={{
    fontSize: 14,
    fontFamily: mono,
    color: '#9B7BC4',
    marginBottom: 6
  }}>
                    {fmt(hovEvent.subTokens)} tokens in the subagent's context
                  </div>}
                <p style={{
    fontSize: 15,
    color: 'var(--cw-text-3)',
    lineHeight: 1.55,
    margin: 0
  }}>
                  {renderWithCode(hovEvent.desc)}
                </p>
                <div style={{
    marginTop: 10,
    padding: '8px 10px',
    borderRadius: 6,
    background: hovEvent.vis === 'full' ? 'rgba(85,138,66,0.08)' : 'var(--cw-surface-2)',
    border: '1px solid ' + (hovEvent.vis === 'full' ? 'rgba(85,138,66,0.2)' : 'var(--cw-border)')
  }}>
                  <div style={{
    display: 'flex',
    alignItems: 'center',
    gap: 6,
    marginBottom: 3
  }}>
                    <span style={{
    fontSize: 13,
    color: hovEvent.vis === 'full' ? '#558A42' : 'var(--cw-text-dim)'
  }}>
                      {hovEvent.vis === 'full' ? '●' : hovEvent.vis === 'brief' ? '◐' : '○'}
                    </span>
                    <span style={{
    fontSize: 12,
    fontWeight: 600,
    color: 'var(--cw-text-2)'
  }}>
                      {VIS_META[hovEvent.vis].label}
                    </span>
                  </div>
                  <div style={{
    fontSize: 13,
    color: 'var(--cw-text-dim)',
    lineHeight: 1.4
  }}>
                    {VIS_META[hovEvent.vis].sub}
                  </div>
                </div>
                {hovEvent.tip && <div style={{
    marginTop: 10,
    padding: '8px 10px',
    borderRadius: 6,
    background: 'rgba(85,138,66,0.06)',
    border: '1px solid rgba(85,138,66,0.15)'
  }}>
                    <div style={{
    fontSize: 12,
    fontWeight: 600,
    color: '#558A42',
    marginBottom: 3,
    display: 'flex',
    alignItems: 'center',
    gap: 4
  }}>
                      <span>💡</span> Save context
                    </div>
                    <div style={{
    fontSize: 13,
    color: 'var(--cw-text-3)',
    lineHeight: 1.5
  }}>
                      {renderWithCode(hovEvent.tip)}
                    </div>
                  </div>}
                {hovEvent.link && <a href={hovEvent.link} style={{
    display: 'inline-block',
    marginTop: 10,
    fontSize: 13,
    color: '#D97757',
    textDecoration: 'none',
    borderBottom: '1px solid rgba(217,119,87,0.3)'
  }}>
                    Learn more →
                  </a>}
              </div> : <div style={{
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    textAlign: 'center',
    gap: 4,
    padding: '12px 0 4px'
  }}>
                <div style={{
    fontSize: 22,
    opacity: 0.2
  }}>👁</div>
                <div style={{
    fontSize: 14,
    fontWeight: 500,
    color: 'var(--cw-text-dim)'
  }}>Hover or click any event</div>
                <div style={{
    fontSize: 12,
    color: 'var(--cw-text-faint)',
    lineHeight: 1.4,
    maxWidth: 200
  }}>
                  Hover to preview. Click to pin so you can scroll.
                </div>
              </div>}

            <div style={{
    padding: '10px 12px',
    borderRadius: 8,
    background: 'rgba(217,119,87,0.05)',
    border: '1px solid rgba(217,119,87,0.12)'
  }}>
              <div style={{
    fontSize: 11,
    fontWeight: 700,
    color: '#D97757',
    textTransform: 'uppercase',
    letterSpacing: 0.5,
    marginBottom: 3
  }}>
                Key takeaway
              </div>
              <div style={{
    fontSize: 13,
    color: 'var(--cw-text-3)',
    lineHeight: 1.5
  }}>
                {takeaway}
              </div>
            </div>

            <div style={{
    padding: '10px 12px',
    borderRadius: 8,
    background: 'var(--cw-surface-2)',
    border: '1px solid var(--cw-border)'
  }}>
              <div style={{
    fontSize: 11,
    fontWeight: 700,
    color: 'var(--cw-text-dim)',
    textTransform: 'uppercase',
    letterSpacing: 0.5,
    marginBottom: 3
  }}>
                In your terminal you see
              </div>
              <div style={{
    fontSize: 13,
    color: 'var(--cw-text-3)',
    lineHeight: 1.5
  }}>
                {terminalView}
              </div>
            </div>
          </div>
        </div>
      </div>

      {}
      <div style={{
    padding: '10px 20px 14px',
    display: 'flex',
    alignItems: 'center',
    gap: 10
  }}>
        <button aria-label={time >= 1 ? 'Restart' : activeGate ? 'Continue' : playing ? 'Pause' : 'Play'} onClick={() => {
    if (time >= 1) {
      setTime(0);
      setGatesPassed(0);
      setSelIdx(null);
      setHovIdx(null);
      setPlaying(true);
    } else if (activeGate) sendPrompt(); else setPlaying(!playing);
  }} style={{
    width: 30,
    height: 30,
    borderRadius: 6,
    border: 'none',
    background: 'rgba(217,119,87,0.1)',
    color: '#D97757',
    cursor: 'pointer',
    fontSize: 15,
    fontWeight: 700,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center'
  }}>
          {time >= 1 ? '↺' : playing ? '⏸' : '▶'}
        </button>
        <div style={{
    flex: 1,
    height: 3,
    borderRadius: 2,
    background: 'var(--cw-track)',
    overflow: 'hidden'
  }}>
          <div style={{
    width: time * 100 + '%',
    height: '100%',
    background: '#D97757',
    transition: 'width 0.1s linear'
  }} />
        </div>
        <span style={{
    fontSize: 12,
    fontFamily: mono,
    color: 'var(--cw-text-faint)',
    minWidth: 30
  }}>
          {Math.round(time * 100)}%
        </span>
        <button onClick={toggleFullscreen} aria-label={isFullscreen ? 'Exit fullscreen' : 'Enter fullscreen'} title={isFullscreen ? 'Exit fullscreen' : 'Fullscreen'} style={{
    width: 28,
    height: 28,
    borderRadius: 6,
    border: '1px solid var(--cw-border)',
    background: 'var(--cw-surface)',
    color: 'var(--cw-text-dim)',
    cursor: 'pointer',
    fontSize: 15,
    flexShrink: 0,
    marginLeft: 4,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center'
  }}>
          {isFullscreen ? '⤡' : '⛶'}
        </button>
      </div>
    </div>
    </>;
};

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 walks through what loads and when. See [the written breakdown](#what-the-timeline-shows) for the same content as a list.

<ContextWindow />

## What the timeline shows

The session walks through a realistic flow with representative token counts:

* **Before you type anything**: CLAUDE.md, auto memory, MCP tool names, and skill descriptions all load into context. Your own setup may add more here, like an [output style](output-styles-claude-code-docs-c315eeed32.md) or text from [`--append-system-prompt`](cli-reference-7bb98e3312.md), which both go into the system prompt the same way.
* **As Claude works**: each file read adds to context, [path-scoped rules](/en/memory#path-specific-rules) load automatically alongside matching files, and a [PostToolUse hook](../07-Hooks/automate-workflows-with-hooks-claude-code-docs-e843f93261.md) fires after each edit.
* **The follow-up prompt**: a [subagent](../09-Agents-Patterns/create-custom-subagents-claude-code-docs-7dc93e85c0.md) 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**: `/compact` replaces the conversation with a structured summary. Most startup content reloads automatically; the table below shows what happens to each mechanism.

## What survives compaction

When a long session compacts, Claude Code summarizes the conversation history to fit the context window. What happens to your instructions depends on how they were loaded:

| Mechanism                                 | After compaction                                                                            |
| :---------------------------------------- | :------------------------------------------------------------------------------------------ |
| System prompt and output style            | Unchanged; not part of message history                                                      |
| Project-root CLAUDE.md and unscoped rules | Re-injected from disk                                                                       |
| Auto memory                               | Re-injected from disk                                                                       |
| Rules with `paths:` frontmatter           | Lost until a matching file is read again                                                    |
| Nested CLAUDE.md in subdirectories        | Lost until a file in that subdirectory is read again                                        |
| Invoked skill bodies                      | Re-injected, capped at 5,000 tokens per skill and 25,000 tokens total; oldest dropped first |
| Hooks                                     | Not applicable; hooks run as code, not context                                              |

Path-scoped rules and nested CLAUDE.md files load into message history when their trigger file is read, so compaction summarizes them away with everything else. They reload the next time Claude reads a matching file. 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`.

## 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. Run `/memory` to check which CLAUDE.md and auto memory files loaded at startup.

## Related resources

For deeper coverage of the features shown in the timeline, see these pages:

* [Extend Claude Code](extend-claude-code-claude-code-docs-3b35aaf641.md): when to use CLAUDE.md vs skills vs rules vs hooks vs MCP
* [Store instructions and memories](how-claude-remembers-your-project-claude-code-docs-f1c064262d.md): CLAUDE.md hierarchy and auto memory
* [Subagents](../09-Agents-Patterns/create-custom-subagents-claude-code-docs-7dc93e85c0.md): delegate research to a separate context window
* [Best practices](../10-Prompting-Guides/best-practices-for-claude-code-claude-code-docs-9686dc1633.md): managing context as your primary constraint
* [Reduce token usage](/en/costs#reduce-token-usage): strategies for keeping context usage low


---
## continue-local-sessions-from-any-device-with-remote-control-claude-code-docs-c1c03fd914.md

# Continue local sessions from any device with Remote Control


Continue a local Claude Code session from your phone, tablet, or any browser using Remote Control. Works with claude.ai/code and the Claude mobile app.


> ## Documentation Index
>
> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt>
>
> Use this file to discover all available pages before exploring further.

Remote Control is in research preview and available on all plans. On Team and Enterprise, it is off by default until an admin enables the Remote Control toggle in [Claude Code admin settings](https://claude.ai/admin-settings/claude-code).

Remote Control connects [claude.ai/code](https://claude.ai/code) or the Claude app for [iOS](https://apps.apple.com/us/app/claude-by-anthropic/id6473753684) and [Android](https://play.google.com/store/apps/details?id=com.anthropic.claude) to a Claude Code session running on your machine. Start a task at your desk, then pick it up from your phone on the couch or a browser on another computer. When you start a Remote Control session on your machine, Claude keeps running locally the entire time, so nothing moves to the cloud. With Remote Control you can:

- **Use your full local environment remotely**: your filesystem, [MCP servers](/docs/en/mcp), tools, and project configuration all stay available, and typing `@` autocompletes file paths from your local project
- **Work from both surfaces at once**: the conversation stays in sync across all connected devices, so you can send messages from your terminal, browser, and phone interchangeably
- **Survive interruptions**: if your laptop sleeps or your network drops, the session reconnects automatically when your machine comes back online

Unlike [Claude Code on the web](/docs/en/claude-code-on-the-web), which runs on cloud infrastructure, Remote Control sessions run directly on your machine and interact with your local filesystem. The web and mobile interfaces are just a window into that local session.

Remote Control requires Claude Code v2.1.51 or later. Check your version with `claude --version`.

This page covers setup, how to start and connect to sessions, and how Remote Control compares to Claude Code on the web.


Requirements

Before using Remote Control, confirm that your environment meets these conditions:

- **Subscription**: available on Pro, Max, Team, and Enterprise plans. API keys are not supported. On Team and Enterprise, an admin must first enable the Remote Control toggle in [Claude Code admin settings](https://claude.ai/admin-settings/claude-code).
- **Authentication**: run `claude` and use `/login` to sign in through claude.ai if you haven’t already.
- **Workspace trust**: run `claude` in your project directory at least once to accept the workspace trust dialog.


Start a Remote Control session

You can start a Remote Control session from the CLI or the VS Code extension. The CLI offers three invocation modes; VS Code uses the `/remote-control` command.

- Server mode

- Interactive session

- From an existing session

- VS Code

Navigate to your project directory and run:

```python
claude remote-control
```

The process stays running in your terminal in server mode, waiting for remote connections. It displays a session URL you can use to [connect from another device](#connect-from-another-device), and you can press spacebar to show a QR code for quick access from your phone. While a remote session is active, the terminal shows connection status and tool activity.Available flags:

[TABLE]

To start a normal interactive Claude Code session with Remote Control enabled, use the `--remote-control` flag (or `--rc`):

```python
claude --remote-control
```

Optionally pass a name for the session:

```python
claude --remote-control "My Project"
```

This gives you a full interactive session in your terminal that you can also control from claude.ai or the Claude app. Unlike `claude remote-control` (server mode), you can type messages locally while the session is also available remotely.

If you’re already in a Claude Code session and want to continue it remotely, use the `/remote-control` (or `/rc`) command:

```python
/remote-control
```

Pass a name as an argument to set a custom session title:

```python
/remote-control My Project
```

This starts a Remote Control session that carries over your current conversation history and displays a session URL and QR code you can use to [connect from another device](#connect-from-another-device). The `--verbose`, `--sandbox`, and `--no-sandbox` flags are not available with this command.

In the [Claude Code VS Code extension](/docs/en/vs-code), type `/remote-control` or `/rc` in the prompt box, or open the command menu with `/` and select it. Requires Claude Code v2.1.79 or later.

```python
/remote-control
```

A banner appears above the prompt box showing connection status. Once connected, click **Open in browser** in the banner to go directly to the session, or find it in the session list at [claude.ai/code](https://claude.ai/code). The session URL is also posted in the conversation.To disconnect, click the close icon on the banner or run `/remote-control` again.Unlike the CLI, the VS Code command does not accept a name argument or display a QR code. The session title is derived from your conversation history or first prompt.


Connect from another device

Once a Remote Control session is active, you have a few ways to connect from another device:

- **Open the session URL** in any browser to go directly to the session on [claude.ai/code](https://claude.ai/code).
- **Scan the QR code** shown alongside the session URL to open it directly in the Claude app. With `claude remote-control`, press spacebar to toggle the QR code display.
- **Open [claude.ai/code](https://claude.ai/code) or the Claude app** and find the session by name in the session list. In the Claude mobile app, tap **Code** in the navigation to reach the session list. Remote Control sessions show a computer icon with a green status dot when online.

The remote session title is chosen in this order:

1.  The name you passed to `--name`, `--remote-control`, or `/remote-control`
2.  The title you set with `/rename`
3.  The last meaningful message in existing conversation history
4.  An auto-generated name like `myhost-graceful-unicorn`, where `myhost` is your machine’s hostname or the prefix you set with `--remote-control-session-name-prefix`

If you didn’t set an explicit name, the title updates to reflect your prompt once you send one. If the environment already has an active session, you’ll be asked whether to continue it or start a new one. If you don’t have the Claude app yet, use the `/mobile` command inside Claude Code to display a download QR code for [iOS](https://apps.apple.com/us/app/claude-by-anthropic/id6473753684) or [Android](https://play.google.com/store/apps/details?id=com.anthropic.claude).


Enable Remote Control for all sessions

By default, Remote Control only activates when you explicitly run `claude remote-control`, `claude --remote-control`, or `/remote-control`. To enable it automatically for every interactive session, run `/config` inside Claude Code and set **Enable Remote Control for all sessions** to `true`. Set it back to `false` to disable. In the Desktop app, you can also toggle this from **Settings → Claude Code → Enable remote control by default**. With this setting on, each interactive Claude Code process registers one remote session. If you run multiple instances, each one gets its own environment and session. To run multiple concurrent sessions from a single process, use [server mode](#start-a-remote-control-session) instead.


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.


Remote Control vs Claude Code on the web

Remote Control and [Claude Code on the web](/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. Claude Code on the web executes in Anthropic-managed cloud infrastructure. Use Remote Control when you’re in the middle of local work and want to keep going from another device. Use Claude Code on the web when you want to kick off a task without any local setup, work on a repo you don’t have cloned, or run multiple tasks in parallel.


Mobile push notifications

When Remote Control is active, Claude can send push notifications to your phone. Claude decides when to push. It typically sends one when a long-running task finishes or when it needs a decision from you to continue. You can also request a push in your prompt, for example `notify me when the tests finish`. Beyond the on/off toggle below, there is no per-event configuration.

Mobile push notifications require Claude Code v2.1.110 or later.

To set up mobile push notifications:

1


Install the Claude mobile app

Download the Claude app for [iOS](https://apps.apple.com/us/app/claude-by-anthropic/id6473753684) or [Android](https://play.google.com/store/apps/details?id=com.anthropic.claude).

2


Sign in with your Claude Code account

Use the same account and organization you use for Claude Code in the terminal.

3


Allow notifications

Accept the notification permission prompt from the operating system.

4


Enable push in Claude Code

In your terminal, run `/config` and enable **Push when Claude decides**.

If notifications don’t arrive:

- If `/config` shows **No mobile registered**, open the Claude app on your phone so it can refresh its push token. The warning clears the next time Remote Control connects.
- On iOS, Focus modes and notification summaries can suppress or delay pushes. Check Settings → Notifications → Claude.
- On Android, aggressive battery optimization can delay delivery. Exempt the Claude app from battery optimization in system settings.


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](#start-a-remote-control-session) to run multiple concurrent sessions from a single process.
- **Local process must keep running**: Remote Control runs as a local process. If you close the terminal, quit VS Code, or otherwise stop the `claude` process, the session ends.
- **Extended network outage**: if your machine is awake but unable to reach the network for more than roughly 10 minutes, the session times out and the process exits. Run `claude remote-control` again to start a new session.
- **Ultraplan disconnects Remote Control**: starting an [ultraplan](/docs/en/ultraplan) session disconnects any active Remote Control session because both features occupy the claude.ai/code interface and only one can be connected at a time.
- **Some commands are local-only**: commands that open an interactive picker in the terminal, such as `/mcp`, `/plugin`, or `/resume`, work only from the local CLI. Commands that produce text output, including `/compact`, `/clear`, `/context`, `/usage`, `/exit`, `/usage-credits`, `/recap`, and `/reload-plugins`, work from mobile and web.


Troubleshooting


”Remote Control requires a claude.ai subscription”

You’re not authenticated with a claude.ai account. Run `claude auth login` and choose the claude.ai option. If `ANTHROPIC_API_KEY` is set in your environment, unset it first.


”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 are limited to inference-only and cannot 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”

Your cached account information is stale or incomplete. Run `claude auth login` to refresh it.


”Remote Control is not yet enabled for your account”

The eligibility check can fail with certain environment variables present:

- `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` or `DISABLE_TELEMETRY`: unset them and try again.
- `CLAUDE_CODE_USE_BEDROCK`, `CLAUDE_CODE_USE_VERTEX`, or `CLAUDE_CODE_USE_FOUNDRY`: Remote Control requires claude.ai authentication and does not work with third-party providers.

If none of these are set, run `/logout` then `/login` to refresh.


”Remote Control is disabled by your organization’s policy”

This error has four distinct causes. Run `/status` first to see which login method and subscription you’re using.

- **You’re authenticated with an API key or Console account**: Remote Control requires claude.ai OAuth. Run `/login` and choose the claude.ai option. If `ANTHROPIC_API_KEY` is set in your environment, unset it.
- **Your Team or Enterprise admin hasn’t enabled it**: Remote Control is off by default on these plans. An admin can enable it at [claude.ai/admin-settings/claude-code](https://claude.ai/admin-settings/claude-code) by turning on the **Remote Control** toggle. This toggle is a server-side organization setting.
- **The admin toggle is grayed out**: your organization has a data retention or compliance configuration that is incompatible with Remote Control. This cannot be changed from the admin panel. Contact Anthropic support to discuss options.
- **The error mentions `disableRemoteControl`**: your IT administrator has disabled Remote Control on this device through [managed settings](/docs/en/settings#settings-files), independent of the organization-wide toggle.


”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:

```python
claude remote-control --verbose
```

Common causes:

- Not signed in: run `claude` and use `/login` to authenticate with your claude.ai account. API key authentication is not supported for Remote Control.
- 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.


Choose the right approach

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.

|                                                     | Trigger                                                                                        | Claude runs on                                                                                              | Setup                                                                                                                                          | Best for                                                      |
|:----------------------------------------------------|:-----------------------------------------------------------------------------------------------|:------------------------------------------------------------------------------------------------------------|:-----------------------------------------------------------------------------------------------------------------------------------------------|:--------------------------------------------------------------|
| [Dispatch](/docs/en/desktop#sessions-from-dispatch) | Message a task from the Claude mobile app                                                      | Your machine (Desktop)                                                                                      | [Pair the mobile app with Desktop](https://support.claude.com/en/articles/13947068)                                                            | Delegating work while you’re away, minimal setup              |
| [Remote Control](/docs/en/remote-control)           | Drive a running session from [claude.ai/code](https://claude.ai/code) or the Claude mobile app | Your machine (CLI or VS Code)                                                                               | Run `claude remote-control`                                                                                                                    | Steering in-progress work from another device                 |
| [Channels](/docs/en/channels)                       | Push events from a chat app like Telegram or Discord, or your own server                       | Your machine (CLI)                                                                                          | [Install a channel plugin](/docs/en/channels#quickstart) or [build your own](/docs/en/channels-reference)                                      | Reacting to external events like CI failures or chat messages |
| [Slack](/docs/en/slack)                             | Mention `@Claude` in a team channel                                                            | Anthropic cloud                                                                                             | [Install the Slack app](/docs/en/slack#setting-up-claude-code-in-slack) with [Claude Code on the web](/docs/en/claude-code-on-the-web) enabled | PRs and reviews from team chat                                |
| [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                       |


Related resources

- [Claude Code on the web](/docs/en/claude-code-on-the-web): run sessions in Anthropic-managed cloud environments instead of on your machine
- [Ultraplan](/docs/en/ultraplan): launch a cloud planning session from your terminal and review the plan in your browser
- [Channels](/docs/en/channels): forward Telegram, Discord, or iMessage into a session so Claude reacts to messages while you’re away
- [Dispatch](/docs/en/desktop#sessions-from-dispatch): message a task from your phone and it can spawn a Desktop session to handle it
- [Authentication](/docs/en/authentication): set up `/login` and manage credentials for claude.ai
- [CLI reference](/docs/en/cli-reference): full list of flags and commands including `claude remote-control`
- [Security](/docs/en/security): how Remote Control sessions fit into the Claude Code security model
- [Data usage](/docs/en/data-usage): what data flows through the Anthropic API during local and remote sessions


---
## costs-32f91ab9ba.md

> ## Documentation Index
> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Manage costs effectively

> Track token usage, set team spend limits, and reduce Claude Code costs with context management, model selection, extended thinking settings, and preprocessing hooks.

Claude Code charges by API token consumption. For subscription plan pricing (Pro, Max, 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 how to [track your costs](#track-your-costs), [manage costs for teams](#managing-costs-for-teams), and [reduce token usage](#reduce-token-usage).

## Track your costs

### Using the `/usage` command

<Note>
  The Session block in `/usage` shows API token usage and is intended for API users. Claude Max and Pro subscribers have usage included in their subscription, so the session cost figure isn't relevant for billing purposes. Subscribers see plan usage bars and activity stats on the same screen.
</Note>

The `/usage` command provides detailed token usage statistics for your current session. The dollar figure is an estimate computed locally from token counts and may differ from your actual bill. For authoritative billing, see the Usage page in the [Claude Console](https://platform.claude.com/usage).

```text theme={null}
Total cost:            $0.55
Total duration (API):  6m 19.7s
Total duration (wall): 6h 33m 10.2s
Total code changes:    0 lines added, 0 lines removed
```

## Managing costs for teams

When using Claude API, you can [set workspace spend limits](../04-API-Reference/Guides/build-with-claude-workspaces-12135e8f23.md#workspace-limits) on the total Claude Code workspace spend. Admins can [view cost and usage reporting](../04-API-Reference/Guides/build-with-claude-workspaces-12135e8f23.md#usage-and-cost-tracking) in the Console.

<Note>
  When you first authenticate Claude Code with your Claude Console account, a workspace called "Claude Code" is automatically created for you. This workspace provides centralized cost tracking and management for all Claude Code usage in your organization. You cannot create API keys for this workspace; it is exclusively for Claude Code authentication and usage.

  For organizations with custom rate limits, Claude Code traffic in this workspace counts toward your organization's overall API rate limits. You can set a [workspace rate limit](../04-API-Reference/Other/api-rate-limits-28d3302987.md#setting-lower-limits-for-workspaces) on this workspace's Limits page in the Claude Console to cap Claude Code's share and protect other production workloads.
</Note>

On Bedrock, Vertex, and Foundry, Claude Code does not send metrics from your cloud. To get cost metrics, several large enterprises reported using [LiteLLM](/en/llm-gateway#litellm-configuration), which is an open-source tool that helps companies [track 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.

### 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:

| Team size     | TPM per user | RPM per user |
| ------------- | ------------ | ------------ |
| 1-5 users     | 200k-300k    | 5-7          |
| 5-20 users    | 100k-150k    | 2.5-3.5      |
| 20-50 users   | 50k-75k      | 1.25-1.75    |
| 50-100 users  | 25k-35k      | 0.62-0.87    |
| 100-500 users | 15k-20k      | 0.37-0.47    |
| 500+ users    | 10k-15k      | 0.25-0.35    |

For example, if you have 200 users, you might request 20k TPM for each user, or 4 million total TPM (200\*20,000 = 4 million).

The TPM per user decreases as team size grows because fewer users tend to use Claude Code concurrently in larger organizations. These rate limits apply at the organization level, not per individual user, which means individual users can temporarily consume more than their calculated share when others aren't actively using the service.

<Note>
  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.
</Note>

### Agent team token costs

[Agent teams](../09-Agents-Patterns/agent-teams-e29da6ed1b.md) 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:

* Use Sonnet for teammates. It balances capability and cost for coordination tasks.
* Keep teams small. Each teammate runs its own context window, so token usage is roughly proportional to team size.
* Keep spawn prompts focused. Teammates load CLAUDE.md, MCP servers, and skills automatically, but everything in the spawn prompt adds to their context from the start.
* Clean up teams when work is done. Active teammates continue consuming tokens even if idle.
* Agent teams are disabled by default. Set `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` in your [settings.json](claude-code-settings-claude-code-docs-d4420b4b52.md) or environment to enable them. See [enable agent teams](/en/agent-teams#enable-agent-teams).

## 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 (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

Use `/usage` to check your current token usage, or [configure your status line](/en/statusline#context-window-usage) to display it continuously.

* **Clear between tasks**: Use `/clear` to start fresh when switching to unrelated work. Stale context wastes tokens on every subsequent message. Use `/rename` before clearing so you can easily find the session later, then `/resume` to return to it.
* **Add custom compaction instructions**: `/compact Focus on code samples and API usage` tells Claude what to preserve during summarization.

You can also customize compaction behavior in your CLAUDE.md:

```markdown theme={null}
# Compact instructions

When you are using compact, please focus on test output and code changes
```

### 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`. For simple subagent tasks, specify `model: haiku` in your [subagent configuration](/en/sub-agents#choose-a-model).

### Reduce MCP server overhead

MCP tool definitions are [deferred by default](/en/mcp#scale-with-mcp-tool-search), so only tool names 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

[Code intelligence plugins](/en/discover-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

Custom [hooks](../07-Hooks/hooks-9168ed62a4.md) 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.

A [skill](../08-Plugins-Skills/extend-claude-with-skills-claude-code-docs.md) 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.

For example, this PreToolUse hook filters test output to show only failures:

<Tabs>
  <Tab title="settings.json">
    Add this to your [settings.json](/en/settings#settings-files) to run the hook before every Bash command:

    ```json theme={null}
    {
      "hooks": {
        "PreToolUse": [
          {
            "matcher": "Bash",
            "hooks": [
              {
                "type": "command",
                "command": "~/.claude/hooks/filter-test-output.sh"
              }
            ]
          }
        ]
      }
    }
    ```
  </Tab>

  <Tab title="filter-test-output.sh">
    The hook calls this script, which checks if the command is a test runner and modifies it to show only failures:

    ```bash theme={null}
    #!/bin/bash
    input=$(cat)
    cmd=$(echo "$input" | jq -r '.tool_input.command')

    # If running tests, filter to show only failures
    if [[ "$cmd" =~ ^(npm test|pytest|go test) ]]; then
      filtered_cmd="$cmd 2>&1 | grep -A 5 -E '(FAIL|ERROR|error:)' | head -100"
      echo "{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"permissionDecision\":\"allow\",\"updatedInput\":{\"command\":\"$filtered_cmd\"}}}"
    else
      echo "{}"
    fi
    ```
  </Tab>
</Tabs>

### Move instructions from CLAUDE.md to skills

Your [CLAUDE.md](how-claude-remembers-your-project-claude-code-docs-f1c064262d.md) 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](../08-Plugins-Skills/extend-claude-with-skills-claude-code-docs.md) 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

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](/en/model-config#adjust-effort-level) with `/effort` or in `/model`, disabling thinking in `/config`, or lowering the budget with `MAX_THINKING_TOKENS=8000`.

### Delegate verbose operations to subagents

Running tests, fetching documentation, or processing log files can consume significant context. Delegate these to [subagents](/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.

### 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](../09-Agents-Patterns/agent-teams-e29da6ed1b.md) for details.

### 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

For longer or more complex work, these habits help avoid wasted tokens from going down the wrong path:

* **Use plan mode for complex tasks**: Press Shift+Tab to enter [plan mode](/en/common-workflows#use-plan-mode-for-safe-code-analysis) before implementation. Claude explores the codebase and proposes an approach for your approval, preventing expensive re-work when the initial direction is wrong.
* **Course-correct early**: If Claude starts heading the wrong direction, press Escape to stop immediately. Use `/rewind` or double-tap Escape to restore conversation and code to a previous checkpoint.
* **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 when they're cheap to fix.

## Background token usage

Claude Code uses tokens for some background functionality even when idle:

* **Conversation summarization**: Background jobs that summarize previous conversations for the `claude --resume` feature
* **Command processing**: Some commands like `/usage` may generate requests to check status

These background processes consume a small amount of tokens (typically under \$0.04 per session) even without active interaction.

## 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 specific billing questions, contact Anthropic support through your [Console account](https://platform.claude.com/login).


---
## costs.md

# Manage costs effectively

Track token usage, set team spend limits, and reduce Claude Code costs with context management, model selection, extended thinking settings, and preprocessing hooks.

Claude Code consumes tokens for each interaction. The average cost is $6 per developer per day, with daily costs remaining below $12 for 90% of users. On average, Claude Code costs ~$100-200/developer per month with Sonnet 4.6.

## Track your costs

### Using the `/cost` command

> The `/cost` command shows API token usage and is intended for API users. Claude Max and Pro subscribers have usage included in their subscription, so `/cost` data isn't relevant for billing purposes. Subscribers can use `/stats` to view usage patterns.

```
Total cost:            $0.55
Total duration (API):  6m 19.7s
Total duration (wall): 6h 33m 10.2s
Total code changes:    0 lines added, 0 lines removed
```

## Managing costs for teams

Set workspace spend limits on the total Claude Code workspace spend. Admins can view cost and usage reporting in the Console.

### Rate limit recommendations

| Team size     | TPM per user | RPM per user |
| ------------- | ------------ | ------------ |
| 1-5 users     | 200k-300k    | 5-7          |
| 5-20 users    | 100k-150k    | 2.5-3.5      |
| 20-50 users   | 50k-75k      | 1.25-1.75    |
| 50-100 users  | 25k-35k      | 0.62-0.87    |
| 100-500 users | 15k-20k      | 0.37-0.47    |
| 500+ users    | 10k-15k      | 0.25-0.35    |

### Agent team token costs

Agent teams spawn multiple Claude Code instances. Token usage scales with the number of active teammates.

- Use Sonnet for teammates
- Keep teams small (3-5)
- Keep spawn prompts focused
- Clean up teams when done

## Reduce token usage

### Manage context proactively

- Use `/clear` between tasks
- Use `/compact Focus on code samples and API usage` for custom compaction
- Customize compaction in CLAUDE.md

### Choose the right model

Sonnet handles most coding tasks well and costs less than Opus. Reserve Opus for complex architectural decisions. Use `/model` to switch mid-session.

### Reduce MCP server overhead

MCP tool definitions are deferred by default. Run `/context` to see what's consuming space. Prefer CLI tools (`gh`, `aws`) when available. Disable unused servers via `/mcp`.

### Install code intelligence plugins

Code intelligence plugins give Claude precise symbol navigation, reducing unnecessary file reads.

### Move instructions from CLAUDE.md to skills

Skills load on-demand only when invoked. Keep CLAUDE.md under 200 lines.

### Adjust extended thinking

Extended thinking is enabled by default. For simpler tasks, reduce with `/effort`, disable in `/config`, or lower the budget with `MAX_THINKING_TOKENS=8000`.

### Delegate verbose operations to subagents

Running tests, fetching docs, or processing logs can consume context. Delegate to subagents so verbose output stays in the subagent's context.

### Write specific prompts

Vague requests trigger broad scanning. Specific requests let Claude work efficiently with minimal file reads.

### Work efficiently on complex tasks

- Use plan mode (Shift+Tab) for complex tasks
- Course-correct early with Escape
- Give verification targets (test cases, screenshots)
- Test incrementally

## Background token usage

Claude Code uses tokens for background functionality even when idle:

- Conversation summarization for `claude --resume`
- Command processing for status checks

Typically under $0.04 per session.

## See Also

- [Agent teams](../09-Agents-Patterns/agent-teams.md)
- [Subagents](../09-Agents-Patterns/create-custom-subagents-claude-code-docs-7dc93e85c0.md)
- [Model configuration](model-config-ca429e15da.md)


---
## cowork-protocol-spec.md

# Claude Code CoWork Protocol Specification

Reverse-engineered from claude binaries 2.1.74-2.1.75 (2026-03-11 to 2026-03-14).
Source: `2.1.75_bunfs_extracted/src/entrypoints/cli.js` (14,697 lines)

## Table of Contents

1. [Architecture Overview](#architecture-overview)
2. [Client Type Identification](#client-type-identification)
3. [OAuth Configuration](#oauth-configuration)
4. [CLI Spawning — Flags & Environment](#cli-spawning)
5. [stdin Protocol (Caller → CLI)](#stdin-protocol)
6. [stdout Protocol (CLI → Caller)](#stdout-protocol)
7. [Session JSONL Format](#session-jsonl-format)
8. [Sessions API](#sessions-api)
9. [WebSocket Subscription](#websocket-subscription)
10. [CoWork-Specific Behavior](#cowork-specific-behavior)
11. [Agent Teams (Teammate Mode)](#agent-teams)
12. [Session Resume Paths](#session-resume-paths)
13. [sdkUrl & Session Ingress Transport](#sdkurl-session-ingress-transport)
14. [Session Creation API](#session-creation-api)
15. [Bridge Orchestrator](#bridge-orchestrator)
16. [Remaining Unknowns](#remaining-unknowns)

---

## Architecture Overview

All three interfaces (CLI terminal, Claude Desktop, claude.ai web) run the **same `claude` binary**.
Differences are purely in:
- How the process is spawned (TTY vs child_process with piped stdio)
- Which env vars are set (entrypoint, auth mechanism, persistence flags)
- Whether stdin/stdout uses interactive Ink/React rendering vs stream-json protocol
- Whether persistence is local-only or dual-write to Sessions API

```
┌──────────────┐   ┌──────────────┐   ┌──────────────┐
│ Claude       │   │ Claude Code  │   │ claude.ai    │
│ Desktop      │   │ CLI          │   │ Web          │
│ (Electron)   │   │ (Terminal)   │   │ (Browser)    │
└──────┬───────┘   └──────┬───────┘   └──────┬───────┘
       │                  │                   │
       │ ENTRYPOINT=      │ (unset→"cli")     │ ENVIRONMENT_KIND=
       │ "claude-desktop" │                   │ "bridge"
       │                  │                   │
       ▼                  ▼                   ▼
┌──────────────┐   ┌──────────────┐   ┌──────────────┐
│ claude CLI   │   │ claude CLI   │   │  Bridge      │
│ (child proc) │   │ (direct)     │   │  (spawner)   │
│ stdin/stdout │   │ TTY I/O      │   │  Yz8()       │
│ stream-json  │   │ interactive  │   └──────┬───────┘
└──────┬───────┘   └──────┬───────┘          │
       │                  │           ┌──────▼───────┐
       │                  │           │ claude CLI   │
       │                  │           │ --print      │
       │                  │           │ stdin/stdout │
       │                  │           │ stream-json  │
       │                  │           └──────┬───────┘
       ▼                  ▼                  ▼
┌─────────────────────────────────────────────────┐
│              Anthropic API                      │
│         /v1/messages (Claude model)             │
└────────────────────┬────────────────────────────┘
                     │
┌────────────────────▼────────────────────────────┐
│              Sessions API                       │
│  /v1/sessions/<id>             (CRUD)           │
│  /v1/sessions/<id>/events      (event log)      │
│  /v1/sessions/ws/<id>/subscribe (WebSocket)     │
│  /v1/code/sessions/<id>/teleport-events         │
│  /v1/session_ingress/session/<id> (legacy)      │
└─────────────────────────────────────────────────┘
```

---

## Client Type Identification

Determined at startup from `CLAUDE_CODE_ENTRYPOINT`:

| CLAUDE_CODE_ENTRYPOINT | clientType      | Context                        |
|------------------------|-----------------|--------------------------------|
| `"sdk-cli"`            | `"sdk-cli"`     | Agent SDK invocation           |
| `"claude-vscode"`      | `"claude-vscode"` | VS Code extension            |
| `"local-agent"`        | `"local-agent"` | Desktop app local agent mode   |
| `"claude-desktop"`     | `"claude-desktop"` | Claude Desktop (Electron)   |
| `"remote"` (or token present) | `"remote"` | Remote / web session        |
| (unset)                | `"cli"`         | Bare terminal                  |

Additional identity in API User-Agent:
```
CLAUDE_AGENT_SDK_VERSION  → "agent-sdk/X.Y.Z"
CLAUDE_AGENT_SDK_CLIENT_APP → "client-app/<name>"
User-Agent: "claude-code/2.1.74 (sdk-cli, agent-sdk/1.0.0, client-app/myapp)"
```

When `CLAUDE_CODE_ENVIRONMENT_KIND=bridge`, session source is set to `"remote-control"`.

---

## OAuth Configuration

### Production Endpoints (s_L)

```
BASE_API_URL:            https://api.anthropic.com
CLAUDE_AI_AUTHORIZE_URL: https://claude.ai/oauth/authorize
CONSOLE_AUTHORIZE_URL:   https://platform.claude.com/oauth/authorize
TOKEN_URL:               https://platform.claude.com/v1/oauth/token
API_KEY_URL:             https://api.anthropic.com/api/oauth/claude_cli/create_api_key
ROLES_URL:               https://api.anthropic.com/api/oauth/claude_cli/roles
CONSOLE_SUCCESS_URL:     https://platform.claude.com/buy_credits?returnUrl=/oauth/code/success%3Fapp%3Dclaude-code
CLAUDEAI_SUCCESS_URL:    https://platform.claude.com/oauth/code/success?app=claude-code
MANUAL_REDIRECT_URL:     https://platform.claude.com/oauth/code/callback
CLIENT_ID:               9d1c250a-e61b-44d9-88ed-5944d1962f5e
MCP_PROXY_URL:           https://mcp-proxy.anthropic.com
MCP_PROXY_PATH:          /v1/mcp/{server_id}
```

Overridable via:
- `CLAUDE_CODE_CUSTOM_OAUTH_URL` — replaces all URLs with custom base
- `CLAUDE_CODE_OAUTH_CLIENT_ID` — replaces CLIENT_ID

### Scopes

```
Claude.ai flow (eH$):
  user:profile
  user:inference
  user:sessions:claude_code
  user:mcp_servers

Console flow (HML):
  org:create_api_key
  user:profile
```

### Token Exchange

```http
POST https://platform.claude.com/v1/oauth/token
Content-Type: application/json

{
  "grant_type": "authorization_code",
  "redirect_uri": "http://localhost:<port>/callback" | MANUAL_REDIRECT_URL,
  "client_id": "9d1c250a-e61b-44d9-88ed-5944d1962f5e",
  "code_verifier": "<PKCE_verifier>",
  "state": "<state>"
}
```

### Token Refresh

```http
POST https://platform.claude.com/v1/oauth/token
Content-Type: application/json

{
  "grant_type": "refresh_token",
  "refresh_token": "<token>",
  "client_id": "9d1c250a-e61b-44d9-88ed-5944d1962f5e",
  "scope": "user:profile user:inference user:sessions:claude_code user:mcp_servers"
}
```

Beta header for all Sessions API calls: `anthropic-beta: oauth-2025-04-20`

### Desktop App Auth

Desktop uses file descriptor auth instead of env vars:
```
CLAUDE_CODE_WEBSOCKET_AUTH_FILE_DESCRIPTOR=<fd_number>
```
Token read from `/proc/self/fd/<N>` (inherited FD from parent Electron process).

---

## CLI Spawning

### Flags for Non-Interactive (Print) Mode

```bash
claude --print \
  --session-id <uuid> \
  --input-format stream-json \
  --output-format stream-json \
  --replay-user-messages \
  [--sdk-url <bridge_endpoint>] \
  [--verbose] \
  [--debug-file <path>] \
  [--permission-mode <mode>]
```

### Environment Variables Set by Bridge

```bash
CLAUDE_CODE_ENVIRONMENT_KIND=bridge        # identifies runtime context
CLAUDE_CODE_SESSION_ACCESS_TOKEN=<token>   # OAuth bearer for API
CLAUDE_CODE_POST_FOR_SESSION_INGRESS_V2=1  # enable remote persistence
CLAUDE_CODE_OAUTH_TOKEN=                   # explicitly cleared
CLAUDE_CODE_FORCE_SANDBOX=1               # if sandbox enabled
CLAUDE_CODE_USE_CCR_V2=1                  # if using CCR v2
CLAUDE_CODE_WORKER_EPOCH=<N>              # worker generation counter
```

### CoWork Tab Additional Vars

```bash
CLAUDE_CODE_IS_COWORK=1                   # eager flush at every turn
CLAUDE_CODE_USE_COWORK_PLUGINS=1          # cowork_plugins/ + cowork_settings.json
```

### All Relevant Environment Variables

| Variable | Purpose |
|----------|---------|
| `CLAUDE_CODE_ENTRYPOINT` | Client identity: sdk-cli, claude-vscode, local-agent, claude-desktop, remote |
| `CLAUDE_CODE_ENVIRONMENT_KIND` | Runtime context: bridge, byoc, anthropic_cloud |
| `CLAUDE_CODE_IS_COWORK` | Eager session flush at every turn boundary |
| `CLAUDE_CODE_USE_COWORK_PLUGINS` | Plugin dir → cowork_plugins/, settings → cowork_settings.json |
| `CLAUDE_CODE_SESSION_ACCESS_TOKEN` | OAuth token for Sessions API (refreshable via stdin) |
| `CLAUDE_CODE_POST_FOR_SESSION_INGRESS_V2` | Enable dual-write: local JSONL + remote Sessions API |
| `CLAUDE_CODE_USE_CCR_V2` | CCR v2 protocol |
| `CLAUDE_CODE_WORKER_EPOCH` | Worker generation counter for CCR v2 |
| `CLAUDE_CODE_FORCE_SANDBOX` | Force sandbox mode |
| `CLAUDE_CODE_EAGER_FLUSH` | Force eager session flush (same effect as IS_COWORK for flushing) |
| `CLAUDE_COWORK_MEMORY_PATH_OVERRIDE` | Override auto-memory directory (shared memory path) |
| `CLAUDE_CODE_REMOTE` | Remote mode flag |
| `CLAUDE_CODE_REMOTE_MEMORY_DIR` | Memory dir in remote mode |
| `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` | Enable agent-teams feature |
| `CLAUDE_CODE_PLAN_MODE_REQUIRED` | Force plan-before-act for teammates |
| `CLAUDE_CODE_WEBSOCKET_AUTH_FILE_DESCRIPTOR` | FD-based auth for Desktop app |
| `CLAUDE_AGENT_SDK_VERSION` | SDK version for User-Agent |
| `CLAUDE_AGENT_SDK_CLIENT_APP` | Client app name for User-Agent |
| `CLAUDE_CODE_CUSTOM_OAUTH_URL` | Override OAuth endpoints |
| `CLAUDE_CODE_OAUTH_CLIENT_ID` | Override OAuth client ID |
| `CLAUDE_CODE_DISABLE_AUTO_MEMORY` | Disable auto-memory |
| `CLAUDE_CODE_SESSION_SOURCE` | Session source identifier |
| `CLAUDE_CODE_SIMPLE` | Disable skills, CLAUDE.md, file attachments |
| `CLAUDE_CODE_QUESTION_PREVIEW_FORMAT` | "markdown" or "html" |

---

## stdin Protocol

Each line is a JSON object terminated by `\n`. Parsed by `XoH.processLine()`.

### User Message

```json
{
  "type": "user",
  "message": { "content": "fix the auth bug in login.ts" },
  "parent_tool_use_id": null,
  "isSynthetic": false,
  "isReplay": false
}
```

### Keep-Alive

```json
{ "type": "keep_alive" }
```

### Environment Variable Update

```json
{
  "type": "update_environment_variables",
  "variables": {
    "CLAUDE_CODE_SESSION_ACCESS_TOKEN": "new-token-value"
  }
}
```

### Permission Response (Approve)

```json
{
  "type": "control_response",
  "response": {
    "request_id": "abc-123",
    "subtype": "success",
    "response": {
      "behavior": "allow",
      "updatedInput": {}
    }
  }
}
```

### Permission Response (Deny)

```json
{
  "type": "control_response",
  "response": {
    "request_id": "abc-123",
    "subtype": "success",
    "response": {
      "behavior": "deny"
    }
  }
}
```

### Permission Cancel

```json
{
  "type": "control_cancel_request",
  "request_id": "abc-123"
}
```

Note: `Nm$()` normalizes `requestId` → `request_id` for camelCase compat.

---

## stdout Protocol

Each line is a JSON object terminated by `\n`. Parsed by `fA_()`.

### Assistant Message

```json
{
  "type": "assistant",
  "message": {
    "content": [
      { "type": "text", "text": "I'll fix that..." },
      { "type": "tool_use", "id": "tu_123", "name": "Read",
        "input": { "file_path": "/src/login.ts" } }
    ]
  },
  "uuid": "msg-uuid",
  "session_id": "session-uuid"
}
```

### Permission Request

```json
{
  "type": "control_request",
  "request_id": "req-uuid",
  "request": {
    "subtype": "can_use_tool",
    "tool_name": "Bash",
    "tool_use_id": "tu_456",
    "input": { "command": "rm -rf /tmp/old" }
  }
}
```

### Result (Success)

```json
{
  "type": "result",
  "subtype": "success",
  "is_error": false,
  "duration_ms": 45230,
  "duration_api_ms": 38100,
  "num_turns": 7,
  "result": "Fixed the auth bug by...",
  "stop_reason": null,
  "session_id": "session-uuid",
  "total_cost_usd": 0.0342,
  "usage": {
    "input_tokens": 15420,
    "output_tokens": 3200,
    "cache_read_input_tokens": 8000,
    "cache_creation_input_tokens": 0
  },
  "modelUsage": {},
  "permission_denials": [],
  "fast_mode_state": {},
  "uuid": "result-uuid"
}
```

### Result Subtypes

| subtype | Meaning |
|---------|---------|
| `"success"` | Normal completion |
| `"error_max_turns"` | Hit max turns limit |
| `"error_max_budget_usd"` | Hit cost budget |
| `"error_during_execution"` | Runtime error |
| `"error_max_structured_output_retries"` | Structured output validation failed repeatedly |

---

## Session JSONL Format

### File Path

```
~/.claude/projects/<PI(projectRoot)>/<session-uuid>.jsonl
```

Where `PI()` hashes the absolute project path. Subagent sessions:
```
~/.claude/projects/<hash>/<parent-session-id>/subagents/agent-<agent-id>.jsonl
```

### Message Entry Shape

Each line is a JSON object. Messages pass the `RQ()` filter:
```js
RQ(H) = H.type === "user" || "assistant" || "attachment" || "system" || "progress"
```

```json
{
  "type": "user|assistant|system|progress|attachment",
  "uuid": "<crypto.randomUUID>",
  "timestamp": "2026-03-14T...",
  "message": { "role": "user|assistant", "content": "..." },

  "parentUuid": "<prev-msg-uuid> | null",
  "logicalParentUuid": "<uuid> | undefined",
  "isSidechain": false,
  "sessionId": "<session-uuid>",
  "version": "1",
  "cwd": "/path/to/project",
  "gitBranch": "main",
  "slug": "claude-sonnet-4-6",
  "userType": "external",

  "agentId": "<agent-uuid> | undefined",
  "agentName": "<name> | undefined",
  "teamName": "<team-name> | undefined",
  "promptId": "<prompt-uuid> | undefined",

  "isMeta": false,
  "toolUseResult": false,
  "isCompactSummary": false,
  "sourceToolAssistantUUID": "<uuid>"
}
```

System messages with `"subtype": "compact_boundary"` mark compaction points.

### Metadata Entries (Non-Message Lines)

```json
{"type":"custom-title","customTitle":"Fix auth bug","sessionId":"..."}
{"type":"ai-title","aiTitle":"Auth module refactor","sessionId":"..."}
{"type":"tag","tag":"bugfix","sessionId":"..."}
{"type":"summary","leafUuid":"...","summary":"..."}
{"type":"agent-name","agentName":"researcher","sessionId":"..."}
{"type":"agent-color","agentColor":"#ff6b6b","sessionId":"..."}
{"type":"agent-setting","agentSetting":"explorer","sessionId":"..."}
{"type":"mode","mode":"plan","sessionId":"..."}
{"type":"pr-link","prNumber":42,"prUrl":"...","prRepository":"...","sessionId":"...","timestamp":"..."}
{"type":"last-prompt","lastPrompt":"fix the auth bug","sessionId":"..."}
{"type":"file-history-snapshot","messageId":"...","snapshot":{}}
{"type":"queue-operation","operation":{}}
```

### Session File Writer

`dT(path, entry)` — synchronous append, mode 0600:
```js
fs.appendFileSync(path, JSON.stringify(entry) + "\n", { mode: 0o600 })
```

`Jq()` singleton manages batched writes (100ms flush interval), with eager flush
when `CLAUDE_CODE_IS_COWORK` or `CLAUDE_CODE_EAGER_FLUSH` is set.

---

## Sessions API

All calls require:
```http
Authorization: Bearer <accessToken>
anthropic-beta: ccr-byoc-2025-07-29
x-organization-uuid: <orgUUID>
```

### List Sessions

```http
GET https://api.anthropic.com/v1/sessions
```

Response: `{ data: [{ id, title, session_status, session_context, created_at, updated_at }] }`

### Get Session

```http
GET https://api.anthropic.com/v1/sessions/<session-id>
```

### Update Session Title

```http
PATCH https://api.anthropic.com/v1/sessions/<session-id>
Content-Type: application/json

{ "title": "New Title" }
```

### Post Events (Single Message)

```http
POST https://api.anthropic.com/v1/sessions/<session-id>/events
Content-Type: application/json

{
  "events": [{
    "uuid": "<uuid>",
    "session_id": "<session-id>",
    "type": "user",
    "parent_tool_use_id": null,
    "message": { "role": "user", "content": "message text" }
  }]
}
```

### Post Events (Batch)

Same endpoint, up to 100 events per batch (`kN$ = 100`).

### Fetch Teleport Events (Paginated)

```http
GET https://api.anthropic.com/v1/code/sessions/<session-id>/teleport-events
  ?limit=1000
  &cursor=<cursor>
```

### Legacy Ingress Fetch

```http
GET https://api.anthropic.com/v1/session_ingress/session/<session-id>
```

### Archive Session

```http
POST https://api.anthropic.com/v1/sessions/<session-id>/archive
```

---

## WebSocket Subscription

### Connection

```
wss://api.anthropic.com/v1/sessions/ws/<session-id>/subscribe
  ?organization_uuid=<orgUuid>

Headers:
  Authorization: Bearer <accessToken>
  anthropic-version: 2023-06-01
```

### Message Handling

Validator `fW6()` accepts any object with a string `type` field:
```js
function fW6(H) {
  if (typeof H !== "object" || H === null || !("type" in H)) return false;
  return typeof H.type === "string";
}
```

Events are forwarded to `callbacks.onMessage(parsedEvent)`.

Reconnection: up to `Abf` attempts with `AW6` ms delay.
Permanent close codes in `DW6` set prevent reconnection.
Ping interval: `LW6` ms.

### Control Messages (via WebSocket)

```json
{
  "type": "control_request",
  "request_id": "<uuid>",
  "request": {
    "subtype": "can_use_tool",
    "tool_name": "Bash",
    "tool_use_id": "...",
    "input": {}
  }
}
```

---

## CoWork-Specific Behavior

### Plugin Isolation

When `CLAUDE_CODE_USE_COWORK_PLUGINS=1` or `--cowork` flag:
- Plugin directory: `~/.claude/cowork_plugins/` (instead of `~/.claude/plugins/`)
- Settings file: `~/.claude/cowork_settings.json` (instead of `~/.claude/settings.json`)
- Function `ae6()` returns `"cowork_settings.json"` when `BkH()` or env var is truthy
- Function `L$_()` returns `"cowork_plugins"` instead of `"plugins"`

### Eager Flush

When `CLAUDE_CODE_IS_COWORK=1` or `CLAUDE_CODE_EAGER_FLUSH=1`:
- `RB()` (= `Jq().flush()`) called at every turn boundary
- `RB()` called at every result exit point (success, error_max_turns, etc.)
- Ensures remote Sessions API receives events in near-real-time

### Shared Memory (CoWork Teams)

`CLAUDE_COWORK_MEMORY_PATH_OVERRIDE=/path/to/shared/memory`
- Overrides the per-project memory directory
- All teammates in a CoWork session share the same MEMORY.md
- `mM$()` returns true when override is active
- `SHD()` reads the env var, `o3()` uses it as first priority

---

## Agent Teams

Agent Teams (teammate mode) is separate from CoWork. Enabled by:
```
CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=true  OR  --agent-teams flag
AND tengu_amber_flint feature flag = true
```

### Teammate Spawning (tmux mode)

The lead constructs a claude command:
```bash
cd /project && claude \
  --agent-id <uuid> \
  --agent-name <sanitized-name> \
  --team-name <team-name> \
  --agent-color <color> \
  --parent-session-id <lead-session-id> \
  [--plan-mode-required] \
  [--agent-type <type>]
```

### Teammate Modes

| Mode | Mechanism |
|------|-----------|
| `"tmux"` | Separate claude process in tmux pane |
| `"in-process"` | AsyncLocalStorage context in same Node process |
| `"auto"` | Chooses based on terminal (iTerm2 native panes → tmux → in-process) |

Configurable via settings `teammateMode` or `--teammate-mode <mode>`.

### Team State Storage

```
~/.claude/teams/<team-name>/config.json
~/.claude/tasks/<team-name>/
```

Config contains `members[]` with agentId, name, agentType, model, prompt, color,
planModeRequired, joinedAt, tmuxPaneId, cwd, subscriptions, backendType.

### SendMessage Tool Schema

Types: `message`, `broadcast`, `shutdown_request`, `shutdown_response`, `plan_approval_response`

```json
{"type":"message","recipient":"researcher","content":"...","summary":"Brief preview"}
{"type":"broadcast","content":"...","summary":"Critical announcement"}
{"type":"shutdown_request","recipient":"researcher","content":"Task complete"}
{"type":"shutdown_response","request_id":"abc","approve":true}
{"type":"plan_approval_response","request_id":"abc","recipient":"researcher","approve":true}
```

### Teammate System Prompt Addendum

```
# Agent Teammate Communication

IMPORTANT: You are running as an agent in a team. To communicate with anyone on your team:
- Use the SendMessage tool with type `message` to send messages to specific teammates
- Use the SendMessage tool with type `broadcast` sparingly for team-wide announcements

Just writing a response in text is not visible to others on your team
- you MUST use the SendMessage tool.

The user interacts primarily with the team lead. Your work is coordinated
through the task system and teammate messaging.
```

---

## Session Resume Paths

### Local Resume

| Flag | Mechanism |
|------|-----------|
| `--continue` | Loads most recent session via `FbA(0)` |
| `--resume <uuid>` | Loads `<uuid>.jsonl` via `eQH(sessionId)` |
| `--resume <search>` | Fuzzy matches title via `UB(query, {exact:true})` |
| `--fork-session` | Creates new session ID, copies messages |
| `--resume-session-at <msg-id>` | Truncates at message UUID |
| `--rewind-files <msg-id>` | Restores files to snapshot, exits |
| `--from-pr [number]` | Sessions linked to PR |

### Remote Resume

| Flag | Mechanism |
|------|-----------|
| `--teleport <id>` | `GET /v1/code/sessions/<id>/teleport-events` (paginated, 1000/page) |
| (fallback) | `GET /v1/session_ingress/session/<id>` |

### Session Loader Flow (ae())

1. Read JSONL → parse via `HqH()` → maps of messages, summaries, titles, tags, snapshots
2. Find leaf UUID (most recent non-sidechain message)
3. Walk `parentUuid` chain via `GrH()` to reconstruct conversation tree
4. Slice at `compact_boundary` via `Ly()` if present
5. Restore fileHistorySnapshots, attributionSnapshots, contentReplacements
6. Run `SessionStart:resume` hooks
7. Return `{messages, turnInterruptionState, agentSetting, ...}` to React app

### Hydration (Remote → Local)

`ZnA(sessionId, ingressUrl)`:
1. Fetch events from remote ingress URL
2. Write to local `<uuid>.jsonl`
3. Set remote ingress URL on session writer for future dual-write

---

## sdkUrl & Session Ingress Transport

**Gap 1 RESOLVED**: `--sdk-url` is NOT an HTTP endpoint. It is a **WebSocket URL** for
session ingress. The CLI opens a persistent WebSocket to it and pipes stream-json
bidirectionally.

### How sdkUrl Works

When `--sdk-url <url>` is passed, the CLI creates a `Yp$` transport (class extending `goH`):

```
┌────────────────────────────┐
│  Bridge Daemon (T38)       │
│  polls /work/poll          │
│  gets work_secret with     │
│  session_ingress_token     │
└─────────┬──────────────────┘
          │ spawns:
          │ claude --print --sdk-url <ws_url> --session-id <id> ...
          ▼
┌────────────────────────────┐          ┌──────────────────────────┐
│  CLI child process         │          │  Anthropic API           │
│  Yp$ class                 │◄──WS───►│  session_ingress/ws/<id> │
│  ├─ WebSocket transport    │          └──────────────────────────┘
│  │  (doH / FoH / mqH)     │
│  ├─ stdin ← WS messages   │
│  ├─ stdout → WS write()   │
│  └─ keep_alive interval   │
└────────────────────────────┘
```

### Transport Selection (`d08()`)

```
d08(url, headers, sessionId, refreshHeaders):
  if CLAUDE_CODE_USE_CCR_V2:
    → convert ws→http, append /worker/events/stream
    → return SSETransport (mqH)
  else if ws:// or wss://:
    if CLAUDE_CODE_POST_FOR_SESSION_INGRESS_V2:
      → return HybridTransport (FoH) — WebSocket + POST fallback
    else:
      → return WebSocketTransport (doH)
  else:
    → Error: unsupported protocol
```

### Session Ingress WebSocket URL

Built by `Wm$()`:
```
wss://{api_host}/v1/session_ingress/ws/{sessionId}
```
For localhost: `ws://` and `/v2/` path prefix.

### HybridTransport POST Fallback

`FoH` extends `doH` (WebSocketTransport), adding:
- Batched POST uploads to `{url}/session/{sessionId}/events` (URL transform via `L1_()`)
- Auth: `Authorization: Bearer {MJ()}` — uses `MJ()` (see session token section)
- Content-Type: `application/json`
- Body: `{ events: [...messages] }`
- Batch size: 500, queue size: 100k, retry with exponential backoff

### CCR v2 Path

When `CLAUDE_CODE_USE_CCR_V2=1`:
- Worker registration: `POST {api}/v1/code/sessions/{id}/worker/register`
- Stream: SSE at `{api}/v1/code/sessions/{id}/worker/events/stream`
- Internal events read/write via `QoH` (CCRClient)
- State reporting: permission_mode, tool activity, metadata

### Key Implication for Local Client

**sdkUrl is optional for local implementations.** When omitted, the CLI uses `goH` (local
stdin/stdout passthrough). The `Yp$` class is only needed when the CLI must talk to a
remote bridge over WebSocket. A local CoWork client can:
1. Spawn CLI with piped stdin/stdout (no `--sdk-url`)
2. Separately dual-write events via `POST /v1/sessions/{id}/events`
3. Subscribe to remote updates via WebSocket subscription

---

## Session Creation API

**Gap 2 RESOLVED**: Full `POST /v1/sessions` schema extracted.

### Create Session (Web/CLI Path)

```http
POST https://api.anthropic.com/v1/sessions
Authorization: Bearer <accessToken>
Content-Type: application/json
anthropic-version: 2023-06-01
anthropic-beta: ccr-byoc-2025-07-29
x-organization-uuid: <orgUUID>
```

Request Body:
```json
{
  "title": "Fix auth bug in login.ts",
  "events": [
    {
      "type": "event",
      "data": {
        "uuid": "<crypto.randomUUID()>",
        "session_id": "",
        "type": "user",
        "parent_tool_use_id": null,
        "message": {
          "role": "user",
          "content": "fix the auth bug in login.ts"
        }
      }
    }
  ],
  "session_context": {
    "sources": [
      {
        "type": "git_repository",
        "git_info": {
          "type": "github",
          "repo": "owner/repo"
        }
      }
    ],
    "outcomes": [
      {
        "type": "git_repository",
        "git_info": {
          "type": "github",
          "repo": "owner/repo",
          "branches": ["claude/task"]
        }
      }
    ],
    "model": "claude-sonnet-4-6"
  },
  "environment_id": "<environment-uuid>"
}
```

Response:
```json
{
  "id": "cse_abc123...",
  "title": "Fix auth bug in login.ts"
}
```

### Create Session (Bridge/Remote Control Path)

Same endpoint, but additional fields:

```json
{
  "title": "optional",
  "events": [],
  "session_context": {
    "sources": [{"type": "git_repository", "git_info": {...}}],
    "outcomes": [{"type": "git_repository", "git_info": {...}}],
    "model": "claude-sonnet-4-6"
  },
  "environment_id": "<environment-uuid>",
  "source": "remote-control",
  "permission_mode": "plan"
}
```

### Fetch Session Details

```http
GET https://api.anthropic.com/v1/sessions/<session-id>
```

Response includes `session_context.sources[]` with:
- `type: "git_repository"` — `url`, `git_info.type`, `git_info.repo`
- `type: "directory"` — path info

### List Code Sessions (with context)

```http
GET https://api.anthropic.com/v1/sessions
```

Response: `{ data: [{ id, title, session_status, session_context, created_at, updated_at }] }`

### Share Transcript

```http
POST https://api.anthropic.com/api/claude_code_shared_session_transcripts
Content-Type: application/json
User-Agent: claude-code/2.1.75

{
  "content": "<transcript>",
  "appearance_id": "<id>"
}
```

Response: `{ transcript_id: "..." }`

---

## WebSocket Event Types

**Gap 3 RESOLVED**: The WebSocket carries the **same stream-json protocol** as stdin/stdout.
All message types listed below are valid over both WebSocket and piped stdio.

### Full Message Type Taxonomy

Messages pass through `Lf_()` filter (passes everything except control_request/control_response)
and `QZH()` adapter:

| Type | Subtypes | Direction | Purpose |
|------|----------|-----------|---------|
| `user` | — | client→server | User message |
| `assistant` | — | server→client | Model response (text, tool_use) |
| `system` | `init`, `status`, `compact_boundary`, `informational` | server→client | System events |
| `result` | `success`, `error_max_turns`, `error_max_budget_usd`, `error_during_execution` | server→client | Turn completion |
| `tool_progress` | — | server→client | Long-running tool status |
| `stream_event` | — | server→client | Streaming delta (text, tool input) |
| `auth_status` | — | server→client | Auth state changes |
| `tool_use_summary` | — | server→client | Tool use digest |
| `rate_limit_event` | — | server→client | Rate limiting info |
| `control_request` | `can_use_tool`, `interrupt`, `hook_callback`, `elicitation`, `mcp_message`, `set_permission_mode` | bidirectional | Permission/control flow |
| `control_response` | `success`, `error` | bidirectional | Response to control_request |
| `control_cancel_request` | — | client→server | Cancel pending request |
| `keep_alive` | — | bidirectional | Connection heartbeat |
| `streamlined_text` | — | server→client | Streamlined text output |
| `streamlined_tool_use_summary` | — | server→client | Streamlined tool digest |
| `update_environment_variables` | — | client→server | Token refresh |

### system.init Event

Sent when session starts:
```json
{
  "type": "system",
  "subtype": "init",
  "slash_commands": ["commit", "compact", "help", ...],
  "timestamp": "..."
}
```

### stream_event Event

Real-time streaming deltas:
```json
{
  "type": "stream_event",
  "event": {
    "type": "content_block_delta",
    "delta": {"type": "text_delta", "text": "partial..."}
  }
}
```

### control_request Subtypes (Full)

| Subtype | Purpose | Fields |
|---------|---------|--------|
| `can_use_tool` | Permission check | `tool_name`, `input`, `tool_use_id`, `permission_suggestions`, `blocked_path`, `decision_reason`, `description`, `agent_id` |
| `interrupt` | Abort current operation | — |
| `hook_callback` | Execute hook | `callback_id`, `input`, `tool_use_id` |
| `elicitation` | MCP elicitation | `mcp_server_name`, `message`, `mode`, `url`, `elicitation_id`, `requested_schema` |
| `mcp_message` | MCP passthrough | `server_name`, `message` |
| `set_permission_mode` | Change permission level | `mode` |

---

## Session Token Architecture

**Gap 4 RESOLVED**: Complete token chain traced.

### Token Hierarchy

```
OAuth accessToken (long-lived, from PKCE flow)
  ├─ Used for: Sessions API CRUD, session listing, teleport, archive
  ├─ Stored: ~/.claude/.credentials.json
  └─ Header: Authorization: Bearer <accessToken>

session_ingress_token (session-scoped, from work secret)
  ├─ Used for: WebSocket ingress, event POST to session, bridge heartbeats
  ├─ Source: pollForWork response → work_secret (base64url JSON)
  └─ Header: Authorization: Bearer <session_ingress_token>
```

### MJ() — Session Token Getter

Priority chain:
1. `process.env.CLAUDE_CODE_SESSION_ACCESS_TOKEN` — highest priority
2. `CI1()` — reads from file descriptor via `CLAUDE_CODE_WEBSOCKET_AUTH_FILE_DESCRIPTOR`
   - Reads `/proc/self/fd/<N>` (inherited from Desktop Electron parent)
   - Cached after first read

### fIH() — Auth Headers Builder

```js
// For sessionKey tokens (sk-ant-sid*)
{ Cookie: "sessionKey=<token>", "X-Organization-Uuid": "<orgUuid>" }

// For bearer tokens (everything else)
{ Authorization: "Bearer <token>" }
```

### Rw() — OAuth Headers Builder

Used for all Sessions API calls:
```js
{
  Authorization: "Bearer <accessToken>",
  "Content-Type": "application/json",
  "anthropic-version": "2023-06-01"
}
```

Plus per-request additions:
```
anthropic-beta: ccr-byoc-2025-07-29
x-organization-uuid: <orgUUID>
```

### Work Secret Structure

The `pollForWork` response includes a `secret` field. Decoded by `Em$()`:

```json
{
  "version": 1,
  "session_ingress_token": "string (required)",
  "api_base_url": "string (required)",
  "use_code_sessions": true
}
```

The `session_ingress_token` is:
- Passed to child process via `CLAUDE_CODE_SESSION_ACCESS_TOKEN` env var
- Used as `accessToken` parameter in bridge session spawn
- Refreshable via token rotation during long sessions
- Bridge updates running sessions via `updateAccessToken()` when new work arrives

### Token Refresh for Running Sessions

The bridge daemon can receive updated tokens for existing sessions:
```js
// In poll loop, when session already exists:
if (existingSession) {
  existingSession.updateAccessToken(workSecret.session_ingress_token);
  // Also schedules token rotation
}
```

---

## Bridge Orchestrator

**Gap 5 RESOLVED**: Full bridge lifecycle traced.

### Entry Point

The bridge is started via `claude remote-control` or `/remote-control` command, which
calls `T38()` — the main bridge poll loop.

### Bridge API Client

Created by `zm$()`, provides these endpoints:

```
┌─────────────────────────────────────────────────────────────────┐
│  Bridge API Surface                                             │
│                                                                 │
│  POST /v1/environments/bridge                                   │
│    → registerBridgeEnvironment(machineName, dir, branch,        │
│       gitRepoUrl, maxSessions, workerType, reuseEnvironmentId)  │
│    ← { environment_id: string }                                 │
│                                                                 │
│  GET  /v1/environments/{envId}/work/poll?ack=true               │
│    → pollForWork(environmentId, accessToken, abortSignal)       │
│    ← { id: workId, data: { type: "session"|"healthcheck",      │
│         id: sessionId }, secret: base64url_work_secret }        │
│    ← null (no work available)                                   │
│                                                                 │
│  POST /v1/environments/{envId}/work/{workId}/ack                │
│    → acknowledgeWork(environmentId, workId, accessToken)        │
│                                                                 │
│  POST /v1/environments/{envId}/work/{workId}/stop               │
│    → stopWork(environmentId, workId, force)                     │
│                                                                 │
│  POST /v1/environments/{envId}/work/{workId}/heartbeat          │
│    → heartbeatWork(environmentId, workId, accessToken)          │
│    ← { lease_extended: bool, state: string }                    │
│                                                                 │
│  POST /v1/environments/{envId}/bridge/reconnect                 │
│    → reconnectSession(environmentId, sessionId)                 │
│                                                                 │
│  DELETE /v1/environments/bridge/{envId}                         │
│    → deregisterEnvironment(environmentId)                       │
│                                                                 │
│  POST /v1/sessions/{id}/archive                                 │
│    → archiveSession(sessionId)                                  │
│                                                                 │
│  POST /v1/sessions/{id}/events                                  │
│    → sendPermissionResponseEvent(sessionId, event, token)       │
│                                                                 │
│  Beta header: anthropic-beta: environments-2025-11-01           │
└─────────────────────────────────────────────────────────────────┘
```

### Bridge Lifecycle (T38)

```
1. REGISTER
   POST /v1/environments/bridge
   Body: { machine_name, directory, branch, git_repo_url,
           max_sessions, metadata: { worker_type } }
   ← environment_id

2. POLL LOOP (infinite)
   GET /v1/environments/{envId}/work/poll?ack=true
   ← null → sleep(poll_interval), retry
   ← { data.type: "healthcheck" } → log, continue
   ← { data.type: "session", data.id: sessionId, secret: ... } → SPAWN

3. SPAWN SESSION
   a. Decode work secret: Em$(secret) → { session_ingress_token, api_base_url, ... }
   b. Build ingress URL: Wm$(api_base_url, sessionId)
      → wss://{host}/v1/session_ingress/ws/{sessionId}
   c. (Optional CCR v2) Register worker:
      POST {api}/v1/code/sessions/{id}/worker/register
   d. Spawn child:
      claude --print --sdk-url <ws_url> --session-id <id>
            --input-format stream-json --output-format stream-json
            --replay-user-messages [--verbose] [--debug-file <path>]
            [--permission-mode <mode>]
      Env: CLAUDE_CODE_SESSION_ACCESS_TOKEN=<ingress_token>
           CLAUDE_CODE_ENVIRONMENT_KIND=bridge
           CLAUDE_CODE_WORKER_EPOCH=<N>
           [CLAUDE_CODE_USE_CCR_V2=1]

4. SESSION MONITORING
   - Track active sessions in Map<sessionId, childProcess>
   - Heartbeat: POST /v1/environments/{envId}/work/{workId}/heartbeat
   - Timeout: configurable per session (sessionTimeoutMs)
   - Token rotation: update child tokens when new work arrives for same session

5. SESSION COMPLETE
   - Archive: POST /v1/sessions/{id}/archive
   - Worktree cleanup (if spawn mode = worktree)
   - Acknowledge work completion
   - Return to poll loop

6. DEREGISTER (on shutdown)
   DELETE /v1/environments/bridge/{envId}
```

### Spawn Modes

| Mode | Mechanism |
|------|-----------|
| `same-dir` | Child process in same directory |
| `worktree` | git worktree created per session |
| `session` | Isolated session directory |
| `single-session` | One session at a time, exit after completion |

### Capacity Management

- `maxSessions` configurable (passed during registration)
- At capacity: enters heartbeat mode (heartbeat_interval_ms)
- Multisession polling: `multisession_poll_interval_ms_at_capacity`
- Session count tracked and reported via status display

### Error Handling

`YE` (BridgeFatalError) class with status codes:
- 401: Authentication failed
- 403: Access denied / session expired
- 404: Not found (Remote Control may not be available)
- 410: Session expired
- 429: Rate limited (polling too frequently)

---

## Remaining Unknowns

The 5 original gaps are now resolved. Remaining minor unknowns:

1. **Exact event schemas for all stream_event subtypes** — the content_block_delta
   structure follows the Anthropic Messages API spec, but edge cases may exist.

2. **session_context full taxonomy** — `sources[]` and `outcomes[]` types beyond
   `git_repository` and `directory` are not fully enumerated.

3. **CCR v2 worker event stream format** — the SSE transport (`mqH`) uses a different
   wire format than the WebSocket path. Not fully traced.

4. **Bridge poll interval config** — `o$H()` returns configurable intervals
   (`poll_interval_ms_not_at_capacity`, `heartbeat_interval_ms`,
   `multisession_poll_interval_ms_at_capacity`, `session_keepalive_interval_ms`)
   but the defaults and server-side config source are unknown.

5. **Token rotation scheduling** — `Y38()` schedules periodic token refresh for
   bridge sessions but the exact interval logic is not fully traced.

These are implementation details, not blocking for a Linux CoWork client.

---

## Building a Linux CoWork Client

### Architecture Decision

Two viable approaches based on findings:

**Approach A: Local Pipe (Simplest)**
- Spawn CLI with piped stdin/stdout, no `--sdk-url`
- Dual-write events via `POST /v1/sessions/{id}/events`
- Subscribe via WebSocket for remote sync

**Approach B: Full Bridge (Production)**
- Register environment via bridge API
- Poll for work, get session_ingress_token
- Spawn CLI with `--sdk-url` pointing to session ingress WebSocket
- Full lifecycle management like claude.ai

### Implementation (Approach A)

```python
import subprocess, json, uuid, threading, time, webbrowser
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlencode, parse_qs, urlparse
import hashlib, base64, secrets, requests

# ── 1. OAuth PKCE Login ──
CLIENT_ID = "9d1c250a-e61b-44d9-88ed-5944d1962f5e"
TOKEN_URL = "https://platform.claude.com/v1/oauth/token"
AUTHORIZE_URL = "https://claude.ai/oauth/authorize"
SCOPES = "user:profile user:inference user:sessions:claude_code user:mcp_servers"
BASE_API = "https://api.anthropic.com"
BETA_HEADER = "ccr-byoc-2025-07-29"

def pkce_pair():
    verifier = secrets.token_urlsafe(64)
    digest = hashlib.sha256(verifier.encode()).digest()
    challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode()
    return verifier, challenge

def oauth_login():
    verifier, challenge = pkce_pair()
    state = secrets.token_urlsafe(32)
    port = 9876
    auth_code = [None]

    class Handler(BaseHTTPRequestHandler):
        def do_GET(self):
            qs = parse_qs(urlparse(self.path).query)
            if "code" in qs:
                auth_code[0] = qs["code"][0]
                self.send_response(200)
                self.end_headers()
                self.wfile.write(b"Login successful. Return to terminal.")
            self.server.shutdown_request(self.request)
        def log_message(self, *a): pass

    server = HTTPServer(("127.0.0.1", port), Handler)
    redirect_uri = f"http://localhost:{port}/callback"
    url = f"{AUTHORIZE_URL}?" + urlencode({
        "response_type": "code",
        "client_id": CLIENT_ID,
        "redirect_uri": redirect_uri,
        "scope": SCOPES,
        "state": state,
        "code_challenge": challenge,
        "code_challenge_method": "S256",
    })
    webbrowser.open(url)
    server.handle_request()

    resp = requests.post(TOKEN_URL, json={
        "grant_type": "authorization_code",
        "client_id": CLIENT_ID,
        "redirect_uri": redirect_uri,
        "code_verifier": verifier,
        "code": auth_code[0],
    })
    tokens = resp.json()
    return tokens["access_token"], tokens.get("refresh_token")

# ── 2. Session Management ──
def api_headers(token, org_uuid):
    return {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json",
        "anthropic-version": "2023-06-01",
        "anthropic-beta": BETA_HEADER,
        "x-organization-uuid": org_uuid,
    }

def create_session(token, org_uuid, title, initial_prompt=None, env_id=None):
    events = []
    if initial_prompt:
        events.append({
            "type": "event",
            "data": {
                "uuid": str(uuid.uuid4()),
                "session_id": "",
                "type": "user",
                "parent_tool_use_id": None,
                "message": {"role": "user", "content": initial_prompt}
            }
        })
    body = {
        "title": title,
        "events": events,
        "session_context": {"sources": [], "outcomes": [], "model": "claude-sonnet-4-6"},
    }
    if env_id:
        body["environment_id"] = env_id
    resp = requests.post(f"{BASE_API}/v1/sessions",
                         json=body, headers=api_headers(token, org_uuid))
    resp.raise_for_status()
    return resp.json()["id"]

def send_event(token, org_uuid, session_id, content, msg_uuid=None):
    body = {"events": [{
        "uuid": msg_uuid or str(uuid.uuid4()),
        "session_id": session_id,
        "type": "user",
        "parent_tool_use_id": None,
        "message": {"role": "user", "content": content}
    }]}
    resp = requests.post(f"{BASE_API}/v1/sessions/{session_id}/events",
                         json=body, headers=api_headers(token, org_uuid))
    return resp.status_code in (200, 201)

# ── 3. Spawn CLI ──
def spawn_cli(session_id, access_token):
    import os
    env = {
        **os.environ,
        "CLAUDE_CODE_SESSION_ACCESS_TOKEN": access_token,
        "CLAUDE_CODE_POST_FOR_SESSION_INGRESS_V2": "1",
        "CLAUDE_CODE_IS_COWORK": "1",
        "CLAUDE_CODE_USE_COWORK_PLUGINS": "1",
        "CLAUDE_CODE_ENVIRONMENT_KIND": "bridge",
        "CLAUDE_CODE_ENTRYPOINT": "claude-desktop",
    }
    return subprocess.Popen(
        ["claude", "--print",
         "--session-id", session_id,
         "--input-format", "stream-json",
         "--output-format", "stream-json",
         "--replay-user-messages"],
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        env=env,
    )

# ── 4. Stream Protocol ──
def send_message(proc, content):
    msg = json.dumps({
        "type": "user",
        "message": {"content": content},
        "parent_tool_use_id": None,
    }) + "\n"
    proc.stdin.write(msg.encode())
    proc.stdin.flush()

def send_control_response(proc, request_id, behavior="allow", updated_input=None):
    resp = {
        "type": "control_response",
        "response": {
            "request_id": request_id,
            "subtype": "success",
            "response": {"behavior": behavior}
        }
    }
    if behavior == "allow" and updated_input:
        resp["response"]["response"]["updatedInput"] = updated_input
    proc.stdin.write((json.dumps(resp) + "\n").encode())
    proc.stdin.flush()

def refresh_token(proc, new_token):
    msg = json.dumps({
        "type": "update_environment_variables",
        "variables": {"CLAUDE_CODE_SESSION_ACCESS_TOKEN": new_token}
    }) + "\n"
    proc.stdin.write(msg.encode())
    proc.stdin.flush()

def read_events(proc, on_assistant, on_permission, on_result):
    for line in proc.stdout:
        try:
            event = json.loads(line)
        except json.JSONDecodeError:
            continue
        t = event.get("type")
        if t == "assistant":
            on_assistant(event)
        elif t == "control_request":
            on_permission(event)
        elif t == "result":
            on_result(event)
            if event.get("subtype") == "success":
                break
        elif t == "system" and event.get("subtype") == "init":
            pass  # Session initialized
        elif t == "keep_alive":
            pass  # Ignore heartbeats

# ── 5. Resume Session ──
# Option A: Local resume
#   claude --resume <session-uuid>
#
# Option B: Remote teleport
#   GET /v1/code/sessions/<id>/teleport-events?limit=1000&cursor=<cursor>
#
# Option C: WebSocket subscription for live sync
#   wss://api.anthropic.com/v1/sessions/ws/<id>/subscribe
#     ?organization_uuid=<orgUuid>
#   Headers: Authorization: Bearer <accessToken>
#            anthropic-version: 2023-06-01
```


---
## creating-custom-skills.md

# How to create custom Skills


Skills are available for users on free, Pro, Max, Team, and Enterprise plans. This feature requires **[code execution to be enabled](https://support.claude.com/en/articles/12111783-create-and-edit-files-with-claude#h_1c99382190)**. Skills are also available in beta for Claude Code users and for all API users using the code execution tool.

Custom Skills let you enhance Claude with specialized knowledge and workflows specific to your organization or personal work style. This article explains how to create, structure, and test your own Skills.

Skills can be as simple as a few lines of instructions or as complex as multi-file packages with executable code. The best Skills:

- Solve a specific, repeatable task

- Have clear instructions that Claude can follow

- Include examples when helpful

- Define when they should be used

- Are focused on one workflow rather than trying to do everything

------------------------------------------------------------------------

## Create a Skill.md file

Every Skill consists of a directory containing at minimum a Skill.md file, which is the core of the Skill. This file must start with a YAML frontmatter to hold name and description fields, which are required metadata. It can also contain additional metadata, instructions for Claude or reference files, executable scripts, or tools.

### Required metadata fields

**name:** A human-friendly name for your Skill (64 characters maximum)

- **Example:** Brand Guidelines

**description:** A clear description of what the Skill does and when to use it.

- This is critical—Claude uses this to determine when to invoke your Skill (200 characters maximum).

- **Example:** Apply Acme Corp brand guidelines to presentations and documents, including official colors, fonts, and logo usage.

### Optional metadata fields

**dependencies:** Software packages required by your Skill.

- **Example:** python\>=3.8, pandas\>=1.5.0

The metadata in the Skill.md file serves as the first level of a progressive disclosure system, providing just enough information for Claude to know when the Skill should be used without having to load all of the content.

### Markdown body

The Markdown body is the second level of detail after the metadata, so Claude will access this if needed after reading the metadata. Depending on your task, Claude can access the Skill.md file and use the Skill.

### Example Skill.md

**Brand guidelines skill**

    ## Metadata
    name: Brand Guidelines
    description: Apply Acme Corp brand guidelines to all presentations and documents

    ## Overview
    This Skill provides Acme Corp's official brand guidelines for creating consistent, professional materials. When creating presentations, documents, or marketing materials, apply these standards to ensure all outputs match Acme's visual identity. Claude should reference these guidelines whenever creating external-facing materials or documents that represent Acme Corp.

    ## Brand Colors

    Our official brand colors are:
    - Primary: #FF6B35 (Coral)
    - Secondary: #004E89 (Navy Blue)
    - Accent: #F7B801 (Gold)
    - Neutral: #2E2E2E (Charcoal)

    ## Typography

    Headers: Montserrat Bold
    Body text: Open Sans Regular
    Size guidelines:
    - H1: 32pt
    - H2: 24pt
    - Body: 11pt

    ## Logo Usage

    Always use the full-color logo on light backgrounds. Use the white logo on dark backgrounds. Maintain minimum spacing of 0.5 inches around the logo.

    ## When to Apply

    Apply these guidelines whenever creating:
    - PowerPoint presentations
    - Word documents for external sharing
    - Marketing materials
    - Reports for clients

    ## Resources

    See the resources folder for logo files and font downloads.

## Add resources

If you have too much information to add to a single Skill.md file (e.g., sections that only apply to specific scenarios), you can add more content by adding files within your Skill directory. For example, add a REFERENCE.md file containing supplemental and reference information to your Skill directory. Referencing it in Skill.md will help Claude decide if it needs to access that resource when executing the Skill.

## Add scripts

For more advanced Skills, attach executable code files to Skill.md, allowing Claude to run code. For example, our document skills use the following programming languages and packages:

- Python (pandas, numpy, matplotlib)

- JavaScript/Node.js

- Packages to help with file editing

- visualization tools

**Note:** Claude and Claude Code can install packages from standard repositories (Python PyPI, JavaScript npm) when loading Skills. It’s not possible to install additional packages at runtime with API Skills—all dependencies must be pre-installed in the container.

------------------------------------------------------------------------

## Package your skill

Once your Skill folder is complete:

1.  Ensure the folder name matches your Skill's name.

2.  Create a ZIP file of the folder.

3.  The ZIP should contain the Skill folder as its root (not a subfolder).

**Correct structure:**

my-Skill.zip

└── my-Skill/

├── Skill.md

└── resources/

**Incorrect structure:**

my-Skill.zip

└── (files directly in ZIP root)

------------------------------------------------------------------------

## Test your skill

### Before uploading

1\. Review your Skill.md for clarity

2\. Check that the description accurately reflects when Claude should use the Skill

3\. Verify all referenced files exist in the correct locations

4\. Test with example prompts to ensure Claude invokes it appropriately

### After uploading to Claude

1\. Enable the Skill in **[Customize \> Skills](https://claude.ai/customize/skills)**.

2\. Try several different prompts that should trigger it

3\. Review Claude's thinking to confirm it's loading the Skill

4\. Iterate on the description if Claude isn't using it when expected

**Note for Team and Enterprise plans:** To make a skill available to all users in your organization, see **[Provision and manage Skills for your organization](https://support.claude.com/en/articles/13119606-provisioning-and-managing-skills-for-your-organization)**.

------------------------------------------------------------------------

## Best practices

**Keep it focused:** Create separate Skills for different workflows. Multiple focused Skills compose better than one large Skill.

**Write clear descriptions:** Claude uses descriptions to decide when to invoke your Skill. Be specific about when it applies.

**Start simple:** Begin with basic instructions in Markdown before adding complex scripts. You can always expand on the Skill later.

**Use examples:** Include example inputs and outputs in your Skill.md file to help Claude understand what success looks like.

**Test incrementally:** Test after each significant change rather than building a complex Skill all at once.

**Skills can build on each other:** While Skills can't explicitly reference other Skills, Claude can use multiple Skills together automatically. This composability is one of the most powerful parts of the Skills feature.

**Review the open Agent Skills specification:** Follow the guidelines at **[agentskills.io](http://agentskills.io)**, so skills you create can work across platforms that adopt the standard.

For a more in-depth guide to skill creation, refer to **[Skill authoring best practices](../04-API-Reference/Agents-Tools/agents-and-tools-agent-skills-best-practices-d1da876439.md)** in our Claude Docs.

------------------------------------------------------------------------

## Security considerations

- Exercise caution when adding scripts to your Skill.md file.

- Don't hardcode sensitive information (API keys, passwords).

- Review any Skills you download before enabling them.

- Use appropriate MCP connections for external service access.

------------------------------------------------------------------------

## Example skills to reference

Visit our repository on GitHub for example Skills you can use as templates: **[https://github.com/anthropics/skills/tree/main/skills](https://github.com/anthropics/skills/tree/main/skills)**.


---
## customize-keyboard-shortcuts-claude-code-docs-f23eb8cfd3.md

# Customize keyboard shortcuts


Customize keyboard shortcuts in Claude Code with a keybindings configuration file.


> ## Documentation Index
>
> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt>
>
> Use this file to discover all available pages before exploring further.

Customizable keyboard shortcuts require Claude Code v2.1.18 or later. Check your version with `claude --version`.

Claude Code supports customizable keyboard shortcuts. Run `/keybindings` to create or open your configuration file at `~/.claude/keybindings.json`.


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.

Changes to the keybindings file are automatically detected and applied without restarting Claude Code.

| Field      | Description                                        |
|:-----------|:---------------------------------------------------|
| `$schema`  | Optional JSON Schema URL for editor autocompletion |
| `$docs`    | Optional documentation URL                         |
| `bindings` | Array of binding blocks by context                 |

This example binds `Ctrl+E` to open an external editor in the chat context, and unbinds `Ctrl+U`:

```python
{
  "$schema": "https://www.schemastore.org/claude-code-keybindings.json",
  "$docs": "https://code.claude.com/docs/en/keybindings",
  "bindings": [
    {
      "context": "Chat",
      "bindings": {
        "ctrl+e": "chat:externalEditor",
        "ctrl+u": null
      }
    }
  ]
}
```


Contexts

Each binding block specifies a **context** where the bindings apply:

| Context           | Description                                                  |
|:------------------|:-------------------------------------------------------------|
| `Global`          | Applies everywhere in the app                                |
| `Chat`            | Main chat input area                                         |
| `Autocomplete`    | Autocomplete menu is open                                    |
| `Settings`        | Settings menu                                                |
| `Confirmation`    | Permission and confirmation dialogs                          |
| `Tabs`            | Tab navigation components                                    |
| `Help`            | Help menu is visible                                         |
| `Transcript`      | Transcript viewer                                            |
| `HistorySearch`   | History search mode (Ctrl+R)                                 |
| `Task`            | Background task is running                                   |
| `ThemePicker`     | Theme picker dialog                                          |
| `Attachments`     | Image attachment navigation in select dialogs                |
| `Footer`          | Footer indicator navigation (tasks, teams, diff)             |
| `MessageSelector` | Rewind and summarize dialog message selection                |
| `DiffDialog`      | Diff viewer navigation                                       |
| `ModelPicker`     | Model picker effort level                                    |
| `Select`          | Generic select/list components                               |
| `Plugin`          | Plugin dialog (browse, discover, manage)                     |
| `Scroll`          | Conversation scrolling and text selection in fullscreen mode |
| `Doctor`          | `/doctor` diagnostics screen                                 |


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

Actions available in the `Global` context:

| Action                 | Default   | Description                 |
|:-----------------------|:----------|:----------------------------|
| `app:interrupt`        | Ctrl+C    | Cancel current operation    |
| `app:exit`             | Ctrl+D    | Exit Claude Code            |
| `app:redraw`           | (unbound) | Force terminal redraw       |
| `app:toggleTodos`      | Ctrl+T    | Toggle task list visibility |
| `app:toggleTranscript` | Ctrl+O    | Toggle verbose transcript   |


History actions

Actions for navigating command history:

| Action             | Default | Description           |
|:-------------------|:--------|:----------------------|
| `history:search`   | Ctrl+R  | Open history search   |
| `history:previous` | Up      | Previous history item |
| `history:next`     | Down    | Next history item     |


Chat actions

Actions available in the `Chat` context:

| Action                | Default                   | Description                                                                                                                                                         |
|:----------------------|:--------------------------|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `chat:cancel`         | Escape                    | Cancel current input                                                                                                                                                |
| `chat:clearInput`     | Ctrl+L                    | Force a full screen redraw, preserving input. In [fullscreen rendering](/docs/en/fullscreen#clear-the-conversation), press twice within two seconds to run `/clear` |
| `chat:clearScreen`    | Cmd+K                     | In [fullscreen rendering](/docs/en/fullscreen#clear-the-conversation), press twice within two seconds to run `/clear`                                               |
| `chat:killAgents`     | Ctrl+X Ctrl+K             | Kill all running [background subagents](/docs/en/sub-agents#run-subagents-in-foreground-or-background) in this session                                              |
| `chat:cycleMode`      | Shift+Tab\*               | Cycle permission modes                                                                                                                                              |
| `chat:modelPicker`    | Meta+P                    | Open model picker                                                                                                                                                   |
| `chat:fastMode`       | Meta+O                    | Toggle fast mode                                                                                                                                                    |
| `chat:thinkingToggle` | Meta+T                    | Toggle extended thinking                                                                                                                                            |
| `chat:submit`         | Enter                     | Submit message                                                                                                                                                      |
| `chat:newline`        | Ctrl+J                    | Insert a newline without submitting                                                                                                                                 |
| `chat:undo`           | Ctrl+\_, Ctrl+Shift+-     | Undo last action                                                                                                                                                    |
| `chat:externalEditor` | Ctrl+G, Ctrl+X Ctrl+E     | Open in external editor                                                                                                                                             |
| `chat:stash`          | Ctrl+S                    | Stash current prompt                                                                                                                                                |
| `chat:imagePaste`     | Ctrl+V (Alt+V on Windows) | Paste image                                                                                                                                                         |

\*On Windows without VT mode (Node \<24.2.0/\<22.17.0, Bun \<1.2.23), defaults to Meta+M.


Autocomplete actions

Actions available in the `Autocomplete` context:

| Action                  | Default | Description         |
|:------------------------|:--------|:--------------------|
| `autocomplete:accept`   | Tab     | Accept suggestion   |
| `autocomplete:dismiss`  | Escape  | Dismiss menu        |
| `autocomplete:previous` | Up      | Previous suggestion |
| `autocomplete:next`     | Down    | Next suggestion     |


Confirmation actions

Actions available in the `Confirmation` context:

| Action                      | Default   | Description                   |
|:----------------------------|:----------|:------------------------------|
| `confirm:yes`               | Y, Enter  | Confirm action                |
| `confirm:no`                | N, Escape | Decline action                |
| `confirm:previous`          | Up        | Previous option               |
| `confirm:next`              | Down      | Next option                   |
| `confirm:nextField`         | Tab       | Next field                    |
| `confirm:previousField`     | (unbound) | Previous field                |
| `confirm:toggle`            | Space     | Toggle selection              |
| `confirm:cycleMode`         | Shift+Tab | Cycle permission modes        |
| `confirm:toggleExplanation` | Ctrl+E    | Toggle permission explanation |


Permission actions

Actions available in the `Confirmation` context for permission dialogs:

| Action                   | Default | Description                  |
|:-------------------------|:--------|:-----------------------------|
| `permission:toggleDebug` | Ctrl+D  | Toggle permission debug info |


Transcript actions

Actions available in the `Transcript` context:

| Action                     | Default           | Description             |
|:---------------------------|:------------------|:------------------------|
| `transcript:toggleShowAll` | Ctrl+E            | Toggle show all content |
| `transcript:exit`          | q, Ctrl+C, Escape | Exit transcript view    |


History search actions

Actions available in the `HistorySearch` context:

| Action                     | Default     | Description                               |
|:---------------------------|:------------|:------------------------------------------|
| `historySearch:next`       | Ctrl+R      | Next match                                |
| `historySearch:accept`     | Escape, Tab | Accept selection                          |
| `historySearch:cancel`     | Ctrl+C      | Cancel search                             |
| `historySearch:execute`    | Enter       | Execute selected command                  |
| `historySearch:cycleScope` | Ctrl+S      | Cycle scope: session, project, everywhere |


Task actions

Actions available in the `Task` context:

| Action            | Default | Description             |
|:------------------|:--------|:------------------------|
| `task:background` | Ctrl+B  | Background current task |


Theme actions

Actions available in the `ThemePicker` context:

| Action                           | Default | Description                |
|:---------------------------------|:--------|:---------------------------|
| `theme:toggleSyntaxHighlighting` | Ctrl+T  | Toggle syntax highlighting |


Help actions

Actions available in the `Help` context:

| Action         | Default | Description     |
|:---------------|:--------|:----------------|
| `help:dismiss` | Escape  | Close help menu |


Tabs actions

Actions available in the `Tabs` context:

| Action          | Default         | Description  |
|:----------------|:----------------|:-------------|
| `tabs:next`     | Tab, Right      | Next tab     |
| `tabs:previous` | Shift+Tab, Left | Previous tab |


Attachments actions

Actions available in the `Attachments` context:

| Action                 | Default           | Description                |
|:-----------------------|:------------------|:---------------------------|
| `attachments:next`     | Right             | Next attachment            |
| `attachments:previous` | Left              | Previous attachment        |
| `attachments:remove`   | Backspace, Delete | Remove selected attachment |
| `attachments:exit`     | Down, Escape      | Exit attachment navigation |


Footer actions

Actions available in the `Footer` context:

| Action                  | Default | Description                              |
|:------------------------|:--------|:-----------------------------------------|
| `footer:next`           | Right   | Next footer item                         |
| `footer:previous`       | Left    | Previous footer item                     |
| `footer:up`             | Up      | Navigate up in footer (deselects at top) |
| `footer:down`           | Down    | Navigate down in footer                  |
| `footer:openSelected`   | Enter   | Open selected footer item                |
| `footer:clearSelection` | Escape  | Clear footer selection                   |


Message selector actions

Actions available in the `MessageSelector` context:

| Action                   | Default                                   | Description       |
|:-------------------------|:------------------------------------------|:------------------|
| `messageSelector:up`     | Up, K, Ctrl+P                             | Move up in list   |
| `messageSelector:down`   | Down, J, Ctrl+N                           | Move down in list |
| `messageSelector:top`    | Ctrl+Up, Shift+Up, Meta+Up, Shift+K       | Jump to top       |
| `messageSelector:bottom` | Ctrl+Down, Shift+Down, Meta+Down, Shift+J | Jump to bottom    |
| `messageSelector:select` | Enter                                     | Select message    |


Diff actions

Actions available in the `DiffDialog` context:

| Action                | Default            | Description            |
|:----------------------|:-------------------|:-----------------------|
| `diff:dismiss`        | Escape             | Close diff viewer      |
| `diff:previousSource` | Left               | Previous diff source   |
| `diff:nextSource`     | Right              | Next diff source       |
| `diff:previousFile`   | Up                 | Previous file in diff  |
| `diff:nextFile`       | Down               | Next file in diff      |
| `diff:viewDetails`    | Enter              | View diff details      |
| `diff:back`           | (context-specific) | Go back in diff viewer |


Model picker actions

Actions available in the `ModelPicker` context:

| Action                       | Default | Description                                       |
|:-----------------------------|:--------|:--------------------------------------------------|
| `modelPicker:decreaseEffort` | Left    | Decrease effort level                             |
| `modelPicker:increaseEffort` | Right   | Increase effort level                             |
| `modelPicker:setAsDefault`   | d       | Set highlighted model as default for new sessions |


Select actions

Actions available in the `Select` context:

| Action            | Default         | Description      |
|:------------------|:----------------|:-----------------|
| `select:next`     | Down, J, Ctrl+N | Next option      |
| `select:previous` | Up, K, Ctrl+P   | Previous option  |
| `select:accept`   | Enter           | Accept selection |
| `select:cancel`   | Escape          | Cancel selection |


Plugin actions

Actions available in the `Plugin` context:

| Action            | Default | Description                                                                |
|:------------------|:--------|:---------------------------------------------------------------------------|
| `plugin:toggle`   | Space   | Toggle plugin selection                                                    |
| `plugin:install`  | I       | Install selected plugins                                                   |
| `plugin:favorite` | F       | Favorite the selected plugin so it sorts near the top of the Installed tab |


Settings actions

Actions available in the `Settings` context:

| Action            | Default | Description                                                                 |
|:------------------|:--------|:----------------------------------------------------------------------------|
| `settings:search` | /       | Enter search mode                                                           |
| `settings:retry`  | R       | Retry loading usage data (on error)                                         |
| `settings:close`  | Enter   | Save changes and close the config panel. Escape discards changes and closes |


Doctor actions

Actions available in the `Doctor` context:

| Action       | Default | Description                                                                                         |
|:-------------|:--------|:----------------------------------------------------------------------------------------------------|
| `doctor:fix` | F       | Send the diagnostics report to Claude to fix the reported issues. Only active when issues are found |


Voice actions

Actions available in the `Chat` context when [voice dictation](/docs/en/voice-dictation) is enabled:

| Action             | Default | Description                                              |
|:-------------------|:--------|:---------------------------------------------------------|
| `voice:pushToTalk` | Space   | Dictate a prompt. Hold or tap depending on `/voice` mode |


Scroll actions

Actions available in the `Scroll` context when [fullscreen rendering](/docs/en/fullscreen) is enabled:

| Action                      | Default              | Description                                                                                               |
|:----------------------------|:---------------------|:----------------------------------------------------------------------------------------------------------|
| `scroll:lineUp`             | (unbound)            | Scroll up one line. Mouse wheel scrolling triggers this action                                            |
| `scroll:lineDown`           | (unbound)            | Scroll down one line. Mouse wheel scrolling triggers this action                                          |
| `scroll:pageUp`             | PageUp               | Scroll up half the viewport height                                                                        |
| `scroll:pageDown`           | PageDown             | Scroll down half the viewport height                                                                      |
| `scroll:top`                | Ctrl+Home            | Jump to the start of the conversation                                                                     |
| `scroll:bottom`             | Ctrl+End             | Jump to the latest message and re-enable auto-follow                                                      |
| `scroll:halfPageUp`         | (unbound)            | Scroll up half the viewport height. Same behavior as `scroll:pageUp`, provided for vi-style rebinds       |
| `scroll:halfPageDown`       | (unbound)            | Scroll down half the viewport height. Same behavior as `scroll:pageDown`, provided for vi-style rebinds   |
| `scroll:fullPageUp`         | (unbound)            | Scroll up the full viewport height                                                                        |
| `scroll:fullPageDown`       | (unbound)            | Scroll down the full viewport height                                                                      |
| `selection:copy`            | Ctrl+Shift+C / Cmd+C | Copy the selected text to the clipboard                                                                   |
| `selection:clear`           | (unbound)            | Clear the active text selection                                                                           |
| `selection:extendLeft`      | Shift+Left           | Extend the active selection one column left                                                               |
| `selection:extendRight`     | Shift+Right          | Extend the active selection one column right                                                              |
| `selection:extendUp`        | Shift+Up             | Extend the active selection one row up. Scrolls the viewport when the selection reaches the top edge      |
| `selection:extendDown`      | Shift+Down           | Extend the active selection one row down. Scrolls the viewport when the selection reaches the bottom edge |
| `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

Use modifier keys with the `+` separator:

- `ctrl` or `control` - Control key
- `shift` - Shift key
- `alt`, `opt`, `option`, or `meta` - Alt key on Windows and Linux, Option key on macOS
- `cmd`, `command`, `super`, or `win` - Command key on macOS, Windows key on Windows, Super key on Linux

The `cmd` group is only detected in terminals that report the Super modifier, such as those supporting the Kitty keyboard protocol or xterm’s `modifyOtherKeys` mode. Most terminals do not send it, so use `ctrl` or `meta` for bindings you want to work everywhere. For example:

```python
ctrl+k          Ctrl + K
shift+tab       Shift + Tab
meta+p          Option + P on macOS, Alt + P elsewhere
ctrl+shift+c    Multiple modifiers
```


Uppercase letters

A standalone uppercase letter implies Shift. For example, `K` is equivalent to `shift+k`. This is useful for vim-style bindings where uppercase and lowercase keys have different meanings. Uppercase letters with modifiers (e.g., `ctrl+K`) are treated as stylistic and do **not** imply Shift: `ctrl+K` is the same as `ctrl+k`.


Chords

Chords are sequences of keystrokes separated by spaces:

```python
ctrl+k ctrl+s   Press Ctrl+K, release, then Ctrl+S
```


Special keys

- `escape` or `esc` - Escape key
- `enter` or `return` - Enter key
- `tab` - Tab key
- `space` - Space bar
- `up`, `down`, `left`, `right` - Arrow keys
- `backspace`, `delete` - Delete keys


Unbind default shortcuts

Set an action to `null` to unbind a default shortcut:

```python
{
  "bindings": [
    {
      "context": "Chat",
      "bindings": {
        "ctrl+s": null
      }
    }
  ]
}
```

This also works for chord bindings. Unbinding every chord that shares a prefix frees that prefix for use as a single-key binding:

```python
{
  "bindings": [
    {
      "context": "Chat",
      "bindings": {
        "ctrl+x ctrl+k": null,
        "ctrl+x ctrl+e": null,
        "ctrl+x": "chat:newline"
      }
    }
  ]
}
```

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

These shortcuts cannot be rebound:

| Shortcut  | Reason                                         |
|:----------|:-----------------------------------------------|
| Ctrl+C    | Hardcoded interrupt/cancel                     |
| Ctrl+D    | Hardcoded exit                                 |
| Ctrl+M    | Identical to Enter in terminals (both send CR) |
| Caps Lock | Not delivered to terminal applications         |


Terminal conflicts

Some shortcuts may conflict with terminal multiplexers:

| Shortcut | Conflict                          |
|:---------|:----------------------------------|
| Ctrl+B   | tmux prefix (press twice to send) |
| Ctrl+A   | GNU screen prefix                 |
| Ctrl+Z   | Unix process suspend (SIGTSTP)    |


Vim mode interaction

When vim mode is enabled via `/config` → Editor mode, keybindings and vim mode operate independently:

- **Vim mode** handles input at the text input level (cursor movement, modes, motions)
- **Keybindings** handle actions at the component level (toggle todos, submit, etc.)
- The Escape key in vim mode switches INSERT to NORMAL mode; it does not trigger `chat:cancel`
- Most Ctrl+key shortcuts pass through vim mode to the keybinding system
- In vim NORMAL mode, `?` shows the help menu (vim behavior)


Validation

Claude Code validates your keybindings and shows warnings for:

- Parse errors (invalid JSON or structure)
- Invalid context names
- Reserved shortcut conflicts
- Terminal multiplexer conflicts
- Duplicate bindings in the same context

Run `/doctor` to see any keybinding warnings.


---
## customize-your-status-line-claude-code-docs-8a9fc80be1.md

# Customize your status line


Configure a custom status bar to monitor context window usage, costs, and git status in Claude Code


> ## Documentation Index
>
> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt>
>
> Use this file to discover all available pages before exploring further.

The status line is a customizable bar at the bottom of Claude Code that runs any shell script you configure. It receives JSON session data on stdin and displays whatever your script prints, giving you a persistent, at-a-glance view of context usage, costs, git status, or anything else you want to track. Status lines are useful when you:

- Want to monitor context window usage as you work
- Need to track session costs
- Work across multiple sessions and need to distinguish them
- Want git branch and status always visible

Here’s an example of a [multi-line status line](#display-multiple-lines) that displays git info on the first line and a color-coded context bar on the second.

This page walks through [setting up a basic status line](#set-up-a-status-line), explains [how the data flows](#how-status-lines-work) from Claude Code to your script, lists [all the fields you can display](#available-data), and provides [ready-to-use examples](#examples) for common patterns like git status, cost tracking, and progress bars.


Set up a status line

Use the [`/statusline` command](#use-the-%2Fstatusline-command) to have Claude Code generate a script for you, or [manually create a script](#manually-configure-a-status-line) and add it to your settings.


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:

```python
/statusline show model name and context percentage with a progress bar
```


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#settings-files). 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](#build-a-status-line-step-by-step).

```python
{
  "statusLine": {
    "type": "command",
    "command": "~/.claude/statusline.sh",
    "padding": 2
  }
}
```

The `command` field runs in a shell, so you can also use inline commands instead of a script file. This example uses `jq` to parse the JSON input and display the model name and context percentage:

```python
{
  "statusLine": {
    "type": "command",
    "command": "jq -r '\"[\\(.model.display_name)] \\(.context_window.used_percentage // 0)% context\"'"
  }
}
```

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](#how-status-lines-work). 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`](#available-data) itself, so the mode is not shown twice.


Disable the status line

Run `/statusline` and ask it to remove or clear your status line (e.g., `/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

This walkthrough shows what’s happening under the hood by manually creating a status line that displays the current model, working directory, and context window usage percentage.

Running [`/statusline`](#use-the-%2Fstatusline-command) with a description of what you want configures all of this for you automatically.

These examples use Bash scripts, which work on macOS and Linux. On Windows, see [Windows configuration](#windows-configuration) for PowerShell and Git Bash examples.

1


Create a script that reads JSON and prints output

Claude Code sends JSON data to your script via stdin. This script uses [`jq`](https://jqlang.github.io/jq/), a command-line JSON parser you may need to install, to extract the model name, directory, and context percentage, then prints a formatted line.Save this to `~/.claude/statusline.sh` (where `~` is your home directory, such as `/Users/username` on macOS or `/home/username` on Linux):

```python
#!/bin/bash
# Read JSON data that Claude Code sends to stdin
input=$(cat)

# Extract fields using jq
MODEL=$(echo "$input" | jq -r '.model.display_name')
DIR=$(echo "$input" | jq -r '.workspace.current_dir')
# The "// 0" provides a fallback if the field is null
PCT=$(echo "$input" | jq -r '.context_window.used_percentage // 0' | cut -d. -f1)

# Output the status line - ${DIR##*/} extracts just the folder name
echo "[$MODEL] 📁 ${DIR##*/} | ${PCT}% context"
```

2


Make it executable

Mark the script as executable so your shell can run it:

```python
chmod +x ~/.claude/statusline.sh
```

3


Add to settings

Tell Claude Code to run your script as the status line. Add this configuration to `~/.claude/settings.json`, which sets `type` to `"command"` (meaning “run this shell command”) and points `command` to your script:

```python
{
  "statusLine": {
    "type": "command",
    "command": "~/.claude/statusline.sh"
  }
}
```

Your status line appears at the bottom of the interface. Settings reload automatically, but changes won’t appear until your next interaction with Claude Code.


How status lines work

Claude Code runs your script and pipes [JSON session data](#available-data) to it via stdin. Your script reads the JSON, extracts what it needs, and prints text to stdout. Claude Code displays whatever your script prints. **When it updates** Your script runs after each new assistant message, after `/compact` finishes, when the permission mode changes, or when vim mode toggles. Updates are debounced at 300ms, meaning rapid changes batch together and your script runs once things settle. If a new update triggers while your script is still running, the in-flight execution is cancelled. If you edit your script, the changes won’t appear until your next interaction with Claude Code triggers an update. These 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`](#manually-configure-a-status-line) to also re-run the command on a fixed timer. **What your script can output**

- **Multiple lines**: each `echo` or `print` statement displays as a separate row. See the [multi-line example](#display-multiple-lines).
- **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](#git-status-with-colors).
- **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](#clickable-links).

The status line runs locally and does not consume API tokens. It temporarily hides during certain UI interactions, including autocomplete suggestions, the help menu, and permission prompts.


Available data

Claude Code sends the following JSON fields to your script via stdin:

| Field                                                                            | Description                                                                                                                                                                                                                                |
|----------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `model.id`, `model.display_name`                                                 | Current model identifier and display name                                                                                                                                                                                                  |
| `cwd`, `workspace.current_dir`                                                   | Current working directory. Both fields contain the same value; `workspace.current_dir` is preferred for consistency with `workspace.project_dir`.                                                                                          |
| `workspace.project_dir`                                                          | Directory where Claude Code was launched, which may differ from `cwd` if the working directory changes during a session                                                                                                                    |
| `workspace.added_dirs`                                                           | Additional directories added via `/add-dir` or `--add-dir`. Empty array if none have been added                                                                                                                                            |
| `workspace.git_worktree`                                                         | Git worktree name when the current directory is inside a linked worktree created with `git worktree add`. Absent in the main working tree. Populated for any git worktree, unlike `worktree.*` which applies only to `--worktree` sessions |
| `cost.total_cost_usd`                                                            | Estimated session cost in USD, computed client-side. May differ from your actual bill                                                                                                                                                      |
| `cost.total_duration_ms`                                                         | Total wall-clock time since the session started, in milliseconds                                                                                                                                                                           |
| `cost.total_api_duration_ms`                                                     | Total time spent waiting for API responses in milliseconds                                                                                                                                                                                 |
| `cost.total_lines_added`, `cost.total_lines_removed`                             | Lines of code changed                                                                                                                                                                                                                      |
| `context_window.total_input_tokens`, `context_window.total_output_tokens`        | Token counts currently in the context window, from the most recent API response. Input includes cache reads and writes. Before v2.1.132 these were cumulative session totals                                                               |
| `context_window.context_window_size`                                             | Maximum context window size in tokens. 200000 by default, or 1000000 for models with extended context.                                                                                                                                     |
| `context_window.used_percentage`                                                 | Pre-calculated percentage of context window used                                                                                                                                                                                           |
| `context_window.remaining_percentage`                                            | Pre-calculated percentage of context window remaining                                                                                                                                                                                      |
| `context_window.current_usage`                                                   | Token counts from the last API call, described in [context window fields](#context-window-fields)                                                                                                                                          |
| `exceeds_200k_tokens`                                                            | Whether the total token count (input, cache, and output tokens combined) from the most recent API response exceeds 200k. This is a fixed threshold regardless of actual context window size.                                               |
| `effort.level`                                                                   | Current reasoning effort (`low`, `medium`, `high`, `xhigh`, or `max`). Reflects the live session value, including mid-session `/effort` changes. Absent when the current model does not support the effort parameter                       |
| `thinking.enabled`                                                               | Whether extended thinking is enabled for the session                                                                                                                                                                                       |
| `rate_limits.five_hour.used_percentage`, `rate_limits.seven_day.used_percentage` | Percentage of the 5-hour or 7-day rate limit consumed, from 0 to 100                                                                                                                                                                       |
| `rate_limits.five_hour.resets_at`, `rate_limits.seven_day.resets_at`             | Unix epoch seconds when the 5-hour or 7-day rate limit window resets                                                                                                                                                                       |
| `session_id`                                                                     | Unique session identifier                                                                                                                                                                                                                  |
| `session_name`                                                                   | Custom session name set with the `--name` flag or `/rename`. Absent if no custom name has been set                                                                                                                                         |
| `transcript_path`                                                                | Path to conversation transcript file                                                                                                                                                                                                       |
| `version`                                                                        | Claude Code version                                                                                                                                                                                                                        |
| `output_style.name`                                                              | Name of the current output style                                                                                                                                                                                                           |
| `vim.mode`                                                                       | Current vim mode (`NORMAL`, `INSERT`, `VISUAL`, or `VISUAL LINE`) when [vim mode](/docs/en/interactive-mode#vim-editor-mode) is enabled                                                                                                    |
| `agent.name`                                                                     | Agent name when running with the `--agent` flag or agent settings configured                                                                                                                                                               |
| `worktree.name`                                                                  | Name of the active worktree. Present only during `--worktree` sessions                                                                                                                                                                     |
| `worktree.path`                                                                  | Absolute path to the worktree directory                                                                                                                                                                                                    |
| `worktree.branch`                                                                | Git branch name for the worktree (for example, `"worktree-my-feature"`). Absent for hook-based worktrees                                                                                                                                   |
| `worktree.original_cwd`                                                          | The directory Claude was in before entering the worktree                                                                                                                                                                                   |
| `worktree.original_branch`                                                       | Git branch checked out before entering the worktree. Absent for hook-based worktrees                                                                                                                                                       |

Full JSON schema

Your status line command receives this JSON structure via stdin:

```python
{
  "cwd": "/current/working/directory",
  "session_id": "abc123...",
  "session_name": "my-session",
  "transcript_path": "/path/to/transcript.jsonl",
  "model": {
    "id": "claude-opus-4-7",
    "display_name": "Opus"
  },
  "workspace": {
    "current_dir": "/current/working/directory",
    "project_dir": "/original/project/directory",
    "added_dirs": [],
    "git_worktree": "feature-xyz"
  },
  "version": "2.1.90",
  "output_style": {
    "name": "default"
  },
  "cost": {
    "total_cost_usd": 0.01234,
    "total_duration_ms": 45000,
    "total_api_duration_ms": 2300,
    "total_lines_added": 156,
    "total_lines_removed": 23
  },
  "context_window": {
    "total_input_tokens": 15500,
    "total_output_tokens": 1200,
    "context_window_size": 200000,
    "used_percentage": 8,
    "remaining_percentage": 92,
    "current_usage": {
      "input_tokens": 8500,
      "output_tokens": 1200,
      "cache_creation_input_tokens": 5000,
      "cache_read_input_tokens": 2000
    }
  },
  "exceeds_200k_tokens": false,
  "effort": {
    "level": "high"
  },
  "thinking": {
    "enabled": true
  },
  "rate_limits": {
    "five_hour": {
      "used_percentage": 23.5,
      "resets_at": 1738425600
    },
    "seven_day": {
      "used_percentage": 41.2,
      "resets_at": 1738857600
    }
  },
  "vim": {
    "mode": "NORMAL"
  },
  "agent": {
    "name": "security-reviewer"
  },
  "worktree": {
    "name": "my-feature",
    "path": "/path/to/.claude/worktrees/my-feature",
    "branch": "worktree-my-feature",
    "original_cwd": "/path/to/project",
    "original_branch": "main"
  }
}
```

**Fields that may be absent** (not present in JSON):

- `session_name`: appears only when a custom name has been set with `--name` or `/rename`
- `workspace.git_worktree`: appears only when the current directory is inside a linked git worktree
- `effort`: appears only when the current model supports the reasoning effort parameter
- `vim`: appears only when vim mode is enabled
- `agent`: appears only when running with the `--agent` flag or agent settings configured
- `worktree`: appears only during `--worktree` sessions. When present, `branch` and `original_branch` may also be absent for hook-based worktrees
- `rate_limits`: appears only for Claude.ai subscribers (Pro/Max) after the first API response in the session. Each window (`five_hour`, `seven_day`) may be independently absent. Use `jq -r '.rate_limits.five_hour.used_percentage // empty'` to handle absence gracefully.

**Fields that may be `null`**:

- `context_window.current_usage`: `null` before the first API call in a session, and again after `/compact` until the next API call repopulates it
- `context_window.used_percentage`, `context_window.remaining_percentage`: may be `null` early in the session

Handle missing fields with conditional access and null values with fallback defaults in your scripts.


Context window fields

The `context_window` object describes the live context window from the most recent API response. As of v2.1.132, `total_input_tokens` and `total_output_tokens` reflect current context usage, not cumulative session totals.

- **Combined totals** (`total_input_tokens`, `total_output_tokens`): tokens currently in the context window. `total_input_tokens` is the sum of `input_tokens`, `cache_creation_input_tokens`, and `cache_read_input_tokens`; `total_output_tokens` is the output tokens from the most recent response. Both are `0` before the first API response.
- **Per-component usage** (`current_usage`): the same token counts broken out by category. Use this when you need cache hits separate from fresh input.

The `current_usage` object contains:

- `input_tokens`: input tokens in current context
- `output_tokens`: output tokens generated
- `cache_creation_input_tokens`: tokens written to cache
- `cache_read_input_tokens`: tokens read from cache

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.


Examples

These examples show common status line patterns. To use any example:

1.  Save the script to a file like `~/.claude/statusline.sh` (or `.py`/`.js`)
2.  Make it executable: `chmod +x ~/.claude/statusline.sh`
3.  Add the path to your [settings](#manually-configure-a-status-line)

The Bash examples use [`jq`](https://jqlang.github.io/jq/) to parse JSON. Python and Node.js have built-in JSON parsing.


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:

Bash

Python

Node.js

```python
#!/bin/bash
# Read all of stdin into a variable
input=$(cat)

# Extract fields with jq, "// 0" provides fallback for null
MODEL=$(echo "$input" | jq -r '.model.display_name')
PCT=$(echo "$input" | jq -r '.context_window.used_percentage // 0' | cut -d. -f1)

# Build progress bar: printf -v creates a run of spaces, then
# ${var// /▓} replaces each space with a block character
BAR_WIDTH=10
FILLED=$((PCT * BAR_WIDTH / 100))
EMPTY=$((BAR_WIDTH - FILLED))
BAR=""
[ "$FILLED" -gt 0 ] && printf -v FILL "%${FILLED}s" && BAR="${FILL// /▓}"
[ "$EMPTY" -gt 0 ] && printf -v PAD "%${EMPTY}s" && BAR="${BAR}${PAD// /░}"

echo "[$MODEL] $BAR $PCT%"
```


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.

Each script checks if the current directory is a git repository, counts staged and modified files, and displays color-coded indicators:

Bash

Python

Node.js

```python
#!/bin/bash
input=$(cat)

MODEL=$(echo "$input" | jq -r '.model.display_name')
DIR=$(echo "$input" | jq -r '.workspace.current_dir')

GREEN='\033[32m'
YELLOW='\033[33m'
RESET='\033[0m'

if git rev-parse --git-dir > /dev/null 2>&1; then
    BRANCH=$(git branch --show-current 2>/dev/null)
    STAGED=$(git diff --cached --numstat 2>/dev/null | wc -l | tr -d ' ')
    MODIFIED=$(git diff --numstat 2>/dev/null | wc -l | tr -d ' ')

    GIT_STATUS=""
    [ "$STAGED" -gt 0 ] && GIT_STATUS="${GREEN}+${STAGED}${RESET}"
    [ "$MODIFIED" -gt 0 ] && GIT_STATUS="${GIT_STATUS}${YELLOW}~${MODIFIED}${RESET}"

    echo -e "[$MODEL] 📁 ${DIR##*/} | 🌿 $BRANCH $GIT_STATUS"
else
    echo "[$MODEL] 📁 ${DIR##*/}"
fi
```


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 total elapsed time since the session started, 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:

Bash

Python

Node.js

```python
#!/bin/bash
input=$(cat)

MODEL=$(echo "$input" | jq -r '.model.display_name')
COST=$(echo "$input" | jq -r '.cost.total_cost_usd // 0')
DURATION_MS=$(echo "$input" | jq -r '.cost.total_duration_ms // 0')

COST_FMT=$(printf '$%.2f' "$COST")
DURATION_SEC=$((DURATION_MS / 1000))
MINS=$((DURATION_SEC / 60))
SECS=$((DURATION_SEC % 60))

echo "[$MODEL] 💰 $COST_FMT | ⏱️ ${MINS}m ${SECS}s"
```


Display multiple lines

Your script can output multiple lines to create a richer display. Each `echo` statement produces a separate row in the status area.

This example combines several techniques: threshold-based colors (green under 70%, yellow 70-89%, red 90%+), a progress bar, and git branch info. Each `print` or `echo` statement creates a separate row:

Bash

Python

Node.js

```python
#!/bin/bash
input=$(cat)

MODEL=$(echo "$input" | jq -r '.model.display_name')
DIR=$(echo "$input" | jq -r '.workspace.current_dir')
COST=$(echo "$input" | jq -r '.cost.total_cost_usd // 0')
PCT=$(echo "$input" | jq -r '.context_window.used_percentage // 0' | cut -d. -f1)
DURATION_MS=$(echo "$input" | jq -r '.cost.total_duration_ms // 0')

CYAN='\033[36m'; GREEN='\033[32m'; YELLOW='\033[33m'; RED='\033[31m'; RESET='\033[0m'

# Pick bar color based on context usage
if [ "$PCT" -ge 90 ]; then BAR_COLOR="$RED"
elif [ "$PCT" -ge 70 ]; then BAR_COLOR="$YELLOW"
else BAR_COLOR="$GREEN"; fi

FILLED=$((PCT / 10)); EMPTY=$((10 - FILLED))
printf -v FILL "%${FILLED}s"; printf -v PAD "%${EMPTY}s"
BAR="${FILL// /█}${PAD// /░}"

MINS=$((DURATION_MS / 60000)); SECS=$(((DURATION_MS % 60000) / 1000))

BRANCH=""
git rev-parse --git-dir > /dev/null 2>&1 && BRANCH=" | 🌿 $(git branch --show-current 2>/dev/null)"

echo -e "${CYAN}[$MODEL]${RESET} 📁 ${DIR##*/}$BRANCH"
COST_FMT=$(printf '$%.2f' "$COST")
echo -e "${BAR_COLOR}${BAR}${RESET} ${PCT}% | ${YELLOW}${COST_FMT}${RESET} | ⏱️ ${MINS}m ${SECS}s"
```


Clickable links

This example creates a clickable link to your GitHub repository. It reads the git remote URL, converts SSH format to HTTPS with `sed`, and wraps the repo name in OSC 8 escape codes. Hold Cmd (macOS) or Ctrl (Windows/Linux) and click to open the link in your browser.

Each script gets the git remote URL, converts SSH format to HTTPS, and wraps the repo name in OSC 8 escape codes. The Bash version uses `printf '%b'` which interprets backslash escapes more reliably than `echo -e` across different shells:

Bash

Python

Node.js

```python
#!/bin/bash
input=$(cat)

MODEL=$(echo "$input" | jq -r '.model.display_name')

# Convert git SSH URL to HTTPS
REMOTE=$(git remote get-url origin 2>/dev/null | sed 's/git@github.com:/https:\/\/github.com\//' | sed 's/\.git$//')

if [ -n "$REMOTE" ]; then
    REPO_NAME=$(basename "$REMOTE")
    # OSC 8 format: \e]8;;URL\a then TEXT then \e]8;;\a
    # printf %b interprets escape sequences reliably across shells
    printf '%b' "[$MODEL] 🔗 \e]8;;${REMOTE}\a${REPO_NAME}\e]8;;\a\n"
else
    echo "[$MODEL]"
fi
```


Rate limit usage

Display Claude.ai subscription rate limit usage in the status line. The `rate_limits` object contains `five_hour` (5-hour rolling window) and `seven_day` (weekly) windows. Each window provides `used_percentage` (0-100) and `resets_at` (Unix epoch seconds when the window resets). This field is only present for Claude.ai subscribers (Pro/Max) after the first API response. Each script handles the absent field gracefully:

Bash

Python

Node.js

```python
#!/bin/bash
input=$(cat)

MODEL=$(echo "$input" | jq -r '.model.display_name')
# "// empty" produces no output when rate_limits is absent
FIVE_H=$(echo "$input" | jq -r '.rate_limits.five_hour.used_percentage // empty')
WEEK=$(echo "$input" | jq -r '.rate_limits.seven_day.used_percentage // empty')

LIMITS=""
[ -n "$FIVE_H" ] && LIMITS="5h: $(printf '%.0f' "$FIVE_H")%"
[ -n "$WEEK" ] && LIMITS="${LIMITS:+$LIMITS }7d: $(printf '%.0f' "$WEEK")%"

[ -n "$LIMITS" ] && echo "[$MODEL] | $LIMITS" || echo "[$MODEL]"
```


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:

Bash

Python

Node.js

```python
#!/bin/bash
input=$(cat)

MODEL=$(echo "$input" | jq -r '.model.display_name')
DIR=$(echo "$input" | jq -r '.workspace.current_dir')
SESSION_ID=$(echo "$input" | jq -r '.session_id')

CACHE_FILE="/tmp/statusline-git-cache-$SESSION_ID"
CACHE_MAX_AGE=5  # seconds

cache_is_stale() {
    [ ! -f "$CACHE_FILE" ] || \
    # stat -f %m is macOS, stat -c %Y is Linux
    [ $(($(date +%s) - $(stat -f %m "$CACHE_FILE" 2>/dev/null || stat -c %Y "$CACHE_FILE" 2>/dev/null || echo 0))) -gt $CACHE_MAX_AGE ]
}

if cache_is_stale; then
    if git rev-parse --git-dir > /dev/null 2>&1; then
        BRANCH=$(git branch --show-current 2>/dev/null)
        STAGED=$(git diff --cached --numstat 2>/dev/null | wc -l | tr -d ' ')
        MODIFIED=$(git diff --numstat 2>/dev/null | wc -l | tr -d ' ')
        echo "$BRANCH|$STAGED|$MODIFIED" > "$CACHE_FILE"
    else
        echo "||" > "$CACHE_FILE"
    fi
fi

IFS='|' read -r BRANCH STAGED MODIFIED < "$CACHE_FILE"

if [ -n "$BRANCH" ]; then
    echo "[$MODEL] 📁 ${DIR##*/} | 🌿 $BRANCH +$STAGED ~$MODIFIED"
else
    echo "[$MODEL] 📁 ${DIR##*/}"
fi
```


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:

settings.json

statusline.ps1

```python
{
  "statusLine": {
    "type": "command",
    "command": "powershell -NoProfile -File C:/Users/username/.claude/statusline.ps1"
  }
}
```

Or, when Git Bash is installed, run a Bash script directly:

settings.json

statusline.sh

```python
{
  "statusLine": {
    "type": "command",
    "command": "~/.claude/statusline.sh"
  }
}
```


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.

```python
{
  "subagentStatusLine": {
    "type": "command",
    "command": "~/.claude/subagent-statusline.sh"
  }
}
```

The command runs once per refresh tick with all visible subagent rows passed as a single JSON object on stdin. The input includes the [base hook fields](/docs/en/hooks#common-input-fields) plus `columns` (the usable row width) and a `tasks` array, where each task has `id`, `name`, `type`, `status`, `description`, `label`, `startTime`, `tokenCount`, `tokenSamples`, and `cwd`. 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 and `disableAllHooks` gates that apply to `statusLine` apply here. Plugins can ship a default `subagentStatusLine` in their [`settings.json`](/docs/en/plugins-reference#standard-plugin-layout).


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
- **Cache slow operations**: your script runs frequently during active sessions, so commands like `git status` can cause lag. See the [caching example](#cache-expensive-operations) for how to handle this.

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

**Status line not appearing**

- Verify your script is executable: `chmod +x ~/.claude/statusline.sh`
- Check that your script outputs to stdout, not stderr
- Run your script manually to verify it produces output
- On Windows with Git Bash installed, backslashes in the `command` path are likely being consumed as escape characters before the script runs. Use forward slashes in the path. See [Windows configuration](#windows-configuration).
- If `disableAllHooks` is set to `true` in your settings, the status line is also disabled. Remove this setting or set it to `false` to re-enable.
- Run `claude --debug` to log the exit code and stderr from the first status line 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**

- Fields may be `null` before the first API response completes
- 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**

- Use `used_percentage` for the simplest accurate context state
- Context percentage may differ from `/context` output due to when each is calculated

**OSC 8 links not clickable**

- Verify your terminal supports OSC 8 hyperlinks (iTerm2, Kitty, WezTerm)
- Terminal.app does not support clickable links
- If link text appears but isn’t clickable, Claude Code may not have detected hyperlink support in your terminal. This commonly affects Windows Terminal and other emulators not in the auto-detection list. Set the `FORCE_HYPERLINK` environment variable to override detection before launching Claude Code:

  ``` shiki
  FORCE_HYPERLINK=1 claude
  ```

  In PowerShell, set the variable in the current session first:

  ``` shiki
  $env:FORCE_HYPERLINK = "1"; claude
  ```
- 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**

- Complex escape sequences (ANSI colors, OSC 8 links) can occasionally cause garbled output if they overlap with other UI updates
- If you see corrupted text, try simplifying your script to plain text output
- Multi-line status lines with escape codes are more prone to rendering issues than single-line plain text

**Workspace trust required**

- The status line command only runs if you’ve accepted the workspace trust dialog for the current directory. Because `statusLine` executes a shell command, it requires the same trust acceptance as hooks and other shell-executing settings.
- If trust isn’t accepted, you’ll see the notification `statusline skipped · restart to fix` instead of your status line output. Restart Claude Code and accept the trust prompt to enable it.

**Script errors or hangs**

- Scripts that exit with non-zero codes or produce no output cause the status line to go blank
- Slow scripts block the status line from updating until they complete. Keep scripts fast to avoid stale output.
- 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**

- System notifications like MCP server errors and auto-updates display on the right side of the same row as your status line. Transient notifications such as the context-low warning also cycle through this area.
- Enabling verbose mode adds a token counter to this area
- On narrow terminals, these notifications may truncate your status line output


---
## data-usage-a28ecced65.md

> ## Documentation Index
> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Data usage

> Learn about Anthropic's data usage policies for Claude

## Data policies

### Data training policy

**Consumer users (Free, Pro, and Max 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, and Max 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

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 Bedrock or Vertex users.

### 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` are retained for 5 years.

### Session quality surveys

When you see the "How is Claude doing this session?" prompt in Claude Code, responding to this survey (including selecting "Dismiss"), only your numeric rating (1, 2, 3, or dismiss) is recorded. We do not collect or store any conversation transcripts, inputs, outputs, or other session data as part of this survey. Unlike thumbs up/down feedback or `/feedback` reports, this session quality survey is a simple product satisfaction metric. Your responses to this survey 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` or `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` is set. To control frequency instead of disabling, set [`feedbackSurveyRate`](/en/settings#available-settings) in your settings file to a probability between `0` and `1`.

### Data retention

Anthropic retains Claude Code data based on your account type and preferences.

**Consumer users (Free, Pro, and Max plans)**:

* Users who allow data use for model improvement: 5-year retention period to support model development and safety improvements
* Users who don't allow data use for model improvement: 30-day retention period
* Privacy settings can be changed at any time at [claude.ai/settings/data-privacy-controls](https://claude.ai/settings/data-privacy-controls).

**Commercial users (Team, Enterprise, and API)**:

* Standard: 30-day retention period
* [Zero data retention](../22-Safety-Policy/zero-data-retention-claude-code-docs-6ec9ee63f1.md): available for Claude Code on Claude for Enterprise. ZDR is enabled on a per-organization basis; each new organization must have ZDR enabled separately by your account team
* Local caching: Claude Code clients store session transcripts locally in plaintext under `~/.claude/projects/` for 30 days by default to enable session resumption. Adjust the period with `cleanupPeriodDays`. See [application data](/en/claude-directory#application-data) for what's stored and how to clear it.

You can delete individual Claude Code on the web sessions at any time. Deleting a session permanently removes the session's event data. For instructions on how to delete sessions, see [Delete sessions](/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, and Max users) and [Privacy Policy](https://www.anthropic.com/legal/privacy).

## Data access

For all first party users, you can learn more about what data is logged for [local Claude Code](#local-claude-code-data-flow-and-dependencies) and [remote Claude Code](#cloud-execution-data-flow-and-dependencies). [Remote Control](continue-local-sessions-from-any-device-with-remote-control-claude-code-docs-c1c03fd914.md) sessions follow the local data flow since all execution happens on your machine. 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

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.

<img src="https://mintcdn.com/claude-code/YcBW2H7CArGcduPb/images/claude-code-data-flow.svg?fit=max&auto=format&n=YcBW2H7CArGcduPb&q=85&s=b600a89f84fc86f9ff7be00a466c0635" alt="Diagram showing Claude Code's external connections: install/update connects to the distribution server, and user requests connect to Anthropic services including Console auth, public-api, and optionally Statsig, Sentry, and bug reporting" width="720" height="520" data-path="images/claude-code-data-flow.svg" />

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:

| Provider               | Encryption at rest                                                                                                                    |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| Anthropic API          | Infrastructure-level disk encryption (AES-256). Enable [Zero Data Retention](../22-Safety-Policy/zero-data-retention-claude-code-docs-6ec9ee63f1.md) for no server-side persistence. |
| Amazon Bedrock         | AES-256 with AWS-managed keys. Customer-managed keys available via AWS KMS.                                                           |
| Google Cloud Vertex AI | Google-managed encryption keys. CMEK available.                                                                                       |
| Microsoft Foundry      | Requests route to Anthropic infrastructure with AES-256 disk encryption.                                                              |

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

When using [Claude Code on the web](claude-code-on-the-web-69d53821d4.md), sessions run in Anthropic-managed virtual machines instead of locally. In cloud environments:

* **Code and data storage:** Your repository is cloned to an isolated VM. Code and session data are subject to the retention and usage policies for your account type (see Data retention section above)
* **Credentials:** GitHub authentication is handled through a secure proxy; your GitHub credentials never enter the sandbox
* **Network traffic:** All outbound traffic goes through a security proxy for audit logging and abuse prevention
* **Session data:** Prompts, code changes, and outputs follow the same data policies as local Claude Code usage

For security details about cloud execution, see [Security](/en/security#cloud-execution-security).

## Telemetry services

Claude Code connects from users' machines to the Statsig service to log operational metrics such as latency, reliability, and usage patterns. This logging does not include any code or file paths. Data is encrypted in transit using TLS and at rest using 256-bit AES encryption. Read more in the [Statsig security documentation](https://www.statsig.com/trust/security). To opt out of Statsig telemetry, set the `DISABLE_TELEMETRY` environment variable.

Claude Code connects from users' machines to Sentry for operational error logging. The data is encrypted in transit using TLS and at rest using 256-bit AES encryption. Read more in the [Sentry security documentation](https://sentry.io/security/). To opt out of error logging, set the `DISABLE_ERROR_REPORTING` environment variable.

When users run the `/feedback` command, a copy of their full conversation history including code is sent to Anthropic. The data is encrypted in transit via TLS. Optionally, a GitHub issue is created in the public repository. To opt out, set the `DISABLE_FEEDBACK_COMMAND` environment variable to `1`.

## Default behaviors by API provider

By default, error reporting, telemetry, and bug reporting are disabled when using Bedrock, Vertex, or Foundry. Session quality surveys and the WebFetch domain safety check are exceptions and run regardless of provider. You can opt out of all non-essential traffic, including surveys, at once by setting `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`. This variable does not affect the WebFetch check, which has its own opt-out. Here are the full default behaviors:

| Service                              | Claude API                                                                             | Vertex API                                                                             | Bedrock API                                                                            | Foundry API                                                                            |
| ------------------------------------ | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| **Statsig (Metrics)**                | Default on.<br />`DISABLE_TELEMETRY=1` to disable.                                     | Default off.<br />`CLAUDE_CODE_USE_VERTEX` must be 1.                                  | Default off.<br />`CLAUDE_CODE_USE_BEDROCK` must be 1.                                 | Default off.<br />`CLAUDE_CODE_USE_FOUNDRY` must be 1.                                 |
| **Sentry (Errors)**                  | Default on.<br />`DISABLE_ERROR_REPORTING=1` to disable.                               | Default off.<br />`CLAUDE_CODE_USE_VERTEX` must be 1.                                  | Default off.<br />`CLAUDE_CODE_USE_BEDROCK` must be 1.                                 | Default off.<br />`CLAUDE_CODE_USE_FOUNDRY` must be 1.                                 |
| **Claude API (`/feedback` reports)** | Default on.<br />`DISABLE_FEEDBACK_COMMAND=1` to disable.                              | Default off.<br />`CLAUDE_CODE_USE_VERTEX` must be 1.                                  | Default off.<br />`CLAUDE_CODE_USE_BEDROCK` must be 1.                                 | Default off.<br />`CLAUDE_CODE_USE_FOUNDRY` must be 1.                                 |
| **Session quality surveys**          | Default on.<br />`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1` to disable.                   | Default on.<br />`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1` to disable.                   | Default on.<br />`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1` to disable.                   | Default on.<br />`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1` to disable.                   |
| **WebFetch domain safety check**     | Default on.<br />`skipWebFetchPreflight: true` in [settings](claude-code-settings-claude-code-docs-d4420b4b52.md) to disable. | Default on.<br />`skipWebFetchPreflight: true` in [settings](claude-code-settings-claude-code-docs-d4420b4b52.md) to disable. | Default on.<br />`skipWebFetchPreflight: true` in [settings](claude-code-settings-claude-code-docs-d4420b4b52.md) to disable. | Default on.<br />`skipWebFetchPreflight: true` in [settings](claude-code-settings-claude-code-docs-d4420b4b52.md) to disable. |

All environment variables can be checked into `settings.json` (see [settings reference](claude-code-settings-claude-code-docs-d4420b4b52.md)).

### 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. Results are cached per hostname for five minutes.

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](claude-code-settings-claude-code-docs-d4420b4b52.md). Disabling the check means WebFetch attempts to retrieve any URL without consulting the blocklist, so combine it with [`WebFetch` permission rules](/en/permissions#webfetch) if you need to restrict which domains Claude can reach.


---
## debug-your-config-615fc7cc73.md

> ## Documentation Index
> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Debug your configuration

> Diagnose why CLAUDE.md, settings, hooks, MCP servers, or skills aren't taking effect. Use /context, /doctor, /hooks, and /mcp to see what actually loaded.

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 [Troubleshooting](../21-Account-Support/troubleshooting-claude-code-docs-3f3657ed0f.md) instead.

## See what loaded into context

The `/context` command shows everything occupying the context window for the current session, broken down by category: system prompt, memory files, skills, MCP tools, and conversation messages. Run it first to confirm whether your `CLAUDE.md`, rules, or skill descriptions are present at all.

For detail on a specific category, follow up with the dedicated command:

| Command        | Shows                                                                       |
| :------------- | :-------------------------------------------------------------------------- |
| `/memory`      | Which `CLAUDE.md` and rules files loaded, plus auto-memory entries          |
| `/skills`      | Available skills from project, user, and plugin sources                     |
| `/agents`      | Configured subagents and their settings                                     |
| `/hooks`       | Active hook configurations                                                  |
| `/mcp`         | Connected MCP servers and their status                                      |
| `/permissions` | Resolved allow and deny rules currently in effect                           |
| `/doctor`      | Configuration diagnostics: invalid keys, schema errors, installation health |
| `/status`      | Active settings sources, including whether managed settings are in effect   |

If a memory file is missing from `/memory`, check its location against [how CLAUDE.md files load](/en/memory#how-claude-md-files-load). Subdirectory `CLAUDE.md` files load on demand when Claude reads a file in that directory with the Read tool, not at session start.

If `/memory` confirms the file loaded but Claude still isn't following a particular instruction, the issue is likely how the instruction is written rather than whether it loaded. CLAUDE.md works well for the kinds of guidance you'd give a new teammate, such as project conventions, build commands, and where files belong.

Adherence drops when an instruction is vague enough to interpret multiple ways, when two files give conflicting direction, or when the file has grown long enough that individual rules get less attention. [Write effective instructions](/en/memory#write-effective-instructions) covers the specificity, size, and structure patterns that keep adherence high.

<Note>
  CLAUDE.md and permissions solve different problems. CLAUDE.md tells Claude how your project works so it makes good decisions. [Permissions](configure-permissions-claude-code-docs-7b0e64d485.md) and [hooks](../07-Hooks/hooks-9168ed62a4.md) 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.
</Note>

## Check resolved settings

Settings merge across managed, user, project, and local scopes. Managed settings always win 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](env-vars-5c624d392b.md), 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.

Run `/doctor` to validate your configuration files and surface invalid keys or schema errors. Run `/status` to see which settings sources are active, including whether managed settings are in effect. To understand which scope wins for a given key, see [How scopes interact](/en/settings#how-scopes-interact).

## 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:

* Project-scoped servers in `.mcp.json` require a one-time approval. If the prompt was dismissed, the server stays disabled until you approve it from `/mcp`.
* A server that fails to start shows as failed in `/mcp`. Relative file paths in `command` or `args` are a frequent cause, since they resolve against the directory you launched Claude Code from rather than the location of `.mcp.json`.
* A server that shows as connected but lists zero tools has started successfully but isn't returning a tool list. Select **Reconnect** from `/mcp`. If the count stays at zero, run `claude --debug mcp` to see the server's stderr output.

For configuration locations and scope rules, see [MCP](../06-MCP-Tools/mcp-208e742686.md).

## Check hooks

Run `/hooks` to list every hook registered for the current session, grouped by event. If a hook you defined doesn't appear, it isn't being read: hooks go under the `"hooks"` key in a settings file, not in a standalone file.

If the hook appears but doesn't fire, the matcher is the usual cause. The `matcher` field is a single string that uses `|` to match multiple tool names, for example `"Edit|Write"`. A misspelled tool name fails silently because the matcher never matches. An array value is a schema error: Claude Code shows a settings error notice, `/doctor` reports the validation failure, and the hook entry is dropped so it won't appear in `/hooks`.

Edits to `settings.json` take effect in the running session after a brief file-stability delay. You don't need to restart. If `/hooks` still shows the old definition a few seconds after saving, 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 hooks` 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](/en/hooks#debug-hooks) for the log format and [hooks troubleshooting](/en/hooks-guide#limitations-and-troubleshooting) for common failure patterns.

## Common causes

Most configuration surprises trace back to a small set of location and syntax rules. Check these before assuming a bug:

| Symptom                                                          | Cause                                                                                                                      | Fix                                                                                                                                                                                                       |
| :--------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Hook never fires                                                 | `matcher` is a JSON array instead of a string                                                                              | Use a single string with `\|` to match multiple tools, for example `"Edit\|Write"`. See [matcher patterns](/en/hooks#matcher-patterns).                                                                   |
| Hook never fires                                                 | `matcher` value is lowercase, for example `"bash"`                                                                         | Matching is case-sensitive. Tool names are capitalized: `Bash`, `Edit`, `Write`, `Read`.                                                                                                                  |
| Hook never fires                                                 | Hooks are in a standalone `.claude/hooks.json` file                                                                        | There is no standalone hooks file. Define hooks under the `"hooks"` key in `settings.json`. See [hook configuration](../07-Hooks/hooks-9168ed62a4.md).                                                                          |
| Permissions, hooks, or env set globally are ignored              | Configuration was added to `~/.claude.json`                                                                                | `~/.claude.json` holds app state and UI toggles. `permissions`, `hooks`, and `env` belong in `~/.claude/settings.json`. These are two different files.                                                    |
| A `settings.json` value seems ignored                            | The same key is set in `settings.local.json`                                                                               | `settings.local.json` overrides `settings.json`, and both override `~/.claude/settings.json`. See [settings precedence](/en/settings#how-scopes-interact).                                                |
| Skill doesn't appear in `/skills`                                | Skill file is at `.claude/skills/name.md` instead of in a folder                                                           | Use a folder with `SKILL.md` inside: `.claude/skills/name/SKILL.md`.                                                                                                                                      |
| Skill appears in `/skills` but Claude never invokes it           | Skill has `disable-model-invocation: true` in its frontmatter, or its description doesn't match how you phrase the request | Check the badge in `/skills`: a "user-only" label means Claude won't trigger it on its own. See [skill invocation](../08-Plugins-Skills/extend-claude-with-skills-claude-code-docs.md).                                                                           |
| Subdirectory `CLAUDE.md` instructions seem ignored               | Subdirectory files load on demand, not at session start                                                                    | They load when Claude reads a file in that directory with the Read tool, not at launch and not when writing or creating files there. See [how CLAUDE.md files load](/en/memory#how-claude-md-files-load). |
| Subagent ignores `CLAUDE.md` instructions                        | Subagents don't always inherit project memory                                                                              | Put critical rules in the agent file body, which becomes the subagent's system prompt. See [subagent configuration](../09-Agents-Patterns/create-custom-subagents-claude-code-docs-7dc93e85c0.md).                                                                      |
| Cleanup logic never runs at session end                          | No `SessionEnd` hook configured                                                                                            | `SessionStart` and `SessionEnd` both exist. See the [hook events list](/en/hooks#hook-events).                                                                                                            |
| MCP servers in `.mcp.json` never load                            | File is under `.claude/` or uses Claude Desktop's config format                                                            | Project MCP config goes at the repository root as `.mcp.json`, not inside `.claude/`. See [MCP configuration](../06-MCP-Tools/mcp-208e742686.md).                                                                                   |
| Project MCP server added but doesn't appear                      | The one-time approval prompt was dismissed                                                                                 | Project-scoped servers require approval. Run `/mcp` to see status and approve.                                                                                                                            |
| MCP server fails to start from some directories                  | `command` or `args` uses a relative file path                                                                              | Use absolute paths for local scripts. Executables on your `PATH` like `npx` or `uvx` work as-is.                                                                                                          |
| MCP server starts without expected environment variables         | Variables are in `settings.json` `env`, which doesn't propagate to MCP child processes                                     | Set per-server `env` inside `.mcp.json` instead.                                                                                                                                                          |
| `Bash(rm *)` deny rule doesn't block `/bin/rm` or `find -delete` | Prefix rules match the literal command string, not the underlying executable                                               | Add explicit patterns for each variant, or use a [PreToolUse hook](../07-Hooks/automate-workflows-with-hooks-claude-code-docs-e843f93261.md) or the [sandbox](../22-Safety-Policy/sandboxing-claude-code-docs-5f97cd27c4.md) for a hard guarantee.                                                                |

## Related resources

For full reference on each configuration surface, see the dedicated page:

* **[`.claude` directory reference](claude-directory-06f83438fe.md)**: every config file location and what reads it
* **[Settings](claude-code-settings-claude-code-docs-d4420b4b52.md)**: precedence order and the full key list
* **[Hooks reference](../07-Hooks/hooks-9168ed62a4.md)**: event names, payloads, and `--debug hooks` output format
* **[MCP](../06-MCP-Tools/mcp-208e742686.md)**: server configuration, approval, and `/mcp` output
* **[Troubleshooting](../21-Account-Support/troubleshooting-claude-code-docs-3f3657ed0f.md)**: `claude doctor`, platform issues, and installation problems


---
## desktop-18b59ad2b5.md

> ## Documentation Index
> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Use Claude Code Desktop

> Get more out of Claude Code Desktop: parallel sessions with Git isolation, drag-and-drop pane layout, integrated terminal and file editor, side chats, computer use, Dispatch sessions from your phone, visual diff review, app previews, PR monitoring, connectors, and enterprise configuration.

The Claude Desktop app has three tabs: **Chat** for conversations, **Cowork** for [Dispatch and longer agentic work](https://claude.com/product/cowork), and **Code** for software development. This page is the reference for the Code tab.

<CardGroup cols={2}>
  <Card title="Download for macOS" icon="apple" href="https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code&utm_medium=docs">
    Universal build for Intel and Apple Silicon
  </Card>

  <Card title="Download for Windows" icon="windows" href="https://claude.ai/api/desktop/win32/x64/setup/latest/redirect?utm_source=claude_code&utm_medium=docs">
    For x64 processors
  </Card>
</CardGroup>

For Windows ARM64, download the [ARM64 installer](https://claude.ai/api/desktop/win32/arm64/setup/latest/redirect?utm_source=claude_code\&utm_medium=docs). Linux is not supported.

After installing, launch Claude, sign in, and click the **Code** tab. The first time you open it on Windows, you need [Git for Windows](https://git-scm.com/downloads/win) installed; restart the app after installing it. For a walkthrough of your first session, see the [Get started guide](../16-Mobile-Desktop/desktop-quickstart.md).

In the Code tab, each conversation is a **session**: it has its own chat history, project folder, and code changes, independent of any other session. The sidebar lists your sessions and lets you run several in parallel. Within a session you can:

* [Review and comment on diffs](#review-changes-with-diff-view), then [watch the resulting PR through CI](#monitor-pull-request-status)
* [Preview your running app](#preview-your-app) in an embedded browser while Claude verifies its own changes
* [Arrange panes](#arrange-your-workspace) for the chat, diff, preview, terminal, and file editor side by side
* Ask a [side question](#ask-a-side-question-without-derailing-the-session) that uses the session's context without derailing it
* [Connect external tools](#connect-external-tools) like GitHub, Slack, and Linear
* Let Claude [open apps and control your screen](#let-claude-use-your-computer)
* Run on your machine, in the [cloud](#run-long-running-tasks-remotely), or over [SSH](#ssh-sessions)

For [scheduled recurring work](../16-Mobile-Desktop/desktop-scheduled-tasks.md), [keyboard shortcuts](#keyboard-shortcuts), or [sending tasks from your phone](#sessions-from-dispatch), see the linked pages and sections. If you already use the terminal-based CLI, see the [CLI comparison](#coming-from-the-cli) for what carries over.

## Start a session

Before you send your first message, configure four things in the prompt area:

* **Environment**: choose where Claude runs. Select **Local** for your machine, **Remote** for Anthropic-hosted cloud sessions, or an [**SSH connection**](#ssh-sessions) for a remote machine you manage. See [environment configuration](#environment-configuration).
* **Project folder**: select the folder or repository Claude works in. For remote sessions, you can add [multiple repositories](#run-long-running-tasks-remotely).
* **Model**: pick a [model](/en/model-config#available-models) from the dropdown next to the send button. You can change this during the session.
* **Permission mode**: choose how much autonomy Claude has from the [mode selector](#choose-a-permission-mode). You can change this during the session.

Type your task and press **Enter** to start. Each session tracks its own context and changes independently.

## 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

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](#choose-a-permission-mode). You can interrupt Claude at any point: click the stop button or type your correction and press **Enter**. Claude stops what it's doing and adjusts based on your input.

The **+** button next to the prompt box gives you access to file attachments, [skills](#use-skills), [connectors](#connect-external-tools), and [plugins](#install-plugins).

### Add files and context to prompts

The prompt box supports two ways to bring in external context:

* **@mention files**: type `@` followed by a filename to add a file to the conversation context. Claude can then read and reference that file. @mention is not available in remote sessions.
* **Attach files**: attach images, PDFs, and other files to your prompt using the attachment button, or drag and drop files directly into the prompt. This is useful for sharing screenshots of bugs, design mockups, or reference documents.

### 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 modes at any time using the mode selector next to the send button. Start with Ask permissions to see exactly what Claude does, then move to Auto accept edits or Plan mode as you get comfortable.

| Mode                   | Settings key        | Behavior                                                                                                                                                                                                                                                                     |
| ---------------------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Ask permissions**    | `default`           | Claude asks before editing files or running commands. You see a diff and can accept or reject each change. Recommended for new users.                                                                                                                                        |
| **Auto accept edits**  | `acceptEdits`       | Claude auto-accepts file edits and common filesystem commands like `mkdir`, `touch`, and `mv`, but still asks before running other terminal commands. Use this when you trust file changes and want faster iteration.                                                        |
| **Plan mode**          | `plan`              | Claude reads files and runs commands to explore, then proposes a plan without editing your source code. Good for complex tasks where you want to review the approach first.                                                                                                  |
| **Auto**               | `auto`              | Claude executes all actions with background safety checks that verify alignment with your request. Reduces permission prompts while maintaining oversight. Enable in your Settings → Claude Code. See [availability requirements](#auto-mode-availability) below.            |
| **Bypass permissions** | `bypassPermissions` | Claude runs without any permission prompts, equivalent to the admin-gated bypass option in the CLI. Enable in your Settings → Claude Code under "Allow bypass permissions mode". Only use this in sandboxed containers or VMs. Enterprise admins can disable this option. |

The `dontAsk` permission mode is available only in the [CLI](/en/permission-modes#allow-only-pre-approved-tools-with-dontask-mode).

<span id="auto-mode-availability" />

Auto mode is a research preview available on Max, Team, Enterprise, and API plans. It is not available on Pro plans or third-party providers. On Team, Enterprise, and API plans it requires Claude Sonnet 4.6, Opus 4.6, or Opus 4.7. On Max plans it requires Claude Opus 4.7.

<Tip title="Best practice">
  Start complex tasks in Plan mode so Claude maps out an approach before making changes. Once you approve the plan, switch to Auto accept edits or Ask permissions to execute it. See [explore first, then plan, then code](/en/best-practices#explore-first-then-plan-then-code) for more on this workflow.
</Tip>

Remote sessions support Auto accept edits and Plan mode. Ask permissions is not available because remote sessions auto-accept file edits by default, and Bypass permissions is not available because the remote environment is already sandboxed.

Enterprise admins can restrict which permission modes are available. See [enterprise configuration](#enterprise-configuration) for details.

### Preview your app

Claude can start a dev server and open an embedded browser 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](#auto-verify-changes) changes after every edit.

The preview pane can also open static HTML files, PDFs, images, and videos from your project. Click an HTML, PDF, image, or video path in the chat to open it in preview.

From the preview pane, you can:

* Interact with your running app directly in the embedded browser
* Watch Claude verify its own changes automatically: it takes screenshots, inspects the DOM, clicks elements, fills forms, and fixes issues it finds
* Start or stop servers from the **Preview** dropdown in the session toolbar
* Persist cookies and local storage across server restarts by selecting **Persist sessions** in the dropdown, so you don't have to re-login during development
* Edit the server configuration or stop all servers at once

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](#configure-preview-servers) for the full reference.

To clear saved session data, toggle **Persist preview sessions** off in Settings → Claude Code. To disable preview entirely, toggle off **Preview** in Settings → Claude Code.

### 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.

When Claude changes files, a diff stats indicator appears showing the number of lines added and removed, such as `+12 -1`. Click this indicator to open the diff viewer, which displays a file list on the left and the changes for each file on the right.

To comment on specific lines, click any line in the diff 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:

* **macOS**: press **Cmd+Enter**
* **Windows**: press **Ctrl+Enter**

Claude reads your comments and makes the requested changes, which appear as a new diff you can review.

### Review your code

In the diff view, click **Review code** in the top-right toolbar to ask Claude to evaluate the changes before you commit. Claude examines the current diffs and leaves comments directly in the diff view. You can respond to any comment or ask Claude to revise.

The review focuses on high-signal issues: compile errors, definite logic errors, security vulnerabilities, and obvious bugs. It does not flag style, formatting, pre-existing issues, or anything a linter would catch.

### Monitor pull request status

After you open a pull request, a CI status bar appears in the session. Claude Code uses the GitHub CLI to poll check results and surface failures.

* **Auto-fix**: when enabled, Claude automatically attempts to fix failing CI checks by reading the failure output and iterating.
* **Auto-merge**: when enabled, Claude merges the PR once all checks pass. The merge method is squash. Auto-merge must be [enabled in your GitHub repository settings](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/configuring-pull-request-merges/managing-auto-merge-for-pull-requests-in-your-repository) for this to work.

Use the **Auto-fix** and **Auto-merge** toggles in the CI status bar to enable either option. Claude Code also sends a desktop notification when CI finishes. To archive the session automatically once the PR merges or closes, turn on [auto-archive](#work-in-parallel-with-sessions) in Settings → Claude Code.

<Note>
  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.
</Note>

## Arrange your workspace

The Code tab is built around panes you can arrange in any layout: chat, diff, preview, terminal, file, plan, tasks, and subagent. 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. Open additional panes from the **Views** menu in the session toolbar.

<Note>
  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.
</Note>

### Run commands in the terminal

The integrated terminal lets you run commands alongside your session without switching to another app. Open it from the **Views** menu 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. The terminal is available in local sessions only.

### Open and edit files

Click a file path in the chat or diff viewer to open it in the file pane. HTML, PDF, image, and video paths open in the [preview pane](#preview-your-app) instead. Make spot edits and click **Save** to write them back. If the file changed on disk since you opened it, the pane warns you and lets you override or discard. Click **Discard** to revert your edits, or click the path in the pane header to copy the absolute path.

The file pane is available in local and SSH sessions. For remote sessions, ask Claude to make the change.

### Open files in other apps

Right-click any file path in the chat, diff viewer, or file pane to open a context menu:

* **Attach as context**: add the file to your next prompt
* **Open in**: open the file in an installed editor such as VS Code, Cursor, or Zed
* **Show in Finder** on macOS, **Show in Explorer** on Windows: open the containing folder
* **Copy path**: copy the absolute path to your clipboard

### Switch view modes

View modes control how much detail appears in the chat transcript. Switch modes from the **Transcript view** dropdown next to the send button, or press **Ctrl+O** on macOS or Windows to cycle through them.

| Mode        | What it shows                                                  |
| ----------- | -------------------------------------------------------------- |
| **Normal**  | Tool calls collapsed into summaries, with full text responses  |
| **Verbose** | Every tool call, file read, and intermediate step Claude takes |
| **Summary** | Only Claude's final responses and the changes it made          |

Use Verbose when debugging why Claude took a particular action. Use Summary when you're running multiple sessions and want to scan results quickly.

### Keyboard shortcuts

Press **Cmd+/** on macOS or **Ctrl+/** on Windows to see all shortcuts available in the Code tab. On Windows, use **Ctrl** in place of **Cmd** for the shortcuts below. Session cycling, the terminal toggle, and the view-mode toggle use **Ctrl** on every platform.

| Shortcut                              | Action                       |
| ------------------------------------- | ---------------------------- |
| `Cmd` `/`                             | Show keyboard shortcuts      |
| `Cmd` `N`                             | New session                  |
| `Cmd` `W`                             | Close session                |
| `Ctrl` `Tab` / `Ctrl` `Shift` `Tab`   | Next or previous session     |
| `Cmd` `Shift` `]` / `Cmd` `Shift` `[` | Next or previous session     |
| `Esc`                                 | Stop Claude's response       |
| `Cmd` `Shift` `D`                     | Toggle diff pane             |
| `Cmd` `Shift` `P`                     | Toggle preview pane          |
| `Cmd` `Shift` `S`                     | Select an element in preview |
| `Ctrl` `` ` ``                        | Toggle terminal pane         |
| `Cmd` `\`                             | Close focused pane           |
| `Cmd` `;`                             | Open side chat               |
| `Ctrl` `O`                            | Cycle view modes             |
| `Cmd` `Shift` `M`                     | Open permission mode menu    |
| `Cmd` `Shift` `I`                     | Open model menu              |
| `Cmd` `Shift` `E`                     | Open effort menu             |
| `1`–`9`                               | Select item in an open menu  |

These shortcuts apply only to the Code tab. The terminal-based [interactive mode shortcuts](/en/interactive-mode#keyboard-shortcuts), such as `Shift+Tab` to cycle modes, do not apply in Desktop.

### Check usage

Click the usage ring next to the model picker to see your current context window usage and your plan usage for the period. Context usage is per session; plan usage is shared across all your Claude Code surfaces.

## 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 test a native app in a mobile simulator, interact with a desktop tool that has no CLI, or automate something that only works through a GUI.

<Note>
  Computer use is a research preview on macOS and Windows that requires a Pro or Max plan. It is not available on Team or Enterprise plans. The Claude Desktop app must be running.
</Note>

Computer use is off by default. [Enable it in Settings](#enable-computer-use) before Claude can control your screen. On macOS, you also need to grant Accessibility and Screen Recording permissions.

<Warning>
  Unlike the [sandboxed Bash tool](../22-Safety-Policy/sandboxing-claude-code-docs-5f97cd27c4.md), 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.
</Warning>

### 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:

* If you have a [connector](#connect-external-tools) for a service, Claude uses the connector.
* If the task is a shell command, Claude uses Bash.
* If the task is browser work and you have [Claude in Chrome](../03-IDE-Integrations/use-claude-code-with-chrome-beta-claude-code-docs-4f2f5a5a96.md) set up, Claude uses that.
* If none of those apply, Claude uses computer use.

The [per-app access tiers](#app-permissions) 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, mobile simulators, or proprietary tools without an API.

### 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.

<Steps>
  <Step title="Update the desktop app">
    Make sure you have the latest version of Claude Desktop. Download or update at [claude.com/download](https://claude.com/download), then restart the app.
  </Step>

  <Step title="Turn on the toggle">
    In the desktop app, go to **Settings > General** (under **Desktop app**). Find the **Computer use** toggle and turn it on. On Windows, the toggle takes effect immediately and setup is complete. On macOS, continue to the next step.

    If you don't see the toggle, confirm you're on macOS or Windows with a Pro or Max plan, then update and restart the app.
  </Step>

  <Step title="Grant macOS permissions">
    On macOS, grant two system permissions before the toggle takes effect:

    * **Accessibility**: lets Claude click, type, and scroll
    * **Screen Recording**: lets Claude see what's on your screen

    The Settings page shows the current status of each permission. If either is denied, click the badge to open the relevant System Settings pane.
  </Step>
</Steps>

### 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](#sessions-from-dispatch).

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:

| Tier         | What Claude can do                                       | Applies to                  |
| :----------- | :------------------------------------------------------- | :-------------------------- |
| View only    | See the app in screenshots                               | Browsers, trading platforms |
| Click only   | Click and scroll, but not type or use keyboard shortcuts | Terminals, IDEs             |
| Full control | Click, type, drag, and use keyboard shortcuts            | Everything else             |

Apps with broad reach, like terminals, Finder or File Explorer, and System Settings or Settings, show an extra warning in the prompt so you know what approving them grants.

You can configure two settings in **Settings > General** (under **Desktop app**):

* **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**: while Claude is working, your other windows are hidden so it interacts with only the approved app. When Claude finishes, hidden windows are restored unless you turn this setting off.

## 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, send work to the cloud, or let Dispatch start sessions for you from your phone.

### Work in parallel with sessions

Click **+ New session** 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 cycle through sessions in the sidebar. For Git repositories, each session gets its own isolated copy of your project using [Git worktrees](/en/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees), so changes in one session don't affect other sessions until you commit them.

Worktrees are stored in `<project-root>/.claude/worktrees/` by default. You can change this to a custom directory in Settings → Claude Code under "Worktree location". You can also set a branch prefix that gets prepended to every worktree branch name, which is useful for keeping Claude-created branches organized. To remove a worktree when you're done, hover over the session in the sidebar and click the archive icon. To have sessions archive themselves when their pull request merges or closes, turn on **Auto-archive after PR merge or close** in Settings → Claude Code. Auto-archive only applies to local sessions that have finished running.

To include gitignored files like `.env` in new worktrees, create a [`.worktreeinclude` file](/en/common-workflows#copy-gitignored-files-to-worktrees) in your project root.

<Note>
  Session isolation requires [Git](https://git-scm.com/downloads). Most Macs include Git by default. Run `git --version` in Terminal to check. On Windows, Git is required for the Code tab to work: [download Git for Windows](https://git-scm.com/downloads/win), install it, and restart the app. If you run into Git errors, ask Claude in the [Cowork tab](https://claude.com/product/cowork) to help troubleshoot your setup.
</Note>

Use the controls at the top of the sidebar to filter sessions by status, project, or environment, and to group sessions by project. To rename a session, click the session title in the toolbar at the top of the active session. To check context usage, see [Check usage](#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](/en/how-claude-code-works#the-context-window) for details on how compaction works.

### 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 and SSH sessions.

### Watch background tasks

The tasks pane shows the background work running inside the current session: subagents, background shell commands, and workflows. Open it from the **Views** menu or drag it into your layout.

Click any entry to see its output in the subagent pane or stop it. To see what other sessions are doing, use the [sidebar](#work-in-parallel-with-sessions).

### Run long-running tasks remotely

For large refactors, test suites, migrations, or other long-running tasks, select **Remote** instead of **Local** when starting a session. Remote sessions run on Anthropic's cloud infrastructure 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 remote sessions from [claude.ai/code](https://claude.ai/code) or the Claude iOS app.

Remote sessions also support multiple repositories. After selecting a cloud environment, click the **+** button next to the repo pill to add additional repositories to the session. Each repo gets its own branch selector. This is useful for tasks that span multiple codebases, such as updating a shared library and its consumers.

See [Claude Code on the web](claude-code-on-the-web-69d53821d4.md) for more on how remote sessions work.

### Continue in another surface

The **Continue in** menu, accessible from the VS Code icon in the bottom right of the session toolbar, lets you move your session to another surface:

* **Claude Code on the Web**: sends your local session to continue running remotely. Desktop pushes your branch, generates a summary of the conversation, and creates a new remote session with the full context. You can then choose to archive the local session or keep it. This requires a clean working tree, and is not available for SSH sessions.
* **Your IDE**: opens your project in a supported IDE at the current working directory.

### Sessions from Dispatch

[Dispatch](https://support.claude.com/en/articles/13947068) is a persistent conversation with Claude that lives in the [Cowork](https://claude.com/product/cowork#dispatch-and-computer-use) tab. You message Dispatch a task, and it decides how to handle it.

A task can end up as a Code session in two ways: you ask for one directly, such as "open a Claude Code session and fix the login bug", or Dispatch decides the task is development work and spawns one on its own. Tasks that typically route to Code include fixing bugs, updating dependencies, running tests, or opening pull requests. Research, document editing, and spreadsheet work stay in Cowork.

Either way, the Code session appears in the Code tab's sidebar with a **Dispatch** badge. You get a push notification on your phone when it finishes or needs your approval.

If you have [computer use](#let-claude-use-your-computer) enabled, Dispatch-spawned Code sessions can use it too. App approvals in those sessions expire after 30 minutes and re-prompt, rather than lasting the full session like regular Code sessions.

For setup, pairing, and Dispatch settings, see the [Dispatch help article](https://support.claude.com/en/articles/13947068). Dispatch requires a Pro or Max plan and is not available on Team or Enterprise plans.

Dispatch is one of several ways to work with Claude when you're away from your terminal. See [Platforms and integrations](/en/platforms#work-when-you-are-away-from-your-terminal) to compare it with Remote Control, Channels, Slack, and scheduled tasks.

## 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.

### Connect external tools

For local and [SSH](#ssh-sessions) sessions, click the **+** button next to the prompt box and select **Connectors** to add integrations like Google Calendar, Slack, GitHub, Linear, Notion, and more. You can add connectors before or during a session. The **+** button is not available in remote sessions, but [routines](routines-3111c7bd3a.md) configure connectors at routine creation time.

To manage or disconnect connectors, go to Settings → Connectors in the desktop app, or select **Manage connectors** from the Connectors menu in the prompt box.

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.

Connectors are [MCP servers](../06-MCP-Tools/mcp-208e742686.md) with a graphical setup flow. Use them for quick integration with supported services. For integrations not listed in Connectors, add MCP servers manually via [settings files](/en/mcp#installing-mcp-servers). You can also [create custom connectors](../14-Connectors/getting-started-with-custom-connectors-using-remote-mcp.md).

### Use skills

[Skills](../08-Plugins-Skills/extend-claude-with-skills-claude-code-docs.md) 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](built-in-commands-claude-code-docs.md), your [custom skills](/en/skills#create-your-first-skill), project skills from your codebase, and skills from any [installed plugins](../08-Plugins-Skills/create-plugins-claude-code-docs.md). Select one and it appears highlighted in the input field. Type your task after it and send as usual.

### Install plugins

[Plugins](../08-Plugins-Skills/create-plugins-claude-code-docs.md) 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.

For local and [SSH](#ssh-sessions) sessions, click the **+** button next to the prompt box and select **Plugins** to see your installed plugins and their skills. To add a plugin, select **Add plugin** from the submenu to open the plugin browser, which shows available plugins from your configured [marketplaces](../08-Plugins-Skills/create-and-distribute-a-plugin-marketplace-claude-code-docs-34a8f3c5e8.md) including the official Anthropic marketplace. Select **Manage plugins** to enable, disable, or uninstall plugins.

Plugins can be scoped 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. Plugins are not available for remote sessions. For the full plugin reference including creating your own plugins, see [plugins](../08-Plugins-Skills/create-plugins-claude-code-docs.md).

### 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 the file manually or click **Edit configuration** in the Preview dropdown to open it in your code editor. The file supports JSON with comments.

```json theme={null}
{
  "version": "0.0.1",
  "configurations": [
    {
      "name": "my-app",
      "runtimeExecutable": "npm",
      "runtimeArgs": ["run", "dev"],
      "port": 3000
    }
  ]
}
```

You can define multiple configurations to run different servers from the same project, such as a frontend and an API. See the [examples](#examples) below.

#### 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 toggle it from the **Preview** dropdown menu.

```json theme={null}
{
  "version": "0.0.1",
  "autoVerify": false,
  "configurations": [...]
}
```

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

Each entry in the `configurations` array accepts the following fields:

| Field               | Type      | Description                                                                                                                                                                                                                                                              |
| ------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `name`              | string    | A unique identifier for this server                                                                                                                                                                                                                                      |
| `runtimeExecutable` | string    | The command to run, such as `npm`, `yarn`, or `node`                                                                                                                                                                                                                     |
| `runtimeArgs`       | string\[] | Arguments passed to `runtimeExecutable`, such as `["run", "dev"]`                                                                                                                                                                                                        |
| `port`              | number    | The port your server listens on. Defaults to 3000                                                                                                                                                                                                                        |
| `cwd`               | string    | Working directory relative to your project root. Defaults to the project root. Use `${workspaceFolder}` to reference the project root explicitly                                                                                                                         |
| `env`               | object    | Additional environment variables as key-value pairs, such as `{ "NODE_ENV": "development" }`. Don't put secrets here since this file is committed to your repo. To pass secrets to your dev server, set them in the [local environment editor](#local-sessions) instead. |
| `autoPort`          | boolean   | How to handle port conflicts. See below                                                                                                                                                                                                                                  |
| `program`           | string    | A script to run with `node`. See [when to use `program` vs `runtimeExecutable`](#when-to-use-program-vs-runtimeexecutable)                                                                                                                                               |
| `args`              | string\[] | Arguments passed to `program`. Only used when `program` is set                                                                                                                                                                                                           |

##### When to use `program` vs `runtimeExecutable`

Use `runtimeExecutable` with `runtimeArgs` to start a dev server through a package manager. For example, `"runtimeExecutable": "npm"` with `"runtimeArgs": ["run", "dev"]` runs `npm run dev`.

Use `program` when you have a standalone script you want to run with `node` directly. For example, `"program": "server.js"` runs `node server.js`. Pass additional flags with `args`.

#### Port conflicts

The `autoPort` field controls what happens when your preferred port is already in use:

* **`true`**: Claude finds and uses a free port automatically. Suitable for most dev servers.
* **`false`**: Claude fails with an error. Use this when your server must use a specific port, such as for OAuth callbacks or CORS allowlists.
* **Not set (default)**: Claude asks whether the server needs that exact port, then saves your answer.

When Claude picks a different port, it passes the assigned port to your server via the `PORT` environment variable.

#### Examples

These configurations show common setups for different project types:

<Tabs>
  <Tab title="Next.js">
    This configuration runs a Next.js app using Yarn on port 3000:

    ```json theme={null}
    {
      "version": "0.0.1",
      "configurations": [
        {
          "name": "web",
          "runtimeExecutable": "yarn",
          "runtimeArgs": ["dev"],
          "port": 3000
        }
      ]
    }
    ```
  </Tab>

  <Tab title="Multiple servers">
    For a monorepo with a frontend and an API server, define multiple configurations. The frontend uses `autoPort: true` so it picks a free port if 3000 is taken, while the API server requires port 8080 exactly:

    ```json theme={null}
    {
      "version": "0.0.1",
      "configurations": [
        {
          "name": "frontend",
          "runtimeExecutable": "npm",
          "runtimeArgs": ["run", "dev"],
          "cwd": "apps/web",
          "port": 3000,
          "autoPort": true
        },
        {
          "name": "api",
          "runtimeExecutable": "npm",
          "runtimeArgs": ["run", "start"],
          "cwd": "server",
          "port": 8080,
          "env": { "NODE_ENV": "development" },
          "autoPort": false
        }
      ]
    }
    ```
  </Tab>

  <Tab title="Node.js script">
    To run a Node.js script directly instead of using a package manager command, use the `program` field:

    ```json theme={null}
    {
      "version": "0.0.1",
      "configurations": [
        {
          "name": "server",
          "program": "server.js",
          "args": ["--verbose"],
          "port": 4000
        }
      ]
    }
    ```
  </Tab>
</Tabs>

## Environment configuration

The environment you pick when [starting a session](#start-a-session) determines where Claude executes and how you connect:

* **Local**: runs on your machine with direct access to your files
* **Remote**: runs on Anthropic's cloud infrastructure. Sessions continue even if you close the app.
* **SSH**: runs on a remote machine you connect to over SSH, such as your own servers, cloud VMs, or dev containers

### Local sessions

The desktop app does not always inherit your full shell environment. On macOS, when you launch the app from the Dock or Finder, it reads your shell profile, such as `~/.zshrc` or `~/.bashrc`, to extract `PATH` and a fixed set of Claude Code variables, but other variables you export there are not picked up. On Windows, the app inherits user and system environment variables but does not read PowerShell profiles.

To set environment variables for local sessions and dev servers on any platform, open the environment dropdown in the prompt box, hover over **Local**, and click the gear icon to open the local environment editor. Variables you save here are stored encrypted on your machine and apply to every local session and preview server you start. You can also add variables to the `env` key in your `~/.claude/settings.json` file, though these reach Claude sessions only and not dev servers. See [environment variables](env-vars-5c624d392b.md) for the full list of supported variables.

[Extended thinking](/en/common-workflows#use-extended-thinking-thinking-mode) is enabled by default, which improves performance on complex reasoning tasks but uses additional tokens. To disable thinking entirely, set `MAX_THINKING_TOKENS` to `0` in the local environment editor. On models with [adaptive reasoning](/en/model-config#adjust-effort-level), any other `MAX_THINKING_TOKENS` value is ignored 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; Opus 4.7 always uses adaptive reasoning and has no fixed-budget mode.

### Remote sessions

Remote sessions continue in the background even if you close the app. Usage counts toward your [subscription plan limits](../17-Billing-Plans/manage-costs-effectively-claude-code-docs-7c26178a4f.md) with no separate compute charges.

You can create custom cloud environments with different network access levels and environment variables. Select the environment dropdown when starting a remote session and choose **Add environment**. See [the cloud environment](/en/claude-code-on-the-web#the-cloud-environment) for details on configuring network access and environment variables.

### 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.

To add an SSH connection, click the environment dropdown before starting a session and select **+ Add SSH connection**. The dialog asks for:

* **Name**: a friendly label for this connection
* **SSH Host**: `user@hostname` or a host defined in `~/.ssh/config`
* **SSH Port**: defaults to 22 if left empty, or uses the port from your SSH config
* **Identity File**: path to your private key, such as `~/.ssh/id_rsa`. Leave empty to use the default key or your SSH config.

Once added, the connection appears in the environment dropdown. Select it to start a session on that machine. Claude runs on the remote machine with access to its files and tools.

The remote machine must run Linux or macOS. 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.

#### Pre-configure SSH connections for your team

Administrators can distribute SSH connections to team members by adding `sshConfigs` to a [managed settings](/en/settings#settings-precedence) file. Connections defined this way appear in each user's environment dropdown automatically and are shown as managed, so users can select them but cannot edit or delete them in the app.

The following example pre-configures a single connection that opens in `~/projects` on the remote host:

```json theme={null}
{
  "sshConfigs": [
    {
      "id": "shared-dev-vm",
      "name": "Shared Dev VM",
      "sshHost": "user@dev.example.com",
      "sshPort": 22,
      "sshIdentityFile": "~/.ssh/id_ed25519",
      "startDirectory": "~/projects"
    }
  ]
}
```

Each entry requires `id`, `name`, and `sshHost`. The `sshPort`, `sshIdentityFile`, and `startDirectory` fields are optional. Users can also add `sshConfigs` to their own `~/.claude/settings.json`, which is where connections added through the dialog are stored.

## 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

These settings are configured through the [admin settings console](https://claude.ai/admin-settings/claude-code):

* **Code in the desktop**: control whether users in your organization can access Claude Code in the desktop app
* **Code in the web**: enable or disable [web sessions](claude-code-on-the-web-69d53821d4.md) for your organization
* **Remote Control**: enable or disable [Remote Control](continue-local-sessions-from-any-device-with-remote-control-claude-code-docs-c1c03fd914.md) for your organization
* **Disable Bypass permissions mode**: prevent users in your organization from enabling bypass permissions mode

### Managed settings

Managed settings override project and user settings and apply when Desktop spawns CLI sessions. You can set these keys in your organization's [managed settings](/en/settings#settings-precedence) file or push them remotely through the admin console.

| Key                                        | Description                                                                                                                                                                                   |
| ------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `permissions.disableBypassPermissionsMode` | set to `"disable"` to prevent users from enabling Bypass permissions mode.                                                                                                                    |
| `disableAutoMode`                          | set to `"disable"` to prevent users from enabling [Auto](/en/permission-modes#eliminate-prompts-with-auto-mode) mode. Removes Auto from the mode selector. Also accepted under `permissions`. |
| `autoMode`                                 | customize what the auto mode classifier trusts and blocks across your organization. See [Configure auto mode](auto-mode-config-f0dacf5866.md).                                                          |
| `sshConfigs`                               | pre-configure [SSH connections](#pre-configure-ssh-connections-for-your-team) that appear in the environment dropdown. Users cannot edit or delete managed connections.                       |

A managed settings file deployed to disk on each machine applies to Desktop sessions. Managed settings pushed remotely through the admin console currently reach CLI and IDE sessions only, so for Desktop deployments either distribute the file via MDM or use the [admin console controls](#admin-console-controls) above.

`permissions.disableBypassPermissionsMode` and `disableAutoMode` also work in user and project settings, but placing them in managed settings prevents users from overriding them. `autoMode` is read from user settings, `.claude/settings.local.json`, and managed settings, but not from the checked-in `.claude/settings.json`: a cloned repo cannot inject its own classifier rules. For the complete list of managed-only settings including `allowManagedPermissionRulesOnly` and `allowManagedHooksOnly`, see [managed-only settings](/en/permissions#managed-only-settings).

### Device management policies

IT teams can manage the desktop app through MDM on macOS or group policy on Windows. Available policies include enabling or disabling the Claude Code feature, controlling auto-updates, and setting a custom deployment URL.

* **macOS**: configure via `com.anthropic.Claude` preference domain using tools like Jamf or Kandji
* **Windows**: configure via registry at `SOFTWARE\Policies\Claude`

### Authentication and SSO

Enterprise organizations can require SSO for all users. See [authentication](../13-Enterprise-Admin/authentication-claude-code-docs-2c6ada8385.md) for plan-level details and [Setting up SSO](../21-Account-Support/setting-up-single-sign-on-sso.md) for SAML and OIDC configuration.

### Data handling

Claude Code processes your code locally in local sessions or on Anthropic's cloud infrastructure in remote sessions. Conversations and code context are sent to Anthropic's API for processing. See [data handling](../22-Safety-Policy/data-usage-claude-code-docs-06b2864aaa.md) for details on data retention, privacy, and compliance.

### Deployment

Desktop can be distributed through enterprise deployment tools:

* **macOS**: distribute via MDM such as Jamf or Kandji using the `.dmg` installer
* **Windows**: deploy via MSIX package or `.exe` installer. See [Deploy Claude Desktop for Windows](https://support.claude.com/en/articles/12622703-deploy-claude-desktop-for-windows) for enterprise deployment options including silent installation

For network configuration such as proxy settings, firewall allowlisting, and LLM gateways, see [network configuration](enterprise-network-configuration-claude-code-docs.md).

For the full enterprise configuration reference, see the [enterprise configuration guide](../13-Enterprise-Admin/enterprise-configuration.md).

## 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 maintains separate session history, but 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 Windows only.

<Tip>
  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.
</Tip>

### 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.

| CLI                                   | Desktop equivalent                                                                                                                       |
| ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `--model sonnet`                      | Model dropdown next to the send button                                                                                                   |
| `--resume`, `--continue`              | Click a session in the sidebar                                                                                                           |
| `--permission-mode`                   | Mode selector next to the send button                                                                                                    |
| `--dangerously-skip-permissions`      | Bypass permissions mode. Enable in Settings → Claude Code → "Allow bypass permissions mode". Enterprise admins can disable this setting. |
| `--add-dir`                           | Add multiple repos with the **+** button in remote sessions                                                                              |
| `--allowedTools`, `--disallowedTools` | No per-session equivalent. Permission rules in [settings files](claude-code-settings-claude-code-docs-d4420b4b52.md) still apply.                                               |
| `--verbose`                           | [Verbose view mode](#switch-view-modes) in the Transcript view dropdown                                                                  |
| `--print`, `--output-format`          | Not available. Desktop is interactive only.                                                                                              |
| `ANTHROPIC_MODEL` env var             | Model dropdown next to the send button                                                                                                   |
| `MAX_THINKING_TOKENS` env var         | Set in the local environment editor. See [environment configuration](#environment-configuration).                                        |

### Shared configuration

Desktop and CLI read the same configuration files, so your setup carries over:

* **[CLAUDE.md](how-claude-remembers-your-project-claude-code-docs-f1c064262d.md)** and `CLAUDE.local.md` files in your project are used by both
* **[MCP servers](../06-MCP-Tools/mcp-208e742686.md)** configured in `~/.claude.json` or `.mcp.json` work in both
* **[Hooks](../07-Hooks/hooks-9168ed62a4.md)** and **[skills](../08-Plugins-Skills/extend-claude-with-skills-claude-code-docs.md)** defined in settings apply to both
* **[Settings](claude-code-settings-claude-code-docs-d4420b4b52.md)** in `~/.claude.json` and `~/.claude/settings.json` are shared. Permission rules, allowed tools, and other settings in `settings.json` apply to Desktop sessions.
* **Models**: Sonnet, Opus, and Haiku are available in both. In Desktop, select the model from the dropdown next to the send button. You can change the model mid-session from the same dropdown.

<Note>
  **MCP servers: desktop chat app vs Claude Code**: MCP servers configured for the Claude Desktop chat app in `claude_desktop_config.json` are separate from Claude Code and will not appear in the Code tab. To use MCP servers in Claude Code, configure them in `~/.claude.json` or your project's `.mcp.json` file. See [MCP configuration](/en/mcp#installing-mcp-servers) for details.
</Note>

### Feature comparison

This table compares core capabilities between the CLI and Desktop. For a full list of CLI flags, see the [CLI reference](cli-reference-7bb98e3312.md).

| Feature                                               | CLI                                                       | Desktop                                                                                                                                                                                                               |
| ----------------------------------------------------- | --------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Permission modes                                      | All modes including `dontAsk`                             | Ask permissions, Auto accept edits, Plan mode, Auto, and Bypass permissions via Settings                                                                                                                              |
| `--dangerously-skip-permissions`                      | CLI flag                                                  | Bypass permissions mode. Enable in Settings → Claude Code → "Allow bypass permissions mode"                                                                                                                           |
| [Third-party providers](enterprise-deployment-overview-claude-code-docs-6eae0ecba2.md) | Bedrock, Vertex, Foundry                                  | Anthropic's API by default. Enterprise deployments can configure Vertex AI and gateway providers. See the [enterprise configuration guide](../13-Enterprise-Admin/enterprise-configuration.md). |
| [MCP servers](../06-MCP-Tools/mcp-208e742686.md)                                | Configure in settings files                               | Connectors UI for local and SSH sessions, or settings files                                                                                                                                                           |
| [Plugins](../08-Plugins-Skills/create-plugins-claude-code-docs.md)                                | `/plugin` command                                         | Plugin manager UI                                                                                                                                                                                                     |
| @mention files                                        | Text-based                                                | With autocomplete; local and SSH sessions only                                                                                                                                                                        |
| File attachments                                      | Not available                                             | Images, PDFs                                                                                                                                                                                                          |
| Session isolation                                     | [`--worktree`](cli-reference-7bb98e3312.md) flag                    | Automatic worktrees                                                                                                                                                                                                   |
| Multiple sessions                                     | Separate terminals                                        | Sidebar tabs                                                                                                                                                                                                          |
| Recurring tasks                                       | Cron jobs, CI pipelines                                   | [Scheduled tasks](../16-Mobile-Desktop/desktop-scheduled-tasks.md)                                                                                                                                                                        |
| Computer use                                          | [Enable via `/mcp`](computer-use-427032da98.md) on macOS            | [App and screen control](#let-claude-use-your-computer) on macOS and Windows                                                                                                                                          |
| Dispatch integration                                  | Not available                                             | [Dispatch sessions](#sessions-from-dispatch) in the sidebar                                                                                                                                                           |
| Scripting and automation                              | [`--print`](cli-reference-7bb98e3312.md), [Agent SDK](headless-b99e3140ec.md) | Not available                                                                                                                                                                                                         |

### What's not available in Desktop

The following features are only available in the CLI or VS Code extension:

* **Third-party providers**: Desktop connects to Anthropic's API by default. Enterprise deployments can configure Vertex AI and gateway providers via [managed settings](../13-Enterprise-Admin/enterprise-configuration.md). For Bedrock or Foundry, use the [CLI](../01-Getting-Started/quickstart-claude-code-docs-a21b84bdea.md).
* **Linux**: the desktop app is available on macOS and Windows only.
* **Inline code suggestions**: Desktop does not provide autocomplete-style suggestions. It works through conversational prompts and explicit code changes.
* **Agent teams**: multi-agent orchestration is available via the [CLI](../09-Agents-Patterns/agent-teams-e29da6ed1b.md) and [Agent SDK](headless-b99e3140ec.md), not in Desktop.

## 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](errors-8648349cb4.md). Those errors and their fixes are the same across the CLI, desktop, and web.

### Check your version

To see which version of the desktop app you're running:

* **macOS**: click **Claude** in the menu bar, then **About Claude**
* **Windows**: click **Help**, then **About**

Click the version number to copy it to your clipboard.

### 403 or authentication errors in the Code tab

If you see `Error 403: Forbidden` or other authentication failures when using the Code tab:

1. Sign out and back in from the app menu. This is the most common fix.
2. Verify you have an active paid subscription: Pro, Max, Team, or Enterprise.
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

If the app opens but shows a blank or unresponsive screen:

1. Restart the app.
2. Check for pending updates. The app auto-updates on launch.
3. On Windows, check Event Viewer for crash logs under **Windows Logs → Application**.

### "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

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

On Windows, Git is required for the Code tab to start local sessions. If you see "Git is required," install [Git for Windows](https://git-scm.com/downloads/win) and restart 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

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.

### 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

* **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

Remote sessions can create branches that don't exist on your local machine. Click the branch name in the session toolbar to copy it, then fetch it locally:

```bash theme={null}
git fetch origin <branch-name>
git checkout <branch-name>
```

### Still stuck?

* Search or file a bug on [GitHub Issues](https://github.com/anthropics/claude-code/issues)
* Visit the [Claude support center](https://support.claude.com/)

When filing a bug, include your desktop app version, your operating system, the exact error message, and relevant logs. On macOS, check Console.app. On Windows, check Event Viewer → Windows Logs → Application.


---
## desktop-scheduled-tasks-eea8d1a9c8.md

> ## Documentation Index
> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Schedule recurring tasks in Claude Code Desktop

> Set up scheduled tasks in Claude Code Desktop to run Claude automatically on a recurring basis for daily code reviews, dependency audits, or morning briefings.

Scheduled tasks start a new session automatically at a time and frequency you choose. Use them for recurring work like daily code reviews, dependency update checks, or morning briefings that pull from your calendar and inbox.

The Desktop app's **Routines** page lets you create both local scheduled tasks and remote [routines](routines-3111c7bd3a.md). A local task runs on your machine with direct access to your files and tools, but only fires while the app is open and your computer is awake. A remote routine runs on Anthropic-managed cloud infrastructure even when your computer is off, and can also fire on API calls or GitHub events. This page covers local scheduled tasks; for remote routines and their trigger options, see [Routines](routines-3111c7bd3a.md).

## Compare scheduling options

Claude Code offers three ways to schedule recurring or one-off work:

|                            | [Cloud](routines-3111c7bd3a.md)          | [Desktop](../16-Mobile-Desktop/desktop-scheduled-tasks.md) | [`/loop`](run-prompts-on-a-schedule-claude-code-docs.md)      |
| :------------------------- | :----------------------------- | :------------------------------------- | :---------------------------------- |
| Runs on                    | Anthropic cloud                | Your machine                           | Your machine                        |
| Requires machine on        | No                             | Yes                                    | Yes                                 |
| Requires open session      | No                             | No                                     | Yes                                 |
| Persistent across restarts | Yes                            | Yes                                    | Restored on `--resume` if unexpired |
| Access to local files      | No (fresh clone)               | Yes                                    | Yes                                 |
| MCP servers                | Connectors configured per task | [Config files](../06-MCP-Tools/mcp-208e742686.md) and connectors | Inherits from session               |
| Permission prompts         | No (runs autonomously)         | Configurable per task                  | Inherits from session               |
| Customizable schedule      | Via `/schedule` in the CLI     | Yes                                    | Yes                                 |
| Minimum interval           | 1 hour                         | 1 minute                               | 1 minute                            |

<Tip>
  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.
</Tip>

<Note>
  By default, scheduled tasks run against whatever state your working directory is in, including uncommitted changes. Enable the worktree toggle when creating the task to give each run its own isolated Git worktree, the same way [parallel sessions](/en/desktop#work-in-parallel-with-sessions) work.
</Note>

## Create a scheduled task

Click **Routines** in the sidebar, then click **New routine** and choose **Local**. Configure these fields:

| Field        | Description                                                                                                                                                                                                                                                                    |
| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Name         | Identifier for the task. Converted to lowercase kebab-case and used as the folder name on disk. Must be unique across your tasks.                                                                                                                                              |
| Description  | Short summary shown in the task list.                                                                                                                                                                                                                                          |
| Instructions | What Claude should do when the task runs. Write this the same way you'd write any message in the prompt box. The instructions input includes pickers for the permission mode and model, and below it you select the working folder and whether to run in an isolated worktree. |
| Schedule     | How often the task runs. See [schedule options](#schedule-options) below.                                                                                                                                                                                                      |

A folder is required before you can save the task. If you haven't trusted that folder yet, Desktop prompts you to trust it before saving.

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, and "remind me at 3pm tomorrow to check the deploy" creates a one-time task that disables itself after it fires.

## Schedule options

Pick a preset from the Schedule control:

* **Manual**: no schedule, only runs when you click **Run now**. Useful for saving a prompt you trigger on demand
* **Hourly**: runs every hour
* **Daily**: shows a time picker, defaults to 9:00 AM local time
* **Weekdays**: same as Daily but skips Saturday and Sunday
* **Weekly**: shows a time picker and a day picker

For intervals the picker doesn't offer, such as every 15 minutes, the first of each month, or a single run at a specific future time, ask Claude in any Desktop session to set the schedule. Use plain language; for example, "schedule a task to run all the tests every 6 hours."

## How scheduled tasks run

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.

When a task fires, you get a desktop notification and a new session appears under a **Scheduled** section in the sidebar. Open it to see what Claude did, review changes, or respond to permission prompts. The session works like any other: Claude can edit files, run commands, create commits, and open pull requests.

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, enable **Keep computer awake** in Settings under **Desktop app → General**. 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 remote [routine](routines-3111c7bd3a.md) instead.

## 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 just post a summary of what was missed."

## Permissions for scheduled tasks

Each task has its own permission mode, which you set when creating or editing the task. Allow rules from `~/.claude/settings.json` also apply to scheduled task sessions. If a task runs in Ask mode and needs to run a tool it doesn't have permission for, the run stalls until you approve it. The session stays open in the sidebar so you can answer later.

To avoid stalls, click **Run now** after creating a task, watch for permission prompts, and select "always allow" for each one. Future runs of that task auto-approve the same tools without prompting. You can review and revoke these approvals from the task's detail page.

## Manage scheduled tasks

Click a task in the **Routines** list to open its detail page. From here you can:

* **Run now**: start the task immediately without waiting for the next scheduled time
* **Status**: toggle between Active and Paused to pause or resume scheduled runs without deleting the task
* **Edit**: change the instructions, schedule, folder, or other settings
* **Review history**: see every past run, including skipped runs. Hover a skipped entry to see why: your computer was asleep, the previous run was still in progress, or other scheduled tasks were already running. Click **Show more** to load older entries.
* **Review allowed permissions**: see and revoke saved tool approvals for this task from the **Always allowed** panel
* **Delete**: remove the task and archive all sessions it created

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 edit a task's prompt on disk, open `~/.claude/scheduled-tasks/<task-name>/SKILL.md` (or under [`CLAUDE_CONFIG_DIR`](env-vars-5c624d392b.md) 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.

## Related resources

* [Routines](routines-3111c7bd3a.md): run tasks on Anthropic-managed infrastructure on a schedule, via API call, or in response to GitHub events, even when your computer is off
* [Run prompts on a schedule](run-prompts-on-a-schedule-claude-code-docs.md): session-scoped scheduling with `/loop` in the CLI
* [Claude Code GitHub Actions](claude-code-github-actions-claude-code-docs-0d633fbd8a.md): run Claude on a schedule in CI instead of on your machine
* [Use Claude Code Desktop](../16-Mobile-Desktop/desktop.md): the full Desktop app guide


---
## devcontainer-38ed6ca20d.md

> ## Documentation Index
> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Development containers

> Learn about the Claude Code development container for teams that need consistent, secure environments.

The reference [devcontainer setup](https://github.com/anthropics/claude-code/tree/main/.devcontainer) and associated [Dockerfile](https://github.com/anthropics/claude-code/blob/main/.devcontainer/Dockerfile) offer a preconfigured development container that you can use as is, or customize for your needs. This devcontainer works with the Visual Studio Code [Dev Containers extension](https://code.visualstudio.com/docs/devcontainers/containers) and similar tools.

The container's enhanced security measures (isolation and firewall rules) allow you to run `claude --dangerously-skip-permissions` to bypass permission prompts for unattended operation.

<Warning>
  While the devcontainer provides substantial protections, no system is completely immune to all attacks.
  When executed with `--dangerously-skip-permissions`, devcontainers don't prevent a malicious project from exfiltrating anything accessible in the devcontainer including Claude Code credentials.
  We recommend only using devcontainers when developing with trusted repositories.
  Always maintain good security practices and monitor Claude's activities.
</Warning>

## Key features

* **Production-ready Node.js**: Built on Node.js 20 with essential development dependencies
* **Security by design**: Custom firewall restricting network access to only necessary services
* **Developer-friendly tools**: Includes git, ZSH with productivity enhancements, fzf, and more
* **Seamless VS Code integration**: Pre-configured extensions and optimized settings
* **Session persistence**: Preserves command history and configurations between container restarts
* **Works everywhere**: Compatible with macOS, Windows, and Linux development environments

## Getting started in 4 steps

1. Install VS Code and the [Dev Containers extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers)
2. Clone the [Claude Code reference implementation](https://github.com/anthropics/claude-code/tree/main/.devcontainer) repository
3. Open the repository in VS Code
4. When prompted, click "Reopen in Container" (or use Command Palette: Cmd+Shift+P → "Dev Containers: Reopen in Container")

Once the container finishes building, open a terminal in VS Code with `` Ctrl+` `` and run `claude` to authenticate and start your first session. The container has Claude Code preinstalled, so you can begin working immediately. Your project files are mounted into the container, and any code Claude writes appears in your local repository.

## Configuration breakdown

The devcontainer setup consists of three primary components:

* [**devcontainer.json**](https://github.com/anthropics/claude-code/blob/main/.devcontainer/devcontainer.json): Controls container settings, extensions, and volume mounts
* [**Dockerfile**](https://github.com/anthropics/claude-code/blob/main/.devcontainer/Dockerfile): Defines the container image and installed tools
* [**init-firewall.sh**](https://github.com/anthropics/claude-code/blob/main/.devcontainer/init-firewall.sh): Establishes network security rules

## Security features

The container implements a multi-layered security approach with its firewall configuration:

* **Precise access control**: Restricts outbound connections to whitelisted domains only (npm registry, GitHub, Claude API, etc.)
* **Allowed outbound connections**: The firewall permits outbound DNS and SSH connections
* **Default-deny policy**: Blocks all other external network access
* **Startup verification**: Validates firewall rules when the container initializes
* **Isolation**: Creates a secure development environment separated from your main system

## Customization options

The devcontainer configuration is designed to be adaptable to your needs:

* Add or remove VS Code extensions based on your workflow
* Modify resource allocations for different hardware environments
* Adjust network access permissions
* Customize shell configurations and developer tooling

## Example use cases

### Secure client work

Use devcontainers to isolate different client projects, ensuring code and credentials never mix between environments.

### Team onboarding

New team members can get a fully configured development environment in minutes, with all necessary tools and settings pre-installed.

### Consistent CI/CD environments

Mirror your devcontainer configuration in CI/CD pipelines to ensure development and production environments match.

## Related resources

* [VS Code devcontainers documentation](https://code.visualstudio.com/docs/devcontainers/containers)
* [Claude Code security best practices](../22-Safety-Policy/security-claude-code-docs-7538e94c51.md)
* [Enterprise network configuration](enterprise-network-configuration-claude-code-docs.md)


---
## devcontainer.md

> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Development containers

> Learn about the Claude Code development container for teams that need consistent, secure environments.

The reference [devcontainer setup](https://github.com/anthropics/claude-code/tree/main/.devcontainer) and associated [Dockerfile](https://github.com/anthropics/claude-code/blob/main/.devcontainer/Dockerfile) offer a preconfigured development container that you can use as is, or customize for your needs. This devcontainer works with the Visual Studio Code [Dev Containers extension](https://code.visualstudio.com/docs/devcontainers/containers) and similar tools.

The container's enhanced security measures (isolation and firewall rules) allow you to run `claude --dangerously-skip-permissions` to bypass permission prompts for unattended operation.

<Warning>
  While the devcontainer provides substantial protections, no system is completely immune to all attacks.
  When executed with `--dangerously-skip-permissions`, devcontainers don't prevent a malicious project from exfiltrating anything accessible in the devcontainer including Claude Code credentials.
  We recommend only using devcontainers when developing with trusted repositories.
  Always maintain good security practices and monitor Claude's activities.
</Warning>

## Key features

* **Production-ready Node.js**: Built on Node.js 20 with essential development dependencies
* **Security by design**: Custom firewall restricting network access to only necessary services
* **Developer-friendly tools**: Includes git, ZSH with productivity enhancements, fzf, and more
* **Seamless VS Code integration**: Pre-configured extensions and optimized settings
* **Session persistence**: Preserves command history and configurations between container restarts
* **Works everywhere**: Compatible with macOS, Windows, and Linux development environments

## Getting started in 4 steps

1. Install VS Code and the Remote - Containers extension
2. Clone the [Claude Code reference implementation](https://github.com/anthropics/claude-code/tree/main/.devcontainer) repository
3. Open the repository in VS Code
4. When prompted, click "Reopen in Container" (or use Command Palette: Cmd+Shift+P → "Remote-Containers: Reopen in Container")

## Configuration breakdown

The devcontainer setup consists of three primary components:

* [**devcontainer.json**](https://github.com/anthropics/claude-code/blob/main/.devcontainer/devcontainer.json): Controls container settings, extensions, and volume mounts
* [**Dockerfile**](https://github.com/anthropics/claude-code/blob/main/.devcontainer/Dockerfile): Defines the container image and installed tools
* [**init-firewall.sh**](https://github.com/anthropics/claude-code/blob/main/.devcontainer/init-firewall.sh): Establishes network security rules

## Security features

The container implements a multi-layered security approach with its firewall configuration:

* **Precise access control**: Restricts outbound connections to whitelisted domains only (npm registry, GitHub, Claude API, etc.)
* **Allowed outbound connections**: The firewall permits outbound DNS and SSH connections
* **Default-deny policy**: Blocks all other external network access
* **Startup verification**: Validates firewall rules when the container initializes
* **Isolation**: Creates a secure development environment separated from your main system

## Customization options

The devcontainer configuration is designed to be adaptable to your needs:

* Add or remove VS Code extensions based on your workflow
* Modify resource allocations for different hardware environments
* Adjust network access permissions
* Customize shell configurations and developer tooling

## Example use cases

### Secure client work

Use devcontainers to isolate different client projects, ensuring code and credentials never mix between environments.

### Team onboarding

New team members can get a fully configured development environment in minutes, with all necessary tools and settings pre-installed.

### Consistent CI/CD environments

Mirror your devcontainer configuration in CI/CD pipelines to ensure development and production environments match.

## Related resources

* [VS Code devcontainers documentation](https://code.visualstudio.com/docs/devcontainers/containers)
* [Claude Code security best practices](security-claude-code-docs.md)
* [Enterprise network configuration](enterprise-network-configuration-claude-code-docs.md)


---
## development-containers-claude-code-docs-2e550b9d86.md

# Development containers


Run Claude Code inside a dev container for consistent, isolated environments across your team.


> ## Documentation Index
>
> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt>
>
> Use this file to discover all available pages before exploring further.

A [development container](https://containers.dev/), or dev container, lets you define an identical, isolated environment that every engineer on your team can run. With Claude Code installed in that container, commands Claude runs execute inside it rather than on the host machine, while edits to your project files appear in your local repository as you work. This page covers [installing Claude Code in a dev container](#add-claude-code-to-your-dev-container) and the configuration topics that follow. Each topic is self-contained, so jump to the ones that match what you need to set up:

- [Persist authentication and settings across rebuilds](#persist-authentication-and-settings-across-rebuilds)
- [Enforce organization policy](#enforce-organization-policy)
- [Restrict network egress](#restrict-network-egress)
- [Run without permission prompts](#run-without-permission-prompts)

While the dev container provides substantial protections, no system is completely immune to all attacks. When executed with `--dangerously-skip-permissions`, dev containers do not prevent a malicious project from exfiltrating anything accessible inside the container, including the Claude Code credentials stored in [`~/.claude`](/docs/en/claude-directory). Only use dev containers when developing with trusted repositories, and monitor Claude’s activities. Avoid mounting host secrets such as `~/.ssh` or cloud credential files into the container; prefer repository-scoped or short-lived tokens.

How dev containers work with your editor

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

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.

New to dev containers? The [VS Code Dev Containers tutorial](https://code.visualstudio.com/docs/devcontainers/tutorial) walks through installing Docker, the extension, and opening your first container. For a fuller hardened example with a firewall and persistent volumes, see [Try the reference container](#try-the-reference-container).

1


Create or update devcontainer.json

Save the following as `.devcontainer/devcontainer.json` in your repository, or add the `features` block to your existing file.The version tag at the end, such as `:1.0`, pins the feature’s install script, not the Claude Code release. The feature installs the latest Claude Code, and Claude Code auto-updates itself inside the container by default.To pin the CLI version or disable auto-update, see [Enforce organization policy](#enforce-organization-policy).

.devcontainer/devcontainer.json

```python
{
  "image": "mcr.microsoft.com/devcontainers/base:ubuntu",
  "features": {
    "ghcr.io/anthropics/devcontainer-features/claude-code:1.0": {}
  }
}
```

Replace the `image` line with your project’s base image or remove it if your existing file uses a Dockerfile.

2


Rebuild the container

Open the VS Code Command Palette with `Cmd+Shift+P` on Mac or `Ctrl+Shift+P` on Windows and Linux, and run **Dev Containers: Rebuild Container**.For other tools, follow that tool’s rebuild action: see [rebuilding in GitHub Codespaces](https://docs.github.com/en/codespaces/developing-in-a-codespace/rebuilding-the-container-in-a-codespace), the [Dev Containers CLI](https://github.com/devcontainers/cli), or your IDE’s dev container documentation.

3


Sign in to Claude Code

Open a terminal in the rebuilt container and run `claude`, then follow the authentication prompt.

What you see at the authentication prompt depends on your provider:

- **Anthropic**: sign in through a browser with your Claude or Anthropic Console account
- **[Amazon Bedrock, Google Vertex AI, or Microsoft Foundry](/docs/en/third-party-integrations)**: Claude Code uses your cloud provider credentials, with no browser prompt

For cloud providers, pass credentials into the container as environment variables through `containerEnv`, a Codespaces secret, or your cloud’s workload identity rather than mounting credential files from the host. See [Amazon Bedrock](/docs/en/amazon-bedrock), [Google Vertex AI](/docs/en/google-vertex-ai), or [Microsoft Foundry](/docs/en/microsoft-foundry) for the credential chain Claude Code reads. See [Choose your API provider](/docs/en/admin-setup#choose-your-api-provider) to decide which path fits your organization.

If the browser sign-in completes but the callback never reaches the container, copy the code shown in the browser and paste it at the `Paste code here if prompted` prompt in the terminal. This can happen when the editor’s port forwarding doesn’t route the localhost callback.


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 [`~/.claude`](/docs/en/claude-directory). Mount a named volume at that path to keep this state across rebuilds. The following example mounts a volume at the home directory of the `node` user:

devcontainer.json

```python
"mounts": [
  "source=claude-code-config,target=/home/node/.claude,type=volume"
]
```

Replace `/home/node` with the home directory of your container’s `remoteUser`. If you mount the volume somewhere other than `~/.claude`, set [`CLAUDE_CONFIG_DIR`](/docs/en/env-vars) to the mount path so Claude Code reads and writes there. 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 across stopping and starting a codespace, but is still cleared when you rebuild the container, so the volume mount 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 makes secrets available as environment variables inside the container automatically.


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#how-scopes-interact), so values there override anything an engineer sets in `~/.claude` or the project’s `.claude/` directory. Copy the file into place from your Dockerfile:

Dockerfile

```python
RUN mkdir -p /etc/claude-code
COPY managed-settings.json /etc/claude-code/managed-settings.json
```

Because the Dockerfile lives in the repository, anyone with write access can change or remove this step. For policy that engineers cannot bypass by editing repository files, deliver managed settings through [server-managed settings](/docs/en/server-managed-settings) or your MDM instead. See [managed settings files](/docs/en/settings#settings-files) for the available keys and the other delivery paths. To set [environment variables](/docs/en/env-vars) that apply to every Claude Code session in the container, add them to `containerEnv` in your `devcontainer.json`. The following example opts out of telemetry and error reporting and prevents Claude Code from auto-updating after install:

devcontainer.json

```python
"containerEnv": {
  "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1",
  "DISABLE_AUTOUPDATER": "1"
}
```

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` as shown above. 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

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 blocks all outbound traffic except the domains Claude Code and your development tools need. 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

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](#restrict-network-egress) 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#permission-settings).


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.

1


Install prerequisites

Install VS Code and the [Dev Containers extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers).

2


Clone the reference

Clone the [Claude Code repository](https://github.com/anthropics/claude-code) and open it in VS Code.

3


Reopen in container

When prompted, click **Reopen in Container**, or run **Dev Containers: Reopen in Container** from the Command Palette.

4


Start Claude Code

Once the container finishes building, open a terminal with `` Ctrl+` `` and run `claude` to sign in and start your first session.

To use this configuration with your own project, copy the `.devcontainer/` directory into your repository and adjust the Dockerfile for your toolchain, or return to [Add Claude Code to your dev container](#add-claude-code-to-your-dev-container) to add only the feature to a setup you already have. The reference configuration consists of three files. None of them are required when you add Claude Code to your own dev container through the feature, but they show one way to combine the pieces.

| File                                                                                                       | Purpose                                                                       |
|------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------|
| [`devcontainer.json`](https://github.com/anthropics/claude-code/blob/main/.devcontainer/devcontainer.json) | Volume mounts, `runArgs` capabilities, VS Code extensions, and `containerEnv` |
| [`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)   | Blocks all outbound network traffic except the allowed domains                |


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.

- [Set up Claude Code for your organization](/docs/en/admin-setup): choose an authentication provider, decide how policy reaches devices, and plan the rollout
- [Server-managed settings](/docs/en/server-managed-settings): deliver managed policy from the Claude.ai admin console so engineers cannot bypass it by editing repository files
- [Monitor usage and audit activity](/docs/en/monitoring-usage): export OpenTelemetry metrics and review what your team is running
- [Network access requirements](/docs/en/network-config#network-access-requirements): the full domain allowlist for proxies and firewalls
- [Telemetry services and opt-out](/docs/en/data-usage#telemetry-services): what Claude Code sends by default and the environment variables that disable it
- [Explore the `.claude` directory](/docs/en/claude-directory): what the volume mount holds, including credentials, settings, and session history
- [Security model](/docs/en/security): how Claude Code’s permission system, sandboxing, and prompt-injection protections fit together
- [Permission modes](/docs/en/permission-modes): the full range from plan mode to auto mode to bypass, and when to use each


---
## development-containers-claude-code-docs.md

# Development containers


Learn about the Claude Code development container for teams that need consistent, secure environments.


The reference [devcontainer setup](https://github.com/anthropics/claude-code/tree/main/.devcontainer) and associated [Dockerfile](https://github.com/anthropics/claude-code/blob/main/.devcontainer/Dockerfile) offer a preconfigured development container that you can use as is, or customize for your needs. This devcontainer works with the Visual Studio Code [Dev Containers extension](https://code.visualstudio.com/docs/devcontainers/containers) and similar tools. The container’s enhanced security measures (isolation and firewall rules) allow you to run `claude --dangerously-skip-permissions` to bypass permission prompts for unattended operation.

While the devcontainer provides substantial protections, no system is completely immune to all attacks. When executed with `--dangerously-skip-permissions`, devcontainers don’t prevent a malicious project from exfiltrating anything accessible in the devcontainer including Claude Code credentials. We recommend only using devcontainers when developing with trusted repositories. Always maintain good security practices and monitor Claude’s activities.


Key features

- **Production-ready Node.js**: Built on Node.js 20 with essential development dependencies
- **Security by design**: Custom firewall restricting network access to only necessary services
- **Developer-friendly tools**: Includes git, ZSH with productivity enhancements, fzf, and more
- **Seamless VS Code integration**: Pre-configured extensions and optimized settings
- **Session persistence**: Preserves command history and configurations between container restarts
- **Works everywhere**: Compatible with macOS, Windows, and Linux development environments


Getting started in 4 steps

1.  Install VS Code and the [Dev Containers extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers)
2.  Clone the [Claude Code reference implementation](https://github.com/anthropics/claude-code/tree/main/.devcontainer) repository
3.  Open the repository in VS Code
4.  When prompted, click “Reopen in Container” (or use Command Palette: Cmd+Shift+P → “Dev Containers: Reopen in Container”)

Once the container finishes building, open a terminal in VS Code with `` Ctrl+` `` and run `claude` to authenticate and start your first session. The container has Claude Code preinstalled, so you can begin working immediately. Your project files are mounted into the container, and any code Claude writes appears in your local repository.


Configuration breakdown

The devcontainer setup consists of three primary components:

- [**devcontainer.json**](https://github.com/anthropics/claude-code/blob/main/.devcontainer/devcontainer.json): Controls container settings, extensions, and volume mounts
- [**Dockerfile**](https://github.com/anthropics/claude-code/blob/main/.devcontainer/Dockerfile): Defines the container image and installed tools
- [**init-firewall.sh**](https://github.com/anthropics/claude-code/blob/main/.devcontainer/init-firewall.sh): Establishes network security rules


Security features

The container implements a multi-layered security approach with its firewall configuration:

- **Precise access control**: Restricts outbound connections to whitelisted domains only (npm registry, GitHub, Claude API, etc.)
- **Allowed outbound connections**: The firewall permits outbound DNS and SSH connections
- **Default-deny policy**: Blocks all other external network access
- **Startup verification**: Validates firewall rules when the container initializes
- **Isolation**: Creates a secure development environment separated from your main system


Customization options

The devcontainer configuration is designed to be adaptable to your needs:

- Add or remove VS Code extensions based on your workflow
- Modify resource allocations for different hardware environments
- Adjust network access permissions
- Customize shell configurations and developer tooling


Example use cases


Secure client work

Use devcontainers to isolate different client projects, ensuring code and credentials never mix between environments.


Team onboarding

New team members can get a fully configured development environment in minutes, with all necessary tools and settings pre-installed.


Consistent CI/CD environments

Mirror your devcontainer configuration in CI/CD pipelines to ensure development and production environments match.


Related resources

- [VS Code devcontainers documentation](https://code.visualstudio.com/docs/devcontainers/containers)
- [Claude Code security best practices](/docs/en/security)
- [Enterprise network configuration](/docs/en/network-config)


---
## diff.md

# Claude Binary Intel Diff

- New: `/home/zack/claude-binary/2.1.74/2.1.74`
- Old: `/home/zack/.local/share/claude/versions/2.1.72`
- Generated (UTC): `2026-03-12T04:12:21.993635+00:00`

## flags
- added: `5`
- removed: `0`
### added
- `--auto-approve`
- `--kill-after`
- `--preserve-status`
- `--remote-control`
- `--signal`

## internal_flags
- added: `1`
- removed: `0`
### added
- `--remote-control`

## env_vars
- added: `5`
- removed: `1`
### added
- `ANTHROPIC_FOUNDRY_AUTH_TOKEN`
- `ANTHROPIC_UNIX_SOCKET`
- `CLAUDE_CODE_FRAME_TIMING_LOG`
- `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS`
- `CLAUDE_SONNET_4_6`
### removed
- `CLAUDE_CODE_TWO_STAGE_CLASSIFIER`

## domains
- added: `0`
- removed: `0`

## model_ids
- added: `2`
- removed: `0`
### added
- `claude-code-feedback`
- `claude-for-hiring`

## bunfs_paths
- added: `0`
- removed: `0`

## code_tokens
- added: `14`
- removed: `7`
### added
- `tengu_auto_mode_state`
- `tengu_chair_sermon`
- `tengu_compact_failedul`
- `tengu_hawthorn_steeple`
- `tengu_hawthorn_window`
- `tengu_image_resize_fallbackw`
- `tengu_marble_whisper2`
- `tengu_message_level_tool_result_budget_enforced`
- `tengu_orchid_trellis`
- `tengu_pewter_ledger`
- `tengu_tool_empty_result`
- `tengu_tool_result_persisted_message_budget`
- `tengu_voice_recording_completed`
- `tengu_voice_stream_early_retry`
### removed
- `tengu_marble_whisper`
- `tengu_native_version_cleanupk`
- `tengu_output_style_command_inline`
- `tengu_output_style_command_inline_help`
- `tengu_output_style_command_menu`
- `tengu_pdf_page_extractionm`
- `tengu_unexpected_tool_resulti`

## http_methods_with_url_context
- added: `0`
- removed: `0`

## urls
- added: `14`
- removed: `10`
### added
- `http://${w}:${q.port}/sse`
- `http://169.254.169.254${FSD`
- `https://${p}/${x}/${d`
- `https://${q}/${K`
- `https://${S}/${h}/${u`
- `https://code.claude.com/docs/en/microsoft-foundryj`
- `https://code.claude.com/docs/en/network-config`
- `https://code.claude.com/docs/en/remote-control`
- `https://example.com/mcp`
- `https://github.com/${fH`
- `https://github.com/${H}/compare/${P}...${z}?quick_pull=1&title=${encodeURIComponent(Xsf)}&body=${encodeURIComponent(Gsf`
- `https://github.com/${MH`
- `https://github.com/${x}/${d`
- `https://login.microsoftonline.com/${fz1}/`
### removed
- `http://${P}:${M.port}/sse`
- `http://169.254.169.254${yhf`
- `https://${h}/${R}/${x`
- `https://${K}/${q`
- `https://${p}/${b}/${d`
- `https://github.com/${_H`
- `https://github.com/${b}/${d`
- `https://github.com/${EH`
- `https://github.com/${H}/compare/${P}...${z}?quick_pull=1&title=${encodeURIComponent(Xa8)}&body=${encodeURIComponent(Ga8`
- `https://login.microsoftonline.com/${nP1}/`



---
## discover-and-install-prebuilt-plugins-through-marketplaces-claude-code-docs.md

# Discover and install prebuilt plugins through marketplaces


Find and install plugins from marketplaces to extend Claude Code with new commands, agents, and capabilities.


Plugins extend Claude Code with skills, agents, hooks, and MCP servers. Plugin marketplaces are catalogs that help you discover and install these extensions without building them yourself. Looking to create and distribute your own marketplace? See [Create and distribute a plugin marketplace](/docs/en/plugin-marketplaces).

## 

How marketplaces work

A marketplace is a catalog of plugins that someone else has created and shared. Using a marketplace is a two-step process:

1

[](#)

Add the marketplace

This registers the catalog with Claude Code so you can browse what’s available. No plugins are installed yet.

2

[](#)

Install individual plugins

Browse the catalog and install the plugins you want.

Think of it like adding an app store: adding the store gives you access to browse its collection, but you still choose which apps to download individually.

## 

Official Anthropic marketplace

The official Anthropic marketplace (`claude-plugins-official`) is automatically available when you start Claude Code. Run `/plugin` and go to the **Discover** tab to browse what’s available. To install a plugin from the official marketplace:

Report incorrect code

Copy


``` shiki
/plugin install plugin-name@claude-plugins-official
```

The official marketplace is maintained by Anthropic. To submit a plugin to the official marketplace, use one of the in-app submission forms:

- **Claude.ai**: [claude.ai/settings/plugins/submit](https://claude.ai/settings/plugins/submit)
- **Console**: [platform.claude.com/plugins/submit](https://platform.claude.com/plugins/submit)

To distribute plugins independently, [create your own marketplace](/docs/en/plugin-marketplaces) and share it with users.

The official marketplace includes several categories of plugins:

### 

Code intelligence

Code intelligence plugins enable Claude Code’s built-in LSP tool, giving Claude the ability to jump to definitions, find references, and see type errors immediately after edits. These plugins configure [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) connections, the same technology that powers VS Code’s code intelligence. These plugins require the language server binary to be installed on your system. If you already have a language server installed, Claude may prompt you to install the corresponding plugin when you open a project.

| Language   | Plugin              | Binary required              |
|:-----------|:--------------------|:-----------------------------|
| C/C++      | `clangd-lsp`        | `clangd`                     |
| C#         | `csharp-lsp`        | `csharp-ls`                  |
| Go         | `gopls-lsp`         | `gopls`                      |
| Java       | `jdtls-lsp`         | `jdtls`                      |
| Kotlin     | `kotlin-lsp`        | `kotlin-language-server`     |
| Lua        | `lua-lsp`           | `lua-language-server`        |
| PHP        | `php-lsp`           | `intelephense`               |
| Python     | `pyright-lsp`       | `pyright-langserver`         |
| Rust       | `rust-analyzer-lsp` | `rust-analyzer`              |
| Swift      | `swift-lsp`         | `sourcekit-lsp`              |
| TypeScript | `typescript-lsp`    | `typescript-language-server` |

You can also [create your own LSP plugin](/docs/en/plugins-reference#lsp-servers) for other languages.

If you see `Executable not found in $PATH` in the `/plugin` Errors tab after installing a plugin, install the required binary from the table above.

#### 

What Claude gains from code intelligence plugins

Once a code intelligence plugin is installed and its language server binary is available, Claude gains two capabilities:

- **Automatic diagnostics**: after every file edit Claude makes, the language server analyzes the changes and reports errors and warnings back automatically. Claude sees type errors, missing imports, and syntax issues without needing to run a compiler or linter. If Claude introduces an error, it notices and fixes the issue in the same turn. This requires no configuration beyond installing the plugin. You can see diagnostics inline by pressing **Ctrl+O** when the “diagnostics found” indicator appears.
- **Code navigation**: Claude can use the language server to jump to definitions, find references, get type info on hover, list symbols, find implementations, and trace call hierarchies. These operations give Claude more precise navigation than grep-based search, though availability may vary by language and environment.

If you run into issues, see [Code intelligence troubleshooting](#code-intelligence-issues).

### 

External integrations

These plugins bundle pre-configured [MCP servers](/docs/en/mcp) so you can connect Claude to external services without manual setup:

- **Source control**: `github`, `gitlab`
- **Project management**: `atlassian` (Jira/Confluence), `asana`, `linear`, `notion`
- **Design**: `figma`
- **Infrastructure**: `vercel`, `firebase`, `supabase`
- **Communication**: `slack`
- **Monitoring**: `sentry`

### 

Development workflows

Plugins that add commands and agents for common development tasks:

- **commit-commands**: Git commit workflows including commit, push, and PR creation
- **pr-review-toolkit**: Specialized agents for reviewing pull requests
- **agent-sdk-dev**: Tools for building with the Claude Agent SDK
- **plugin-dev**: Toolkit for creating your own plugins

### 

Output styles

Customize how Claude responds:

- **explanatory-output-style**: Educational insights about implementation choices
- **learning-output-style**: Interactive learning mode for skill building

## 

Try it: add the demo marketplace

Anthropic also maintains a [demo plugins marketplace](https://github.com/anthropics/claude-code/tree/main/plugins) (`claude-code-plugins`) with example plugins that show what’s possible with the plugin system. Unlike the official marketplace, you need to add this one manually.

1

[](#)

Add the marketplace

From within Claude Code, run the `plugin marketplace add` command for the `anthropics/claude-code` marketplace:

Report incorrect code

Copy


``` shiki
/plugin marketplace add anthropics/claude-code
```

This downloads the marketplace catalog and makes its plugins available to you.

2

[](#)

Browse available plugins

Run `/plugin` to open the plugin manager. This opens a tabbed interface with four tabs you can cycle through using **Tab** (or **Shift+Tab** to go backward):

- **Discover**: browse available plugins from all your marketplaces
- **Installed**: view and manage your installed plugins
- **Marketplaces**: add, remove, or update your added marketplaces
- **Errors**: view any plugin loading errors

Go to the **Discover** tab to see plugins from the marketplace you just added.

3

[](#)

Install a plugin

Select a plugin to view its details, then choose an installation scope:

- **User scope**: install for yourself across all projects
- **Project scope**: install for all collaborators on this repository
- **Local scope**: install for yourself in this repository only

For example, select **commit-commands** (a plugin that adds git workflow commands) and install it to your user scope.You can also install directly from the command line:

Report incorrect code

Copy


``` shiki
/plugin install commit-commands@anthropics-claude-code
```

See [Configuration scopes](/docs/en/settings#configuration-scopes) to learn more about scopes.

4

[](#)

Use your new plugin

After installing, the plugin’s commands are immediately available. Plugin commands are namespaced by the plugin name, so **commit-commands** provides commands like `/commit-commands:commit`.Try it out by making a change to a file and running:

Report incorrect code

Copy


``` shiki
/commit-commands:commit
```

This stages your changes, generates a commit message, and creates the commit.Each plugin works differently. Check the plugin’s description in the **Discover** tab or its homepage to learn what commands and capabilities it provides.

The rest of this guide covers all the ways you can add marketplaces, install plugins, and manage your configuration.

## 

Add marketplaces

Use the `/plugin marketplace add` command to add marketplaces from different sources.

**Shortcuts**: You can use `/plugin market` instead of `/plugin marketplace`, and `rm` instead of `remove`.

- **GitHub repositories**: `owner/repo` format (for example, `anthropics/claude-code`)
- **Git URLs**: any git repository URL (GitLab, Bitbucket, self-hosted)
- **Local paths**: directories or direct paths to `marketplace.json` files
- **Remote URLs**: direct URLs to hosted `marketplace.json` files

### 

Add from GitHub

Add a GitHub repository that contains a `.claude-plugin/marketplace.json` file using the `owner/repo` format—where `owner` is the GitHub username or organization and `repo` is the repository name. For example, `anthropics/claude-code` refers to the `claude-code` repository owned by `anthropics`:

Report incorrect code

Copy


``` shiki
/plugin marketplace add anthropics/claude-code
```

### 

Add from other Git hosts

Add any git repository by providing the full URL. This works with any Git host, including GitLab, Bitbucket, and self-hosted servers: Using HTTPS:

Report incorrect code

Copy


``` shiki
/plugin marketplace add https://gitlab.com/company/plugins.git
```

Using SSH:

Report incorrect code

Copy


``` shiki
/plugin marketplace add [email protected]:company/plugins.git
```

To add a specific branch or tag, append `#` followed by the ref:

Report incorrect code

Copy


``` shiki
/plugin marketplace add https://gitlab.com/company/plugins.git#v1.0.0
```

### 

Add from local paths

Add a local directory that contains a `.claude-plugin/marketplace.json` file:

Report incorrect code

Copy


``` shiki
/plugin marketplace add ./my-marketplace
```

You can also add a direct path to a `marketplace.json` file:

Report incorrect code

Copy


``` shiki
/plugin marketplace add ./path/to/marketplace.json
```

### 

Add from remote URLs

Add a remote `marketplace.json` file via URL:

Report incorrect code

Copy


``` shiki
/plugin marketplace add https://example.com/marketplace.json
```

URL-based marketplaces have some limitations compared to Git-based marketplaces. If you encounter “path not found” errors when installing plugins, see [Troubleshooting](/docs/en/plugin-marketplaces#plugins-with-relative-paths-fail-in-url-based-marketplaces).

## 

Install plugins

Once you’ve added marketplaces, you can install plugins directly (installs to user scope by default):

Report incorrect code

Copy


``` shiki
/plugin install plugin-name@marketplace-name
```

To choose a different [installation scope](/docs/en/settings#configuration-scopes), use the interactive UI: run `/plugin`, go to the **Discover** tab, and press **Enter** on a plugin. You’ll see options for:

- **User scope** (default): install for yourself across all projects
- **Project scope**: install for all collaborators on this repository (adds to `.claude/settings.json`)
- **Local scope**: install for yourself in this repository only (not shared with collaborators)

You may also see plugins with **managed** scope—these are installed by administrators via [managed settings](/docs/en/settings#settings-files) and cannot be modified. Run `/plugin` and go to the **Installed** tab to see your plugins grouped by scope.

Make sure you trust a plugin before installing it. Anthropic does not control what MCP servers, files, or other software are included in plugins and cannot verify that they work as intended. Check each plugin’s homepage for more information.

## 

Manage installed plugins

Run `/plugin` and go to the **Installed** tab to view, enable, disable, or uninstall your plugins. Type to filter the list by plugin name or description. You can also manage plugins with direct commands. Disable a plugin without uninstalling:

Report incorrect code

Copy


``` shiki
/plugin disable plugin-name@marketplace-name
```

Re-enable a disabled plugin:

Report incorrect code

Copy


``` shiki
/plugin enable plugin-name@marketplace-name
```

Completely remove a plugin:

Report incorrect code

Copy


``` shiki
/plugin uninstall plugin-name@marketplace-name
```

The `--scope` option lets you target a specific scope with CLI commands:

Report incorrect code

Copy


``` shiki
claude plugin install formatter@your-org --scope project
claude plugin uninstall formatter@your-org --scope project
```

### 

Apply plugin changes without restarting

When you install, enable, or disable plugins during a session, some changes (like new commands and hooks) take effect immediately. Others, including LSP server updates, require a restart. To activate all pending plugin changes without restarting, run:

Report incorrect code

Copy


``` shiki
/reload-plugins
```

Claude Code reloads all active plugins and reports what was loaded. If any LSP servers were added or updated, it will let you know those require a restart to take effect.

## 

Manage marketplaces

You can manage marketplaces through the interactive `/plugin` interface or with CLI commands.

### 

Use the interactive interface

Run `/plugin` and go to the **Marketplaces** tab to:

- View all your added marketplaces with their sources and status
- Add new marketplaces
- Update marketplace listings to fetch the latest plugins
- Remove marketplaces you no longer need

### 

Use CLI commands

You can also manage marketplaces with direct commands. List all configured marketplaces:

Report incorrect code

Copy


``` shiki
/plugin marketplace list
```

Refresh plugin listings from a marketplace:

Report incorrect code

Copy


``` shiki
/plugin marketplace update marketplace-name
```

Remove a marketplace:

Report incorrect code

Copy


``` shiki
/plugin marketplace remove marketplace-name
```

Removing a marketplace will uninstall any plugins you installed from it.

### 

Configure auto-updates

Claude Code can automatically update marketplaces and their installed plugins at startup. When auto-update is enabled for a marketplace, Claude Code refreshes the marketplace data and updates installed plugins to their latest versions. If any plugins were updated, you’ll see a notification prompting you to run `/reload-plugins`. Toggle auto-update for individual marketplaces through the UI:

1.  Run `/plugin` to open the plugin manager
2.  Select **Marketplaces**
3.  Choose a marketplace from the list
4.  Select **Enable auto-update** or **Disable auto-update**

Official Anthropic marketplaces have auto-update enabled by default. Third-party and local development marketplaces have auto-update disabled by default. To disable all automatic updates entirely for both Claude Code and all plugins, set the `DISABLE_AUTOUPDATER` environment variable. See [Auto updates](/docs/en/setup#auto-updates) for details. To keep plugin auto-updates enabled while disabling Claude Code auto-updates, set `FORCE_AUTOUPDATE_PLUGINS=true` along with `DISABLE_AUTOUPDATER`:

Report incorrect code

Copy


``` shiki
export DISABLE_AUTOUPDATER=true
export FORCE_AUTOUPDATE_PLUGINS=true
```

This is useful when you want to manage Claude Code updates manually but still receive automatic plugin updates.

## 

Configure team marketplaces

Team admins can set up automatic marketplace installation for projects by adding marketplace configuration to `.claude/settings.json`. When team members trust the repository folder, Claude Code prompts them to install these marketplaces and plugins. Add `extraKnownMarketplaces` to your project’s `.claude/settings.json`:

Report incorrect code

Copy


``` shiki
{
  "extraKnownMarketplaces": {
    "my-team-tools": {
      "source": {
        "source": "github",
        "repo": "your-org/claude-plugins"
      }
    }
  }
}
```

For full configuration options including `extraKnownMarketplaces` and `enabledPlugins`, see [Plugin settings](/docs/en/settings#plugin-settings).

## 

Security

Plugins and marketplaces are highly trusted components that can execute arbitrary code on your machine with your user privileges. Only install plugins and add marketplaces from sources you trust. Organizations can restrict which marketplaces users are allowed to add using [managed marketplace restrictions](/docs/en/plugin-marketplaces#managed-marketplace-restrictions).

## 

Troubleshooting

### 

/plugin command not recognized

If you see “unknown command” or the `/plugin` command doesn’t appear:

1.  **Check your version**: Run `claude --version`. Plugins require version 1.0.33 or later.
2.  **Update Claude Code**:
    - **Homebrew**: `brew upgrade claude-code`
    - **npm**: `npm update -g @anthropic-ai/claude-code`
    - **Native installer**: Re-run the install command from [Setup](/docs/en/setup)
3.  **Restart Claude Code**: After updating, restart your terminal and run `claude` again.

### 

Common issues

- **Marketplace not loading**: Verify the URL is accessible and that `.claude-plugin/marketplace.json` exists at the path
- **Plugin installation failures**: Check that plugin source URLs are accessible and repositories are public (or you have access)
- **Files not found after installation**: Plugins are copied to a cache, so paths referencing files outside the plugin directory won’t work
- **Plugin skills not appearing**: Clear the cache with `rm -rf ~/.claude/plugins/cache`, restart Claude Code, and reinstall the plugin.

For detailed troubleshooting with solutions, see [Troubleshooting](/docs/en/plugin-marketplaces#troubleshooting) in the marketplace guide. For debugging tools, see [Debugging and development tools](/docs/en/plugins-reference#debugging-and-development-tools).

### 

Code intelligence issues

- **Language server not starting**: verify the binary is installed and available in your `$PATH`. Check the `/plugin` Errors tab for details.
- **High memory usage**: language servers like `rust-analyzer` and `pyright` can consume significant memory on large projects. If you experience memory issues, disable the plugin with `/plugin disable <plugin-name>` and rely on Claude’s built-in search tools instead.
- **False positive diagnostics in monorepos**: language servers may report unresolved import errors for internal packages if the workspace isn’t configured correctly. These don’t affect Claude’s ability to edit code.

## 

Next steps

- **Build your own plugins**: See [Plugins](/docs/en/plugins) to create skills, agents, and hooks
- **Create a marketplace**: See [Create a plugin marketplace](/docs/en/plugin-marketplaces) to distribute plugins to your team or community
- **Technical reference**: See [Plugins reference](/docs/en/plugins-reference) for complete specifications


---
## discover-plugins-c8a77f0998.md

> ## Documentation Index
> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Discover and install prebuilt plugins through marketplaces

> Find and install plugins from marketplaces to extend Claude Code with new skills, agents, and capabilities.

Plugins extend Claude Code with skills, agents, hooks, and MCP servers. Plugin marketplaces are catalogs that help you discover and install these extensions without building them yourself.

Looking to create and distribute your own marketplace? See [Create and distribute a plugin marketplace](../08-Plugins-Skills/create-and-distribute-a-plugin-marketplace-claude-code-docs-34a8f3c5e8.md).

## How marketplaces work

A marketplace is a catalog of plugins that someone else has created and shared. Using a marketplace is a two-step process:

<Steps>
  <Step title="Add the marketplace">
    This registers the catalog with Claude Code so you can browse what's available. No plugins are installed yet.
  </Step>

  <Step title="Install individual plugins">
    Browse the catalog and install the plugins you want.
  </Step>
</Steps>

Think of it like adding an app store: adding the store gives you access to browse its collection, but you still choose which apps to download individually.

## Official Anthropic marketplace

The official Anthropic marketplace (`claude-plugins-official`) is automatically available when you start Claude Code. Run `/plugin` and go to the **Discover** tab to browse what's available, or view the catalog at [claude.com/plugins](https://claude.com/plugins).

To install a plugin from the official marketplace, use `/plugin install <name>@claude-plugins-official`. For example, to install the GitHub integration:

```shell theme={null}
/plugin install github@claude-plugins-official
```

If Claude Code reports that the plugin is not found in any marketplace, your marketplace is either missing or outdated. Run `/plugin marketplace update claude-plugins-official` to refresh it, or `/plugin marketplace add anthropics/claude-plugins-official` if you haven't added it before. Then retry the install.

<Note>
  The official marketplace is maintained by Anthropic. To submit a plugin to the official marketplace, use one of the in-app submission forms:

  * **Claude.ai**: [claude.ai/settings/plugins/submit](https://claude.ai/settings/plugins/submit)
  * **Console**: [platform.claude.com/plugins/submit](https://platform.claude.com/plugins/submit)

  To distribute plugins independently, [create your own marketplace](../08-Plugins-Skills/create-and-distribute-a-plugin-marketplace-claude-code-docs-34a8f3c5e8.md) and share it with users.
</Note>

The official marketplace includes several categories of plugins:

### Code intelligence

Code intelligence plugins enable Claude Code's built-in LSP tool, giving Claude the ability to jump to definitions, find references, and see type errors immediately after edits. These plugins configure [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) connections, the same technology that powers VS Code's code intelligence.

These plugins require the language server binary to be installed on your system. If you already have a language server installed, Claude may prompt you to install the corresponding plugin when you open a project.

| Language   | Plugin              | Binary required              |
| :--------- | :------------------ | :--------------------------- |
| C/C++      | `clangd-lsp`        | `clangd`                     |
| C#         | `csharp-lsp`        | `csharp-ls`                  |
| Go         | `gopls-lsp`         | `gopls`                      |
| Java       | `jdtls-lsp`         | `jdtls`                      |
| Kotlin     | `kotlin-lsp`        | `kotlin-language-server`     |
| Lua        | `lua-lsp`           | `lua-language-server`        |
| PHP        | `php-lsp`           | `intelephense`               |
| Python     | `pyright-lsp`       | `pyright-langserver`         |
| Rust       | `rust-analyzer-lsp` | `rust-analyzer`              |
| Swift      | `swift-lsp`         | `sourcekit-lsp`              |
| TypeScript | `typescript-lsp`    | `typescript-language-server` |

You can also [create your own LSP plugin](/en/plugins-reference#lsp-servers) for other languages.

<Note>
  If you see `Executable not found in $PATH` in the `/plugin` Errors tab after installing a plugin, install the required binary from the table above.
</Note>

#### What Claude gains from code intelligence plugins

Once a code intelligence plugin is installed and its language server binary is available, Claude gains two capabilities:

* **Automatic diagnostics**: after every file edit Claude makes, the language server analyzes the changes and reports errors and warnings back automatically. Claude sees type errors, missing imports, and syntax issues without needing to run a compiler or linter. If Claude introduces an error, it notices and fixes the issue in the same turn. This requires no configuration beyond installing the plugin. You can see diagnostics inline by pressing **Ctrl+O** when the "diagnostics found" indicator appears.
* **Code navigation**: Claude can use the language server to jump to definitions, find references, get type info on hover, list symbols, find implementations, and trace call hierarchies. These operations give Claude more precise navigation than grep-based search, though availability may vary by language and environment.

If you run into issues, see [Code intelligence troubleshooting](#code-intelligence-issues).

### External integrations

These plugins bundle pre-configured [MCP servers](../06-MCP-Tools/mcp-208e742686.md) so you can connect Claude to external services without manual setup:

* **Source control**: `github`, `gitlab`
* **Project management**: `atlassian` (Jira/Confluence), `asana`, `linear`, `notion`
* **Design**: `figma`
* **Infrastructure**: `vercel`, `firebase`, `supabase`
* **Communication**: `slack`
* **Monitoring**: `sentry`

### Development workflows

Plugins that add skills and agents for common development tasks:

* **commit-commands**: Git commit workflows including commit, push, and PR creation
* **pr-review-toolkit**: Specialized agents for reviewing pull requests
* **agent-sdk-dev**: Tools for building with the Claude Agent SDK
* **plugin-dev**: Toolkit for creating your own plugins

### Output styles

Customize how Claude responds:

* **explanatory-output-style**: Educational insights about implementation choices
* **learning-output-style**: Interactive learning mode for skill building

## Try it: add the demo marketplace

Anthropic also maintains a [demo plugins marketplace](https://github.com/anthropics/claude-code/tree/main/plugins) (`claude-code-plugins`) with example plugins that show what's possible with the plugin system. Unlike the official marketplace, you need to add this one manually.

<Steps>
  <Step title="Add the marketplace">
    From within Claude Code, run the `plugin marketplace add` command for the `anthropics/claude-code` marketplace:

    ```shell theme={null}
    /plugin marketplace add anthropics/claude-code
    ```

    This downloads the marketplace catalog and makes its plugins available to you.
  </Step>

  <Step title="Browse available plugins">
    Run `/plugin` to open the plugin manager. This opens a tabbed interface with four tabs you can cycle through using **Tab** (or **Shift+Tab** to go backward):

    * **Discover**: browse available plugins from all your marketplaces
    * **Installed**: view and manage your installed plugins
    * **Marketplaces**: add, remove, or update your added marketplaces
    * **Errors**: view any plugin loading errors

    Go to the **Discover** tab to see plugins from the marketplace you just added.
  </Step>

  <Step title="Install a plugin">
    Select a plugin to view its details, then choose an installation scope:

    * **User scope**: install for yourself across all projects
    * **Project scope**: install for all collaborators on this repository
    * **Local scope**: install for yourself in this repository only

    For example, select **commit-commands** (a plugin that adds git workflow skills) and install it to your user scope.

    You can also install directly from the command line:

    ```shell theme={null}
    /plugin install commit-commands@anthropics-claude-code
    ```

    See [Configuration scopes](/en/settings#configuration-scopes) to learn more about scopes.
  </Step>

  <Step title="Use your new plugin">
    After installing, run `/reload-plugins` to activate the plugin. Plugin skills are namespaced by the plugin name, so **commit-commands** provides skills like `/commit-commands:commit`.

    Try it out by making a change to a file and running:

    ```shell theme={null}
    /commit-commands:commit
    ```

    This stages your changes, generates a commit message, and creates the commit.

    Each plugin works differently. Check the plugin's description in the **Discover** tab or its homepage to learn what skills and capabilities it provides.
  </Step>
</Steps>

The rest of this guide covers all the ways you can add marketplaces, install plugins, and manage your configuration.

## Add marketplaces

Use the `/plugin marketplace add` command to add marketplaces from different sources.

<Tip>
  **Shortcuts**: You can use `/plugin market` instead of `/plugin marketplace`, and `rm` instead of `remove`.
</Tip>

* **GitHub repositories**: `owner/repo` format (for example, `anthropics/claude-code`)
* **Git URLs**: any git repository URL (GitLab, Bitbucket, self-hosted)
* **Local paths**: directories or direct paths to `marketplace.json` files
* **Remote URLs**: direct URLs to hosted `marketplace.json` files

### Add from GitHub

Add a GitHub repository that contains a `.claude-plugin/marketplace.json` file using the `owner/repo` format—where `owner` is the GitHub username or organization and `repo` is the repository name.

For example, `anthropics/claude-code` refers to the `claude-code` repository owned by `anthropics`:

```shell theme={null}
/plugin marketplace add anthropics/claude-code
```

### Add from other Git hosts

Add any git repository by providing the full URL. This works with any Git host, including GitLab, Bitbucket, and self-hosted servers:

Using HTTPS:

```shell theme={null}
/plugin marketplace add https://gitlab.com/company/plugins.git
```

Using SSH:

```shell theme={null}
/plugin marketplace add git@gitlab.com:company/plugins.git
```

To add a specific branch or tag, append `#` followed by the ref:

```shell theme={null}
/plugin marketplace add https://gitlab.com/company/plugins.git#v1.0.0
```

### Add from local paths

Add a local directory that contains a `.claude-plugin/marketplace.json` file:

```shell theme={null}
/plugin marketplace add ./my-marketplace
```

You can also add a direct path to a `marketplace.json` file:

```shell theme={null}
/plugin marketplace add ./path/to/marketplace.json
```

### Add from remote URLs

Add a remote `marketplace.json` file via URL:

```shell theme={null}
/plugin marketplace add https://example.com/marketplace.json
```

<Note>
  URL-based marketplaces have some limitations compared to Git-based marketplaces. If you encounter "path not found" errors when installing plugins, see [Troubleshooting](/en/plugin-marketplaces#plugins-with-relative-paths-fail-in-url-based-marketplaces).
</Note>

## Install plugins

Once you've added marketplaces, you can install plugins directly (installs to user scope by default):

```shell theme={null}
/plugin install plugin-name@marketplace-name
```

To choose a different [installation scope](/en/settings#configuration-scopes), use the interactive UI: run `/plugin`, go to the **Discover** tab, and press **Enter** on a plugin. You'll see options for:

* **User scope** (default): install for yourself across all projects
* **Project scope**: install for all collaborators on this repository (adds to `.claude/settings.json`)
* **Local scope**: install for yourself in this repository only (not shared with collaborators)

You may also see plugins with **managed** scope—these are installed by administrators via [managed settings](/en/settings#settings-files) and cannot be modified.

<Warning>
  Make sure you trust a plugin before installing it. Anthropic does not control what MCP servers, files, or other software are included in plugins and cannot verify that they work as intended. Check each plugin's homepage for more information.
</Warning>

## Manage installed plugins

Run `/plugin` and go to the **Installed** tab to view, enable, disable, or uninstall your plugins. The list is grouped by scope and sorted so you see problems first: plugins with load errors or unresolved dependencies appear at the top, followed by your favorites, with disabled plugins folded behind a collapsed header at the bottom.

From the list you can:

* press `f` to favorite or unfavorite the selected plugin
* type to filter by plugin name or description
* press Enter to open a plugin's detail view and enable, disable, or uninstall it

When you install a plugin that declares dependencies, the install output lists which dependencies were auto-installed alongside it.

You can also manage plugins with direct commands.

Disable a plugin without uninstalling:

```shell theme={null}
/plugin disable plugin-name@marketplace-name
```

Re-enable a disabled plugin:

```shell theme={null}
/plugin enable plugin-name@marketplace-name
```

Completely remove a plugin:

```shell theme={null}
/plugin uninstall plugin-name@marketplace-name
```

The `--scope` option lets you target a specific scope with CLI commands:

```shell theme={null}
claude plugin install formatter@your-org --scope project
claude plugin uninstall formatter@your-org --scope project
```

### Apply plugin changes without restarting

When you install, enable, or disable plugins during a session, run `/reload-plugins` to pick up all changes without restarting:

```shell theme={null}
/reload-plugins
```

Claude Code reloads all active plugins and shows counts for plugins, skills, agents, hooks, plugin MCP servers, and plugin LSP servers.

## Manage marketplaces

You can manage marketplaces through the interactive `/plugin` interface or with CLI commands.

### Use the interactive interface

Run `/plugin` and go to the **Marketplaces** tab to:

* View all your added marketplaces with their sources and status
* Add new marketplaces
* Update marketplace listings to fetch the latest plugins
* Remove marketplaces you no longer need

### Use CLI commands

You can also manage marketplaces with direct commands.

List all configured marketplaces:

```shell theme={null}
/plugin marketplace list
```

Refresh plugin listings from a marketplace:

```shell theme={null}
/plugin marketplace update marketplace-name
```

Remove a marketplace:

```shell theme={null}
/plugin marketplace remove marketplace-name
```

<Warning>
  Removing a marketplace will uninstall any plugins you installed from it.
</Warning>

### Configure auto-updates

Claude Code can automatically update marketplaces and their installed plugins at startup. When auto-update is enabled for a marketplace, Claude Code refreshes the marketplace data and updates installed plugins to their latest versions. If any plugins were updated, you'll see a notification prompting you to run `/reload-plugins`.

Toggle auto-update for individual marketplaces through the UI:

1. Run `/plugin` to open the plugin manager
2. Select **Marketplaces**
3. Choose a marketplace from the list
4. Select **Enable auto-update** or **Disable auto-update**

Official Anthropic marketplaces have auto-update enabled by default. Third-party and local development marketplaces have auto-update disabled by default.

To disable all automatic updates entirely for both Claude Code and all plugins, set the `DISABLE_AUTOUPDATER` environment variable. See [Auto updates](/en/setup#auto-updates) for details.

To keep plugin auto-updates enabled while disabling Claude Code auto-updates, set `FORCE_AUTOUPDATE_PLUGINS=1` along with `DISABLE_AUTOUPDATER`:

```bash theme={null}
export DISABLE_AUTOUPDATER=1
export FORCE_AUTOUPDATE_PLUGINS=1
```

This is useful when you want to manage Claude Code updates manually but still receive automatic plugin updates.

## Configure team marketplaces

Team admins can set up automatic marketplace installation for projects by adding marketplace configuration to `.claude/settings.json`. When team members trust the repository folder, Claude Code prompts them to install these marketplaces and plugins.

Add `extraKnownMarketplaces` to your project's `.claude/settings.json`:

```json theme={null}
{
  "extraKnownMarketplaces": {
    "my-team-tools": {
      "source": {
        "source": "github",
        "repo": "your-org/claude-plugins"
      }
    }
  }
}
```

For full configuration options including `extraKnownMarketplaces` and `enabledPlugins`, see [Plugin settings](/en/settings#plugin-settings).

## Security

Plugins and marketplaces are highly trusted components that can execute arbitrary code on your machine with your user privileges. Only install plugins and add marketplaces from sources you trust. Organizations can restrict which marketplaces users are allowed to add using [managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions).

## Troubleshooting

### /plugin command not recognized

If you see "unknown command" or the `/plugin` command doesn't appear:

1. **Check your version**: Run `claude --version` to see what's installed.
2. **Update Claude Code**:
   * **Homebrew**: `brew upgrade claude-code` (or `brew upgrade claude-code@latest` if you installed that cask)
   * **npm**: `npm update -g @anthropic-ai/claude-code`
   * **Native installer**: Re-run the install command from [Setup](../01-Getting-Started/advanced-setup-claude-code-docs-0526bc1300.md)
3. **Restart Claude Code**: After updating, restart your terminal and run `claude` again.

### Common issues

* **Marketplace not loading**: Verify the URL is accessible and that `.claude-plugin/marketplace.json` exists at the path
* **Plugin installation failures**: Check that plugin source URLs are accessible and repositories are public (or you have access)
* **Files not found after installation**: Plugins are copied to a cache, so paths referencing files outside the plugin directory won't work
* **Plugin skills not appearing**: Clear the cache with `rm -rf ~/.claude/plugins/cache`, restart Claude Code, and reinstall the plugin.

For detailed troubleshooting with solutions, see [Troubleshooting](/en/plugin-marketplaces#troubleshooting) in the marketplace guide. For debugging tools, see [Debugging and development tools](/en/plugins-reference#debugging-and-development-tools).

### Code intelligence issues

* **Language server not starting**: verify the binary is installed and available in your `$PATH`. Check the `/plugin` Errors tab for details.
* **High memory usage**: language servers like `rust-analyzer` and `pyright` can consume significant memory on large projects. If you experience memory issues, disable the plugin with `/plugin disable <plugin-name>` and rely on Claude's built-in search tools instead.
* **False positive diagnostics in monorepos**: language servers may report unresolved import errors for internal packages if the workspace isn't configured correctly. These don't affect Claude's ability to edit code.

## Next steps

* **Build your own plugins**: See [Plugins](../08-Plugins-Skills/create-plugins-claude-code-docs.md) to create skills, agents, and hooks
* **Create a marketplace**: See [Create a plugin marketplace](../08-Plugins-Skills/create-and-distribute-a-plugin-marketplace-claude-code-docs-34a8f3c5e8.md) to distribute plugins to your team or community
* **Technical reference**: See [Plugins reference](../08-Plugins-Skills/plugins-reference-44aeea7968.md) for complete specifications


---
## enterprise-deployment-overview-claude-code-docs-6eae0ecba2.md

# Enterprise deployment overview


Learn how Claude Code can integrate with various third-party services and infrastructure to meet enterprise deployment requirements.


> ## Documentation Index
>
> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt>
>
> Use this file to discover all available pages before exploring further.

Organizations can deploy Claude Code through Anthropic directly or through a cloud provider. This page helps you choose the right configuration.


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, and billing management. Best for smaller teams that need to get started quickly. **Claude for Enterprise** adds SSO and domain capture, role-based permissions, compliance API access, and managed policy settings for deploying organization-wide Claude Code configurations. Best for larger organizations with security and compliance requirements. Learn more about [Team plans](../17-Billing-Plans/what-is-the-team-plan.md) and [Enterprise plans](../17-Billing-Plans/what-is-the-enterprise-plan.md). If your organization has specific infrastructure requirements, compare the options below:

[TABLE]

Select a deployment option to view setup instructions:

- [Claude for Teams or Enterprise](/docs/en/authentication#claude-for-teams-or-enterprise)
- [Anthropic Console](/docs/en/authentication#claude-console-authentication)
- [Amazon Bedrock](/docs/en/amazon-bedrock)
- [Claude Platform on AWS](/docs/en/claude-platform-on-aws)
- [Google Vertex AI](/docs/en/google-vertex-ai)
- [Microsoft Foundry](/docs/en/microsoft-foundry)


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:

- **Corporate proxy**: Routes traffic through an HTTP/HTTPS proxy. Use this if your organization requires all outbound traffic to pass through a proxy server for security monitoring, compliance, or network policy enforcement. Configure with the `HTTPS_PROXY` or `HTTP_PROXY` environment variables. Learn more in [Enterprise network configuration](/docs/en/network-config).
- **LLM Gateway**: A service that sits between Claude Code and the cloud provider to handle authentication and routing. Use this if you need centralized usage tracking across teams, custom rate limiting or budgets, or centralized authentication management. Configure with the `ANTHROPIC_BASE_URL`, `ANTHROPIC_BEDROCK_BASE_URL`, `ANTHROPIC_AWS_BASE_URL`, or `ANTHROPIC_VERTEX_BASE_URL` environment variables. Learn more in [LLM gateway configuration](/docs/en/llm-gateway).

The following examples show the environment variables to set in your shell or shell profile (`.bashrc`, `.zshrc`). See [Settings](/docs/en/settings) for other configuration methods.


Amazon Bedrock

- Corporate proxy

- LLM Gateway

Route Bedrock traffic through your corporate proxy by setting the following [environment variables](/docs/en/env-vars):

```python
# Enable Bedrock
export CLAUDE_CODE_USE_BEDROCK=1
export AWS_REGION=us-east-1

# Configure corporate proxy
export HTTPS_PROXY='https://proxy.example.com:8080'
```

Route Bedrock traffic through your LLM gateway by setting the following [environment variables](/docs/en/env-vars):

```python
# Enable Bedrock
export CLAUDE_CODE_USE_BEDROCK=1

# Configure LLM gateway
export ANTHROPIC_BEDROCK_BASE_URL='https://your-llm-gateway.com/bedrock'
export CLAUDE_CODE_SKIP_BEDROCK_AUTH=1  # If gateway handles AWS auth
```


Microsoft Foundry

- Corporate proxy

- LLM Gateway

Route Foundry traffic through your corporate proxy by setting the following [environment variables](/docs/en/env-vars):

```python
# Enable Microsoft Foundry
export CLAUDE_CODE_USE_FOUNDRY=1
export ANTHROPIC_FOUNDRY_RESOURCE=your-resource
export ANTHROPIC_FOUNDRY_API_KEY=your-api-key  # Or omit for Entra ID auth

# Configure corporate proxy
export HTTPS_PROXY='https://proxy.example.com:8080'
```

Route Foundry traffic through your LLM gateway by setting the following [environment variables](/docs/en/env-vars):

```python
# Enable Microsoft Foundry
export CLAUDE_CODE_USE_FOUNDRY=1

# Configure LLM gateway
export ANTHROPIC_FOUNDRY_BASE_URL='https://your-llm-gateway.com'
export CLAUDE_CODE_SKIP_FOUNDRY_AUTH=1  # If gateway handles Azure auth
```


Google Vertex AI

- Corporate proxy

- LLM Gateway

Route Vertex AI traffic through your corporate proxy by setting the following [environment variables](/docs/en/env-vars):

```python
# Enable Vertex
export CLAUDE_CODE_USE_VERTEX=1
export CLOUD_ML_REGION=us-east5
export ANTHROPIC_VERTEX_PROJECT_ID=your-project-id

# Configure corporate proxy
export HTTPS_PROXY='https://proxy.example.com:8080'
```

Route Vertex AI traffic through your LLM gateway by setting the following [environment variables](/docs/en/env-vars):

```python
# Enable Vertex
export CLAUDE_CODE_USE_VERTEX=1

# Configure LLM gateway
export ANTHROPIC_VERTEX_BASE_URL='https://your-llm-gateway.com/vertex'
export CLAUDE_CODE_SKIP_VERTEX_AUTH=1  # If gateway handles GCP auth
```

Use `/status` in Claude Code to verify your proxy and gateway configuration is applied correctly.


Best practices for organizations


Invest in documentation and memory

We strongly recommend investing in documentation so that Claude Code understands your codebase. Organizations can deploy CLAUDE.md files at multiple levels:

- **Organization-wide**: Deploy to system directories like `/Library/Application Support/ClaudeCode/CLAUDE.md` (macOS) for company-wide standards
- **Repository-level**: Create `CLAUDE.md` files in repository roots containing project architecture, build commands, and contribution guidelines. Check these into source control so all users benefit

Learn more in [Memory and CLAUDE.md files](/docs/en/memory).


Simplify deployment

If you have a custom development environment, we find that creating a “one click” way to install Claude Code is key to growing adoption across an organization.


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

If you deploy through [Bedrock](/docs/en/amazon-bedrock), [Vertex AI](/docs/en/google-vertex-ai), [Foundry](/docs/en/microsoft-foundry), or [Claude Platform on AWS](/docs/en/claude-platform-on-aws), pin specific model versions using `ANTHROPIC_DEFAULT_OPUS_MODEL`, `ANTHROPIC_DEFAULT_SONNET_MODEL`, and `ANTHROPIC_DEFAULT_HAIKU_MODEL`. Without pinning, model aliases resolve to the latest version, which may not yet be enabled in your account when Anthropic releases an update. 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 latest version is unavailable.


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).


Leverage MCP for integrations

MCP is a great way to give Claude Code more information, such as connecting to ticket management systems or error logs. We recommend that one central team configures MCP servers and checks a `.mcp.json` configuration into the codebase so that all users benefit. [Learn more](/docs/en/mcp). At Anthropic, we trust Claude Code to power development across every Anthropic codebase. We hope you enjoy using Claude Code as much as we do.


Next steps

Once you’ve chosen a deployment option and configured access for your team:

1.  **Roll out to your team**: Share installation instructions and have team members [install Claude Code](/docs/en/setup) and authenticate with their credentials.
2.  **Set up shared configuration**: Create a [CLAUDE.md file](/docs/en/memory) in your repositories to help Claude Code understand your codebase and coding standards.
3.  **Configure permissions**: Review [security settings](/docs/en/security) to define what Claude Code can and cannot do in your environment.


---
## enterprise-network-configuration-claude-code-docs-5c48e6754e.md

# Enterprise network configuration


Configure Claude Code for enterprise environments with proxy servers, custom Certificate Authorities (CA), and mutual Transport Layer Security (mTLS) authentication.


> ## Documentation Index
>
> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt>
>
> Use this file to discover all available pages before exploring further.

Claude Code supports various enterprise network and security configurations through environment variables. This includes routing traffic through corporate proxy servers, trusting custom Certificate Authorities (CA), and authenticating with mutual Transport Layer Security (mTLS) certificates for enhanced security.

All environment variables shown on this page can also be configured in [`settings.json`](/docs/en/settings).


Proxy configuration


Environment variables

Claude Code respects standard proxy environment variables:

```python
# HTTPS proxy (recommended)
export HTTPS_PROXY=https://proxy.example.com:8080

# HTTP proxy (if HTTPS not available)
export HTTP_PROXY=http://proxy.example.com:8080

# Bypass proxy for specific requests - space-separated format
export NO_PROXY="localhost 192.168.1.1 example.com .example.com"
# Bypass proxy for specific requests - comma-separated format
export NO_PROXY="localhost,192.168.1.1,example.com,.example.com"
# Bypass proxy for all requests
export NO_PROXY="*"
```

Claude Code does not support SOCKS proxies.


Basic authentication

If your proxy requires basic authentication, include credentials in the proxy URL:

```python
export HTTPS_PROXY=http://username:password@proxy.example.com:8080
```

Avoid hardcoding passwords in scripts. Use environment variables or secure credential storage instead.

For proxies requiring advanced authentication (NTLM, Kerberos, etc.), consider using an LLM Gateway service that supports your authentication method.


CA certificate store

By default, Claude Code trusts both its bundled Mozilla CA certificates and your operating system’s certificate store. Enterprise TLS-inspection proxies such as CrowdStrike Falcon and Zscaler work without additional configuration when their root certificate is installed in the OS trust store. `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:

```python
export CLAUDE_CODE_CERT_STORE=bundled
```

To trust only the OS certificate store:

```python
export CLAUDE_CODE_CERT_STORE=system
```

`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

If your enterprise environment uses a custom CA, configure Claude Code to trust it directly:

```python
export NODE_EXTRA_CA_CERTS=/path/to/ca-cert.pem
```


mTLS authentication

For enterprise environments requiring client certificate authentication:

```python
# Client certificate for authentication
export CLAUDE_CODE_CLIENT_CERT=/path/to/client-cert.pem

# Client private key
export CLAUDE_CODE_CLIENT_KEY=/path/to/client-key.pem

# Optional: Passphrase for encrypted private key
export CLAUDE_CODE_CLIENT_KEY_PASSPHRASE="your-passphrase"
```


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.

| URL                            | Required for                                                                                                                           |
|--------------------------------|----------------------------------------------------------------------------------------------------------------------------------------|
| `api.anthropic.com`            | Claude API requests                                                                                                                    |
| `claude.ai`                    | claude.ai account authentication                                                                                                       |
| `platform.claude.com`          | Anthropic Console account authentication                                                                                               |
| `downloads.claude.ai`          | Plugin executable downloads; native installer and native auto-updater                                                                  |
| `storage.googleapis.com`       | Native installer and native auto-updater on versions prior to 2.1.116                                                                  |
| `bridge.claudeusercontent.com` | [Claude in Chrome](/docs/en/chrome) extension WebSocket bridge                                                                         |
| `raw.githubusercontent.com`    | Changelog feed for [`/release-notes`](/docs/en/commands) and the release notes shown after updating; plugin marketplace install counts |

If you install Claude Code through npm or manage your own binary distribution, end users may not need access to `downloads.claude.ai` or `storage.googleapis.com`. Claude Code also sends optional operational telemetry by default, which you can disable with environment variables. See [Telemetry services](/docs/en/data-usage#telemetry-services) for how to disable it before finalizing your allowlist. When using [Amazon Bedrock](/docs/en/amazon-bedrock), [Google Vertex AI](/docs/en/google-vertex-ai), or [Microsoft Foundry](/docs/en/microsoft-foundry), model traffic and authentication go to your provider 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). [Claude Code on the web](/docs/en/claude-code-on-the-web) and [Code Review](/docs/en/code-review) connect to your repositories from Anthropic-managed infrastructure. 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). The Claude GitHub App registers its IP ranges, so enabling this setting allows access without manual configuration. To [add the ranges to your allow list manually](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) instead, or to configure other firewalls, see the [Anthropic API IP addresses](../04-API-Reference/Other/api-ip-addresses-cc3c763ed7.md). For self-hosted [GitHub Enterprise Server](/docs/en/github-enterprise-server) instances behind a firewall, allowlist the same [Anthropic API IP addresses](../04-API-Reference/Other/api-ip-addresses-cc3c763ed7.md) so Anthropic infrastructure can reach your GHES host to clone repositories and post review comments.


Additional resources

- [Claude Code settings](/docs/en/settings)
- [Environment variables reference](/docs/en/env-vars)
- [Troubleshooting guide](/docs/en/troubleshooting)


---
## enterprise-network-configuration-claude-code-docs.md

# Enterprise network configuration


Configure Claude Code for enterprise environments with proxy servers, custom Certificate Authorities (CA), and mutual Transport Layer Security (mTLS) authentication.


Claude Code supports various enterprise network and security configurations through environment variables. This includes routing traffic through corporate proxy servers, trusting custom Certificate Authorities (CA), and authenticating with mutual Transport Layer Security (mTLS) certificates for enhanced security.

All environment variables shown on this page can also be configured in [`settings.json`](settings.md).


Proxy configuration


Environment variables

Claude Code respects standard proxy environment variables:

```python
# HTTPS proxy (recommended)
export HTTPS_PROXY=https://proxy.example.com:8080

# HTTP proxy (if HTTPS not available)
export HTTP_PROXY=http://proxy.example.com:8080

# Bypass proxy for specific requests - space-separated format
export NO_PROXY="localhost 192.168.1.1 example.com .example.com"
# Bypass proxy for specific requests - comma-separated format
export NO_PROXY="localhost,192.168.1.1,example.com,.example.com"
# Bypass proxy for all requests
export NO_PROXY="*"
```

Claude Code does not support SOCKS proxies.


Basic authentication

If your proxy requires basic authentication, include credentials in the proxy URL:

```python
export HTTPS_PROXY=http://username:password@proxy.example.com:8080
```

Avoid hardcoding passwords in scripts. Use environment variables or secure credential storage instead.

For proxies requiring advanced authentication (NTLM, Kerberos, etc.), consider using an LLM Gateway service that supports your authentication method.


CA certificate store

By default, Claude Code trusts both its bundled Mozilla CA certificates and your operating system’s certificate store. Enterprise TLS-inspection proxies such as CrowdStrike Falcon and Zscaler work without additional configuration when their root certificate is installed in the OS trust store.

System CA store integration requires the native Claude Code binary distribution. When running on the Node.js runtime, the system CA store is not merged automatically. In that case, set `NODE_EXTRA_CA_CERTS=/path/to/ca-cert.pem` to trust an enterprise root CA.

`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:

```python
export CLAUDE_CODE_CERT_STORE=bundled
```

To trust only the OS certificate store:

```python
export CLAUDE_CODE_CERT_STORE=system
```

`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

If your enterprise environment uses a custom CA, configure Claude Code to trust it directly:

```python
export NODE_EXTRA_CA_CERTS=/path/to/ca-cert.pem
```


mTLS authentication

For enterprise environments requiring client certificate authentication:

```python
# Client certificate for authentication
export CLAUDE_CODE_CLIENT_CERT=/path/to/client-cert.pem

# Client private key
export CLAUDE_CODE_CLIENT_KEY=/path/to/client-key.pem

# Optional: Passphrase for encrypted private key
export CLAUDE_CODE_CLIENT_KEY_PASSPHRASE="your-passphrase"
```


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.

| URL | Required for |
|----|----|
| `api.anthropic.com` | Claude API requests |
| `claude.ai` | claude.ai account authentication |
| `platform.claude.com` | Anthropic Console account authentication |
| `downloads.claude.ai` | Plugin executable downloads; native installer and native auto-updater |
| `storage.googleapis.com` | Native installer and native auto-updater on versions prior to 2.1.116 |
| `bridge.claudeusercontent.com` | [Claude in Chrome](/docs/en/chrome) extension WebSocket bridge |

If you install Claude Code through npm or manage your own binary distribution, end users may not need access to `downloads.claude.ai` or `storage.googleapis.com`. When using [Amazon Bedrock](/docs/en/amazon-bedrock), [Google Vertex AI](/docs/en/google-vertex-ai), or [Microsoft Foundry](/docs/en/microsoft-foundry), model traffic and authentication go to your provider 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). [Claude Code on the web](/docs/en/claude-code-on-the-web) and [Code Review](/docs/en/code-review) connect to your repositories from Anthropic-managed infrastructure. 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). The Claude GitHub App registers its IP ranges, so enabling this setting allows access without manual configuration. To [add the ranges to your allow list manually](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) instead, or to configure other firewalls, see the [Anthropic API IP addresses](../04-API-Reference/Other/api-ip-addresses-cc3c763ed7.md). For self-hosted [GitHub Enterprise Server](/docs/en/github-enterprise-server) instances behind a firewall, allowlist the same [Anthropic API IP addresses](../04-API-Reference/Other/api-ip-addresses-cc3c763ed7.md) so Anthropic infrastructure can reach your GHES host to clone repositories and post review comments.


Additional resources

- [Claude Code settings](/docs/en/settings)
- [Environment variables reference](/docs/en/env-vars)
- [Troubleshooting guide](troubleshooting.md)


---
*Truncated: 107 more documents not shown (size limit)*
