references/getting-started/best-practices.md
<!-- source: https://code.claude.com/docs/en/best-practices.md / last verified: 2026-08-07 -->
# Best practices
Patterns for getting the most out of Claude Code: verification, planning, prompting, environment setup, session management, and scaling with parallel/automated sessions.
## Signature / Usage
```bash
# non-interactive mode for CI, hooks, scripts
claude -p "fix all lint errors"
claude -p "List all API endpoints" --output-format json
claude --permission-mode auto -p "fix all lint errors"
# fan out across files
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
```
## Options / Props
| Strategy | Purpose |
|----------|---------|
| Give Claude a way to verify its work | Tests, build, screenshot diff, or a `/goal` condition close the loop so Claude iterates until it passes |
| Explore first, then plan, then code | Use plan mode (`Shift+Tab` to `⏸ plan mode on`) to separate research from execution for non-trivial changes |
| Provide specific context | Reference files with `@`, paste images, give URLs, pipe data (`cat error.log \| claude`) |
| Configure environment | CLAUDE.md, permissions/auto mode/sandboxing, CLI tools (`gh`, `aws`), MCP servers, hooks, skills, subagents, plugins |
| Manage session | `Esc` to stop, `Esc+Esc`/`/rewind` to restore, `/clear` between unrelated tasks, subagents for investigation |
| Automate and scale | `claude -p` non-interactive mode, worktrees/Desktop/web/agent teams for parallel sessions, fan-out loops, auto mode |
## Notes
- Context window fills fast and LLM performance degrades as it fills; this is the constraint underlying most advice on this page.
- CLAUDE.md guidance: keep under 200 lines, include only what Claude can't infer, use imports (`@path/to/import`), check into git.
- After two failed corrections on the same issue in one session, `/clear` and rewrite the prompt rather than continuing to correct.
- Common failure patterns: kitchen-sink sessions, repeated correcting without clearing, over-specified CLAUDE.md, trust-then-verify gap, unscoped "investigate" tasks.
## Related
- [How Claude Code works](./how-claude-code-works.md)
- [Common workflows](./common-workflows.md)
- [How Claude remembers your project](./memory.md)
- [Extend Claude Code](./features-overview.md)
- [Keep Claude working toward a goal](./goal.md)
- [Explore the context window](./context-window.md)
references/getting-started/common-workflows.md
<!-- source: https://code.claude.com/docs/en/common-workflows.md / last verified: 2026-08-07 -->
# Common workflows
Short prompt recipes for exploring codebases, fixing bugs, refactoring, testing, PRs, documentation, images, file references, scheduling, and asking Claude about its own capabilities.
## Signature / Usage
```bash
claude --worktree feature-auth # isolated parallel session
claude --permission-mode plan # plan before editing
claude --continue # resume most recent session
git log --oneline -20 | claude -p "summarize these recent commits"
```
## Options / Props
| Scheduling option | Where it runs | Best for |
|--------------------|----------------|----------|
| Routines | Anthropic-managed infrastructure | Tasks that run even when your computer is off; can trigger on API calls/GitHub events |
| Desktop scheduled tasks | Your machine, via desktop app | Tasks needing direct access to local files/uncommitted changes |
| GitHub Actions | CI pipeline | Tasks tied to repo events or cron alongside workflow config |
| `/loop` | Current CLI session | Quick polling while a session is open |
## Notes
- `@file` and `@directory` reference files/directories without waiting for a full read; `@server:resource` fetches MCP resources.
- `claude --from-pr 1234` opens the session picker filtered to sessions linked to that PR after `gh pr create`.
- Delegate research with "use a subagent to investigate X" to keep large file reads out of the main context.
## Related
- [Best practices](./best-practices.md)
- [How Claude Code works](./how-claude-code-works.md)
- [Extend Claude Code](./features-overview.md)
references/getting-started/context-window.md
<!-- source: https://code.claude.com/docs/en/context-window.md / last verified: 2026-08-07 -->
# Explore the context window
An interactive simulation of how Claude Code's context window fills during a session: what loads automatically, what each file read costs, and when rules/hooks fire.
## Signature / Usage
```text
/context # live breakdown of current session's context usage by category
/autocompact 500k # set the auto-compact window for this session and later
/autocompact auto # return to the window tuned for the model
```
## Options / Props
| 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/skill and 25,000 tokens total; oldest dropped first |
| Hooks | Not applicable; hooks run as code, not context |
## Notes
- Timeline order before you type anything: system prompt, auto memory (MEMORY.md), environment info, MCP tool names (deferred schemas), skill descriptions, `~/.claude/CLAUDE.md`, project CLAUDE.md.
- Path-scoped rules load automatically alongside matching files as Claude works; a `PostToolUse` hook can fire after edits and feed output back via `additionalContext`.
- A subagent handling a follow-up keeps its large file reads in its own context window; only the summary and a small metadata trailer return to the main conversation.
- `/compact` replaces conversation history with a structured summary; most startup content reloads automatically (see the compaction table above).
- Auto-compact window: 100K-1M tokens, settable via `/autocompact`, the `--autocompact` flag, or `CLAUDE_CODE_AUTO_COMPACT_WINDOW` (highest precedence). Fable 5, Sonnet 5, Opus 4.6+, and Sonnet 4.6 support a 1M token context window.
## Related
- [How Claude Code works](./how-claude-code-works.md)
- [How Claude remembers your project](./memory.md)
- [How Claude Code uses prompt caching](./prompt-caching.md)
- [Best practices](./best-practices.md)
- [Extend Claude Code](./features-overview.md)
references/getting-started/feature-availability.md
<!-- source: https://code.claude.com/docs/en/feature-availability.md / last verified: 2026-08-07 -->
# Feature availability
Compares which Claude Code features are available across Anthropic subscription plans, Anthropic Console, Amazon Bedrock, Claude Platform on AWS, Google Cloud's Agent Platform, and Microsoft Foundry.
## Options / Props
| Requires a Claude subscription (not available via Console API key or 3rd-party provider) |
|---|
| Claude Code on the web, mobile, Slack, Desktop, Routines (`/schedule`), Ultrareview, Code Review (Team/Enterprise), Remote Control, Chrome extension, Computer use (Pro/Max), Artifacts, Voice dictation |
| CLI capability | Claude subscription | Console | Bedrock | Claude Platform on AWS | Google Cloud's Agent Platform | Microsoft Foundry |
|---|---|---|---|---|---|---|
| Web search | v | v | x | v | see note | v (Anthropic-hosted) |
| Fast mode | v | v | x | x | x | x |
| Auto mode | v | v | see note | v | see note | see note |
| Advisor | v | v | x | x | x | x |
| Channels | v | v | x | x | x | x |
| GitHub Actions | v | v | v | x | v | v |
| GitLab CI/CD | v | v | v | v | v | x |
| Plan feature | Pro | Max | Team | Enterprise |
|---|---|---|---|---|
| Claude Code on the web | v | v | v | v (premium/Chat+Code seat) |
| Routines | v | v | v | v |
| Computer use | v | v | x | x |
| Code Review | x | x | v | v |
| Analytics dashboard | x | x | v | v |
| Server-managed settings | x | x | v | v |
| SSO | x | x | v | v |
| Zero Data Retention | x | x | x | v (separate enablement) |
## Notes
- Features that work on every provider: CLI, Agent SDK, VS Code/JetBrains extensions, subagents, hooks, commands, skills, CLAUDE.md memory, plugins, MCP servers, checkpoints, sandboxing, Workflows, OpenTelemetry metrics, managed settings file.
- If authenticating through an LLM gateway, feature availability matches the underlying provider the gateway forwards to; Anthropic-only features like Advisor work only if the gateway forwards requests intact to the Anthropic API.
## Related
- [Overview](./overview.md)
- [Advanced setup](./setup.md)
references/getting-started/features-overview.md
<!-- source: https://code.claude.com/docs/en/features-overview.md / last verified: 2026-08-07 -->
# Extend Claude Code
Understand when to use CLAUDE.md, Skills, subagents, hooks, MCP, agent teams, code intelligence, and plugins to extend Claude Code beyond its built-in tools.
## Options / Props
| Feature | What it does | When to use it |
|---------|----------------|------------------|
| CLAUDE.md | Persistent context loaded every conversation | Project conventions, "always do X" rules |
| Skill | Instructions, knowledge, workflows Claude can use | Reusable content, reference docs, repeatable tasks |
| Subagent | Isolated execution context returning summarized results | Context isolation, parallel tasks, specialized workers |
| Agent teams | Coordinate multiple independent Claude Code sessions | Parallel research, feature development, competing hypotheses |
| Code intelligence | Language-server navigation and diagnostics | Typed languages, large codebases where grep is slow |
| MCP | Connect to external services | External data or actions |
| Hook | Script/HTTP/prompt/subagent triggered by lifecycle events | Automation that must run on every matching event |
| Artifact | Publish session output as a private, interactive web page | Output to see or share visually |
| Plugin | Bundle skills, hooks, subagents, MCP servers as one installable unit | Reuse the same setup across repos or distribute via a marketplace |
| Context loading | When | What loads | Cost |
|-------------------|------|-------------|------|
| CLAUDE.md | Session start | Full content | Every request |
| Skills | Session start + when used | Descriptions at start, full content when used | Low (descriptions every request) |
| MCP servers | Session start | Tool names; full schemas on demand | Low until a tool is used |
| Subagents | When spawned | Fresh context with specified skills | Isolated from main session |
| Hooks | On trigger | Nothing (runs externally) unless it returns context | Zero |
## Notes
- Build-up order: CLAUDE.md for repeated conventions -> user-invocable skill for repeated prompts -> skill for repeated playbooks -> MCP server for repeated data copy-paste -> code intelligence plugin for symbol lookups -> subagent for context-flooding side tasks -> hook for must-happen-every-time actions -> plugin for cross-repo reuse.
- Skill vs Subagent: skills are reusable content loaded into any context; subagents are isolated workers with their own context window that return only a summary.
- Detailed setup, configuration syntax, and API-level detail for Skills, subagents, hooks, MCP, and plugins belong to the extension mechanisms themselves rather than this getting-started overview; consult the dedicated Claude Code extend documentation (e.g. an `anthropic-claude-code-extend` skill) for that depth.
- CLAUDE.md is additive across scopes (all levels contribute); skills/subagents override by name (managed > user > project); MCP servers override by name (local > project > user); hooks merge from all sources.
## Related
- [How Claude remembers your project](./memory.md)
- [How Claude Code works](./how-claude-code-works.md)
- [Best practices](./best-practices.md)
- [Explore the context window](./context-window.md)
references/getting-started/glossary.md
<!-- source: https://code.claude.com/docs/en/glossary.md / last verified: 2026-08-07 -->
# Glossary
Definitions for Claude Code terminology: agentic loop, compaction, CLAUDE.md, hooks, subagents, MCP, and other core concepts.
## Options / Props
| Term | Definition |
|------|------------|
| Agent teams | Multiple independent Claude Code sessions coordinated by a team lead, shared task list, peer-to-peer messaging; experimental (`CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1`) |
| Agentic coding | Workflow where the AI reads files, runs commands, and makes changes autonomously, vs. chat-based assistants that only respond with text |
| Agentic harness | The tools, context management, and execution environment that turn a language model into a capable coding agent (Claude Code is the harness) |
| Agentic loop | The cycle: gather context, take action, verify results, repeat until done; interruptible at any point |
| Artifact | A live, interactive web page published from a session to a private claude.ai URL |
| Auto memory | Notes Claude writes for itself under `~/.claude/projects/`; first 200 lines/25KB of `MEMORY.md` loads every session |
| Auto mode | A permission mode where a separate classifier model reviews actions in the background so most run without approval prompts |
| Bare mode | `--bare` starts without hooks, skills, plugins, MCP, auto memory, or CLAUDE.md |
| Bundled skills | Prompt-based playbooks included with Claude Code, such as `/batch`, `/code-review`, `/debug`, `/loop` |
| Channel | An MCP server that pushes events into a running session (e.g. Telegram, Discord, iMessage) |
| Checkpoint | A restore point created at each prompt; `Esc` twice or `/rewind` restores code/conversation |
| `.claude` directory | Project-scoped config: settings, hooks, skills, subagents, rules, auto memory |
| CLAUDE.md | Persistent instructions loaded at the start of every session as a user message after the system prompt |
| Command | Reusable instruction invoked with `/name`; distinct from `claude` CLI subcommands and MCP server `command` field |
| Compaction | Automatic summarization when the context window approaches its limit |
| Connector | An MCP server added to a claude.ai account rather than configured locally |
| Context window | The working memory for a session: history, files, outputs, CLAUDE.md, memory, skills, system instructions |
| Dispatch | Phone-initiated task router that spawns a Desktop app session (Pro/Max) |
| Effort level | Controls thinking-budget depth per turn (Fable 5, Opus 4.6+, Sonnet 4.6+) |
| Extended thinking | Visible step-by-step reasoning before responding |
| Hook | User-defined handler executing at a lifecycle point (shell command, HTTP endpoint, MCP tool, LLM prompt, or subagent) |
| Managed settings | Settings enforced org-wide by IT/DevOps; user/project settings cannot override |
| MCP (Model Context Protocol) | Open standard connecting AI tools to external data sources and services |
| MCP server | A program giving Claude tools/prompts/resources over MCP |
| MCP Tool Search | Defers MCP tool schemas until needed; only tool names load at startup |
| Non-interactive mode | `-p`/`--print`; executes a single prompt and exits, formerly "headless mode" |
| Output style | Modifies Claude's system prompt to change response behavior/tone/format |
| Permission mode | Baseline approval behavior: `default` (Manual), `acceptEdits`, `plan`, `auto`, `dontAsk`, `bypassPermissions` |
| Permission rule | Settings entry allowing/asking/denying a tool call; evaluated deny -> ask -> allow, first match wins |
| Plan mode | Claude researches and proposes changes without editing source files |
| Plugin | Bundle of skills, hooks, subagents, MCP servers packaged as one installable unit |
| Project trust | Dialog accepting a directory before Claude Code loads its `.claude/settings.json`/`.mcp.json` |
| Prompt injection | Hostile instructions embedded in a file/page/tool result attempting to redirect Claude |
| Remote Control | Continue a local session from phone/browser via claude.ai; execution/files stay local |
| Rules | Modular instruction files in `.claude/rules/`, optionally path-scoped with `paths:` frontmatter |
| Sandboxing | OS-level filesystem/network isolation for the Bash tool |
| Session | A conversation tied to the current directory with its own context window |
| Settings layers | Precedence order: managed policy > CLI args > `.claude/settings.local.json` > `.claude/settings.json` > `~/.claude/settings.json` |
| Skill | A `SKILL.md` file of instructions/knowledge/workflow; recommended successor to custom commands |
| Subagent | Specialized assistant in its own context window with custom system prompt, tools, and permissions |
| Surface | Any place Claude Code is accessed: CLI, VS Code, JetBrains, Desktop, claude.ai |
| Teleport | `/teleport` pulls a cloud session into the local terminal; `--cloud` sends a local task to the web |
| Tool | An action Claude can take: read a file, edit code, run a shell command, search the web, spawn a subagent |
| Turn | One complete response from Claude within a session; Stop hooks fire at the end of each turn |
| Verification loop | Giving Claude a runnable check so it iterates until the check passes instead of stopping after one attempt |
| Worktree isolation | Runs Claude in a separate git worktree under `.claude/worktrees/` (`-w` flag or `isolation: worktree`) |
## Notes
- Deprecated/renamed terms: "Headless mode" is now Non-interactive mode; "Custom commands" is now Skills (`.claude/commands/` files still work); "Slash commands" is now Commands.
- For model-level concepts (tokens, temperature, RAG) see the separate platform glossary; this page covers Claude Code product terminology only.
## Related
- [How Claude Code works](./how-claude-code-works.md)
- [Extend Claude Code](./features-overview.md)
- [How Claude remembers your project](./memory.md)
- [Explore the context window](./context-window.md)
references/getting-started/goal.md
<!-- source: https://code.claude.com/docs/en/goal.md / last verified: 2026-08-07 -->
# Keep Claude working toward a goal
`/goal` sets a completion condition and Claude keeps working across turns, without re-prompting, until an evaluator model confirms the condition is met.
## Signature / Usage
```text
/goal all tests in test/auth pass and the lint step is clean
/goal # check status
/goal clear # remove active goal (aliases: stop, off, reset, none, cancel)
```
```bash
claude -p "/goal CHANGELOG.md has an entry for every PR merged this week"
```
## Options / Props
| Approach | Next turn starts when | Stops when |
|----------|-------------------------|-------------|
| `/goal` | Previous turn finishes | A model confirms the condition is met |
| `/loop` | A time interval elapses | You stop it, or Claude decides the work is done |
| Stop hook | Previous turn finishes | Your own script or prompt decides |
## Notes
- Requires Claude Code v2.1.139 or later. One goal active per session; setting a new one replaces the old.
- `/goal` doesn't change permissions; pair with auto mode for unattended runs. Condition max 4,000 characters; include a turn/time bound (e.g. "or stop after 20 turns") to bound runtime.
- Evaluator is a small fast model (Haiku by default on the Claude API) that judges only what Claude has surfaced in the conversation; it does not run commands or read files independently.
- Requires the trust dialog accepted for the workspace (it's part of the hooks system); unavailable when `disableAllHooks` or `allowManagedHooksOnly` is set.
- Resuming a session with an active goal restores the condition but resets turn count, timer, and token-spend baseline.
## Related
- [Best practices](./best-practices.md)
- [Common workflows](./common-workflows.md)
references/getting-started/how-claude-code-works.md
<!-- source: https://code.claude.com/docs/en/how-claude-code-works.md / last verified: 2026-08-07 -->
# How Claude Code works
Explains the agentic loop, built-in tools, sessions, context window, checkpoints, and permissions that power Claude Code.
## Signature / Usage
```text
gather context -> take action -> verify results -> repeat until task complete
```
## Options / Props
| Tool category | What Claude can do |
|----------------|---------------------|
| File operations | Read files, edit code, create files, rename/reorganize |
| Search | Find files by pattern, search content with regex, explore codebases |
| Execution | Run shell commands, start servers, run tests, use git |
| Web | Search the web, fetch documentation, look up error messages |
| Code intelligence | See type errors/warnings after edits, jump to definitions, find references (requires code intelligence plugins) |
| Permission mode | Behavior |
|------------------|----------|
| Manual (default) | Claude asks before file edits and shell commands |
| Accept edits | Edits files and runs common filesystem commands without asking |
| Plan | Explores and proposes a plan without editing source files |
| Auto | Evaluates all actions with background safety checks |
## Notes
- Claude Code is the agentic harness around the Claude model: it provides tools, context management, and the execution environment.
- Each session starts with a fresh context window; JSONL transcripts are stored under `~/.claude/projects/`. `--continue`/`--resume` reopen the same session ID; `--fork-session`/`/branch` copy history into a new ID.
- Context holds conversation history, file contents, command outputs, CLAUDE.md, auto memory, loaded skills, and system instructions; Claude Code auto-compacts as it fills (clears older tool outputs first, then summarizes).
- Checkpoints (file-edit snapshots, `Esc` twice to rewind) are separate from git and don't cover Bash/external-process changes or symlinked/hard-linked files.
- Skills load on demand (descriptions at session start, full content when used); subagents get their own fresh, isolated context window.
## Related
- [Explore the context window](./context-window.md)
- [How Claude remembers your project](./memory.md)
- [Extend Claude Code](./features-overview.md)
- [Best practices](./best-practices.md)
references/getting-started/memory.md
<!-- source: https://code.claude.com/docs/en/memory.md / last verified: 2026-08-07 -->
# How Claude remembers your project
CLAUDE.md files give Claude persistent, user-written instructions; auto memory lets Claude accumulate its own learnings across sessions.
## Signature / Usage
```markdown
See @README for project overview and @package.json for available npm commands.
# Additional Instructions
- git workflow @docs/git-instructions.md
```
```bash
/init # generate a starting CLAUDE.md from the codebase
/memory # browse and edit CLAUDE.md / auto memory files
/context # verify which memory files loaded
```
## Options / Props
| Scope | Location | Purpose |
|-------|----------|---------|
| Managed policy | e.g. `/etc/claude-code/CLAUDE.md` (Linux/WSL) | Org-wide instructions, cannot be excluded |
| User instructions | `~/.claude/CLAUDE.md` | Personal preferences for all projects |
| Project instructions | `./CLAUDE.md` or `./.claude/CLAUDE.md` | Team-shared instructions via source control |
| Local instructions | `./CLAUDE.local.md` | Personal project-specific notes; gitignore this |
| | CLAUDE.md files | Auto memory |
|---|---|---|
| Who writes it | You | Claude |
| Contains | Instructions and rules | Learnings and patterns |
| Loaded into | Every session | Every session (first 200 lines or 25KB) |
## Notes
- All discovered CLAUDE.md files are concatenated (not overridden), ordered broadest-to-most-specific; subdirectory CLAUDE.md files load on demand when Claude reads files there.
- Target under 200 lines per CLAUDE.md; move task-specific content to `.claude/rules/` (optionally path-scoped via `paths:` frontmatter) or to skills.
- Claude Code reads `CLAUDE.md`, not `AGENTS.md`; import it with `@AGENTS.md` or symlink `CLAUDE.md -> AGENTS.md`.
- Auto memory lives at `~/.claude/projects/<project>/memory/`, shared across worktrees of the same repo; `MEMORY.md` is the loaded index, topic files load on demand. Toggle with `autoMemoryEnabled` or `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1`.
- Project-root CLAUDE.md and auto memory survive `/compact` (re-read from disk); path-scoped rules and nested CLAUDE.md do not reload automatically.
- To hard-enforce a rule regardless of Claude's judgment, use a `PreToolUse` hook instead of a CLAUDE.md instruction, since CLAUDE.md is advisory context, not enforced configuration. Hook syntax and configuration are covered by the Claude Code extension documentation.
## Related
- [How Claude Code works](./how-claude-code-works.md)
- [Explore the context window](./context-window.md)
- [Best practices](./best-practices.md)
- [Extend Claude Code](./features-overview.md)
references/getting-started/overview.md
<!-- source: https://code.claude.com/docs/en/overview.md / last verified: 2026-08-07 -->
# Overview
Claude Code is an agentic coding tool that reads your codebase, edits files, runs commands, and integrates with your development tools. Available in the terminal, IDE, desktop app, and browser.
## Signature / Usage
```bash
# Terminal (native install)
# Step 1 - download to an exclusive temp file and print it for review. Nothing is executed here;
# if any step fails the temp file is removed and the chain stops.
installer="$(mktemp "${TMPDIR:-/tmp}/claude-install.XXXXXX")" \
&& curl -fsSL https://claude.ai/install.sh -o "${installer}" \
&& cat "${installer}" \
|| { rm -f -- "${installer:-}"; unset installer; echo "download failed; nothing was executed" >&2; false; }
```
Read the script printed above. Run the next block only if you have reviewed it and decided to proceed — it is a separate step so that copying the block above never executes anything.
```bash
# Step 2 - only after you have read the script above and decided to proceed, run it yourself.
# The temp file is removed afterwards; the final status is the installer's own exit status.
if [ -s "${installer:-}" ]; then
bash "${installer}"; status=$?; rm -f -- "${installer}"; unset installer
else
echo "no downloaded installer to run (Step 1 failed or was not run)" >&2; status=1
fi
(exit "${status}")
cd your-project
claude
```
## Options / Props
| Surface | Description |
|---------|-------------|
| Terminal | Full-featured CLI; install via native installer, Homebrew, WinGet, or Linux package managers |
| VS Code | Extension with inline diffs, @-mentions, plan review |
| Desktop app | Standalone app with visual diff review, parallel sessions, scheduled tasks |
| Web | claude.ai/code; no local setup, runs in cloud sandbox |
| JetBrains | Plugin for IntelliJ, PyCharm, WebStorm; requires the CLI installed separately |
## Notes
- Every surface connects to the same underlying Claude Code engine; CLAUDE.md files, settings, and MCP servers work across all of them.
- Claude Code can automate repetitive work, build features, fix bugs, create commits/PRs, connect tools via MCP, be customized with CLAUDE.md/skills/hooks, run agent teams and subagents, be scripted via the CLI, and run on a schedule.
## Related
- [Quickstart](./quickstart.md)
- [How Claude Code works](./how-claude-code-works.md)
- [How Claude remembers your project](./memory.md)
- [Common workflows](./common-workflows.md)
- [Best practices](./best-practices.md)
references/getting-started/prompt-caching.md
<!-- source: https://code.claude.com/docs/en/prompt-caching.md / last verified: 2026-08-07 -->
# How Claude Code uses prompt caching
Claude Code manages prompt caching automatically. Explains why a model switch triggers a slow uncached turn, what `/compact` costs, why CLAUDE.md edits don't apply mid-session, and how to check the cache hit rate.
## Signature / Usage
```bash
# environment variables
ENABLE_PROMPT_CACHING_1H=1 # opt into 1-hour TTL on API key / third-party providers
FORCE_PROMPT_CACHING_5M=1 # force 5-minute TTL regardless of authentication
DISABLE_PROMPT_CACHING=1 # disable caching for all models
```
## Options / Props
| Layer | Content | Changes when |
|-------|---------|----------------|
| System prompt | Core instructions, tool definitions, output style | Loaded tool definitions change, or Claude Code upgrades |
| Project context | CLAUDE.md, auto memory, unscoped rules | Session starts, or after `/clear`/`/compact` |
| Conversation | Messages, responses, tool results | Every turn |
| Field (from API response) | Meaning |
|------------------------------|---------|
| `cache_creation_input_tokens` | Tokens written to cache this turn, billed at cache write rate |
| `cache_read_input_tokens` | Tokens served from cache this turn, billed at ~10% of standard input rate |
## Notes
- The API caches by matching the request prefix; a change anywhere in the prefix recomputes everything after it. Model and effort level are each part of the cache key, so switching either invalidates the whole cache.
- Invalidates the cache: switching models, changing effort level, turning on fast mode, connecting/disconnecting an MCP server (when its tools are loaded into the prefix rather than deferred), enabling/disabling a plugin that provides MCP servers, denying an entire tool, compacting the conversation, upgrading Claude Code.
- Keeps the cache: editing repo files, editing CLAUDE.md mid-session (applies on next `/clear`/`/compact`/restart, not immediately), changing output style (same deferred-apply behavior), changing permission mode, invoking skills/commands, `/recap`, `/rewind`, spawning a subagent (builds its own separate cache).
- TTL: Claude subscriptions request the 1-hour TTL automatically; API key / third-party providers default to 5 minutes unless `ENABLE_PROMPT_CACHING_1H=1` is set.
- This page covers Claude Code's own request-shaping and caching behavior in the CLI. For the underlying Messages API prompt caching mechanism (cache breakpoints, pricing, cross-application usage), see the anthropic-api-core skill.
## Related
- [Explore the context window](./context-window.md)
- [How Claude Code works](./how-claude-code-works.md)
- [Best practices](./best-practices.md)
references/getting-started/quickstart.md
<!-- source: https://code.claude.com/docs/en/quickstart.md / last verified: 2026-08-07 -->
# Quickstart
Walk through installing Claude Code, logging in, starting a session, and making a first code change.
## Signature / Usage
```bash
claude --version # confirm install
claude # start interactive session, prompts login on first use
claude "task" # run a one-time task
claude -p "query" # run one-off query, then exit
claude -c # continue most recent conversation in current directory
claude -r # resume a previous conversation
```
## Options / Props
| Session command | What it does |
|------------------|--------------|
| `/clear` | Clear conversation history |
| `/help` | Show available commands |
| `/exit` or Ctrl+D twice | Exit Claude Code |
## Notes
- Steps: install → log in (`/login` to switch accounts) → start session in a project directory → ask questions → make a code change → use git conversationally → fix bugs/add features → try common workflows.
- Whether Claude asks before changing files depends on permission mode; `Shift+Tab` cycles `default` (asks every time) → `acceptEdits` → `plan`. Some accounts also have `auto` mode.
- Type `/` to see all commands and skills; Tab for command completion; `↑` for history.
## Related
- [Overview](./overview.md)
- [How Claude Code works](./how-claude-code-works.md)
- [Best practices](./best-practices.md)
- [Common workflows](./common-workflows.md)
- [Extend Claude Code](./features-overview.md)
references/getting-started/README.md
# Getting started
Claude Code CLI 本体のリファレンス。Skills / MCP / subagents / hooks / plugins の拡張機能は anthropic-claude-code-extend、Agent SDK は anthropic-agent-sdk を参照。
| Name | Description | Path |
|------|-------------|------|
| Best practices | Claude Code を最大限に活用するためのパターン: 検証、計画、プロンプティング、環境設定、セッション管理 | [best-practices.md](./best-practices.md) |
| Common workflows | コードベース調査、バグ修正、リファクタリング、テスト、PR、ドキュメント作成、画像、ファイル参照、スケジューリングの短いプロンプトレシピ | [common-workflows.md](./common-workflows.md) |
| Explore the context window | コンテキストウィンドウがセッション中どう満杯になるか、ファイル読取コスト、ルール・フック発火をシミュレート | [context-window.md](./context-window.md) |
| Feature availability | Claude Code の機能を Anthropic サブスクリプション、Console API、Amazon Bedrock など複数プロバイダで比較 | [feature-availability.md](./feature-availability.md) |
| Extend Claude Code | CLAUDE.md、Skills、subagents、hooks、MCP、agent teams、code intelligence、plugins の使い分けを理解 | [features-overview.md](./features-overview.md) |
| Glossary | Claude Code 用語の定義: agentic loop、compaction、CLAUDE.md、hooks、subagents、MCP など | [glossary.md](./glossary.md) |
| Keep Claude working toward a goal | `/goal` で完了条件を設定するとクラウドが複数ターン続行して条件を満たすまで動作 | [goal.md](./goal.md) |
| How Claude Code works | agentic loop、ビルトインツール、セッション、コンテキストウィンドウ、チェックポイント、パーミッションを解説 | [how-claude-code-works.md](./how-claude-code-works.md) |
| How Claude remembers your project | CLAUDE.md でユーザーが書いた永続命令、auto memory でクラウドが習得した学習を自動蓄積 | [memory.md](./memory.md) |
| Overview | Claude Code はコードベースを読取・ファイル編集・コマンド実行・開発ツール連携するエージェント型コーディングツール | [overview.md](./overview.md) |
| How Claude Code uses prompt caching | Claude Code がプロンプトキャッシングを自動管理。モデル切替でキャッシュ無効化される理由など | [prompt-caching.md](./prompt-caching.md) |
| Quickstart | Claude Code をインストール、ログイン、セッション開始、最初のコード編集まで | [quickstart.md](./quickstart.md) |
| Advanced setup | システム要件、プラットフォーム別インストール、バージョン管理、アンインストール | [setup.md](./setup.md) |
references/getting-started/setup.md
<!-- source: https://code.claude.com/docs/en/setup.md / last verified: 2026-08-07 -->
# Advanced setup
System requirements, platform-specific installation, version management, and uninstallation for Claude Code.
## Signature / Usage
```bash
# macOS, Linux, WSL
# Step 1 - download to an exclusive temp file and print it for review. Nothing is executed here;
# if any step fails the temp file is removed and the chain stops.
installer="$(mktemp "${TMPDIR:-/tmp}/claude-install.XXXXXX")" \
&& curl -fsSL https://claude.ai/install.sh -o "${installer}" \
&& cat "${installer}" \
|| { rm -f -- "${installer:-}"; unset installer; echo "download failed; nothing was executed" >&2; false; }
```
Read the script printed above. Run the next block only if you have reviewed it and decided to proceed — it is a separate step so that copying the block above never executes anything.
```bash
# Step 2 - only after you have read the script above and decided to proceed, run it yourself.
# The temp file is removed afterwards; the final status is the installer's own exit status.
if [ -s "${installer:-}" ]; then
bash "${installer}"; status=$?; rm -f -- "${installer}"; unset installer
else
echo "no downloaded installer to run (Step 1 failed or was not run)" >&2; status=1
fi
(exit "${status}")
# Homebrew
brew install --cask claude-code # stable channel
brew install --cask claude-code@latest # latest channel
# WinGet
winget install Anthropic.ClaudeCode
claude --version
claude doctor
claude update
```
## Options / Props
| Requirement | Value |
|-------------|-------|
| OS | macOS 13.0+, Windows 10 1809+/Server 2019+, Ubuntu 20.04+, Debian 10+, Alpine Linux 3.19+ |
| Hardware | 4 GB+ RAM, x64 or ARM64 |
| Shell | Bash, Zsh, PowerShell, or CMD |
| Windows option | Requires | Sandboxing | When to use |
|------------------|----------|------------|-------------|
| Native Windows | None; Git for Windows optional | Not supported | Windows-native projects/tools |
| WSL 2 | WSL 2 enabled | Supported | Linux toolchains, sandboxed execution |
| WSL 1 | WSL 1 enabled | Not supported | If WSL 2 unavailable |
| `autoUpdatesChannel` | Behavior |
|------------------------|----------|
| `"latest"` (default) | New features as soon as released |
| `"stable"` | ~1 week old, skips releases with major regressions |
## Notes
- Native installations auto-update in the background; Homebrew, WinGet, apt/dnf/apk installs require manual updates unless `CLAUDE_CODE_PACKAGE_MANAGER_AUTO_UPDATE=1` (Homebrew/WinGet only).
- `minimumVersion` sets a floor auto-update won't downgrade below; managed settings `requiredMinimumVersion`/`requiredMaximumVersion` make Claude Code refuse to start outside a version range.
- `DISABLE_AUTOUPDATER=1` stops only the background check; `DISABLE_UPDATES` blocks all update paths including manual ones.
- npm install (`npm install -g @anthropic-ai/claude-code`) requires Node.js 22+ for the package manager itself but installs a native binary that doesn't use Node.js at runtime; never use `sudo npm install -g`.
- Releases publish a signed `manifest.json` (GPG key fingerprint `31DD DE24 DDFA B679 F42D 7BD2 BAA9 29FF 1A7E CACE`) for binary integrity verification; macOS/Windows binaries also carry platform-native code signatures.
- Uninstalling requires removing the binary/version files, then optionally `~/.claude`, `~/.claude.json`, project `.claude/`, and `.mcp.json` (deletes all settings, allowed tools, MCP config, and session history).
## Related
- [Overview](./overview.md)
- [Quickstart](./quickstart.md)
- [Feature availability](./feature-availability.md)
references/sessions/channels-reference.md
<!-- source: https://code.claude.com/docs/en/channels-reference / last verified: 2026-08-07 -->
# Channels reference
The MCP server contract for building a custom channel: a subprocess Claude Code spawns over stdio, which declares the `claude/channel` capability, emits `notifications/claude/channel` events, and optionally exposes a reply tool and permission relay. Research preview; requires the [`@modelcontextprotocol/sdk`](https://www.npmjs.com/package/@modelcontextprotocol/sdk) package and a Node-compatible runtime (Bun/Node/Deno).
## Signature / Usage
```ts
import { Server } from '@modelcontextprotocol/sdk/server/index.js'
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
const mcp = new Server(
{ name: 'your-channel', version: '0.0.1' },
{
capabilities: {
experimental: { 'claude/channel': {} }, // required: registers the listener
// 'claude/channel/permission': {}, // optional: opt in to permission relay
// tools: {}, // two-way only: enables reply-tool discovery
},
instructions: 'Messages arrive as <channel source="your-channel" ...>. Reply with the reply tool.',
},
)
await mcp.connect(new StdioServerTransport())
await mcp.notification({
method: 'notifications/claude/channel',
params: { content: 'build failed on main', meta: { severity: 'high', run_id: '1234' } },
})
```
```bash
claude --dangerously-load-development-channels server:webhook # bare .mcp.json server
claude --dangerously-load-development-channels plugin:yourplugin@yourmarketplace
```
## Options / Props
| Name | Type | Description |
|------|------|-------------|
| `capabilities.experimental['claude/channel']` | `object` | Required, always `{}`. Presence registers the notification listener |
| `capabilities.experimental['claude/channel/permission']` | `object` | Optional, always `{}`. Opts in to receiving permission relay requests |
| `capabilities.tools` | `object` | Two-way only, always `{}`. Standard MCP tool capability for a reply tool |
| `instructions` | `string` | Added to Claude's system prompt; explains the `<channel>` tag attributes and reply routing |
| `notifications/claude/channel` params `content` | `string` | Event body, delivered as the `<channel>` tag's body |
| `notifications/claude/channel` params `meta` | `Record<string,string>` | Becomes `<channel>` tag attributes; keys must be identifiers (letters/digits/underscore only) |
## Notes
- Claude Code spawns your server as a subprocess over stdio — chat platforms poll the platform API locally, webhook channels listen on a local HTTP port.
- `mcp.notification()` resolving means the message reached the transport, not that Claude processed it; if the session hasn't loaded your server as a channel or org policy blocks it, events are dropped silently with no error to your server. For delivery confirmation, track state yourself and use a reply tool.
- Events queue and are delivered together on Claude's next turn if several arrive while busy; run separate sessions to process independent streams concurrently.
- **Reply tool** (two-way channels): add `tools: {}` to capabilities, register `ListToolsRequestSchema`/`CallToolRequestSchema` handlers, and tell Claude in `instructions` when/how to call it.
- **Gate inbound messages**: check the sender's identity (not the room/chat identity) against an allowlist before calling `mcp.notification()` — an ungated channel is a prompt injection vector.
- **Relay permission prompts**: declare `claude/channel/permission`, handle `notifications/claude/channel/permission_request` (fields `request_id` — 5 lowercase letters excluding `l`, `tool_name`, `description`, `input_preview`), and reply with `notifications/claude/channel/permission` (`request_id`, `behavior: 'allow'|'deny'`). The local terminal dialog stays open in parallel; whichever answer arrives first wins. Only declare this capability if your channel already authenticates the sender — anyone who can reply can approve or deny tool use.
- Custom channels aren't on the approved allowlist during the research preview; use `--dangerously-load-development-channels` to bypass it per-entry (org `channelsEnabled` policy still applies). Package as a plugin and publish to a marketplace to make it installable via `/plugin install`.
## Related
- [Channels](./channels.md): install and use the built-in Telegram, Discord, iMessage, and fakechat channels
- MCP: the underlying protocol channel servers implement (see the official Model Context Protocol documentation)
references/sessions/channels.md
<!-- source: https://code.claude.com/docs/en/channels / last verified: 2026-08-07 -->
# Channels
A channel is an MCP server that pushes events (webhooks, chat messages, alerts) into a running Claude Code session so Claude can react while you're away. Channels can be two-way — Claude reads an event and replies through the same channel, like a chat bridge. Research preview; requires Anthropic authentication via claude.ai or a Console API key, not available on Bedrock/Google Cloud's Agent Platform/Microsoft Foundry, and Team/Enterprise orgs must explicitly enable it.
## Signature / Usage
```bash
/plugin install telegram@claude-plugins-official
/telegram:configure <token>
claude --channels plugin:telegram@claude-plugins-official
# Bare .mcp.json server, or multiple plugins space-separated:
claude --channels plugin:fakechat@claude-plugins-official plugin:discord@claude-plugins-official
```
## Options / Props
| Name | Type | Description |
|------|------|-------------|
| `--channels <entry...>` | flag | Space-separated list of `plugin:<name>@<marketplace>` entries to enable for this session |
| `channelsEnabled` | managed setting | Master switch; must be `true` for any channel to deliver messages |
| `allowedChannelPlugins` | managed setting | Replaces the Anthropic-maintained allowlist with an org-specific one |
## Notes
- Supported out of the box: Telegram, Discord, iMessage (chat bridges), and fakechat (a localhost demo with no auth). Each requires [Bun](https://bun.sh).
- Every approved channel maintains a sender allowlist; unlisted senders are silently dropped. Telegram/Discord bootstrap via a pairing code; iMessage lets your own address through automatically and others by handle.
- A channel with the [permission relay capability](./channels-reference.md#relay-permission-prompts) can forward tool-approval prompts to a remote device so you can approve/deny while away from the terminal.
- During the research preview, only plugins on the Anthropic-curated (or org's `allowedChannelPlugins`) allowlist can register via `--channels`; use `--dangerously-load-development-channels` to test a channel you're building.
- Comparison: Claude Code on the web runs in cloud sandboxes; Claude in Slack spawns a web session from an `@Claude` mention; a standard MCP server is pulled on demand, nothing is pushed; Remote Control lets *you* drive a local session, channels push *external* events into it.
## Related
- [Channels reference](./channels-reference.md): build your own channel (MCP server contract, reply tools, permission relay)
- [Remote Control](./remote-control.md): drive a running session from another device
references/sessions/checkpointing.md
<!-- source: https://code.claude.com/docs/en/checkpointing / last verified: 2026-08-07 -->
# Checkpointing
Claude Code automatically captures the state of your code before each user prompt, so you can undo changes or rewind the conversation and code to a previous point with `/rewind`.
## Signature / Usage
```text
/rewind
```
Or press `Esc` twice with an empty prompt input to open the rewind menu. Select a prior prompt, then choose an action.
## Options / Props
| Name | Description |
|------|-------------|
| Restore code and conversation | Revert both code and conversation to the selected point |
| Restore conversation | Rewind the conversation 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 |
| Summarize up to here | Compress the conversation before this point, keeping later messages intact |
| Never mind | Return to the message list without changes |
## Notes
- Every user prompt creates a checkpoint; Claude Code keeps snapshots for the 100 most recent checkpoints per session, and checkpoints persist with the conversation across resumes (deleted after `cleanupPeriodDays`, default 30 days).
- The two code-restore options appear only if the checkpoint has tracked file changes; otherwise the menu offers only conversation restore, summarize options, and Never mind.
- If you ran `/clear` earlier in the same process, the rewind menu shows a `/resume <session-id> (previous session)` entry to get back to the pre-clear conversation.
- **Not tracked**: files modified by Bash commands (`rm`, `mv`, `cp`, etc.), most subagent edits (except a foreground-forked skill via `context: fork` with `background: false`), external/manual edits outside the session, and symlinked or hard-linked paths (restore skips these with a `Restored the code, but skipped N files` warning).
- Checkpointing is session-level recovery, not a replacement for version control — use git for permanent history and collaboration.
## Related
- [Manage sessions](./sessions.md): `/clear`, `/compact`, and `/branch` for other ways to manage session state
- [Worktrees](./worktrees.md): isolate file edits across parallel sessions
references/sessions/deep-links.md
<!-- source: https://code.claude.com/docs/en/deep-links / last verified: 2026-08-07 -->
# Deep links
A `claude-cli://` URL that opens Claude Code in a new terminal window, optionally carrying a working directory and a pre-filled (not auto-sent) prompt. Useful for one-click entry points in runbooks, monitoring alerts, dashboards, and READMEs.
## Signature / Usage
```text
claude-cli://open
claude-cli://open?repo=acme/payments&q=Investigate%20the%20failed%20deploy
claude-cli://open?cwd=/Users/me/project&q=review%20open%20PRs
```
```bash
# macOS
open "claude-cli://open?repo=acme/payments&q=review%20open%20PRs"
# Linux
xdg-open "claude-cli://open?repo=acme/payments&q=review%20open%20PRs"
```
```powershell
# Windows PowerShell
Start-Process "claude-cli://open?repo=acme/payments&q=review%20open%20PRs"
```
## Options / Props
| Name | Type | Description |
|------|------|-------------|
| `q` | string | Text to pre-fill in the prompt box, URL-encoded; `%0A` for line breaks. Max 5,000 characters |
| `cwd` | string | Absolute path for the working directory. Network/UNC paths and paths with invisible/bidi control characters are rejected |
| `repo` | string | GitHub `owner/name` slug; resolves to the local clone you most recently ran `claude` in. Falls back to your home directory if no matching clone is known |
## Notes
- `cwd` and `repo` both set the working directory; if both are passed, `cwd` wins even if that path doesn't exist.
- The prompt is never auto-sent — a `Prompt from an external link` warning stays visible until you send or clear it, and prompts over 1,000 characters show a character count reminding you to review before pressing Enter.
- GitHub-rendered Markdown (READMEs, issues, PRs, wikis) strips `claude-cli://` links, showing only the label with no clickable link — put the URL in a code block instead so readers can copy it.
- The handler registers with the OS only after you send your **first prompt** of an interactive session (not just on startup); registration is user-level (`~/Applications/...` on macOS, a `.desktop` file on Linux, a registry key on Windows).
- Disable registration entirely with `disableDeepLinkRegistration: "disable"` in `settings.json`, or enforce it via managed settings.
- The VS Code extension registers a separate handler, `vscode://anthropic.claude-code/open`, which opens an editor tab instead of a terminal.
## Related
- [Manage sessions](./sessions.md): name, resume, and switch conversations opened via a deep link
references/sessions/README.md
# Sessions
| Name | Description | Path |
|------|-------------|------|
| Channels | MCP サーバーがイベント(webhook、チャットメッセージ、アラート)を実行中セッションにプッシュ。双方向化でチャットブリッジ化も可能 | [channels.md](./channels.md) |
| Channels reference | カスタムチャネル構築向け MCP サーバーコントラクト。stdio 経由の subprocess で `claude/channel` capability 宣言・通知発行 | [channels-reference.md](./channels-reference.md) |
| Checkpointing | Claude Code がユーザープロンプト前に自動的にコード状態をキャプチャ。`/rewind` で変更を取り消し・会話やコードを前の位置に戻す | [checkpointing.md](./checkpointing.md) |
| Deep links | `claude-cli://` URL でターミナルウィンドウ起動、working directory と事前埋込プロンプト指定可能 | [deep-links.md](./deep-links.md) |
| Remote Control | claude.ai/code またはモバイルアプリを机上の Claude Code セッションに接続。ローカル実行のまま遠隔操作可 | [remote-control.md](./remote-control.md) |
| Manage sessions | セッションはプロジェクトディレクトリに紐付けた保存済み会話。JSONL で局所保存。resume・branch・切り替え可能 | [sessions.md](./sessions.md) |
| Worktrees | git worktree は separate working directory。各 Claude Code セッションを独立 worktree で実行すれば編集が衝突しない | [worktrees.md](./worktrees.md) |
references/sessions/remote-control.md
<!-- source: https://code.claude.com/docs/en/remote-control / last verified: 2026-08-07 -->
# Remote Control
Connects claude.ai/code or the Claude mobile app to a Claude Code session running on your machine, so you can start a task at your desk and continue it from your phone or another browser. Claude keeps running locally the entire time — code execution and filesystem access never leave your machine. Research preview, available on all plans (off by default for Team/Enterprise until an Owner enables it).
## Signature / Usage
```bash
claude remote-control # server mode: waits for remote connections
claude --remote-control # interactive session, also controllable remotely
claude --remote-control "My Project" # same, with a custom session title
/remote-control # promote an existing session to Remote Control
/remote-control My Project # same, with a custom title
```
## Options / Props
| Name | Type | Description |
|------|------|-------------|
| `--name "My Project"` | flag | Custom session title shown at claude.ai/code |
| `-c`, `--continue` | flag | Resume the most recent Remote Control session from this directory (server mode only) |
| `--session-id <id>` | flag | Resume a specific Remote Control session by ID (server mode only) |
| `--spawn <mode>` | flag | `same-dir` (default), `worktree` (each session gets its own git worktree), or `session` (single-session mode) |
| `--capacity <N>` | flag | Max concurrent sessions in server mode, default 32 |
| `--[no-]create-session-in-dir` | flag | Pre-create one session in the current directory at server start (on by default) |
| `--sandbox` / `--no-sandbox` | flag | Enable/disable sandboxing for filesystem and network isolation |
## Notes
- Requirements: Pro/Max/Team/Enterprise (no API keys), sign-in via `/login`, `api.anthropic.com` as the endpoint (not Bedrock/Google Cloud's Agent Platform/Microsoft Foundry, and not a custom `ANTHROPIC_BASE_URL`), feature-flag evaluation enabled (`DISABLE_TELEMETRY`/`DO_NOT_TRACK`/etc. must be unset), and workspace trust already accepted for the project directory.
- All traffic is outbound HTTPS only — Claude Code never opens inbound ports. Session transcripts are stored on Anthropic servers while connected, to keep devices in sync and support reconnection.
- **Trusted Devices** (beta, Team/Enterprise): requires an enrolled device plus a sign-in no more than 18 hours old (Face ID/Touch ID/Windows Hello/passkey step-up) before a device can view or steer a Remote Control session.
- Enable auto-connect for every session with `/config` → **Enable Remote Control for all sessions**, or the `remoteControlAtStartup` setting.
- Mobile push notifications require the Claude mobile app signed in with the same account, plus `/config` → **Push when Claude decides** / **Push when actions required**.
- Some commands are local-terminal-only (`/plugin`, `/resume`); text-output commands (`/compact`, `/clear`, `/context`, `/usage`, `/recap`, `/reload-plugins`) and `/model`, `/effort`, `/fast`, `/color`, `/rename`, `/mcp`, `/config`, `/autocompact` work from mobile/web with adapted argument-passing.
- Compare with Claude Code on the web (cloud infra, no local filesystem), Dispatch (message a task to spawn a Desktop session), and Channels (push external events into a session).
## Related
- [Channels](./channels.md): push events into a running session instead of steering it remotely
- [Manage sessions](./sessions.md): naming, resuming, and the session picker
references/sessions/sessions.md
<!-- source: https://code.claude.com/docs/en/sessions / last verified: 2026-08-07 -->
# Manage sessions
A session is a saved conversation tied to a project directory, stored locally as JSONL so you can resume, branch, or switch between tasks. This page covers the CLI; the desktop app, Claude Code on the web, and the VS Code extension each keep their own session history.
## Signature / Usage
```bash
claude --continue # resume the most recent session in this directory
claude --resume # open the interactive session picker
claude --resume <name> # resume a named session directly
claude --resume <session-id> # resume by ID, searches this project then every project
claude --from-pr <number> # session picker filtered to sessions linked to a PR
/resume [<name>] # switch conversation from inside a session
/branch [<name>] # copy the conversation and switch into the copy
claude --continue --fork-session # branch from the CLI
/rename <name> # rename the current session
/export [<file>] # copy or save the rendered transcript
```
## Options / Props
| Name | Type | Description |
|------|------|-------------|
| `--continue` | flag | Resumes the most recent session in the current directory |
| `--resume [name\|id]` | flag/arg | Opens the session picker, or resumes a specific session directly |
| `--from-pr <number>` | flag | Opens the session picker filtered to sessions linked to that pull request |
| `--fork-session` | flag | Combine with `--continue`/`--resume` to branch into a new session ID |
| `-n <name>` | flag | Set a session name at startup |
| `--no-session-persistence` | flag | Suppresses transcript writes for one non-interactive `claude -p` run |
## Notes
- What a resumed session restores: conversation history, model (unless retired/disallowed/pinned by flag), agent (with tool restrictions), permission mode (`plan`/`bypassPermissions` never restored), active goal, and unexpired scheduled tasks. Flags like `--mcp-config`, `--settings`, `--plugin-dir`, `--fallback-model`, and `--add-dir` are **not** restored and must be passed again.
- Resuming a session inactive for over an hour and above 100,000 tokens (Pro/Max) offers a dialog: **Resume from summary** (runs `/compact`), **Resume full session as-is**, or **Don't ask me again**.
- The session picker defaults to the current worktree plus directories added with `/add-dir`; widen with `Ctrl+W` (all worktrees) or `Ctrl+A` (all projects).
- `/clear` saves the previous conversation; resume it with `/resume` or the rewind menu's previous-session entry.
- Transcripts are stored as JSONL at `~/.claude/projects/<project>/<session-id>.jsonl`. The entry format is internal and can change between releases — use `/export` or the script interfaces (`claude -p --output-format json`, `claude -p --resume`, hook `transcript_path`, or the Agent SDK) instead of parsing JSONL directly.
- Agent SDK session persistence (mirroring transcripts to S3/Redis/custom backends, resuming across hosts) is a separate topic — see the `anthropic-agent-sdk` skill.
## Related
- [Worktrees](./worktrees.md): run isolated parallel sessions on separate branches
- [Checkpointing](./checkpointing.md): rewind code and conversation to an earlier point
- [Remote Control](./remote-control.md): continue a local session from another device
references/sessions/worktrees.md
<!-- source: https://code.claude.com/docs/en/worktrees / last verified: 2026-08-07 -->
# Worktrees
A git worktree is a separate working directory with its own files and branch, sharing repository history and remote with the main checkout. Running each Claude Code session in its own worktree keeps edits from colliding, so one session can build a feature while another fixes a bug. Requires a git repository unless you replace the git logic with `WorktreeCreate`/`WorktreeRemove` hooks.
## Signature / Usage
```bash
claude --worktree feature-auth # or -w; creates .claude/worktrees/feature-auth on branch worktree-feature-auth
claude --worktree "#1234" # branch from PR #1234 (quote so the shell doesn't treat # as a comment)
git worktree add ../project-feature-a -b feature-a # manual worktree creation
git worktree list
git worktree remove ../project-feature-a
```
```json
{
"worktree": { "baseRef": "head" }
}
```
## Options / Props
| Name | Type | Description |
|------|------|-------------|
| `--worktree <name>` / `-w` | flag | Creates an isolated worktree under `.claude/worktrees/<name>/` on a new branch and starts Claude there |
| `worktree.baseRef` | setting | `"fresh"` (default, branches from the remote default branch) or `"head"` (branches from current local `HEAD`, carrying unpushed commits) |
| `isolation: worktree` | subagent frontmatter | Runs a custom subagent (`.claude/agents/`) in its own temporary worktree |
| `.worktreeinclude` | file | `.gitignore`-syntax list of gitignored files (e.g. `.env`) to copy into every new worktree |
## Notes
- Claude Code enforces isolation for any session running in a worktree (interactive, background, or subagent): it blocks `Edit`/`Write`/`NotebookEdit` targeting the main checkout, blocks Bash/PowerShell/Monitor commands whose working directory resolves there, and blocks git redirects (`git -C`, `--git-dir`, `GIT_DIR`/`GIT_WORK_TREE`, or a `cd` before `git`) into the main checkout.
- On exit, an unnamed session's clean worktree is auto-removed; a named session, or one with uncommitted/untracked changes or new commits, prompts you to keep or remove it. `-p` runs have no exit prompt — clean up with `git worktree remove`.
- Resuming a session returns it to its worktree (interactive, `-p --continue/--resume`, and the Agent SDK) after Claude Code verifies the directory is still a genuine separate checkout; a periodic sweep also removes stale subagent/background-session worktrees older than `cleanupPeriodDays` that hold no uncommitted work.
- Worktrees share the repository's `.git` directory, project-scope plugins, and saved "don't ask again" permission approvals with the main checkout — approvals persist even after the worktree is removed.
- Agent SDK session resume across worktrees follows the same re-entry logic described here; for SDK-side session *storage* (mirroring transcripts to S3/Redis/custom backends), see the `anthropic-agent-sdk` skill.
## Related
- [Manage sessions](./sessions.md): resuming a worktree-bound session
- [Checkpointing](./checkpointing.md): rewind file changes within a single session
references/settings/auto-mode-config.md
<!-- source: https://code.claude.com/docs/en/auto-mode-config.md / last verified: 2026-08-07 -->
# Configure auto mode
Auto mode lets Claude Code run without routine permission prompts by routing tool calls through a classifier that blocks anything irreversible, destructive, or aimed outside your environment. Deny and explicit ask rules are evaluated *before* the classifier and still block/prompt. This page is the configuration reference; see permission-modes docs for what auto mode is and how to enable it.
Available to all users on every provider (Anthropic API, Claude Platform on AWS, Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, signed-in Claude apps gateway). By default, the classifier trusts only the working directory and the current repo's configured remotes.
## Common boundaries
Auto mode allows pushes to any branch of the working repository, including the default branch, and PR creation by default (since v2.1.211; before that, only the working branch, Claude-created branches, and the default branch). A non-default branch whose name marks it as a deploy target (`production`, `release`, `gh-pages`) isn't covered by that default — the classifier judges it on its own terms. Force pushes, secrets entering a commit, or content that would leave the repo via CI/deploy stay blocked regardless.
### Add a human checkpoint
```json
{ "permissions": { "ask": ["Bash(git push *)", "Bash(gh pr create *)"] } }
```
| Boundary | Mechanism | Behavior in auto mode |
| --- | --- | --- |
| Prompt before the action | `permissions.ask` | Always prompts for content-scoped rules; classifier can't auto-approve |
| Never run the action | `permissions.deny` | Blocks before the classifier is consulted; nothing can override it |
| One-off boundary for this session | State it in conversation | Classifier blocks it, but can be lost to context compaction — use `ask`/`deny` for a durable guarantee |
## Where the classifier reads configuration
The classifier reads the same CLAUDE.md content Claude reads, so project-wide instructions steer both. For cross-project rules, use the `autoMode` settings block:
| Scope | File | Use for |
| --- | --- | --- |
| One developer | `~/.claude/settings.json` | Personal trusted infrastructure |
| Organization-wide | Managed settings | Trusted infrastructure distributed to all developers |
| `--settings` flag or Agent SDK | Inline JSON | Per-invocation overrides for automation |
**Not read** from `.claude/settings.json` or `.claude/settings.local.json` (project-directory files a repo or build step could inject rules into). Before v2.1.207, `.claude/settings.local.json` was also read — move any `autoMode` there to `~/.claude/settings.json`. Entries from each scope combine additively; a developer-added `allow` entry can override an organization `soft_deny` entry.
## Define trusted infrastructure
`autoMode.environment` is usually the only field needed. Three entry kinds (v2.1.198+; before v2.1.195 only the first five):
- **Context slots** (no rules of their own; describe posture): Organization, Primary use of Claude Code, Cloud provider(s), Repository visibility, Internal sharing/snippet hosting, Org-specific CLIs, Secrets management, CI/CD deploy targets, Network posture, Protected deployment namespaces/environments, Data retention/declassification.
- **Trust slots** (name what's inside the boundary; default `None configured` except repo/source-control which default to the working repo+remotes): Trusted repo, Source control, Trusted internal domains, Trusted cloud buckets, Key internal services, Internal package registry.
- **Sensitivity slots** (name what protective rules treat as high-risk; default to broad heuristics like `prod`/`production` in the name): Sensitive data locations & audiences, Sensitive remote targets, Protected IaC scopes.
```json
{
"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"
]
}
}
```
Include the literal string `"$defaults"` to splice in the built-in entries alongside your own (position matters). Entries are prose, not regex/tool patterns — write them like describing your infrastructure to a new engineer: organization/primary use, source control orgs, cloud providers and trusted buckets, trusted internal domains, key internal services, internal package registry, sensitive data locations & audiences, sensitive remote targets, protected IaC scopes, additional context. (The registry/sensitivity entries require v2.1.195+.)
## Override the block and allow rules
```json
{
"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"],
"soft_deny": ["$defaults", "Never run database migrations outside the migrations CLI, even against dev databases"],
"hard_deny": ["$defaults", "Never send repository contents to third-party code-review APIs"]
}
}
```
Precedence inside the classifier: `hard_deny` (unconditional) > `soft_deny` (blocks unless overridden) > `allow` (exceptions to `soft_deny`) > explicit user intent (overrides remaining soft blocks only when the message directly and specifically names the exact action — general requests like "clean up the repo" don't count). **Omitting `"$defaults"` from an array discards the built-in rules for that section entirely** — only do this after reviewing `claude auto-mode defaults` output and copying what you still want.
## Route all shell commands through the classifier
```json
{ "autoMode": { "classifyAllShell": true } }
```
By default, narrow Bash/PowerShell allow rules (e.g. `Bash(npm test)`) still resolve before the classifier in auto mode; only broad rules (`Bash(*)`, wildcarded interpreters) are suspended. Setting `classifyAllShell: true` suspends every shell allow rule, trading latency (each command becomes a classifier call) for coverage. Requires v2.1.193+; applies only while auto mode is active.
## Inspect the defaults and your effective config
| Command | Purpose |
| --- | --- |
| `claude auto-mode defaults` | Print built-in `environment`/`allow`/`soft_deny`/`hard_deny` rules as JSON (`--label <prefix>` filters by label prefix, v2.1.208+) |
| `claude auto-mode config` | Print what the classifier actually uses, with your settings applied and defaults otherwise |
| `claude auto-mode critique` | AI feedback on your custom `allow`/`soft_deny`/`hard_deny` rules |
| `claude auto-mode reset` | Remove `autoMode` from `~/.claude/settings.json`, restoring defaults (`--yes` skips confirmation; v2.1.212+; doesn't touch managed/`--settings` sources) |
## Review denials
Denials appear under `/permissions` → **Recently denied**; press `r` to mark for retry. The shown reason is usually the fixed text `Blocked by classifier` (v2.1.208+); some sessions show a short model-written explanation instead. Fix a denial by adding the destination to `autoMode.environment`, adding an `allow` rule, or stating the one-off intent and retrying. Programmatic reaction: the `PermissionDenied` hook.
## Options / Props
| Key | Type | Description |
| --- | --- | --- |
| `autoMode.environment` | array | Trusted repos/buckets/domains/services (prose); `"$defaults"` splices in built-ins |
| `autoMode.allow` | array | Exceptions to `soft_deny` (prose) |
| `autoMode.soft_deny` | array | Destructive actions user intent can clear (prose) |
| `autoMode.hard_deny` | array | Unconditional security boundaries (prose) |
| `autoMode.classifyAllShell` | boolean | Route every shell command through the classifier while auto mode is active |
## Notes
This page was retrieved in full (no truncation observed).
## Related
- [settings.md](./settings.md): the `autoMode` key's place among other settings, and settings-file precedence
- [errors.md](./errors.md): classifier failure messages (`Auto mode cannot determine the safety of an action`, `Auto mode classifier transcript exceeded context window`)
references/settings/claude-directory.md
<!-- source: https://code.claude.com/docs/en/claude-directory.md / last verified: 2026-08-07 -->
# Explore the .claude directory
Where Claude Code reads CLAUDE.md, settings.json, hooks, skills, commands, subagents, workflows, rules, and auto memory — both in a project's `.claude/` and in `~/.claude` in your home directory. Commit project files to git to share with your team; `~/.claude` is personal, applies across all projects. On Windows, `~/.claude` resolves to `%USERPROFILE%\.claude`; if `CLAUDE_CONFIG_DIR` is set, every `~/.claude` path lives under that directory instead.
## Signature / Usage
Project tree (root of repo unless noted):
```text
your-project/
CLAUDE.md # committed — project instructions loaded every session
.mcp.json # committed — project-scoped MCP servers
.worktreeinclude # committed — gitignored files to copy into new worktrees
.claude/
settings.json # committed — permissions, hooks, statusLine, model, env, outputStyle
settings.local.json # gitignored — personal overrides, highest precedence of user-editable files
rules/*.md # committed — topic-scoped instructions, optionally paths-gated
skills/<name>/SKILL.md # committed — reusable prompts, /name or auto-invoked
commands/*.md # committed — single-file prompts (same mechanism as skills)
output-styles/*.md # committed — project-scoped output styles
agents/*.md # committed — subagent definitions
workflows/*.js # committed — dynamic workflow scripts
agent-memory/<name>/MEMORY.md # committed, Claude-written — project-scoped subagent memory
```
Global tree (`~/`):
```text
~/.claude.json # local — app state, OAuth, UI toggles, personal MCP servers
~/.claude/
CLAUDE.md # local — personal preferences across every project
settings.json # local — defaults for all projects
keybindings.json # local — custom keyboard shortcuts
themes/*.json # local — custom color themes
projects/<project>/memory/MEMORY.md # local, Claude-written — auto memory
rules/*.md # local — user-level rules
skills/, commands/, output-styles/, agents/, workflows/, agent-memory/ # personal counterparts of the project folders
```
## Options / Props
### What's not shown in the tree
| File | Location | Purpose |
| --- | --- | --- |
| `managed-settings.json` | System-level, varies by OS | Enterprise-enforced settings you can't override (apart from narrow exceptions) |
| `CLAUDE.local.md` | Project root | Private preferences for this project, loaded alongside CLAUDE.md; create manually, add to `.gitignore` |
| Installed plugins | `~/.claude/plugins` | Cloned marketplaces, installed plugin versions, per-plugin data; orphaned versions deleted 14 days after update/uninstall |
### Choose the right file
| You want to | Edit | Scope |
| --- | --- | --- |
| Give Claude project context and conventions | `CLAUDE.md` | project or global |
| Allow or block specific tool calls | `settings.json` `permissions`/`hooks` | project or global |
| Run a script before/after tool calls | `settings.json` `hooks` | project or global |
| Set environment variables for the session | `settings.json` `env` | project or global |
| Keep personal overrides out of git | `settings.local.json` | project only |
| Add a prompt/capability invoked with `/name` | `skills/<name>/SKILL.md` | project or global |
| Define a specialized subagent | `agents/*.md` | project or global |
| Orchestrate many subagents from a script | `workflows/*.js` | project or global |
| Connect external tools over MCP | `.mcp.json` | project only |
| Change how Claude formats responses | `output-styles/*.md` | project or global |
### File reference (Commit column = typically checked into git)
| File | Scope | Commit | What it does |
| --- | --- | --- | --- |
| `CLAUDE.md` | Project and global | Yes | Instructions loaded every session |
| `rules/*.md` | Project and global | Yes | Topic-scoped instructions, optionally path-gated (via `paths:` frontmatter) |
| `settings.json` | Project and global | Yes | Permissions, hooks, env vars, model defaults |
| `settings.local.json` | Project only | No | Personal overrides, gitignored when Claude Code saves a setting to it |
| `.mcp.json` | Project only | Yes | Team-shared MCP servers |
| `.worktreeinclude` | Project only | Yes | Gitignored files to copy into new worktrees |
| `skills/<name>/SKILL.md` | Project and global | Yes | Reusable prompts, `/name` or auto-invoked |
| `commands/*.md` | Project and global | Yes | Single-file prompts, same mechanism as skills |
| `output-styles/*.md` | Project and global | Yes | Custom system-prompt sections |
| `agents/*.md` | Project and global | Yes | Subagent definitions with own prompt and tools |
| `workflows/*.js` | Project and global | Yes | Dynamic workflow scripts, saved from `/workflows`, each becomes a `/<name>` command |
| `agent-memory/<name>/` | Project and global | Yes | Persistent memory for subagents (`memory:` frontmatter) |
| `~/.claude.json` | Global only | No | App state, OAuth, UI toggles, personal MCP servers |
| `projects/<project>/memory/` | Global only | No | Auto memory: Claude's notes to itself across sessions |
| `keybindings.json` | Global only | No | Custom keyboard shortcuts |
| `themes/*.json` | Global only | No | Custom color themes |
Key example fields per file:
- `CLAUDE.md` — free markdown, e.g. `## Commands`, `## Stack`, `## Rules` sections.
- `.mcp.json` — `{"mcpServers": {"<name>": {"command": "...", "args": [...], "env": {"TOKEN": "${TOKEN}"}}}}`.
- `.worktreeinclude` — `.gitignore`-syntax lines, e.g. `.env`, `config/secrets.json`.
- `.claude/settings.json` — `{"permissions": {"allow": [...], "deny": [...]}, "hooks": {"PostToolUse": [...]}}`.
- `rules/*.md` frontmatter — `paths: ["**/*.test.ts"]` to path-gate loading; rules without `paths:` load like CLAUDE.md at session start.
- `skills/<name>/SKILL.md` frontmatter — `description`, `disable-model-invocation: true` (user-only skills), `argument-hint`; body can use `` !`shell command` `` injection and `$ARGUMENTS`/`$0`/`$1` positional args.
- `agents/*.md` frontmatter — `name`, `description`, `tools: Read, Grep, Glob` to restrict tool access; body becomes the subagent's system prompt.
- `agent-memory/<name>/MEMORY.md` — Claude writes/maintains this itself once a subagent's frontmatter sets `memory: project` (or `memory: local` for `.claude/agent-memory-local/`, `memory: user` for `~/.claude/agent-memory/`).
- `~/.claude.json` — `{"autoConnectIde": true, "externalEditorContext": true, "mcpServers": {...}}`.
- `~/.claude/keybindings.json` — see `keybindings.md`.
- `~/.claude/themes/*.json` — see `terminal-config.md`.
- `~/.claude/projects/<project>/memory/MEMORY.md` — Claude-maintained index (first 200 lines / 25KB loaded at session start); links to topic files (e.g. `debugging.md`) read on demand.
- `~/.claude/output-styles/*.md` frontmatter — `description`, `keep-coding-instructions: true` to keep default task instructions alongside custom additions.
## Application data
Beyond authored config, `~/.claude` holds data Claude Code writes during sessions — plaintext, not encrypted at rest.
### Cleaned up automatically (age > `cleanupPeriodDays`, default 30, swept at startup)
| Path under `~/.claude/` | Contents |
| --- | --- |
| `projects/<project>/<session>.jsonl` | Full conversation transcript |
| `projects/<project>/<session>/subagents/` | Subagent transcripts |
| `projects/<project>/<session>/tool-results/` | Large tool outputs spilled to files |
| `file-history/<session>/` | Pre-edit snapshots for checkpoint restore (100 most recent checkpoints) |
| `plans/` | Plan-mode plan files |
| `debug/` | Per-session debug logs (`--debug`/`/debug` only) |
| `paste-cache/`, `image-cache/` | Large pastes and attached images |
| `session-env/` | Per-session environment metadata |
| `tasks/` | Per-session task lists |
| `shell-snapshots/` | Aliases/functions/shell options applied to each Bash command; removed on clean exit |
| `backups/` | Timestamped `~/.claude.json` backups before config migrations |
| `feedback-bundles/` | Redacted transcript archives from `/feedback` |
| `todos/`, `statsig/`, `logs/` | Legacy, no longer written |
`sessions/` (one file per running session, for crash/concurrency detection) is not part of the age-based sweep — removed on session exit instead.
### Kept until you delete them
| Path under `~/.claude/` | Contents |
| --- | --- |
| `history.jsonl` | Every prompt typed, with timestamp/project path (up-arrow recall) |
| `stats-cache.json` | Aggregated token/cost counts for `/usage` |
| `remote-settings.json` | Cached server-managed settings |
| `cache/changelog.md` | Cached changelog for post-update release notes |
| `policy-limits.json` | Cached feature policy settings |
### Clear local data
`claude project purge [path]` deletes transcripts/memory under `projects/`, per-session `tasks/`/`debug/`/`file-history/`, matching `history.jsonl` lines, and the project's `~/.claude.json` entry. `--dry-run` previews the plan; `--yes` skips confirmation; `--all` purges every project (deletes `history.jsonl` outright); `-i` steps through items one at a time. Never touches `shell-snapshots/` or `backups/` (not project-scoped). Do not manually delete `~/.claude.json`, `~/.claude/settings.json`, or `~/.claude/plugins/` — those hold auth, preferences, and installed plugins.
## Notes
This page's content is authored as an interactive JS explorer component; the textual descriptions, examples, and reference tables above were extracted from its embedded data and the surrounding prose. No truncation observed.
## Related
- [settings.md](./settings.md): the full `settings.json` key reference and scope precedence
- [debug-your-config.md](./debug-your-config.md): inspection commands (`/context`, `/doctor`, `/hooks`, `/mcp`, `/status`)
- [keybindings.md](./keybindings.md) and [terminal-config.md](./terminal-config.md): `keybindings.json` and `themes/*.json` detail
references/settings/cli-reference.md
<!-- source: https://code.claude.com/docs/en/cli-reference.md / last verified: 2026-08-07 -->
# CLI reference
Complete reference for the Claude Code command-line interface: commands and flags. `claude --help` doesn't list every flag, so absence from `--help` doesn't mean unavailable.
## Signature / Usage
```bash
claude "explain this project"
claude -p "explain this function"
cat logs.txt | claude -p "explain"
claude --continue
claude --resume auth-refactor
```
## CLI commands
| Command | Description |
| --- | --- |
| `claude` | Start interactive session |
| `claude "query"` | Start interactive session with initial prompt |
| `claude -p "query"` | Query via SDK, then exit |
| `cat file \| claude -p "query"` | Process piped content |
| `claude -c` / `claude -c -p "query"` | Continue most recent conversation in current directory |
| `claude -r "<session>" "query"` | Resume session by ID or name |
| `claude update` | Update to latest version |
| `claude gateway` | Start the self-hosted Claude apps gateway server (`--config gateway.yaml` required) |
| `claude install [version]` | Install/reinstall the native binary (`stable`, `latest`, or a version like `2.1.118`) |
| `claude auth login` | Sign in (`--email`, `--sso`, `--console`) |
| `claude auth logout` | Log out |
| `claude auth status` | Auth status as JSON (`--text` for readable); exit 0 logged in / 1 not |
| `claude agents` | Open agent view for background sessions (`--cwd`, `--json`, `--json --all`, `--permission-mode`, `--model`, `--effort`, `--agent`, `--settings`, `--add-dir`, `--plugin-dir`, `--mcp-config`) |
| `claude attach <id>` | Attach to a background session in this terminal |
| `claude auto-mode defaults` | Print built-in auto mode classifier rules as JSON (`--label <prefix>`, v2.1.208+) |
| `claude auto-mode reset` | Restore default auto mode config, removing `autoMode` from user settings (`-y`/`--yes`; v2.1.212+) |
| `claude daemon status` | Print background-session supervisor state/version/socket dir/worker count |
| `claude daemon stop --any` | Stop the supervisor and its sessions (`--keep-workers` to leave sessions running) |
| `claude doctor` | Read-only install/settings diagnostics without starting a session |
| `claude logs <id>` | Print recent output from a background session |
| `claude mcp` | Configure MCP servers |
| `claude mcp login <name>` | Run an MCP server's OAuth flow (`--no-browser` for SSH; v2.1.186+) |
| `claude mcp logout <name>` | Clear stored OAuth credentials for an MCP server (v2.1.186+) |
| `claude plugin` (alias `claude plugins`) | Manage plugins |
| `claude project purge [path]` | Delete local state for a project (`--dry-run`, `-y`/`--yes`, `-i`/`--interactive`, `--all`) |
| `claude remote-control` | Start a Remote Control server (server mode, no local interactive session) |
| `claude respawn <id>` | Restart a background session, keeping conversation intact (`--all`) |
| `claude rm <id>` | Remove a background session from the list (transcript stays on disk) |
| `claude setup-token` | Generate a long-lived OAuth token for CI/scripts |
| `claude stop <id>` (alias `claude kill`) | Stop a background session |
| `claude ultrareview [target]` | Run ultrareview non-interactively (`--json`, `--timeout <minutes>`, default 30) |
Mistyped subcommands get a "Did you mean" suggestion instead of starting a session. As of v2.1.199, a **leading** `--dangerously-skip-permissions`/`--allow-dangerously-skip-permissions` flag routes `daemon <subcommand>` correctly instead of being swallowed as the prompt text.
## CLI flags
| Flag | Description |
| --- | --- |
| `--add-dir` | Add additional working directories (file access only, not config discovery); persist via `permissions.additionalDirectories` |
| `--advisor <model>` | Enable the server-side advisor for this session (`opus`/`sonnet`/full ID; not `fable`) |
| `--agent` | Specify an agent for the session (overrides `agent` setting) |
| `--agents` | Define custom subagents via JSON (same fields as frontmatter, plus `prompt`) |
| `--allow-dangerously-skip-permissions` | Add `bypassPermissions` to the Shift+Tab cycle without starting in it |
| `--allowedTools`, `--allowed-tools` | Tools that execute without prompting |
| `--append-subagent-system-prompt` | Append text to every subagent's system prompt (print mode only; v2.1.205+) |
| `--append-system-prompt` | Append text to the default system prompt |
| `--append-system-prompt-file` | Append system prompt text from a file |
| `--autocompact <auto\|tokens>` | Set the auto-compact window for this session (v2.1.221+) |
| `--ax-screen-reader` | Screen-reader friendly flat-text output; forces classic renderer (v2.1.181+) |
| `--bare` | Minimal mode: skip hooks/skills/plugins/MCP/auto memory/CLAUDE.md discovery; sets `CLAUDE_CODE_SIMPLE` |
| `--betas` | Beta headers for API requests (API key users only) |
| `--bg`, `--background` | Start as a background agent, print session ID and return immediately; combine with `--exec` or `--agent`; cannot combine with `-p` |
| `--channels` | (Research preview) MCP servers whose channel notifications to listen for |
| `--chrome` / `--no-chrome` | Enable/disable Chrome browser integration |
| `--cloud` | Create a new web session on claude.ai |
| `--continue`, `-c` | Load the most recent conversation in the current directory |
| `--dangerously-load-development-channels` | Enable non-allowlisted channels for local development |
| `--dangerously-skip-permissions` | Skip permission prompts; equivalent to `--permission-mode bypassPermissions` |
| `--debug` | Debug mode with optional category filter, e.g. `--debug='mcp,startup'` or `--debug='!1p'` |
| `--debug-file <path>` | Write debug logs to a specific path; implicitly enables debug mode |
| `--disable-slash-commands` | Disable all skills and commands for this session |
| `--disallowedTools`, `--disallowed-tools` | Deny rules; bare tool name removes the tool, `"*"` removes all, `"mcp__*"` removes MCP tools |
| `--effort` | Effort level for the session: `low`/`medium`/`high`/`xhigh`/`max`/`ultracode` |
| `--exclude-dynamic-system-prompt-sections` | Move per-machine system-prompt sections into the first user message (improves cache reuse) |
| `--exec` | Run a shell command as a PTY-backed background job instead of a Claude session (use with `--bg`) |
| `--fallback-model` | Comma-separated fallback model chain, tried in order |
| `--fork-session` | On resume, create a new session ID instead of reusing the original |
| `--forward-subagent-text` | Emit subagent text/thinking as `assistant`/`user` messages with `parent_tool_use_id` (needs `--print --output-format stream-json`; v2.1.211+) |
| `--from-pr` | Open the session picker filtered to sessions linked to a PR/MR |
| `--ide` | Auto-connect to IDE on startup if exactly one is available |
| `--init` | Run Setup hooks with the `init` matcher before the session (print mode only) |
| `--init-only` | Run Setup and `SessionStart` hooks, then exit without starting a conversation |
| `--include-hook-events` | Include hook lifecycle events in the output stream (`--output-format stream-json`) |
| `--include-partial-messages` | Include partial streaming events (`--print --output-format stream-json`) |
| `--input-format` | `text` or `stream-json` (print mode) |
| `--json-schema` | Get JSON output matching a JSON Schema after the workflow completes (print mode only) |
| `--maintenance` | Run Setup hooks with the `maintenance` matcher before the session (print mode only) |
| `--max-budget-usd` | Max USD spend on API calls before stopping (print mode only; subagent spend counts) |
| `--max-turns` | Limit agentic turns (print mode only); errors when reached |
| `--mcp-config` | Load MCP servers from JSON files/strings (space-separated) |
| `--model` | Model alias (`sonnet`/`opus`/`haiku`/`fable`) or full name for this session |
| `--name`, `-n` | Set a display name for the session (shown in `/resume`, terminal title) |
| `--no-session-persistence` | Disable session persistence (print mode only) |
| `--output-format` | `text`, `json`, or `stream-json` (print mode) |
| `--permission-mode` | `default`/`acceptEdits`/`plan`/`auto`/`dontAsk`/`bypassPermissions`/`manual` (alias for `default`, v2.1.200+); overrides `defaultMode` |
| `--permission-prompt-tool` | MCP tool to handle permission prompts in non-interactive mode |
| `--plugin-dir` | Load a plugin from a directory or `.zip` for this session only (repeatable) |
| `--plugin-url` | Fetch a plugin `.zip` from a URL for this session only (repeatable) |
| `--print`, `-p` | Print response without interactive mode |
| `--prompt-suggestions` | Emit a `prompt_suggestion` message after each turn (needs `--print --output-format stream-json --verbose`) |
| `--remote` | Deprecated alias for `--cloud` |
| `--remote-control`, `--rc` | Start an interactive session with Remote Control enabled |
| `--remote-control-session-name-prefix <prefix>` | Prefix for auto-generated Remote Control session names (default: hostname) |
| `--replay-user-messages` | Re-emit stdin user messages on stdout for acknowledgment |
| `--resume`, `-r` | Resume a session by ID/name, or show a picker |
| `--safe-mode` | Disable all customizations to troubleshoot a broken configuration; sets `CLAUDE_CODE_SAFE_MODE` |
| `--session-id` | Use a specific session ID (must be a valid UUID) |
| `--setting-sources` | Comma-separated setting sources to load: `user`, `project`, `local` |
| `--settings` | Path to a settings JSON file or inline JSON string (max 2 MiB); overrides matching keys for this session |
| `--strict-mcp-config` | Only use MCP servers from `--mcp-config`, ignoring all other MCP configuration |
| `--system-prompt` | Replace the entire system prompt |
| `--system-prompt-file` | Load system prompt from a file, replacing the default |
| `--teleport` | Resume a web session in the local terminal |
| `--teammate-mode` | Agent-team teammate display: `in-process` (default), `auto`, `tmux`, `iterm2` |
| `--tmux` | Create a tmux session for the worktree (requires `--worktree`; `--tmux=classic` for traditional tmux) |
| `--tools` | Restrict which built-in tools Claude can use (`""` disables all, `"default"` all, or a comma list) |
| `--verbose` | Full turn-by-turn output; overrides `viewMode` setting |
| `--version`, `-v` | Output the version number |
| `--worktree`, `-w` | Start in an isolated git worktree at `<repo>/.claude/worktrees/<name>`; accepts `#<number>` or a PR URL |
## Notes
- `--enable-auto-mode` was removed in v2.1.111; use `--permission-mode auto` instead.
- Session-scoped flags (`--model`, `--effort`, `--fallback-model`) apply only to the session launched with them and don't persist as a saved default; use `/model`, `/effort`, or the corresponding settings key to persist.
## Related
- [settings.md](./settings.md): the settings-file equivalents of many flags (`model`, `effortLevel`, `fallbackModel`, `defaultMode`)
- [env-vars.md](./env-vars.md): env vars behind several flags (`CLAUDE_CODE_SAFE_MODE`, `CLAUDE_CODE_SIMPLE`)
- [errors.md](./errors.md): the `--bg and --print conflict` and other command-line errors
references/settings/debug-your-config.md
<!-- source: https://code.claude.com/docs/en/debug-your-config.md / last verified: 2026-08-07 -->
# Debug your configuration
Diagnose why CLAUDE.md, settings, hooks, MCP servers, or skills aren't taking effect. For installation/auth/connectivity problems, see the troubleshoot-install docs instead.
## See what loaded into context
`/context` shows everything in the context window by category: system prompt, system tools, MCP tools, custom subagents (with source), memory files, skills, conversation messages. Run it first to confirm CLAUDE.md/rules/skill descriptions loaded.
| Command | Shows |
| --- | --- |
| `/memory` | Memory file locations (user/project scopes) with edit links, auto memory folder/toggle |
| `/skills` | Available skills from project, user, and plugin sources |
| `/hooks` | Active hook configurations |
| `/mcp` | Connected MCP servers and status |
| `/permissions` | Resolved allow/deny rules in effect |
| `/doctor` | Setup checkup: install health, invalid settings files, unused extensions, duplicate subagent names, checked-in CLAUDE.md content Claude can derive, with proposed fixes |
| `/debug [issue]` | Enables debug logging and prompts Claude to diagnose using logs/settings paths |
| `/status` | Active settings sources, including whether managed settings are in effect |
Subdirectory `CLAUDE.md` files load on demand (when Claude reads a file in that directory), not at session start.
## Check resolved settings
Precedence: **Managed** first (apart from a few exceptions) > closer scope wins among **Local** > **Project** > **User**; CLI flags and env vars are another override layer.
`/doctor` reports invalid settings files, duplicate installs, unused extensions, and trimmable checked-in CLAUDE.md content, then proposes fixes applied only after confirmation. `claude doctor` (terminal) prints the same diagnostics read-only without starting a session. `/status` shows which settings sources are active.
## Check MCP servers
`/mcp` lists every configured server, connection status, and project approval state.
- Project-scoped `.mcp.json` servers require one-time approval; if dismissed, they stay disabled until approved from `/mcp`.
- A failed-to-start server usually has a relative path in `command`/`args` (resolves against the launch directory, not `.mcp.json`'s location).
- Connected-but-zero-tools: select **Reconnect** from `/mcp`; if still zero, run `claude --debug=mcp` and check `~/.claude/debug/<session-id>.txt`.
## Check hooks
`/hooks` lists every registered hook by event. Common failure causes:
- `matcher` must be a single string using `|` (or `,`, v2.1.191+) to match multiple tools, e.g. `"Edit|Write"` — an array value is a schema error that rejects the whole settings file.
- Misspelled tool name → matches nothing, silently.
- Edits take effect after a brief file-stability delay; re-run `/hooks` if it still shows the old definition.
If `/hooks` shows the hook but it still doesn't fire, run `claude --debug` and trigger the tool call to see matcher evaluation and exit code/output live.
## Test against a clean configuration
`claude --safe-mode` disables all customizations (CLAUDE.md, skills, plugins, hooks, MCP servers, custom commands/agents) while keeping auth, model selection, built-in tools, and permissions. Managed hooks/policy still apply.
For a fully clean slate, point `CLAUDE_CONFIG_DIR` at an empty directory and launch from a directory with no `.claude`/`.mcp.json`/`CLAUDE.md`:
```bash
cd /tmp && CLAUDE_CONFIG_DIR=/tmp/claude-clean claude
```
Managed settings still apply (system path outside `~/.claude`). Linux/Windows prompt for login again (credentials live under the config dir); macOS Keychain credentials carry over.
## Check common causes
| Symptom | Cause | Fix |
| --- | --- | --- |
| Hook never fires | `matcher` is a JSON array | Use a string with `\|`, e.g. `"Edit\|Write"` |
| Hook never fires | `matcher` uses `,` before v2.1.191 | Use `\|`, or upgrade |
| Hook never fires | `matcher` is lowercase (e.g. `"bash"`) | Matching is case-sensitive: `Bash`, `Edit`, `Write`, `Read` |
| Hook never fires | Hooks defined in a standalone file | There is no standalone hooks file for project/user config — use the `"hooks"` key in `settings.json` (only plugins load `hooks/hooks.json`) |
| Global permissions/hooks/env ignored | Added to `~/.claude.json` | That file holds app state/UI toggles; `permissions`/`hooks`/`env` belong in `~/.claude/settings.json` |
| `settings.json` value seems ignored | Same key set in `settings.local.json` | `settings.local.json` overrides `settings.json`, both override `~/.claude/settings.json` |
| Skill doesn't appear in `/skills` | File at `.claude/skills/name.md` instead of a folder | Use `.claude/skills/name/SKILL.md` |
| Skill in `/skills` but never auto-invoked | `disable-model-invocation: true`, or description doesn't match phrasing | Check the "user-only" badge in `/skills` |
| Subdirectory CLAUDE.md ignored | Loads on demand, not at session start | Loads only when Claude Reads a file in that directory |
| Subagent ignores CLAUDE.md | Built-in Explore/Plan agents skip CLAUDE.md | Restate the instruction in the delegating prompt; custom subagents load CLAUDE.md normally |
| Cleanup logic never runs at session end | No `SessionEnd` hook configured | Add one in `settings.json` |
| `.mcp.json` servers never load | File under `.claude/` or Desktop-app-format | Project MCP config goes at the repo root as `.mcp.json` |
| `mcpServers` under `settings.json` never appears | `settings.json` doesn't read an `mcpServers` key | Use `.mcp.json` (project) or `claude mcp add --scope user` |
| Project MCP server added but doesn't appear | One-time approval prompt dismissed | Approve from `/mcp` |
| MCP server fails to start from some directories | Relative path in `command`/`args` | Use absolute paths (executables on `PATH` like `npx`/`uvx` are fine) |
| MCP server starts without expected env vars | Server's `.mcp.json` entry doesn't set them | Set per-server `env` inside the `.mcp.json` entry |
| `Bash(rm *)` deny rule doesn't block `/bin/rm`/`find -delete` | Prefix rules match the literal command string | Add explicit patterns for each variant, or use a `PreToolUse` hook / sandbox |
## Related
- [claude-directory.md](./claude-directory.md): every config file location and what reads it
- [settings.md](./settings.md): precedence order and the full key list
## Notes
This page was retrieved in full (no truncation observed).
references/settings/env-vars.md
<!-- source: https://code.claude.com/docs/en/env-vars.md / last verified: 2026-08-07 -->
# Environment variables
Reference for environment variables that control Claude Code behavior: model selection, authentication, request routing, and feature toggles. Many behaviors are also configurable via a settings file field, a CLI flag, or an in-session command like `/model`.
## Set environment variables
**In your shell**: lasts for that terminal session.
```bash
export API_TIMEOUT_MS="1200000"
claude
```
**In a settings file**: applies every time `claude` runs, under the `env` key.
```json ~/.claude/settings.json
{
"env": {
"API_TIMEOUT_MS": "1200000",
"BASH_DEFAULT_TIMEOUT_MS": "300000"
}
}
```
| File | Applies to |
| --- | --- |
| `~/.claude/settings.json` | You, in every project |
| `.claude/settings.json` | Everyone in the project, checked into source control |
| `.claude/settings.local.json` | You, in this project only (gitignored) |
| Managed settings | Everyone in your organization |
A running session applies new/changed `env` values on file save; a feature that reads its variables once at startup (e.g. OpenTelemetry monitoring) keeps its startup values until relaunch. Removing a variable from the file doesn't unset it in a running session.
## Precedence
When a behavior has both an env var and a settings key, **the environment variable takes precedence** (e.g. `ANTHROPIC_MODEL` overrides `model`; `CLAUDE_CODE_AUTO_CONNECT_IDE` overrides `autoConnectIde`). When the same variable is set in both your shell and a settings file `env` block, **the settings file value applies** (Claude Code writes it into the process environment, replacing the shell-inherited value). To force-unset a variable you can't remove from your shell profile, set it to `""` in the `env` block — Claude Code treats an empty value as unset for provider selection (subprocesses still inherit the empty value). Between settings files, `env` follows normal settings precedence (managed > local > project > user).
Numeric variables (timeouts, token budgets, retry counts) accept scientific notation and digit separators (`2e3` = 2000, `64_000` = 64000), except where noted as plain-digits-only. For on/off variables, `1`/`true` = on, `0`/`false` = off (any casing), **except** these which read only "is it set at all" (any non-empty value including `0` turns it on; unset or empty turns it off): `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`, `DISABLE_TELEMETRY`, `DISABLE_ERROR_REPORTING`, `CLAUDE_CODE_TMUX_TRUECOLOR`, `FALLBACK_FOR_ALL_PRIMARY_MODELS`, `IS_DEMO`. `FORCE_HYPERLINK` reads a number; only `0` turns it off.
## Variables
Alphabetical reference of every environment variable.
| Variable | Purpose |
| --- | --- |
| `ANTHROPIC_API_KEY` | API key sent as `X-Api-Key`. Overrides a Pro/Max/Team/Enterprise subscription when set. In `-p` mode always used; interactive mode prompts to approve once. `unset ANTHROPIC_API_KEY` to use subscription instead |
| `ANTHROPIC_AUTH_TOKEN` | Custom `Authorization` header value (prefixed with `Bearer `) |
| `ANTHROPIC_AWS_API_KEY` | Workspace API key for Claude Platform on AWS; sent as `x-api-key`, takes precedence over AWS SigV4 |
| `ANTHROPIC_AWS_BASE_URL` | Override Claude Platform on AWS endpoint URL |
| `ANTHROPIC_AWS_WORKSPACE_ID` | Required for Claude Platform on AWS; sent as `anthropic-workspace-id` header |
| `ANTHROPIC_BASE_URL` | Override the API endpoint (proxy/gateway). Non-first-party host disables MCP tool search by default (`ENABLE_TOOL_SEARCH=true` to re-enable if the proxy forwards `tool_reference`). Disables Remote Control when not `api.anthropic.com` |
| `ANTHROPIC_BEDROCK_BASE_URL` | Override Amazon Bedrock endpoint URL |
| `ANTHROPIC_BEDROCK_MANTLE_BASE_URL` | Override Amazon Bedrock Mantle endpoint URL |
| `ANTHROPIC_BEDROCK_SERVICE_TIER` | Amazon Bedrock service tier (`default`, `flex`, `priority`); sent as `X-Amzn-Bedrock-Service-Tier` |
| `ANTHROPIC_BETAS` | Comma-separated `anthropic-beta` header values, works with all auth methods |
| `ANTHROPIC_CUSTOM_HEADERS` | Custom headers, `Name: Value` newline-separated |
| `ANTHROPIC_CUSTOM_MODEL_OPTION` | Model ID added as a custom entry in the `/model` picker |
| `ANTHROPIC_CUSTOM_MODEL_OPTION_DESCRIPTION` | Description for the custom model entry (default `Custom model (<model-id>)`) |
| `ANTHROPIC_CUSTOM_MODEL_OPTION_NAME` | Display name for the custom model entry (default: the model ID) |
| `ANTHROPIC_CUSTOM_MODEL_OPTION_SUPPORTED_CAPABILITIES` | Comma-separated capabilities the custom model supports, e.g. `effort,thinking` |
| `ANTHROPIC_DEFAULT_FABLE_MODEL` | Model ID for the `fable` alias and Fable-5 recognition for automatic fallback on third-party providers |
| `ANTHROPIC_DEFAULT_FABLE_MODEL_DESCRIPTION` / `_NAME` / `_SUPPORTED_CAPABILITIES` | Pinned Fable model display/capability overrides |
| `ANTHROPIC_DEFAULT_HAIKU_MODEL` | Model ID for the `haiku` alias and background functionality |
| `ANTHROPIC_DEFAULT_HAIKU_MODEL_DESCRIPTION` / `_NAME` / `_SUPPORTED_CAPABILITIES` | Pinned Haiku model display/capability overrides |
| `ANTHROPIC_DEFAULT_OPUS_MODEL` | Model ID for the `opus` alias and plan-mode phase of `opusplan` |
| `ANTHROPIC_DEFAULT_OPUS_MODEL_DESCRIPTION` / `_NAME` / `_SUPPORTED_CAPABILITIES` | Pinned Opus model display/capability overrides |
| `ANTHROPIC_DEFAULT_SONNET_MODEL` | Model ID for the `sonnet` alias and execution phase of `opusplan` |
| `ANTHROPIC_DEFAULT_SONNET_MODEL_DESCRIPTION` / `_NAME` / `_SUPPORTED_CAPABILITIES` | Pinned Sonnet model display/capability overrides |
| `ANTHROPIC_FOUNDRY_API_KEY` | API key for Microsoft Foundry |
| `ANTHROPIC_FOUNDRY_AUTH_TOKEN` | Bearer token for Microsoft Foundry, e.g. Entra access token; takes precedence over `ANTHROPIC_FOUNDRY_API_KEY` and the Azure default credential chain |
| `ANTHROPIC_FOUNDRY_BASE_URL` | Full base URL for the Microsoft Foundry resource |
| `ANTHROPIC_FOUNDRY_RESOURCE` | Microsoft Foundry resource name (required if `ANTHROPIC_FOUNDRY_BASE_URL` unset) |
| `ANTHROPIC_MODEL` | Model setting name (see model-config.md) |
| `ANTHROPIC_SMALL_FAST_MODEL` | Deprecated; use `ANTHROPIC_DEFAULT_HAIKU_MODEL` |
| `ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION` | Override AWS region for the Haiku-class model on Amazon Bedrock/Mantle |
| `ANTHROPIC_VERTEX_BASE_URL` | Override Google Cloud's Agent Platform endpoint URL |
| `ANTHROPIC_VERTEX_PROJECT_ID` | GCP project ID for Google Cloud's Agent Platform; overridden by `GCLOUD_PROJECT`/`GOOGLE_CLOUD_PROJECT`/credential file project |
| `ANTHROPIC_WORKSPACE_ID` | Workspace ID for workload identity federation, when the federation rule spans multiple workspaces |
| `API_FORCE_IDLE_TIMEOUT` | Override the 5-minute streaming body idle timeout; `0` disables it, `1` forces it on for every provider |
| `API_TIMEOUT_MS` | API request timeout in ms (default 600000/10 min; max 2147483647) |
| `AWS_BEARER_TOKEN_BEDROCK` | Amazon Bedrock API key |
| `BASH_DEFAULT_TIMEOUT_MS` | Default long-running Bash command timeout (default 120000/2 min) |
| `BASH_MAX_OUTPUT_LENGTH` | Max characters of Bash output read back (default 30000; max 150000) |
| `BASH_MAX_TIMEOUT_MS` | Max timeout the model can set for Bash commands (default 600000/10 min); ceiling is the larger of this and `BASH_DEFAULT_TIMEOUT_MS` |
| `CCR_FORCE_BUNDLE` | `1` forces `claude --cloud` to bundle/upload the local repo even when GitHub access is available |
| `CLAUDECODE` | `1` in subprocesses Claude Code spawns (Bash/PowerShell tools, tmux, hooks, status line, stdio MCP subprocesses); IDE extensions also set it |
| `CLAUDE_AFK_COUNTDOWN_MS` | On-screen countdown before an unanswered `AskUserQuestion` auto-continues (default 20000) |
| `CLAUDE_AFK_TIMEOUT_MS` | Idle ms before an unanswered `AskUserQuestion` auto-continues; overrides the `askUserQuestionTimeout` setting when set |
| `CLAUDE_AGENT_SDK_DISABLE_BUILTIN_AGENTS` | `1` disables built-in subagent types (Explore, Plan) in non-interactive (`-p`) mode |
| `CLAUDE_AGENT_SDK_MCP_NO_PREFIX` | `1` skips the `mcp__<server>__` prefix on SDK-created MCP server tool names |
| `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS` | Stall timeout for background subagents (default 600000/10 min); resets on each streaming progress event |
| `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` | Percentage (1-100) of the auto-compact window that triggers compaction; can only lower, not raise, the default |
| `CLAUDE_AUTO_BACKGROUND_TASKS` | `1` force-enables auto-backgrounding of long-running agent tasks (~2 min) and long MCP tool calls in non-interactive mode |
| `CLAUDE_AX_SCREEN_READER` | `1` enables screen-reader flat-text output; `0` forces it off even if the `axScreenReader` setting is `true` |
| `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR` | Return to the original working directory after each Bash/PowerShell command in the main session |
| `CLAUDE_BYTE_STREAM_IDLE_TIMEOUT_MS` | Timeout for the byte-level streaming idle watchdog only (clamped 10s-30min) |
| `CLAUDE_CLIENT_PRESENCE_FILE` | Path to a file an external tool creates on unlock/deletes on lock; while present, skips Remote Control mobile push notifications |
| `CLAUDE_CODE_ACCESSIBILITY` | `1` keeps the native terminal cursor visible (disables inverted-text cursor) for screen magnifiers |
| `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD` | `1` loads memory files (`CLAUDE.md`, `.claude/CLAUDE.md`, `.claude/rules/*.md`, `CLAUDE.local.md`) from `--add-dir` directories |
| `CLAUDE_CODE_ALT_SCREEN_FULL_REPAINT` | `1` repaints the full screen every frame in fullscreen rendering instead of incremental updates |
| `CLAUDE_CODE_ALWAYS_ENABLE_EFFORT` | `1` sends the effort parameter on every request, even for unrecognized model IDs (except models known to reject it) |
| `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` | Interval (ms) to refresh credentials via `apiKeyHelper` |
| `CLAUDE_CODE_ARTIFACT_AUTO_OPEN` | `0` stops auto-opening the browser when a new artifact is published |
| `CLAUDE_CODE_ATTRIBUTION_HEADER` | `0` omits the attribution block (client version + prompt fingerprint) from the system prompt start |
| `CLAUDE_CODE_AUTO_COMPACT_WINDOW` | Auto-compact window in tokens (100000-1000000), plain integer only; takes precedence over `/autocompact`, `--autocompact`, and the `autoCompactWindow` setting |
| `CLAUDE_CODE_AUTO_CONNECT_IDE` | Override automatic IDE connection (`false`/`true`); takes precedence over the `autoConnectIde` setting |
| `CLAUDE_CODE_AWS_CHAIN_RESOLVE_TIMEOUT_MS` | Wait time for the AWS default credential provider chain (default 60000) |
| `CLAUDE_CODE_BRIDGE_SESSION_ID` | Set automatically in Bash/hook subprocesses while a Remote Control connection is active; the session's `session_` ID |
| `CLAUDE_CODE_CERT_STORE` | Comma-separated CA sources for TLS: `bundled` (Mozilla set) and/or `system`. Default `bundled,system` |
| `CLAUDE_CODE_CHILD_SESSION` | `1` in subprocesses Claude Code spawns directly (Bash/PowerShell/Monitor tools, hooks, status line); not set for stdio MCP subprocesses |
| `CLAUDE_CODE_CLIENT_CERT` | Path to client certificate file for mTLS |
| `CLAUDE_CODE_CLIENT_KEY` | Path to client private key file for mTLS |
| `CLAUDE_CODE_CLIENT_KEY_PASSPHRASE` | Passphrase for encrypted `CLAUDE_CODE_CLIENT_KEY` |
| `CLAUDE_CODE_CONNECT_TIMEOUT_MS` | Removed (no-op) since v2.1.186; use `API_TIMEOUT_MS` |
| `CLAUDE_CODE_DEBUG_LOGS_DIR` | Override debug log file path (a file path, not a directory). Requires `--debug`/`/debug`/`DEBUG` to actually enable logging. Default `~/.claude/debug/<session-id>.txt` |
| `CLAUDE_CODE_DEBUG_LOG_LEVEL` | Min log level written to the debug log: `verbose`, `debug` (default), `info`, `warn`, `error` |
| `CLAUDE_CODE_DISABLE_1M_CONTEXT` | `1` disables 1M context window support entirely |
| `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING` | `1` disables adaptive reasoning on Opus 4.6/Sonnet 4.6, falling back to a fixed `MAX_THINKING_TOKENS` budget. No effect on Fable 5, Sonnet 5, or Opus 4.7+ |
| `CLAUDE_CODE_DISABLE_ADMIN_ENV_UNION` | `1` stops merging managed-settings `env` blocks per key across admin sources; only the highest-priority source's whole `env` block applies (pre-v2.1.223 behavior) |
| `CLAUDE_CODE_DISABLE_ADVISOR_TOOL` | `1` disables the advisor tool; `/advisor` unavailable, `advisorModel` ignored, `--advisor` accepted but no-op |
| `CLAUDE_CODE_DISABLE_AGENT_VIEW` | `1` turns off background agents/agent view (`claude agents`, `--bg`, `/background`). Same as `disableAgentView` setting |
| `CLAUDE_CODE_DISABLE_ALTERNATE_SCREEN` | `1` disables fullscreen rendering, using the classic main-screen renderer; native scrollback stays usable. Takes precedence over `CLAUDE_CODE_NO_FLICKER` and the `tui` setting |
| `CLAUDE_CODE_DISABLE_ARTIFACT` | `1` disables the Artifact tool. Same as `disableArtifact` setting |
| `CLAUDE_CODE_DISABLE_ATTACHMENTS` | `1` disables attachment processing; `@` file mentions sent as plain text instead of expanded content |
| `CLAUDE_CODE_DISABLE_AUTO_MEMORY` | `1` disables auto memory; `0` forces it on even under `--bare` or `autoMemoryEnabled: false` |
| `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` | `1` disables all background task functionality: `run_in_background`, auto-backgrounding, Ctrl+B |
| `CLAUDE_CODE_DISABLE_BEDROCK_CONTENT_TYPE_GUARD` | `1` skips the check that an Amazon Bedrock streaming response has `application/vnd.amazon.eventstream` content-type (for gateways that rewrite only the header) |
| `CLAUDE_CODE_DISABLE_BG_EXIT_HANDOFF` | `1` stops handing off a background session's running shells/workflows/subagents to the next process when the supervisor stops/restarts |
| `CLAUDE_CODE_DISABLE_BG_SHELL_PRESSURE_REAP` | `1` stops terminating background shell commands on OS memory-pressure signals (macOS/Linux only) |
| `CLAUDE_CODE_DISABLE_BUNDLED_SKILLS` | `1` disables bundled skills/workflows. Same as `disableBundledSkills` setting |
| `CLAUDE_CODE_DISABLE_CLAUDE_MDS` | `1` prevents loading any CLAUDE.md memory files (user, project, auto-memory) |
| `CLAUDE_CODE_DISABLE_CRON` | `1` disables scheduled tasks; `/loop` and cron tools unavailable, already-scheduled tasks stop firing |
| `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` | `1` strips `anthropic-beta` headers and beta tool-schema fields for gateways that reject them; also disables MCP tool search |
| `CLAUDE_CODE_DISABLE_EXPLORE_PLAN_AGENTS` | `1` disables the built-in Explore/Plan subagents; Claude explores directly or via general-purpose subagent instead |
| `CLAUDE_CODE_DISABLE_FAST_MODE` | `1` disables fast mode |
| `CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY` | `1` disables the session quality survey. Also disabled by `DISABLE_TELEMETRY`/`DO_NOT_TRACK`/`CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` unless `CLAUDE_CODE_ENABLE_FEEDBACK_SURVEY_FOR_OTEL` opts back in |
| `CLAUDE_CODE_DISABLE_FILE_CHECKPOINTING` | `1` disables file checkpointing; `/rewind` can't restore code changes. Overrides `fileCheckpointingEnabled` |
| `CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS` | `1` removes built-in commit/PR workflow instructions and git status from the system prompt |
| `CLAUDE_CODE_DISABLE_LEGACY_MODEL_REMAP` | `1` prevents auto-remapping Opus 4.0/4.1 to the current Opus version on the Anthropic API |
| `CLAUDE_CODE_DISABLE_MOUSE` | `1` disables mouse tracking in fullscreen rendering (keyboard scrolling with PgUp/PgDn still works) |
| `CLAUDE_CODE_DISABLE_MOUSE_CLICKS` | `1` disables click/drag/hover in fullscreen rendering while keeping wheel scrolling |
| `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` | Any non-empty value disables auto-updates, telemetry, error reporting, `/feedback`, release notes, gateway model discovery, and availability checks. Unlike most on/off vars, `0`/`false` still disables it |
| `CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK` | `1` disables the non-streaming fallback when a streaming request fails mid-stream |
| `CLAUDE_CODE_DISABLE_NOTIFICATION_PRESENCE_CHECK` | `1` sends the `PushNotification` tool's desktop notification even while you're actively typing/focused on the terminal |
| `CLAUDE_CODE_DISABLE_OFFICIAL_MARKETPLACE_AUTOINSTALL` | `1` disables automatic registration of the official plugin marketplace (checked at first interactive launch) |
| `CLAUDE_CODE_DISABLE_POLICY_SKILLS` | `1` skips loading skills from the system-wide managed skills directory |
| `CLAUDE_CODE_DISABLE_TERMINAL_TITLE` | `1` disables automatic terminal title updates; also skips the background title-generation request in Agent SDK/`claude -p` |
| `CLAUDE_CODE_DISABLE_THINKING` | `1` omits the `thinking` parameter entirely, for proxies/gateways that reject it |
| `CLAUDE_CODE_DISABLE_VIRTUAL_SCROLL` | `1` disables virtual scrolling in fullscreen rendering, rendering every message |
| `CLAUDE_CODE_DISABLE_WORKFLOWS` | `1` disables dynamic workflows. Same as `disableWorkflows` setting |
| `CLAUDE_CODE_EFFORT_LEVEL` | Effort level for supported models: `low`/`medium`/`high`/`xhigh`/`max`/`auto`. Takes precedence over `/effort` and the `effortLevel` setting |
| `CLAUDE_CODE_ENABLE_APPEND_SUBAGENT_PROMPT` | `1` enables appending extra text to every subagent's system prompt (set automatically by `--append-subagent-system-prompt`) |
| `CLAUDE_CODE_ENABLE_AUTO_MODE` | No-op, kept for compatibility; auto mode is available by default on every provider |
| `CLAUDE_CODE_ENABLE_AWAY_SUMMARY` | Override session-recap availability: `0` forces off, `1` forces on regardless of `awaySummaryEnabled` |
| `CLAUDE_CODE_ENABLE_BACKGROUND_PLUGIN_REFRESH` | `1` refreshes plugin state at turn boundaries in non-interactive mode after a background install completes |
| `CLAUDE_CODE_ENABLE_FEEDBACK_SURVEY_FOR_OTEL` | `1` routes the session quality survey to your own OTEL collector instead of Anthropic when nonessential traffic is blocked |
| `CLAUDE_CODE_ENABLE_FINE_GRAINED_TOOL_STREAMING` | Controls whether tool call inputs stream as Claude generates them; `0` opts out, `1` forces on behind a proxy |
| `CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY` | `1` populates the `/model` picker from the gateway's `/v1/models` endpoint when `ANTHROPIC_BASE_URL` points at an Anthropic-compatible gateway |
| `CLAUDE_CODE_ENABLE_OPUS_4_7_FAST_MODE` | Removed in v2.1.142 |
| `CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION` | `false` disables prompt suggestions (the grayed-out predictions after Claude responds) |
| `CLAUDE_CODE_ENABLE_TASKS` | Controls structured Task tools vs. legacy `TodoWrite`; Task tools are default since v2.1.142, `0` reverts to `TodoWrite` |
| `CLAUDE_CODE_ENABLE_TELEMETRY` | `1` enables OpenTelemetry data collection; required before configuring OTel exporters |
| `CLAUDE_CODE_EXIT_AFTER_STOP_DELAY` | Milliseconds to wait after the query loop becomes idle before auto-exiting (automated workflows/SDK) |
| `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` | `1` enables agent teams (experimental, disabled by default) |
| `CLAUDE_CODE_EXTRA_BODY` | JSON object merged into the top level of every API request body, for provider-specific parameters |
| `CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS` | Override the default token limit for file reads |
| `CLAUDE_CODE_FORCE_SESSION_PERSISTENCE` | `1` forces transcript persistence/prompt history/`claude agents` registration even when launched from inside another Claude Code session |
| `CLAUDE_CODE_FORCE_STRIKETHROUGH` | `1` forces `~~text~~` strikethrough rendering when the terminal supports it but isn't auto-detected |
| `CLAUDE_CODE_FORCE_SYNC_OUTPUT` | `1` force-enables synchronized output (DEC 2026) for terminals not auto-detected; no effect under tmux |
| `CLAUDE_CODE_FORK_SUBAGENT` | `1`/`0` lets Claude spawn forked subagents (inherit full conversation context), overriding server-side rollout |
| `CLAUDE_CODE_FORWARD_SUBAGENT_TEXT` | `1` emits subagent text/thinking blocks in `claude -p --output-format stream-json` output, same as `--forward-subagent-text` |
| `CLAUDE_CODE_GIT_BASH_PATH` | Windows only: path to the Git Bash `bash.exe` when not on PATH |
| `CLAUDE_CODE_GLOB_HIDDEN` | `false` excludes dotfiles from Glob tool results (included by default) |
| `CLAUDE_CODE_GLOB_NO_IGNORE` | `false` makes the Glob tool respect `.gitignore` patterns (ignored by default) |
| `CLAUDE_CODE_GLOB_TIMEOUT_SECONDS` | Timeout for Glob tool file discovery (default 20s, 60s on WSL) |
| `CLAUDE_CODE_HIDE_CWD` | `1` hides the working directory in the startup logo (screenshares/recordings) |
| `CLAUDE_CODE_IDE_HOST_OVERRIDE` | Override the host address used to connect to the IDE extension |
| `CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL` | `1` skips IDE extension auto-installation. Same as `autoInstallIdeExtension: false` |
| `CLAUDE_CODE_IDE_SKIP_VALID_CHECK` | `1` skips validation of IDE lockfile entries during connection |
| `CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS` | Max concurrently running subagents per session before the Agent tool refuses to spawn another (default 20) |
| `CLAUDE_CODE_MAX_CONTEXT_TOKENS` | Override the assumed context window size for the active model, e.g. for a gateway-routed model with a nonstandard window |
| `CLAUDE_CODE_MAX_OUTPUT_TOKENS` | Max output tokens for most requests; defaults to 32000 for unrecognized model IDs |
| `CLAUDE_CODE_MAX_RETRIES` | Number of retry attempts for failed API requests (default 10, capped 15 unless `CLAUDE_CODE_RETRY_WATCHDOG` is set) |
| `CLAUDE_CODE_MAX_SUBAGENTS_PER_SESSION` | Cap on subagents one session can spawn (default 200) |
| `CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH` | Subagent nesting depth below the main conversation (default 3); `1` disables nesting |
| `CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY` | Max read-only tools/subagents executing in parallel (default 10) |
| `CLAUDE_CODE_MAX_TURNS` | Cap agentic turns when no explicit `--max-turns` is passed |
| `CLAUDE_CODE_MAX_WEB_SEARCHES_PER_SESSION` | Cap on total WebSearch calls one session can make (default 200) |
| `CLAUDE_CODE_MCP_ALLOWLIST_ENV` | `1` spawns stdio MCP servers with only a safe baseline environment plus the server's configured `env` |
| `CLAUDE_CODE_MCP_AUTO_BACKGROUND_MS` | Elapsed time before a still-running MCP tool call moves to a background task (default 120000); `0` disables |
| `CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT` | Idle timeout for MCP tool calls with no response/progress; overrides per-transport defaults |
| `CLAUDE_CODE_NATIVE_CURSOR` | `1` shows the terminal's own cursor at the input caret instead of a drawn block |
| `CLAUDE_CODE_NEW_INIT` | `1` makes `/init` run an interactive setup flow (asks which files to generate) |
| `CLAUDE_CODE_NO_FLICKER` | `1` enables fullscreen rendering. Same as the `tui` setting; also `/tui fullscreen` |
| `CLAUDE_CODE_OAUTH_REFRESH_TOKEN` | OAuth refresh token for Claude.ai auth; `claude auth login` exchanges it directly. Requires `CLAUDE_CODE_OAUTH_SCOPES` |
| `CLAUDE_CODE_OAUTH_SCOPES` | Space-separated OAuth scopes the refresh token was issued with |
| `CLAUDE_CODE_OAUTH_TOKEN` | OAuth access token for Claude.ai auth; alternative to `/login` for SDK/automation. Generate with `claude setup-token` |
| `CLAUDE_CODE_OPUS_4_6_FAST_MODE_OVERRIDE` | Removed in v2.1.160, now a no-op |
| `CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH` | Max length of content-bearing OTEL attributes in UTF-16 code units (default 61440, i.e. 60KB) |
| `CLAUDE_CODE_OTEL_DIAG_STDERR` | `1` writes OpenTelemetry exporter diagnostic errors to stderr (otherwise only with `--debug`) |
| `CLAUDE_CODE_OTEL_FLUSH_TIMEOUT_MS` | Timeout for flushing pending OTEL spans (default 5000) |
| `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS` | Interval for refreshing dynamic OTEL headers (default 1740000/29 min) |
| `CLAUDE_CODE_OTEL_SHUTDOWN_TIMEOUT_MS` | Timeout for the OTEL exporter to finish on shutdown (default 2000) |
| `CLAUDE_CODE_PACKAGE_MANAGER_AUTO_UPDATE` | `1` lets Claude Code run your package manager's upgrade command in the background (Homebrew/WinGet) |
| `CLAUDE_CODE_PERFORCE_MODE` | `1` enables Perforce-aware write protection (Edit/Write/NotebookEdit fail with a `p4 edit` hint) |
| `CLAUDE_CODE_PLUGIN_CACHE_DIR` | Override the plugins root directory (default `~/.claude/plugins`) |
| `CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS` | Timeout for git operations installing/updating plugins (default 120000) |
| `CLAUDE_CODE_PLUGIN_KEEP_MARKETPLACE_ON_FAILURE` | `1` keeps the existing marketplace cache when `git pull` fails instead of re-cloning (offline/airgapped) |
| `CLAUDE_CODE_PLUGIN_PREFER_HTTPS` | `1` clones GitHub `owner/repo` shorthand over HTTPS instead of SSH |
| `CLAUDE_CODE_PLUGIN_SEED_DIR` | Path(s) to read-only plugin seed directories (`:`/`;`-separated), for pre-populated container images |
| `CLAUDE_CODE_POWERSHELL_RESPECT_EXECUTION_POLICY` | `1` stops passing `-ExecutionPolicy Bypass` when spawning PowerShell; respects the machine's effective policy instead |
| `CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS` | Max wait after the final turn for background subagents/workflows in `-p` mode (default 600000/10 min); `0` waits indefinitely |
| `CLAUDE_CODE_PROCESS_WRAPPER` | Corporate launcher argv prefix for processes Claude Code starts from its own binary. Set in `env` block only, not shell export |
| `CLAUDE_CODE_PROPAGATE_TRACEPARENT` | `1` propagates W3C trace context (`traceparent` header/env var) when `ANTHROPIC_BASE_URL` points at a custom proxy |
| `CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST` | Set by embedding host platforms; Claude Code ignores provider-selection/model-selection env vars and managed keys in favor of the host's routing |
| `CLAUDE_CODE_PROXY_RESOLVES_HOSTS` | `1` allows the proxy to perform DNS resolution instead of the caller |
| `CLAUDE_CODE_REMOTE` | Set automatically to `true` in cloud sessions; read to detect cloud-session context |
| `CLAUDE_CODE_REMOTE_SESSION_ID` | Set automatically in cloud sessions to the current session ID |
| `CLAUDE_CODE_RESUME_INTERRUPTED_TURN` | `1` auto-resumes if the previous session ended mid-turn (SDK mode) |
| `CLAUDE_CODE_RESUME_INTERRUPTED_TURN_MAX_AGE_MS` | Max age of the last transcript message for auto-resume to continue automatically; unset/`0` = no bound |
| `CLAUDE_CODE_RESUME_PROMPT` | Override the injected continuation message when resuming a mid-turn session (default `Continue from where you left off.`) |
| `CLAUDE_CODE_RETRY_WATCHDOG` | `1` retries `429`/`529` indefinitely for unattended sessions; also raises other transient-error retries to ~300 |
| `CLAUDE_CODE_SAFE_MODE` | `1` starts in safe mode (see `--safe-mode` in `cli-reference.md`); set automatically by that flag |
| `CLAUDE_CODE_SCRIPT_CAPS` | JSON object limiting how many times specific scripts may be invoked per session (with `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB`) |
| `CLAUDE_CODE_SCROLL_SPEED` | Mouse wheel scroll multiplier in fullscreen rendering (0-20, fractional allowed) |
| `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS` | Time budget for `SessionEnd` hooks (default 1.5s, auto-raised up to 60s) |
| `CLAUDE_CODE_SESSION_ID` | Set automatically to the current session ID in Bash/PowerShell/hook/stdio-MCP subprocesses |
| `CLAUDE_CODE_SHELL` | Shell Claude Code uses for Bash tool commands: a `bash` or `zsh` binary path |
| `CLAUDE_CODE_SHELL_PREFIX` | Command prefix wrapping shell commands Claude Code spawns (Bash tool, hooks, status line, stdio MCP startup), for logging/auditing |
| `CLAUDE_CODE_SIMPLE` | `1` runs with a minimal system prompt and only Bash/file-read/file-edit tools. Same as `--bare` |
| `CLAUDE_CODE_SIMPLE_SYSTEM_PROMPT` | `1` uses a shorter system prompt and abbreviated tool descriptions on any model; `0`/`false`/`no`/`off` opts out |
| `CLAUDE_CODE_SKIP_ANTHROPIC_AWS_AUTH` | Skip client-side auth for Claude Platform on AWS (gateways that sign requests themselves) |
| `CLAUDE_CODE_SKIP_AWS_CRED_CACHE` | `1` turns off the in-process AWS credential cache; resolves the chain on every API request |
| `CLAUDE_CODE_SKIP_BEDROCK_AUTH` | Skip AWS authentication for Amazon Bedrock (e.g. via an LLM gateway) |
| `CLAUDE_CODE_SKIP_FAST_MODE_NETWORK_ERRORS` | `1` treats a failed fast mode availability check as available; still honors an org-disabled response |
| `CLAUDE_CODE_SKIP_FAST_MODE_ORG_CHECK` | `1` skips the fast mode availability check entirely (for intercepting proxies) |
| `CLAUDE_CODE_SKIP_FOUNDRY_AUTH` | Skip Azure authentication for Microsoft Foundry, for a proxy that injects its own `Authorization` header |
| `CLAUDE_CODE_SKIP_MANTLE_AUTH` | Skip AWS authentication for Amazon Bedrock Mantle |
| `CLAUDE_CODE_SKIP_PROMPT_HISTORY` | `1` skips writing prompt history/session transcripts to disk (ephemeral scripted sessions) |
| `CLAUDE_CODE_SKIP_VERTEX_AUTH` | Skip Google authentication for Google Cloud's Agent Platform |
| `CLAUDE_CODE_STOP_HOOK_BLOCK_CAP` | Max consecutive times a `Stop`/`SubagentStop` hook may block the turn before Claude Code overrides it (default 8); `0` disables |
| `CLAUDE_CODE_SUBAGENT_MODEL` | Model for all subagents/agent teams/workflow agents; takes precedence over per-invocation `model` and frontmatter |
| `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB` | `1` strips Anthropic/cloud-provider credentials from subprocess environments (Bash tool, hooks, MCP stdio) |
| `CLAUDE_CODE_SYNC_PLUGIN_INSTALL` | `1` in `-p` mode waits for plugin installation to complete before the first query |
| `CLAUDE_CODE_SYNC_PLUGIN_INSTALL_TIMEOUT_MS` | Timeout for synchronous plugin installation; proceeds without plugins on exceed |
| `CLAUDE_CODE_SYNC_SKILLS` | `1` downloads enabled claude.ai skills into `~/.claude/skills/` before the first query, resyncs every 10 min (`-p` mode only) |
| `CLAUDE_CODE_SYNC_SKILLS_INSTALL_TIMEOUT_MS` | Timeout for a mid-session skills resync (default 30000) |
| `CLAUDE_CODE_SYNC_SKILLS_WAIT_TIMEOUT_MS` | Timeout for the first query to wait on the initial skills sync (default 5000) |
| `CLAUDE_CODE_SYNTAX_HIGHLIGHT` | `false` disables syntax highlighting in diff output |
| `CLAUDE_CODE_TASK_LIST_ID` | Share a task list across sessions by setting the same ID in multiple instances |
| `CLAUDE_CODE_TEAM_TEARDOWN_PARK_TIMEOUT_MS` | How long a non-interactive session waits at exit for its agent team to tear down (default 10000, range 1000-60000) |
| `CLAUDE_CODE_TMPDIR` | Override the temp directory for internal temp files (default `/tmp` macOS, `os.tmpdir()` Linux/Windows) |
| `CLAUDE_CODE_TMUX_TRUECOLOR` | Any non-empty value allows 24-bit truecolor inside tmux (default clamps to 256 colors) |
| `CLAUDE_CODE_USE_ANTHROPIC_AWS` | Use Claude Platform on AWS |
| `CLAUDE_CODE_USE_BEDROCK` | Use Amazon Bedrock |
| `CLAUDE_CODE_USE_FOUNDRY` | Use Microsoft Foundry |
| `CLAUDE_CODE_USE_MANTLE` | Use the Amazon Bedrock Mantle endpoint |
| `CLAUDE_CODE_USE_NATIVE_FILE_SEARCH` | `1` discovers custom commands/subagents/output styles using Node.js file APIs instead of ripgrep |
| `CLAUDE_CODE_USE_POWERSHELL_TOOL` | Controls the PowerShell tool; behavior varies by platform (auto on Windows without Git Bash, opt-in elsewhere, requires `pwsh` on Linux/macOS/WSL) |
| `CLAUDE_CODE_USE_VERTEX` | Use Google Cloud's Agent Platform |
| `CLAUDE_CONFIG_DIR` | Override the configuration directory (default `~/.claude`); useful for multiple accounts side by side |
| `CLAUDE_DISABLE_ADOPT` | `1` stops in-flight background work instead of carrying it over when backgrounding a session |
| `CLAUDE_EFFORT` | Set automatically in Bash/hook subprocesses to the active effort level for the turn |
| `CLAUDE_ENABLE_BYTE_WATCHDOG` | `1`/`0` force-enable/disable the byte-level streaming idle watchdog |
| `CLAUDE_ENABLE_BYTE_WATCHDOG_BEDROCK` | `1` enables the byte-level watchdog on Amazon Bedrock eventstream responses (off by default) |
| `CLAUDE_ENABLE_STREAM_WATCHDOG` | `0`/`1` force-disable/enable the event-level streaming idle watchdog (on by default for all providers) |
| `CLAUDE_ENV_FILE` | Path to a shell script Claude Code runs before each Bash command in the same shell process (persist venv/conda activation) |
| `CLAUDE_PID` | Set automatically to Claude Code's own process ID in spawned subprocesses; used to refuse a self-matching `pkill` pattern |
| `CLAUDE_REMOTE_CONTROL_SESSION_NAME_PREFIX` | Prefix for auto-generated Remote Control session names (default: hostname) |
| `CLAUDE_STREAM_IDLE_TIMEOUT_MS` | Timeout before the event-/byte-level streaming watchdogs close a stalled connection (min 300000 when set explicitly) |
| `DEBUG` | `1` enables debug mode (equivalent to `--debug`); only `1`/`true`/`yes`/`on` are truthy |
| `DISABLE_AUTOUPDATER` | `1` disables automatic background updates; manual `claude update` still works |
| `DISABLE_AUTO_COMPACT` | `1` disables automatic compaction; manual `/compact` remains available. Overrides `autoCompactEnabled` |
| `DISABLE_COMPACT` | `1` disables all compaction, automatic and manual `/compact` |
| `DISABLE_COST_WARNINGS` | `1` disables cost warning messages |
| `DISABLE_DOCTOR_COMMAND` | `1` hides the `/doctor` skill and `/checkup` alias (doesn't affect `claude doctor` terminal command) |
| `DISABLE_ERROR_REPORTING` | Any non-empty value opts out of error reporting; `0`/`false` still opts out |
| `DISABLE_EXTRA_USAGE_COMMAND` | `1` hides `/usage-credits` |
| `DISABLE_FEEDBACK_COMMAND` | `1` disables `/feedback` (also `/bug`, `/share`). Older name `DISABLE_BUG_COMMAND` also accepted |
| `DISABLE_GROWTHBOOK` | `1` disables GrowthBook feature-flag fetching; uses code defaults, makes Remote Control unavailable |
| `DISABLE_INSTALLATION_CHECKS` | `1` disables installation warnings |
| `DISABLE_INSTALL_GITHUB_APP_COMMAND` | `1` hides `/install-github-app` |
| `DISABLE_INTERLEAVED_THINKING` | `1` prevents sending the interleaved-thinking beta header |
| `DISABLE_LOGIN_COMMAND` | `1` hides `/login` |
| `DISABLE_LOGOUT_COMMAND` | `1` hides `/logout` |
| `DISABLE_PROMPT_CACHING` | `1` disables prompt caching for all models (takes precedence over per-model settings) |
| `DISABLE_PROMPT_CACHING_FABLE` | `1` disables prompt caching for Fable models |
| `DISABLE_PROMPT_CACHING_HAIKU` | `1` disables prompt caching for Haiku models |
| `DISABLE_PROMPT_CACHING_OPUS` | `1` disables prompt caching for Opus models |
| `DISABLE_PROMPT_CACHING_SONNET` | `1` disables prompt caching for Sonnet models |
| `DISABLE_TELEMETRY` | Any non-empty value opts out of telemetry; `0`/`false` still opts out. Also disables feature-flag fetching |
| `DISABLE_UPDATES` | `1` blocks all updates including manual `claude update`/`claude install` (stricter than `DISABLE_AUTOUPDATER`) |
| `DISABLE_UPGRADE_COMMAND` | `1` hides `/upgrade` |
| `DO_NOT_TRACK` | `1` opts out of telemetry, same effect as `DISABLE_TELEMETRY`; standard boolean semantics (`0` leaves telemetry on) |
| `ENABLE_CLAUDEAI_MCP_SERVERS` | `false` disables claude.ai MCP servers (enabled by default for logged-in users) |
| `ENABLE_PROMPT_CACHING_1H` | `1` requests a 1-hour prompt cache TTL instead of the default 5 minutes (billed at a higher rate) |
| `ENABLE_PROMPT_CACHING_1H_BEDROCK` | Deprecated; use `ENABLE_PROMPT_CACHING_1H` |
| `ENABLE_TOOL_SEARCH` | Controls MCP tool search: unset (auto per-provider), `true` (always defer), `auto`/`auto:N` (threshold mode), `false` (load all upfront) |
| `FALLBACK_FOR_ALL_PRIMARY_MODELS` | Any non-empty value stops every model from retrying with a repeated-overload error when no fallback model is configured; `0`/`false` still enables it |
| `FORCE_AUTOUPDATE_PLUGINS` | `1` forces plugin auto-updates even when `DISABLE_AUTOUPDATER` disables the main auto-updater |
| `FORCE_HYPERLINK` | `1` enables OSC 8 hyperlinks when not auto-detected, `0` disables. Parsed as a number, not a boolean |
| `FORCE_PROMPT_CACHING_5M` | `1` forces the 5-minute prompt cache TTL, overriding `ENABLE_PROMPT_CACHING_1H` |
| `HTTP_PROXY` | HTTP proxy server for network connections |
| `HTTPS_PROXY` | HTTPS proxy server for network connections |
| `IS_DEMO` | Any non-empty value enables demo mode (hides email/org from header and `/status`, skips onboarding); `0`/`false` still enables it |
| `MAX_MCP_OUTPUT_TOKENS` | Max tokens allowed in MCP tool responses (default 25000); warning above 10,000 |
| `MAX_STRUCTURED_OUTPUT_RETRIES` | Retries when the model's response fails `--json-schema` validation in `-p` mode (default 5) |
| `MAX_THINKING_TOKENS` | Fixed extended-thinking token budget; `0` disables thinking on the Anthropic API except Fable 5 |
| `MCP_CLIENT_SECRET` | OAuth client secret for MCP servers requiring pre-configured credentials |
| `MCP_CONNECTION_NONBLOCKING` | Controls whether startup waits for MCP servers to connect (non-blocking by default); `0` restores the blocking 5s wait |
| `MCP_CONNECT_TIMEOUT_MS` | How long blocking MCP startup waits for the connection batch (default 5000) |
| `MCP_DISCOVERY_CACHE` | `0` turns off the cross-process MCP discovery cache |
| `MCP_OAUTH_CALLBACK_PORT` | Fixed port for the OAuth redirect callback, alternative to `--callback-port` |
| `MCP_REMOTE_SERVER_CONNECTION_BATCH_SIZE` | Max remote MCP servers (HTTP/SSE) to connect in parallel at startup (default 20) |
| `MCP_SERVER_CONNECTION_BATCH_SIZE` | Max local MCP servers (stdio) to connect in parallel at startup (default 3) |
| `MCP_TIMEOUT` | Timeout for MCP server startup (default 30000/30s) |
| `MCP_TOOL_TIMEOUT` | Timeout for MCP tool execution (default 100000000, ~28 hours); HTTP/SSE/connector servers also have a 60s per-request timer |
| `NO_PROXY` | Domains/IPs to bypass the proxy for |
| `OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT` | Standard OTEL SDK attribute value length limit; Claude Code caps content attributes at the smaller of this and `CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH` |
| `OTEL_LOG_ASSISTANT_RESPONSES` | `1` includes the model's response text on `assistant_response` OTEL log events |
| `OTEL_LOG_RAW_API_BODIES` | `1` emits request/response JSON as OTEL log events; `file:<dir>` writes untruncated bodies to disk |
| `OTEL_LOG_TOOL_CONTENT` | `1` includes tool input/output content in OTEL span events (off by default) |
| `OTEL_LOG_TOOL_DETAILS` | `1` includes tool input arguments, MCP server names, workflow names, raw errors, refusal categories in OTEL (off by default) |
| `OTEL_LOG_USER_PROMPTS` | `1` includes user prompt text in OTEL traces/logs (redacted by default) |
| `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` | `false` excludes account UUID from metrics attributes (included by default) |
| `OTEL_METRICS_INCLUDE_ENTRYPOINT` | `true` includes the session entrypoint in metrics attributes (excluded by default) |
| `OTEL_METRICS_INCLUDE_RESOURCE_ATTRIBUTES` | `false` excludes `OTEL_RESOURCE_ATTRIBUTES` keys from metric datapoint labels (included by default) |
| `OTEL_METRICS_INCLUDE_SESSION_ID` | `false` excludes session ID from metrics attributes (included by default) |
| `OTEL_METRICS_INCLUDE_VERSION` | `true` includes Claude Code version in metrics attributes (excluded by default) |
| `SLASH_COMMAND_TOOL_CHAR_BUDGET` | Character budget for skill metadata shown to the Skill tool (default 1% of context window, fallback 8000) |
| `TASK_MAX_OUTPUT_LENGTH` | Max characters in subagent output before truncation (default 32000, max 160000) |
| `USE_BUILTIN_RIPGREP` | `0` uses system-installed `rg` instead of the bundled one |
| `VERTEX_REGION_CLAUDE_*` (per model, e.g. `VERTEX_REGION_CLAUDE_5_OPUS`, `VERTEX_REGION_CLAUDE_FABLE_5`, `VERTEX_REGION_CLAUDE_HAIKU_4_5`) | Override the Google Cloud's Agent Platform region for that specific model version |
Standard OpenTelemetry exporter variables (`OTEL_METRICS_EXPORTER`, `OTEL_LOGS_EXPORTER`, `OTEL_EXPORTER_OTLP_ENDPOINT`, `OTEL_EXPORTER_OTLP_PROTOCOL`, `OTEL_EXPORTER_OTLP_HEADERS`, `OTEL_METRIC_EXPORT_INTERVAL`, `OTEL_RESOURCE_ATTRIBUTES`, and signal-specific variants) are also supported; see the monitoring-usage docs.
## Retry-tuning variables
Also documented in `errors.md`: `CLAUDE_CODE_MAX_RETRIES` (default 10, capped 15), `CLAUDE_CODE_RETRY_WATCHDOG` (unset by default; `1` retries `429`/`529` indefinitely and raises other retry counts to ~300), and `API_TIMEOUT_MS` (default 600000).
## Related
- [settings.md](./settings.md): the settings-file equivalents and precedence rules
- [model-config.md](./model-config.md): the `ANTHROPIC_DEFAULT_*_MODEL` family in context
- [errors.md](./errors.md): retry-tuning variables in action
references/settings/errors.md
<!-- source: https://code.claude.com/docs/en/errors.md / last verified: 2026-08-07 -->
# Error reference
Runtime error messages Claude Code displays, with what each means and how to recover, plus checks for when responses seem off without an error. For installation errors (`command not found`, TLS failures during setup), see the troubleshoot-install docs instead. Except for Wrapper and IDE errors (printed by the launching program), these apply across the CLI, Desktop app, and Claude Code on the web, since all three wrap the same CLI.
## Find your error (message → category)
| Message | Category |
| --- | --- |
| `API Error: 500 Internal server error` | Server errors |
| `API Error: Repeated 529 Overloaded errors` | Server errors |
| `Request timed out` | Server errors (or Network, if it mentions your connection) |
| `Server error mid-response` / `Connection closed mid-response` / `Response stalled mid-stream` | Server errors — response above may be incomplete |
| `Connection closed while thinking` / `Response stalled while thinking` | Automatic retries |
| `<model> is temporarily unavailable, so auto mode cannot determine the safety of...` | Server errors — auto mode classifier |
| `Auto mode could not evaluate this action and is blocking it for safety` | Server errors — auto mode classifier |
| `Auto mode classifier transcript exceeded context window` | Server errors — auto mode classifier |
| `Agent terminated early due to an API error` | Server errors |
| `You've hit your session limit` / `You've hit your weekly limit` / `You've hit your Opus limit` | Usage limits |
| `Usage credits required for 1M context` | Usage limits |
| `Server is temporarily limiting requests` | Usage limits (not your plan quota) |
| `Request rejected (429)` | Usage limits |
| `Credit balance is too low` | Usage limits |
| `Could not update your spend limit` | Usage limits |
| `Not logged in · Please run /login` | Authentication |
| `Could not resolve authentication method` | Authentication |
| `Invalid API key` | Authentication |
| `Your apiKeyHelper script is failing` | Authentication |
| `This organization has been disabled` | Authentication |
| `Your organization has disabled API key authentication` | Authentication |
| `Your organization has disabled Claude subscription access` | Authentication |
| `Routines are disabled by your organization's policy` | Authentication |
| `Remote Control is only available when using Claude via api.anthropic.com` | Authentication |
| `OAuth token revoked` / `OAuth token has expired` | Authentication |
| `API Error: 401 Invalid authentication credentials` | Authentication |
| `Login expired · Please run /login` / `Failed to authenticate: OAuth session expired and could not be refreshed` | Authentication |
| `does not meet scope requirement user:profile` | Authentication — OAuth scope |
| `claude.ai rejected the session token` | Authentication |
| `AWS credentials expired or invalid` | Authentication |
| `AWS authentication failed` | Authentication |
| `AWS default-chain credential resolve timed out` | Authentication |
| `Unable to connect to API` | Network |
| `Unable to connect to Anthropic services` (during setup) | Network |
| `Socket is closed` | Network |
| `Waiting for API response · will retry in` | Automatic retries (or Network, if persistent) |
| `Bedrock streaming response has content-type "..."; expected "application/vnd.amazon.eventstream"` | Network |
| `SSL certificate verification failed` / `SSL certificate error (...)` | Network |
| `403` with `x-deny-reason: host_not_allowed` (cloud/routine session) | Network |
| `Couldn't reconnect to your Remote Control session` | Network |
| `Prompt is too long` | Request errors |
| `Context exceeds the ...-token limit by ... tokens` (in `/context`) | Request errors |
| `Error during compaction: Conversation too long` | Request errors |
| `Request too large` | Request errors |
| `Image was too large` / `Unable to resize image` | Request errors |
| `PDF too large` / `PDF is password protected` | Request errors |
| `Extra inputs are not permitted` | Request errors |
| `There's an issue with the selected model` | Request errors |
| `Model ... is not a recognized model id` | Request errors |
| `Claude Opus is not available with the Claude Pro plan` | Request errors |
| `Model ... is restricted by your organization's settings` | Request errors |
| `thinking.type.enabled is not supported for this model` | Request errors |
| `max_tokens must be greater than thinking.budget_tokens` | Request errors — thinking budget exceeds output limit |
| `API Error: 400 due to tool use concurrency issues` | Request errors — tool use/thinking block mismatch |
| `<model> can't help with this. Start a new session to continue` | Request errors — usage policy refusal |
| `Claude Code is unable to respond to this request, which appears to violate our Usage Policy` | Request errors — usage policy refusal |
| `<model>'s safeguards flagged this message` / `has safety measures that flagged this message for a cybersecurity topic` | Request errors — cybersecurity safety flag |
| `Installation was killed before it could finish (exit code 137)` | Installation errors |
| `The connection dropped while downloading the update` / `Download timed out: exceeded the total deadline` | Installation errors |
| `--bg and --print conflict` | Command-line errors |
| `Error: --json-schema is not a valid JSON Schema` | Command-line errors |
| `Error: Settings file exceeds the 2MiB limit` | Command-line errors |
| `Error: Workspace not trusted` (starting Remote Control) | Command-line errors |
| `Could not import <server>: <reason>` | Command-line errors |
| `Error: MCP tool <name> (passed via --permission-prompt-tool) not found` | Command-line errors |
| ``Shell command failed for pattern "!`git ... origin/HEAD...`"`` | Command-line errors — security review needs origin/HEAD |
| `Input must be provided either through stdin or as a prompt argument when using --print` | Command-line errors |
| `Diff is too large for ultrareview` / `PR #<N> is too large for ultrareview` | Command-line errors |
| `Could not find merge-base with <branch>` | Command-line errors |
| `Your checkout has no branches (detached HEAD only)` | Command-line errors |
| `Failed to resume the conversation` | Command-line errors |
| `Marketplace "<name>" is registered from an untrusted source` | Plugin errors |
| `references ${user_config.*} in a shell-form command` / `Monitor "<name>" from plugin <plugin> references ${user_config.*}` / `headersHelper for MCP server '<name>' references ${user_config.*}` | Plugin errors |
| `would be spawned with zero tools — refusing` | Tool errors |
| `File is covered by a Read deny rule in your permission settings` | Tool errors |
| `Error: this write left the memory index at MEMORY.md at ..., over its ... read limit` | Tool errors |
| `pkill: refusing to run` | Tool errors — pattern matches the Claude Code process |
| `Can't open MCP settings while no terminal is attached to this background session` / `Can't open MCP settings in a background session` | Background session errors |
| `This session has no saved transcript` | Background session errors |
| `This session was running agent '<name>', which is no longer available` | Background session errors |
| `CLAUDE_CODE_PROCESS_WRAPPER: launcher ...` | Background session errors |
| `EUNKNOWN: unknown error, uv_spawn` | Background session errors |
| `Claude Code process exited with code N` | Wrapper and IDE errors |
| `Restored the code, but skipped N files` | Rewind warnings |
| `Ignoring N permissions.allow entries from ... this workspace has not been trusted` | Configuration warnings |
| `... is not matched by file permission checks` | Configuration warnings |
| Responses seem lower quality than usual | Response quality (not a specific error message) |
## Automatic retries
Claude Code retries transient failures up to 10 times with exponential backoff before showing an error (tunable — see Options table). It doesn't always retry a failure that arrives partway through a response.
**Retried**: server errors/overloads/timeouts before any response has streamed; a dropped connection before any text/tool-call/thinking has been produced (re-issued with the same backoff) or after thinking finished but before text/tool-call started (re-issued up to 2 more times, then `Connection closed while thinking...`); a stalled stream in the same window (aborted and re-issued once, outside the 10-attempt budget; a second stall ends with `Response stalled while thinking...`); temporary 429 throttles (including claude.ai-subscription throttles without quota headers, v2.1.199+).
**Not retried**: TLS certificate validation failures (reported immediately so you can fix cert setup — transient TLS conditions like handshake timeout are still retried); a failure arriving after Claude completed a text block or tool call (kept as-is with an incomplete-response notice, to avoid double-running tool calls); a failure after the full response completed (nothing to retry); an Amazon Bedrock streaming response with an unexpected content-type (retrying would hit the same gateway rewrite).
While retrying, the spinner shows `Retrying in Ns · attempt x/y`; if no data arrives for 20 seconds (90 seconds while consulting the advisor) it shows `Waiting for API response · will retry in … · check your network` before any retry starts.
### Tune retry behavior
| Variable | Default | Effect |
| --- | --- | --- |
| `CLAUDE_CODE_MAX_RETRIES` | 10 | Retry attempt count, capped at 15 (cap removed when `CLAUDE_CODE_RETRY_WATCHDOG=1`) |
| `CLAUDE_CODE_RETRY_WATCHDOG` | unset | `1` retries `429`/`529` indefinitely in unattended sessions (e.g. CI) and raises other transient-error retries to ~300 (roughly 3 hours of backoff) |
| `API_TIMEOUT_MS` | 600000 | Per-request timeout (ms) |
## Server errors
Come from the inference provider (Anthropic, or the provider behind Bedrock/Vertex/Foundry/a custom gateway).
- **`API Error: 500 Internal server error`** — unexpected server-side failure, unrelated to your prompt/settings/account. Check status.claude.com (or the provider's status page), wait, retry with "try again"; run `/feedback` if it persists with no posted incident.
- **`API Error: Repeated 529 Overloaded errors`** — capacity-wide overload, already retried several times; not your usage limit. Check status, retry later, or `/model` to switch models (capacity is tracked per model).
- **`Request timed out`** — no response before the connection deadline (default 10 min). Retry, break work into smaller prompts, or raise `API_TIMEOUT_MS`.
- **The response above may be incomplete** (`Server error mid-response` / `Connection closed mid-response` / `Response stalled mid-stream`) — a mid-stream failure after Claude completed a text block or tool call; output kept, turn not discarded. Reply `continue` to resume from the last completed block; in non-interactive mode, resume the session and send `continue`.
- **Auto mode cannot determine the safety of an action** — the classifier model failed (overloaded/rate-limited/unreachable, or on Amazon Bedrock, your account can't invoke the classifier model). Retry after a few seconds; on Bedrock, check IAM policy or contact your AWS account team for Mantle model access. An unparseable classifier response blocks with `run with --debug for details` — retry, or check the debug log. A separate API safety check on earlier conversation content blocks with a distinct message — retrying won't help; switch permission mode or start fresh. An oversized classifier transcript falls back to manual approval — approve manually or run `/compact`.
- **`Agent terminated early due to an API error`** — a subagent's request failed terminally (e.g. hit a usage limit, retries exhausted). Match the detail after the colon to its own section and follow those steps; then ask Claude to retry or resume the subagent.
## Usage limits
Most mean a quota tied to your account/plan is exhausted. Two exceptions: `Server is temporarily limiting requests` is a server-side throttle unrelated to plan quota, and `Usage credits required for 1M context` is an entitlement check, not exhaustion.
- **Session/weekly/Opus limit hit** — blocked until the reset time shown. Session/weekly limits are shared across models; Opus limit only affects Opus (switch models with `/model` to keep working). `/usage` shows limits/reset times; `/usage-credits` buys more usage.
- **`Usage credits required for 1M context`** — the `[1m]` model variant needs usage credits on your plan. `/model` to a non-`[1m]` variant, or `/usage-credits` to turn on billing; set `CLAUDE_CODE_DISABLE_1M_CONTEXT=1` to remove 1M variants from the picker entirely.
- **`Server is temporarily limiting requests`** — short-lived server throttle, not your plan quota; retried automatically (v2.1.199+). Wait and retry; check status.claude.com if persistent.
- **`Request rejected (429)`** — hit your API key/Bedrock project/GCP project rate limit. Check `/status` for the active credential, check your provider console's limit tier, reduce concurrency (`CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY`, fewer parallel subagents, or a smaller model).
- **`Credit balance is too low`** — Console org out of prepaid credits. Add credits/enable auto-reload, or `/login` to switch to subscription auth.
- **`Could not update your spend limit`** — the server rejected a spend-limit change. If a reason is given, choose a value that satisfies it; otherwise retry, or change it from claude.ai billing settings.
## Authentication errors
Run `/status` to see the active credential. Key messages: `Not logged in` (`/login`, or check `ANTHROPIC_API_KEY`/`apiKeyHelper` for automation); `Could not resolve authentication method` (background/cloud/SDK sessions with no credential reaching the worker — upgrade if on an old version); `Invalid API key` (check for typos/revocation, check `env | grep ANTHROPIC` for a stray `.env`-loaded key, or unset it and `/login`); `Your apiKeyHelper script is failing` (run the helper command directly to reproduce; it must print the key to stdout and exit 0); `This organization has been disabled` / `Your organization has disabled API key authentication` / `...Claude subscription access` (env var takes precedence over `/login` — unset it; or ask an admin to re-enable the relevant auth method); `Routines are disabled by your organization's policy` (ask an Owner to enable Routines); `Remote Control is only available when using Claude via api.anthropic.com` (unset `ANTHROPIC_BASE_URL`); `OAuth token revoked/expired` and `Login expired` (`/login`, or `/logout` then `/login` if it recurs); `API Error: 401 Invalid authentication credentials` (check whether `/status` shows an API key overriding your login); AWS credential/chain errors (re-run `aws sso login` or raise `CLAUDE_CODE_AWS_CHAIN_RESOLVE_TIMEOUT_MS`).
## Network and connection errors
Local network/proxy/firewall or cloud-network-policy failures. `Unable to connect to API` (ECONNREFUSED/ECONNRESET/ETIMEDOUT, "fetch failed"): confirm `curl -I https://api.anthropic.com` works, set `HTTPS_PROXY` behind a corporate proxy, check firewall/DNS. `Unable to connect to Anthropic services` (first-run setup probe): same checks, message names the failing proxy variable. `Socket is closed` (streaming connection dropped, e.g. Windows corporate proxy): retried automatically since v2.1.214, update if older. `Bedrock streaming response has an unexpected content-type`: a gateway is rewriting the eventstream body/header — fix the gateway or set `CLAUDE_CODE_DISABLE_BEDROCK_CONTENT_TYPE_GUARD=1`. SSL certificate errors: export your CA bundle to `NODE_EXTRA_CA_CERTS` (never disable validation with `NODE_TLS_REJECT_UNAUTHORIZED=0`). `Host not allowed in a cloud session` (`403`/`x-deny-reason: host_not_allowed`): add the domain to the cloud environment's **Custom** network allowlist. `Couldn't reconnect to your Remote Control session`: run `/remote-control` to retry, or start without `--resume`.
## Request errors
Content-of-request problems, mostly rejected by the API. `Prompt is too long` / `Context exceeds the token limit`: run `/compact` or `/clear`, check `/context` for what's consuming the window, disable unused MCP servers. `Error during compaction: Conversation too long`: Esc twice to step back several turns, then retry `/compact`, or `/clear`. `Request too large` (32MB HTTP body cap): `/compact`, or reference large files by path instead of pasting. `Image was too large` / `Unable to resize image`: resize below 8000px (or 2000px with many images), convert to PNG/JPEG/GIF/WebP. PDF errors (too large/password-protected/invalid): extract with `pdftotext` or read a page range instead. `Extra inputs are not permitted`: a gateway stripped the `anthropic-beta` header — configure pass-through or set `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1`. `There's an issue with the selected model` / `Model ... is not a recognized model id`: run `/model` to pick a valid one; check `--model`/`ANTHROPIC_MODEL`/settings for a stale ID. `Claude Opus is not available with the Claude Pro plan`: `/model` to a plan-included model, or `/logout`+`/login` after upgrading. `Model ... is restricted by your organization's settings`: `/model` shows only allowed models; ask an admin for access. `thinking.type.enabled is not supported for this model`: `claude update` (version floors vary by model). Thinking-budget-exceeds-output-limit (`max_tokens must be greater than thinking.budget_tokens`): lower `MAX_THINKING_TOKENS` or raise `CLAUDE_CODE_MAX_OUTPUT_TOKENS`. Tool use/thinking block mismatch (`API Error: 400 due to tool use concurrency issues`): `/rewind` to a checkpoint before the corrupted turn; update if on Opus 4.7/4.8 pre-v2.1.156. Usage Policy refusal and cybersecurity safety flags: `/rewind` past the triggering turn, `/clear` for a fresh conversation, or `/feedback` to report a false positive; apply to the Cyber Verification Program for legitimate cybersecurity work.
## Installation errors
From the install script, `claude install`, or `claude update`. `Installation was killed before it could finish` (exit code 137 = OOM on Linux): free memory or add swap, then rerun. `The connection dropped while downloading the update` / `Download timed out`: rerun `claude update`, set `HTTPS_PROXY` if needed, ask network team to allow `downloads.claude.ai`.
## Command-line errors
From the `claude` CLI and its subcommands. `--bg and --print conflict`: drop `-p`/`--print`, `--bg` takes the prompt directly. `--json-schema is not a valid JSON Schema`: fix the keyword the diagnostic names. `Settings file exceeds the 2MiB limit`: point `--settings` at a real settings file under 2 MiB. `Workspace not trusted when starting Remote Control`: run `claude` in the directory first to accept the trust dialog (home directory trust is never saved — use a project directory). `Could not import a server from Claude Desktop`: rename the server to letters/numbers/hyphens/underscores only. `MCP permission prompt tool not found`: confirm the server is connected (`claude mcp list`) and the tool name matches `mcp__<server>__<tool>`; raise `MCP_TIMEOUT` if it's slow to start. `/security-review` fails without `origin/HEAD`: run `git remote set-head origin <default-branch>` (fetch the branch first if needed). `Input must be provided...when using --print`: run `claude` in a real terminal, or pass/pipe a prompt with `-p`. `Diff is too large for ultrareview`: pass a closer base branch or split the change. `Could not find merge-base with the base branch`: pass the base branch explicitly or `git fetch --unshallow origin`. `Your checkout has no branches`: `git checkout -b <name>` at the current commit. `Failed to resume the conversation`: retry `claude --resume <session-id>`, or start a new session.
## Plugin errors
`Marketplace "<name>" is registered from an untrusted source` (reserved name not under `github.com/anthropics`): `claude plugin marketplace remove` then re-add from the official source, or rename a third-party marketplace. Plugin command references `${user_config.*}` in a shell-form hook/monitor/`headersHelper`: switch the hook to exec form (`args` array) or read `$CLAUDE_PLUGIN_OPTION_<KEY>`/an env var inside the script instead of shell-interpolating the value.
## Tool errors
`Agent would be spawned with zero tools`: fix each `tools` frontmatter entry the message groups as unrecognized/not-available-to-subagents/matched-no-tools, or delete the `tools` field. `File is covered by a Read deny rule`: narrow the `Read` deny rule if Claude should edit the file, or add a matching `Edit` deny rule if it must stay untouched. `Memory index is over its read limit` (MEMORY.md > 200 lines/25KB): let Claude rewrite it — one line per entry, detail moved to topic files. `pkill: refusing to run` (pattern matches the Claude Code process, Linux only): narrow the pattern or use `pkill -P $$`.
## Background session errors
`Can't open MCP settings while no terminal is attached` and similar: attach from agent view's **Needs input** list, or use the non-interactive form (`/mcp reconnect <server>`, etc.). `This session has no saved transcript` (stopped before first response): resume the original conversation with `claude --resume`, or `claude respawn <id>` to start fresh. `This session was running agent '<name>', which is no longer available`: re-create the agent file, or resume with an explicit `--agent <name>`. `CLAUDE_CODE_PROCESS_WRAPPER` launcher errors: point the variable at an absolute executable path ending in `exec "$@"`; check `/status`'s Self-exec entry. `EUNKNOWN` starting a background session on Windows (software restriction policy blocking the executable): ask an admin to allowlist the Claude Code executable, or install PowerShell 7 if the service doesn't outlive the terminal.
## Wrapper and IDE errors
`Claude Code process exited with code N` (from an IDE extension/Agent SDK wrapper, not Claude Code itself): follow the wrapper's **View output logs** link, reproduce by running `claude` directly in a terminal, or run `claude doctor`.
## Rewind warnings
`Restored the code, but skipped N files` (`/rewind` skipped symlinks/hard links, paths whose directory changed, or unreadable backups): run with `--debug` to see the skipped paths in the debug log; links you created on purpose were left untouched, others should be inspected before trusting.
## Configuration warnings
Written to stderr at startup, not shown as conversation errors. `Ignoring N permissions.allow entries...this workspace has not been trusted`: run `claude` interactively in the directory and accept the trust dialog, or set `hasTrustDialogAccepted` in `~/.claude.json` for non-interactive (`-p`) use. `...is not matched by file permission checks` (a `Write`/`NotebookEdit`/`MultiEdit`/`Glob` path rule, which only `Edit`/`Read` rules actually enforce): replace with the equivalent `Edit(path)` or `Read(path)` rule at the source the warning names.
## Responses seem lower quality than usual
Not an error message — check `/model` (stale model pin), `/effort` (reasoning level), `/context` (window pressure — `/compact`/`/clear`), and `/doctor` (oversized CLAUDE.md/unused extensions) before assuming a regression. Prefer `/rewind` over in-thread corrections, since correcting keeps the wrong attempt anchoring later answers. Run `/feedback` (includes the transcript) if quality still seems off, or if a suspected-prompt-injection warning repeats after `claude update`.
## Report an error
For components this page doesn't cover: MCP connection/auth issues → MCP docs; hook failures → hooks docs (`Debug hooks`); install/permission errors → troubleshoot-install docs. Otherwise run `/feedback` (sends the transcript; offers a prefilled GitHub issue; on third-party providers or without Anthropic credentials, saves a local archive instead), `claude doctor` for read-only diagnostics, or check status.claude.com for active incidents.
## Notes
- For the raw HTTP status code definitions behind these messages, see the Claude Platform API error reference (platform.claude.com).
## Related
- [env-vars.md](./env-vars.md): `CLAUDE_CODE_MAX_RETRIES`, `CLAUDE_CODE_RETRY_WATCHDOG`, `API_TIMEOUT_MS`
- [auto-mode-config.md](./auto-mode-config.md): the auto mode classifier errors in context
- [model-config.md](./model-config.md): model-selection errors (`There's an issue with the selected model`, `Model ... is not a recognized model id`, `availableModels` restriction errors)
- [debug-your-config.md](./debug-your-config.md): `/status`, `/doctor`, and `claude --safe-mode` used throughout this page's fixes
references/settings/fast-mode.md
<!-- source: https://code.claude.com/docs/en/fast-mode.md / last verified: 2026-08-07 -->
# Speed up responses with fast mode
A research-preview, high-speed configuration for Claude Opus, up to 2.5x faster at a higher cost per token. Toggle with `/fast` for interactive work (rapid iteration, live debugging); toggle off when cost matters more than latency. Fast mode is not a different model — same Opus quality/capabilities, different API configuration. Supported on Opus 5 and Opus 4.8 only (not Sonnet, Haiku, or other models). Not supported in the VS Code extension. Opus 4.7 fast-mode support was deprecated June 25, 2026 and removed July 24, 2026.
## Signature / Usage
```json ~/.claude/settings.json
{ "fastMode": true }
```
Or type `/fast` and press Tab to toggle. Enabling fast mode auto-switches to Opus if on a different model; shows "Fast mode ON"; a `↯` icon appears next to the prompt. Turning fast mode off keeps you on Opus (doesn't revert model) — use `/model` to switch elsewhere.
## Options / Props
| Setting | Description |
| --- | --- |
| `fastMode` (settings) | Persists on/off across sessions when toggled in an interactive session |
| `fastModePerSessionOptIn` | `true` resets fast mode off at the start of every session; users still enable with `/fast`. Deployable org-wide via server-managed settings |
| `CLAUDE_CODE_DISABLE_FAST_MODE=1` | Disable fast mode entirely |
Pricing (per MTok, flat across the full 1M context window): Opus 5 and Opus 4.8 both $10 input / $50 output.
## Notes
- **Cost tradeoff**: the first time you enable fast mode in a conversation, you pay full fast-mode uncached input price for the *entire* conversation context — enable at session start rather than mid-conversation for the lowest cost. Applies once per conversation.
- **Model switching**: switching away from a fast-mode-capable Opus model turns fast mode off; switching back turns it on again only if your saved preference is on (a switch never turns fast mode on for a session whose saved preference is off).
- **Requirements**: Anthropic Console API or subscription plans only (not Amazon Bedrock/Google Cloud's Agent Platform/Microsoft Foundry/Claude Platform on AWS); usage credits must be turned on; Team/Enterprise orgs need an Owner to enable it (disabled by default for those plans). Fast mode usage draws from usage credits even with remaining plan usage.
- **Behind proxies/gateways**: the availability check hits `api.anthropic.com` directly and ignores `ANTHROPIC_BASE_URL`, so it can fail on networks that block direct egress even though inference works through a gateway. Fixes: `CLAUDE_CODE_SKIP_FAST_MODE_NETWORK_ERRORS=1` (treats a failed check as available, still honors an org-disabled response) or `CLAUDE_CODE_SKIP_FAST_MODE_ORG_CHECK=1` (skips the check entirely — needed when a proxy intercepts and answers the check itself, or when authenticating with `ANTHROPIC_AUTH_TOKEN` alone).
- **Rate limits**: separate pool shared across all supported Opus models. On limit, falls back to standard speed/pricing automatically (icon turns gray); re-enables when the cooldown expires. Running out of usage credits mid-session retries each request at standard speed with no cooldown.
- Fast mode vs. effort level: fast mode = same quality, lower latency, higher cost; lower effort = less thinking time, faster, potentially lower quality. Combine both for maximum speed on straightforward tasks.
## Related
- [model-config.md](./model-config.md): effort levels and the Opus/Sonnet/Haiku alias family
- [env-vars.md](./env-vars.md): `CLAUDE_CODE_DISABLE_FAST_MODE`, `CLAUDE_CODE_SKIP_FAST_MODE_NETWORK_ERRORS`, `CLAUDE_CODE_SKIP_FAST_MODE_ORG_CHECK`
- [statusline.md](./statusline.md): the `fast_mode` JSON field exposed to a custom status line
references/settings/keybindings.md
<!-- source: https://code.claude.com/docs/en/keybindings.md / last verified: 2026-08-07 -->
# Customize keyboard shortcuts
Claude Code supports customizable keyboard shortcuts via a keybindings configuration file. Run `/keybindings` to create or open `~/.claude/keybindings.json`. Changes are auto-detected and applied without restarting.
## Signature / Usage
```json
{
"$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
}
}
]
}
```
## Options / Props
| Field | Description |
| --- | --- |
| `$schema` | Optional JSON Schema URL for editor autocompletion |
| `$docs` | Optional documentation URL |
| `bindings` | Array of `{ context, bindings }` blocks. `context` selects where the keystroke→action map applies; set an action to `null` to unbind a default |
### Contexts
`Global`, `Chat`, `Autocomplete`, `Settings`, `Confirmation`, `Tabs`, `Help`, `Transcript`, `HistorySearch`, `Task`, `ThemePicker`, `Attachments`, `Footer`, `MessageSelector`, `DiffDialog`, `ModelPicker`, `Select`, `Plugin`, `Scroll`. (Before v2.1.205, `Doctor` context / `doctor:fix` action existed for `/doctor`.)
### Key action groups (selected defaults)
| Group | Examples |
| --- | --- |
| App (`Global`) | `app:interrupt` Ctrl+C, `app:exit` Ctrl+D (×2 within 800ms), `app:toggleTodos` Ctrl+T, `app:toggleTranscript` Ctrl+O |
| History | `history:search` Ctrl+R, `history:previous`/`next` Up/Down |
| Chat | `chat:cancel` Escape, `chat:clearInput` Ctrl+L, `chat:cycleMode` Shift+Tab, `chat:modelPicker` Meta+P, `chat:fastMode` Meta+O, `chat:thinkingToggle` Meta+T, `chat:submit` Enter, `chat:newline` Ctrl+J, `chat:externalEditor` Ctrl+G / Ctrl+X Ctrl+E, `chat:stash` Ctrl+S, `chat:killAgents` Ctrl+X Ctrl+K |
| Autocomplete | `autocomplete:accept` Tab, `autocomplete:dismiss` Escape |
| Confirmation | `confirm:yes` Y/Enter, `confirm:no` N/Escape, `confirm:cycleMode` Shift+Tab, `confirm:toggleExplanation` Ctrl+E |
| Transcript | `transcript:toggleShowAll` Ctrl+E (classic renderer only), `transcript:exit` q/Ctrl+C/Escape |
| History search | `historySearch:next` Ctrl+R, `historySearch:accept` Escape/Tab, `historySearch:cycleScope` Ctrl+S (fullscreen only) |
| Task | `task:background` Ctrl+B / Ctrl+X Ctrl+B |
| Diff | `diff:dismiss` Escape, `diff:previousFile`/`nextFile` Up/Down or K/J, `diff:viewDetails` Enter |
| Model picker | `modelPicker:decreaseEffort`/`increaseEffort` Left/Right, `modelPicker:thisSessionOnly` s |
| Select | `select:next`/`previous` Down/Up (J/K, Ctrl+N/P), `select:accept` Enter, `select:cancel` Escape |
| Settings | `settings:search` /, `settings:retry` R |
| Voice | `voice:pushToTalk` Space (when voice dictation enabled) |
| Scroll (fullscreen only) | `scroll:pageUp`/`pageDown` PageUp/PageDown, `scroll:top`/`bottom` Ctrl+Home/End, `selection:copy` Ctrl+Shift+C / Cmd+C |
## Keystroke syntax
- **Modifiers**: `ctrl`/`control`, `shift`, `alt`/`opt`/`option`/`meta` (Alt on Win/Linux, Option on macOS), `cmd`/`command`/`super`/`win` (only detected in terminals reporting the Super modifier — prefer `ctrl`/`meta` for portability). Combine with `+`: `ctrl+k`, `shift+tab`, `meta+p`, `ctrl+shift+c`.
- **Uppercase letters**: a standalone uppercase letter implies Shift (`K` = `shift+k`); with a modifier, case is stylistic only (`ctrl+K` = `ctrl+k`).
- **Chords**: space-separated sequences, e.g. `ctrl+k ctrl+s`.
- **Special keys**: `escape`/`esc`, `enter`/`return`, `tab`, `space`, `up`/`down`/`left`/`right`, `backspace`, `delete`.
## Unbind default shortcuts
```json
{ "bindings": [{ "context": "Chat", "bindings": { "ctrl+s": null } }] }
```
Unbinding every chord sharing a prefix frees that prefix as a single-key binding; a chord in any active context keeps its prefix reserved, so unbind each chord in its own context.
## Notes
- Reserved shortcuts that cannot be rebound: Ctrl+C (interrupt), Ctrl+D (exit), Ctrl+M (same as Enter in terminals), Caps Lock (not delivered to terminal apps).
- Terminal-multiplexer conflicts: Ctrl+B (tmux prefix, press twice), Ctrl+A (GNU screen prefix), Ctrl+Z (Unix SIGTSTP).
- Vim mode (`/config` → Editor mode) and keybindings operate independently: vim mode handles text-input-level motions; keybindings handle component-level actions. Vim keys aren't remappable through this file — use `vimInsertModeRemaps` for INSERT-mode sequences like `jj`→Escape.
- Claude Code validates the file at load and logs warnings (parse errors, invalid contexts, reserved/multiplexer conflicts, duplicate bindings) to the debug log; start with `--debug` to see them.
## Related
- [terminal-config.md](./terminal-config.md): terminal-side key handling (Shift+Enter, Option-as-Meta) vs. this file's Claude-Code-side handling
references/settings/model-config.md
<!-- source: https://code.claude.com/docs/en/model-config.md / last verified: 2026-08-07 -->
# Model configuration
Configure which Claude model Claude Code uses, model aliases like `opusplan`, effort levels, extended thinking, and extended context.
## Available models
The `model` setting accepts a **model alias** or a **model name** (Anthropic API: full model name; Amazon Bedrock: inference profile ARN; Microsoft Foundry: deployment name; Google Cloud's Agent Platform: version name).
`ANTHROPIC_BASE_URL` changes where requests are sent, not which model answers them; for routing through a gateway see the LLM gateway docs.
### Model aliases
| Alias | Behavior |
| --- | --- |
| `default` | Clears any override; reverts to the recommended model for your account type, or the organization default model if set |
| `best` | Fable 5 where available, otherwise the latest Opus |
| `fable` | Claude Fable 5, for the hardest/longest-running tasks |
| `sonnet` | Latest Sonnet, for daily coding |
| `opus` | Latest Opus, for complex reasoning |
| `haiku` | Fast/efficient Haiku, for simple tasks |
| `sonnet[1m]` | Sonnet with 1M token context |
| `opus[1m]` | Opus with 1M token context |
| `opusplan` | Hybrid: `opus` in plan mode, `sonnet` for execution |
`opus`/`sonnet` resolve differently per provider: Anthropic API → Opus 5 / Sonnet 5; Claude Platform on AWS → Opus 5 / Sonnet 4.6; Amazon Bedrock, Google Cloud's Agent Platform → Opus 5 / Sonnet 4.5; Microsoft Foundry → Opus 4.6 / Sonnet 4.5. Pin an older/newer version with the full model name or `ANTHROPIC_DEFAULT_OPUS_MODEL`/`ANTHROPIC_DEFAULT_SONNET_MODEL`.
### Fable 5
Claude Fable 5 is the most capable model, suited to long autonomous sessions. Not the default — select with `/model fable`. Safety-classifier-flagged requests (mostly cybersecurity/biology) trigger automatic model fallback. Requires v2.1.170+; unavailable under zero data retention.
### Setting your model
Priority order: `/model <alias|name>` (session, saves as default via `Enter`, or session-only via `s`) > `claude --model <alias|name>` (startup) > `ANTHROPIC_MODEL` env var > `model` in settings file.
```bash
claude --model opus
```
```text
/model sonnet
```
```json
{ "permissions": { "allow": ["Bash(npm run lint)"] }, "model": "opus" }
```
Resumed sessions (`--resume`/`--continue`/`/resume`) keep the transcript's saved model unless it's retired or excluded by `availableModels`, or you pass `--model`/`ANTHROPIC_MODEL` explicitly. Provider-deployment-ID platforms (Bedrock/Vertex/Foundry) don't restore the transcript model at all.
## Restrict model selection
Admins use `availableModels` in managed/policy settings to allowlist models (matches family alias, version prefix, or full ID):
```json
{ "availableModels": ["sonnet", "haiku"] }
```
Applies everywhere a model can be specified: main session model, alias resolution (`ANTHROPIC_DEFAULT_*_MODEL`), fast mode, subagent/teammate/skill/command models, advisor model, background agent dispatch. On the Anthropic API and Claude Platform on AWS, a blocked family alias resolves to the newest permitted version instead of being rejected outright.
### Enforce the allowlist for the Default model
```json
{ "availableModels": ["sonnet", "haiku"], "enforceAvailableModels": true }
```
Extends the allowlist to the Default option. Requires v2.1.175+. Has no effect when `availableModels` is unset or `[]`.
### Organization default model
Enterprise admins set an org-wide or per-role default from the claude.ai admin console (requires v2.1.196+). The Default row shows "Org default". Any explicit model selection (`--model`, `ANTHROPIC_MODEL`, `model` in settings) still takes precedence, unless the admin turns on override.
### Organization effort limits
Enterprise admins can cap the max effort level per model per role (requires v2.1.195+); levels above the cap aren't offered and are silently clamped in non-interactive/background contexts.
## Special model behavior
### `default` model setting
Max/Team Premium/Enterprise pay-as-you-go/Anthropic API/Claude Platform on AWS/Amazon Bedrock/Google Cloud's Agent Platform → Opus 5. Pro/Team Standard/Enterprise subscription seats → Sonnet 5. Microsoft Foundry → Sonnet 4.5.
### `opusplan` model setting
`opus` in plan mode, `sonnet` in execution. Shares the `opus` model setting's context window; force 1M in both phases with `opusplan[1m]`.
### Fallback model chains
```bash
claude --fallback-model sonnet,haiku
```
```json
{ "fallbackModel": ["claude-sonnet-5", "claude-haiku-4-5"] }
```
Tries each model in order on overload/unavailable/non-retryable server errors (not auth/billing/rate-limit/request-size/transport errors). Switch lasts one turn. Capped at 3 models after dedup. `"default"` expands to the default model. Entries outside `availableModels`, or with a smaller context window than the primary during compaction, are dropped.
### Automatic model fallback
Fable 5 and Opus 5 run safety classifiers (cybersecurity/biology). A flagged request re-runs on a fallback model automatically: Fable 5 biology → Opus 5; Fable 5 cybersecurity → Opus 4.8; Opus 5 cybersecurity → Opus 4.8 (Opus 5 biology has no fallback, ends in refusal). Turn off automatic switching with `switchModelsOnFlag: false` in settings, which instead pauses for you to choose. `claude --safe-mode` disables customizations to check whether CLAUDE.md/skills/MCP/hooks content is triggering the classifier.
### Adjust effort level
| Model | Levels |
| --- | --- |
| Fable 5 | `low`, `medium`, `high`, `xhigh`, `max` |
| Opus 5, Sonnet 5, Opus 4.8, Opus 4.7 | `low`, `medium`, `high`, `xhigh`, `max` |
| Opus 4.6, Sonnet 4.6 | `low`, `medium`, `high`, `max` |
Default is `high` everywhere except Opus 4.7 (`xhigh`). Set via `/effort [level]`, `--effort <level>`, `CLAUDE_CODE_EFFORT_LEVEL` env var (highest precedence), the `effortLevel` setting (`low`/`medium`/`high`/`xhigh`; not `max`/`ultracode`), or skill/subagent frontmatter `effort:`.
`ultracode` (via `/effort ultracode` or `--effort ultracode`) sends `xhigh` and has Claude orchestrate dynamic workflows for substantive tasks; session-only.
Include `ultrathink` anywhere in a prompt for one-off deeper reasoning without changing the session effort setting.
### Extended thinking
| Control | How |
| --- | --- |
| Toggle for session | Option+T (macOS) / Alt+T (Windows/Linux) |
| Global default | `/config` → thinking mode toggle, saves `alwaysThinkingEnabled` |
| Disable regardless of effort | `MAX_THINKING_TOKENS=0` (no effect on Fable 5) |
Thinking output is collapsed by default; `Ctrl+O` toggles verbose mode. `showThinkingSummaries: true` in settings shows full (non-redacted) summaries.
### Extended context
Fable 5, Sonnet 5, Opus 4.6+, and Sonnet 4.6 support a 1M-token context window. Opus auto-upgrades to 1M on Max/Team/Enterprise plans; Sonnet 4.6 1M requires usage credits on every plan including Max. Sonnet 5 on the Anthropic API always runs at 1M (no `[1m]` suffix needed), auto-compacting around 967K tokens. Disable entirely with `CLAUDE_CODE_DISABLE_1M_CONTEXT=1`.
## Add a custom model option
```bash
export ANTHROPIC_CUSTOM_MODEL_OPTION="my-gateway/claude-opus-5"
export ANTHROPIC_CUSTOM_MODEL_OPTION_NAME="Opus via Gateway"
export ANTHROPIC_CUSTOM_MODEL_OPTION_DESCRIPTION="Custom deployment routed through the internal LLM gateway"
```
Adds one entry to the bottom of the `/model` picker without replacing built-in aliases; skips ID validation. Must also be listed in `availableModels` if that allowlist is set.
## Environment variables
| Variable | Description |
| --- | --- |
| `ANTHROPIC_DEFAULT_FABLE_MODEL` | Model for `fable`, and Fable-5 recognition for automatic fallback on third-party providers |
| `ANTHROPIC_DEFAULT_OPUS_MODEL` | Model for `opus`, or `opusplan` in plan mode |
| `ANTHROPIC_DEFAULT_SONNET_MODEL` | Model for `sonnet`, or `opusplan` outside plan mode |
| `ANTHROPIC_DEFAULT_HAIKU_MODEL` | Model for `haiku`, and background functionality |
| `CLAUDE_CODE_SUBAGENT_MODEL` | Model for all subagents/agent teams/workflow agents; overrides per-invocation `model` and frontmatter; `inherit` restores normal resolution |
`ANTHROPIC_SMALL_FAST_MODEL` is deprecated in favor of `ANTHROPIC_DEFAULT_HAIKU_MODEL`.
### Pin models for third-party deployments
```bash
export ANTHROPIC_DEFAULT_OPUS_MODEL='us.anthropic.claude-opus-4-8' # Amazon Bedrock
export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-8' # Vertex / Foundry
```
Append `[1m]` for extended context: `ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-8[1m]'`.
### Customize pinned model display and capabilities
`ANTHROPIC_DEFAULT_OPUS_MODEL_NAME`, `_DESCRIPTION`, `_SUPPORTED_CAPABILITIES` (comma-separated: `effort`, `xhigh_effort`, `max_effort`, `thinking`, `adaptive_thinking`, `interleaved_thinking`) — same suffixes apply to Sonnet/Haiku/Fable/`ANTHROPIC_CUSTOM_MODEL_OPTION`.
### Override model IDs per version (`modelOverrides`)
```json
{
"modelOverrides": {
"claude-opus-4-7": "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/opus-prod",
"claude-sonnet-4-6": "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/sonnet-prod"
}
}
```
Maps individual Anthropic model IDs to provider-specific strings (Bedrock ARN, Vertex version, Foundry deployment name), for governance/cost allocation/regional routing.
### Prompt caching configuration
| Variable | Effect |
| --- | --- |
| `DISABLE_PROMPT_CACHING` | Disable for all models (takes precedence) |
| `DISABLE_PROMPT_CACHING_HAIKU` / `_SONNET` / `_OPUS` / `_FABLE` | Disable per model tier |
## Options / Props
| Setting | Values | Description |
| --- | --- | --- |
| `model` | alias or full model ID | Initial model selection for a session |
| `availableModels` | array of model families/IDs | Allowlist restricting selectable models |
| `enforceAvailableModels` | boolean | Extend allowlist to the Default option |
| `effortLevel` | `low` \| `medium` \| `high` \| `xhigh` | Persisted effort level |
| `fallbackModel` | array (max 3) | Ordered fallback chain for overload/unavailable |
| `modelOverrides` | map | Anthropic model ID → provider-specific ID |
## Related
- [settings.md](./settings.md): where `model`, `availableModels`, `fallbackModel`, `effortLevel` live in the settings file
- [fast-mode.md](./fast-mode.md): the Opus-only fast mode toggle that interacts with model switching
- [statusline.md](./statusline.md): displaying the current model/effort in a status line
## Notes
This page was retrieved in full (no truncation observed).
references/settings/README.md
# Settings
| Name | Description | Path |
|------|-------------|------|
| Configure auto mode | auto mode で自動パーミッションチェッカーを通してツール呼び出しをルーティング。破壊的・環境外アクションをブロック | [auto-mode-config.md](./auto-mode-config.md) |
| CLI reference | Claude Code コマンドラインインターフェースの完全リファレンス: コマンドとフラグ | [cli-reference.md](./cli-reference.md) |
| Explore the .claude directory | Claude Code が読込む CLAUDE.md、settings.json、hooks、skills、commands、subagents、workflows、rules、auto memory の場所解説 | [claude-directory.md](./claude-directory.md) |
| Debug your configuration | CLAUDE.md、settings、hooks、MCP サーバー、skills が効いていない原因の診断 | [debug-your-config.md](./debug-your-config.md) |
| Environment variables | Claude Code の動作を制御する環境変数リファレンス: モデル選択、認証、リクエストルーティング、機能トグル | [env-vars.md](./env-vars.md) |
| Error reference | Claude Code が表示するランタイムエラーメッセージ。各エラーの意味と回復方法を解説 | [errors.md](./errors.md) |
| Speed up responses with fast mode | Claude Opus 向けの高速設定(最大 2.5 倍高速)。反面トークンあたりの費用が上昇 | [fast-mode.md](./fast-mode.md) |
| Customize keyboard shortcuts | Claude Code でカスタマイズ可能なキーボードショートカット設定 | [keybindings.md](./keybindings.md) |
| Model configuration | Claude Code が使用するモデル、model aliases(opusplan など)、effort levels、extended thinking を設定 | [model-config.md](./model-config.md) |
| Claude Code settings | Claude Code をグローバル・プロジェクトレベル設定、環境変数、managed policy で設定 | [settings.md](./settings.md) |
| Customize your status line | Claude Code 下部のカスタマイズ可能なステータスバー。シェルスクリプトで コンテキスト使用率、コスト、git 状態等を表示 | [statusline.md](./statusline.md) |
| Configure your terminal for Claude Code | Shift+Enter 改行、ターミナルベル・通知、tmux、色テーマ、Vim モードなどターミナル固有の設定 | [terminal-config.md](./terminal-config.md) |
references/settings/settings.md
<!-- source: https://code.claude.com/docs/en/settings.md / last verified: 2026-08-07 -->
# Claude Code settings
Configure Claude Code with global and project-level settings, environment variables, and managed policy. Run `/config` for an interactive settings UI, or `/config key=value` (v2.1.181+) to change one option directly.
## Configuration scopes
| Scope | Location | Who it affects | Shared with team? |
| --- | --- | --- | --- |
| Managed | Server-managed settings, plist/registry, or system-level `managed-settings.json` | All org members (server-managed) or all users on the machine (plist/registry/file) | Yes (deployed by IT) |
| User | `~/.claude/` | You, across all projects | No |
| Project | `.claude/` in repository | All collaborators on this repository | Yes (committed to git) |
| Local | `.claude/settings.local.json` at repo root | You, in this repository only | No (gitignored when Claude Code saves a setting to it) |
Precedence, highest to lowest: **Managed** > command-line arguments > **Local** > **Project** > **User**. Permission rules merge across scopes rather than override; a few security-sensitive settings honor a restrictive value from certain scopes that otherwise couldn't override them.
What uses scopes:
| 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, `~/.claude` resolves to `%USERPROFILE%\.claude`.
## Settings files
- **User settings**: `~/.claude/settings.json`, applies to all projects.
- **Project settings**: `.claude/settings.json` (checked into source control) or `.claude/settings.local.json` (not checked in; Claude Code adds it to your global git excludes the first time it saves a setting there). Read/written at the git repository root (resolved through worktrees), except outside a git repo, when the repo root is your home directory, or in Agent SDK sessions.
- **Managed settings**: for centralized control, delivered via server-managed settings (claude.ai admin console or a self-hosted Claude apps gateway), MDM/OS-level policy (macOS `com.anthropic.claudecode` plist, Windows `HKLM\SOFTWARE\Policies\ClaudeCode` or `HKCU\...`), or file-based `managed-settings.json` / `managed-mcp.json` (macOS `/Library/Application Support/ClaudeCode/`, Linux/WSL `/etc/claude-code/`, Windows `C:\Program Files\ClaudeCode\`). File-based managed settings also support a `managed-settings.d/` drop-in directory, merged alphabetically on top of the base file (systemd-style; use numeric prefixes to control order).
- **Other configuration**: `~/.claude.json` holds OAuth session, user/local-scope MCP server configs, per-project state, and caches. Project-scoped MCP servers live in `.mcp.json`.
Claude Code keeps the 5 most recent timestamped backups of configuration files.
```json Example settings.json
{
"$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",
"OTEL_EXPORTER_OTLP_PROTOCOL": "http/protobuf"
},
"companyAnnouncements": ["Welcome to Acme Corp! Review our code guidelines at docs.acme.com"]
}
```
### When edits take effect
Most keys (`permissions`, `hooks`, `apiKeyHelper`, etc.) reload live without a restart, across user/project/local/managed scopes; the `ConfigChange` hook fires per change. Two keys apply only on next restart: `model` (use `/model` to switch mid-session) and `outputStyle` (part of the system prompt, rebuilt on `/clear` or restart).
### Invalid entries in managed settings
Managed settings parse tolerantly: an invalid entry is stripped with a warning, and the rest of the policy still applies (`/doctor` lists stripped entries). Certain security-enforcement fields (`allowedMcpServers`, `allowManagedMcpServersOnly`, `availableModels`, `enforceAvailableModels`, `forceLoginOrgUUID`, `deniedMcpServers`, `sandbox.credentials`) fail toward the more restrictive behavior instead of being dropped outright. `requiredMinimumVersion`/`requiredMaximumVersion` fail open (stripped, not enforced). This tolerance applies only to managed settings — user/project/local settings files that fail validation are rejected wholesale.
## Available settings
`settings.json` supports many keys, listed alphabetically below.
| Key | Description | Example |
| --- | --- | --- |
| `advisorModel` | Model for the server-side advisor tool. Accepts `"opus"`, `"sonnet"`, or a full model ID. Written automatically by `/advisor`. Unset to disable | `"opus"` |
| `agent` | Run the main thread as a named subagent; sets the default agent for `claude agents` | `"code-reviewer"` |
| `agentPushNotifEnabled` | Default `false`. Allow Claude to send proactive push notifications via Remote Control | `true` |
| `allowAllClaudeAiMcps` | (Managed only) Load claude.ai connectors alongside a deployed `managed-mcp.json` | `true` |
| `allowedChannelPlugins` | (Managed only) Allowlist of channel plugins that may push messages | `[{ "marketplace": "claude-plugins-official", "plugin": "telegram" }]` |
| `allowedHttpHookUrls` | Allowlist of URL patterns HTTP hooks may target (`*` wildcard). Undefined = no restriction, `[]` = block all | `["https://hooks.example.com/*"]` |
| `allowedMcpServers` | (Managed) Allowlist of MCP servers users can configure. Undefined = no restriction, `[]` = lockdown | `[{ "serverName": "github" }]` |
| `allowManagedHooksOnly` | (Managed only) Only managed/SDK/force-enabled-plugin hooks load | `true` |
| `allowManagedMcpServersOnly` | (Managed only) Only managed `allowedMcpServers` respected; `deniedMcpServers` still merges | `true` |
| `allowManagedPermissionRulesOnly` | (Managed only) Only managed settings can define `allow`/`ask`/`deny` permission rules | `true` |
| `alwaysThinkingEnabled` | Enable extended thinking by default. Set `MAX_THINKING_TOKENS=0` in `env` to force off (except Fable 5) | `true` |
| `apiKeyHelper` | Shell command that generates an auth value, sent as `X-Api-Key`/`Authorization: Bearer`. Refresh interval via `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` | `/bin/generate_temp_api_key.sh` |
| `askUserQuestionTimeout` | Default `"never"`. Idle time before an unanswered `AskUserQuestion` dialog auto-continues (`"60s"`, `"5m"`, `"10m"`, `"never"`) | `"5m"` |
| `attribution` | Customize git commit/PR attribution | `{"commit": "Generated with Claude Code", "pr": ""}` |
| `autoCompactEnabled` | Default `true`. Auto-compact when context nears the limit | `false` |
| `autoCompactWindow` | Tokens (100000-1000000) before auto-compact triggers. Set via `/autocompact`; `--autocompact` flag and `CLAUDE_CODE_AUTO_COMPACT_WINDOW` env var can override | `500000` |
| `autoMemoryDirectory` | Custom directory for auto memory storage | `"~/my-memory-dir"` |
| `autoMemoryEnabled` | Default `true`. Toggle with `/memory` or `CLAUDE_CODE_DISABLE_AUTO_MEMORY` | `false` |
| `autoMode` | Customize auto mode classifier: `environment`, `allow`, `soft_deny`, `hard_deny` prose-rule arrays; include `"$defaults"` to inherit built-ins. Read from user settings, `--settings`, and managed settings only (not project/local) | `{"soft_deny": ["$defaults", "Never run terraform apply"]}` |
| `autoMode.classifyAllShell` | Default `false`. Route every Bash/PowerShell command through the classifier while auto mode is active | `true` |
| `autoScrollEnabled` | Default `true`. Follow output to bottom in fullscreen rendering | `false` |
| `autoUpdatesChannel` | Default `"latest"`. `"stable"` or `"latest"` release channel | `"stable"` |
| `availableModels` | Restrict which models are selectable for main session, subagents, skills, advisor | `["sonnet", "haiku"]` |
| `awaySummaryEnabled` | Show a one-line session recap on return. Same as `CLAUDE_CODE_ENABLE_AWAY_SUMMARY` | `true` |
| `awsAuthRefresh` | Script that refreshes the `.aws` directory | `aws sso login --profile myprofile` |
| `awsCredentialExport` | Script that outputs JSON AWS credentials | `/bin/generate_aws_grant.sh` |
| `axScreenReader` | Screen-reader friendly flat-text output; forces classic renderer. `CLAUDE_AX_SCREEN_READER` and `--ax-screen-reader` take precedence | `true` |
| `blockedMarketplaces` | (Managed only) Blocklist of plugin marketplace sources | `[{ "source": "github", "repo": "untrusted/plugins" }]` |
| `browserExternalPageTools` | (Managed only) `"disabled"` blocks Claude's tools for external pages in the Desktop Browser pane | `"disabled"` |
| `channelsEnabled` | (Managed only) Allow channels for the organization | `true` |
| `claudeMd` | (Managed only) Org-managed CLAUDE.md-style memory | `"Always run make lint before committing."` |
| `claudeMdExcludes` | Glob patterns/paths of CLAUDE.md files to skip loading | `["**/vendor/**/CLAUDE.md"]` |
| `cleanupPeriodDays` | Default `30`, min `1`. Age cutoff for deleting old session files/app data at startup | `20` |
| `companyAnnouncements` | Startup announcements, cycled randomly if multiple | `["Welcome to Acme Corp!"]` |
| `defaultShell` | Default `"bash"` (or `"powershell"` on Windows without Bash). Default shell for `!` commands | `"powershell"` |
| `deniedMcpServers` | (Managed) Denylist of MCP servers, applies to all scopes, takes precedence over allowlist | `[{ "serverName": "filesystem" }]` |
| `disableAgentView` | Turn off background agents/agent view (`claude agents`, `--bg`, `/background`) | `true` |
| `disableAllHooks` | Disable all hooks and any custom status line | `true` |
| `disableArtifact` | Disable the Artifact tool | `true` |
| `disableAutoMode` | `"disable"` prevents auto mode activation; also `permissions.disableAutoMode` | `"disable"` |
| `disableBrowserExternalNavigation` | (Managed only) Turn off external browsing in the Desktop Browser pane | `true` |
| `disableBundledSkills` | Disable bundled skills/workflows (built-ins like `/init` stay typable but hidden from the model) | `true` |
| `disableClaudeAiConnectors` | Disable claude.ai MCP connectors. `true` in any source wins | `true` |
| `disableDeepLinkRegistration` | `"disable"` prevents registering the `claude-cli://` protocol handler | `"disable"` |
| `disabledMcpjsonServers` | Specific `.mcp.json` servers to reject | `["filesystem"]` |
| `disableMobileSimulatorTools` | (Managed only) Block Claude's tools for the Desktop iOS Simulator pane | `true` |
| `disableRemoteControl` | Disable Remote Control entirely | `true` |
| `disableSideloadFlags` | (Managed only) Reject `--plugin-dir`, `--plugin-url`, `--agents`, `--mcp-config` CLI flags | `true` |
| `disableSkillShellExecution` | Disable inline shell execution (`` !`...` ``) in skills/commands from non-bundled sources | `true` |
| `disableWorkflows` | Default `false`. Disable dynamic workflows and bundled workflow commands | `true` |
| `editorMode` | Default `"normal"`. `"normal"` or `"vim"` prompt key-binding mode | `"vim"` |
| `effortLevel` | Persist effort level (`"low"`, `"medium"`, `"high"`, `"xhigh"`) across sessions. Set via `/effort` | `"xhigh"` |
| `emojiCompletionEnabled` | Default `true`. Emoji shortcode suggestions on `:` | `false` |
| `enableAllProjectMcpServers` | Auto-approve all `.mcp.json` project servers | `true` |
| `enableArtifact` | Enable/disable the Artifact tool for this user; ignored in project/local settings | `true` |
| `enabledMcpjsonServers` | Specific `.mcp.json` servers to approve | `["memory", "github"]` |
| `enforceAvailableModels` | Extend `availableModels` allowlist to the Default model option | `true` |
| `env` | Environment variables applied to every session and spawned subprocesses. Set to `""` to override a shell export as unset | `{"FOO": "bar"}` |
| `fallbackModel` | Ordered fallback model(s) when primary is overloaded/unavailable. `"default"` expands to the default model; capped at 3 models; does not merge across files (highest-precedence file wins) | `["claude-sonnet-5", "claude-haiku-4-5"]` |
| `fastMode` | Turn fast mode on for sessions where available. `/fast` writes `true` here | `true` |
| `fastModePerSessionOptIn` | `true` disables fast mode persistence across sessions; each session starts with fast mode off | `true` |
| `feedbackSurveyRate` | Probability (0-1) the session quality survey appears when eligible. `0` suppresses it entirely | `0.05` |
| `fileCheckpointingEnabled` | Default `true`. Snapshot files before each edit so `/rewind` can restore them | `false` |
| `fileSuggestion` | Custom script for `@` file autocomplete | `{"type": "command", "command": "~/.claude/file-suggestion.sh"}` |
| `footerLinksRegexes` | Render extra clickable footer badges when a regex matches turn output (`pattern`, `url` template, optional `label`). User/`--settings`/managed settings only | `[{"type": "regex", "pattern": "\\b(?<key>PROJ-\\d+)\\b", "url": "https://issues.example.com/browse/{key}", "label": "{key}"}]` |
| `forceLoginMethod` | `claudeai`/`console`/`gateway` restricts which login type is allowed | `claudeai` |
| `forceLoginGatewayUrl` | Pre-fills and locks the gateway URL on the `/login` Cloud gateway screen. Managed policy tier only | `"https://claude-gateway.example.com"` |
| `forceLoginOrgUUID` | Require login to belong to a specific Anthropic org (single UUID or array of UUIDs) | `"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"` |
| `forceRemoteSettingsRefresh` | (Managed only) Block CLI startup until remote managed settings are freshly fetched; exits on fetch failure | `true` |
| `gcpAuthRefresh` | Custom script that refreshes GCP Application Default Credentials | `gcloud auth application-default login` |
| `hooks` | Configure custom commands to run at lifecycle events | See hooks documentation |
| `httpHookAllowedEnvVars` | Allowlist of env var names HTTP hooks may interpolate into headers | `["MY_TOKEN", "HOOK_SECRET"]` |
| `includeGitInstructions` | Default `true`. Include built-in commit/PR workflow instructions and git status in the system prompt | `false` |
| `inputNeededNotifEnabled` | Default `false`. Push notification via Remote Control when a permission prompt/question is waiting | `true` |
| `language` | Claude's preferred response language; also sets voice dictation and auto-generated session title language | `"japanese"` |
| `minimumVersion` | Floor that prevents background auto-updates/`claude update` from installing a version below this | `"2.1.100"` |
| `model` | Override the default model. `--model` and `ANTHROPIC_MODEL` override this for one session | `"claude-sonnet-5"` |
| `modelOverrides` | Map Anthropic model IDs to provider-specific model IDs (e.g. Amazon Bedrock inference profile ARNs) | `{"claude-opus-4-6": "arn:aws:bedrock:..."}` |
| `otelHeadersHelper` | Script to generate dynamic OpenTelemetry headers, run at startup and periodically | `/bin/generate_otel_headers.sh` |
| `outputStyle` | Configure an output style to adjust the system prompt | `"Explanatory"` |
| `parentSettingsBehavior` | (Managed only) Default `"first-wins"`. Whether parent-process-supplied managed settings (Agent SDK/IDE) apply alongside an admin-deployed managed tier: `"first-wins"` or `"merge"` | `"merge"` |
| `permissions` | See Permission settings below | — |
| `plansDirectory` | Default `~/.claude/plans`. Customize where plan files are stored | `"./plans"` |
| `pluginSuggestionMarketplaces` | (Managed only) Marketplace names whose plugins can appear as contextual install suggestions | `["acme-corp-plugins"]` |
| `pluginTrustMessage` | (Managed only) Custom message appended to the plugin trust warning before installation | `"All plugins from our marketplace are approved by IT"` |
| `policyHelper` | Admin-deployed executable that computes managed settings dynamically at startup. MDM/system `managed-settings.json` only | `{"path": "/usr/local/bin/claude-policy"}` |
| `preferredNotifChannel` | Default `"auto"`. `"auto"`, `"terminal_bell"`, `"iterm2"`, `"iterm2_with_bell"`, `"kitty"`, `"ghostty"`, `"notifications_disabled"` | `"terminal_bell"` |
| `prefersReducedMotion` | Reduce/disable UI animations (spinners, shimmer, flash effects) | `true` |
| `processWrapper` | Corporate launcher command prefixing background processes Claude Code starts. `CLAUDE_CODE_PROCESS_WRAPPER` env var takes precedence | `"/opt/corp/launcher --profile claude"` |
| `prUrlTemplate` | URL template for the PR badge/tool-result summaries; substitutes `{host}`/`{owner}`/`{repo}`/`{number}`/`{url}` | `"https://reviews.example.com/{owner}/{repo}/pull/{number}"` |
| `remote.defaultEnvironmentId` | Default cloud environment for cloud sessions created from the CLI (e.g. `claude --cloud`) | `"env_0123abcd"` |
| `remoteControlAtStartup` | Auto-connect Remote Control at every session start instead of waiting for `/remote-control` | `false` |
| `requiredMaximumVersion` | (Managed only) Max Claude Code version allowed to start; exits at startup if the running version is newer | `"2.1.150"` |
| `requiredMinimumVersion` | (Managed only) Min Claude Code version required to start; exits at startup if the running version is older | `"2.1.150"` |
| `respectGitignore` | Default `true`. Whether the `@` file picker respects `.gitignore` patterns | `false` |
| `respondToBashCommands` | Default `true`. Whether Claude responds after an input-box `!` shell command runs | `false` |
| `showClearContextOnPlanAccept` | Default `false`. Show the "clear context" option on the plan accept screen | `true` |
| `showThinkingSummaries` | Default `false`. Show extended thinking summaries (unredacted) in interactive sessions | `true` |
| `showTurnDuration` | Default `true`. Show turn duration messages after responses (e.g. "Cooked for 1m 6s") | `false` |
| `skillListingBudgetFraction` | Default `0.01`. Fraction of the model's context window reserved for the skill listing shown each turn | `0.02` |
| `skillListingMaxDescChars` | Default `1536`. Per-skill character cap on combined `description`/`when_to_use` text in the skill listing | `2048` |
| `skillOverrides` | Per-skill visibility overrides keyed by skill name: `"on"`, `"name-only"`, `"user-invocable-only"`, `"off"` | `{"legacy-context": "name-only", "deploy": "off"}` |
| `skipWebFetchPreflight` | Skip the WebFetch domain safety check that pings `api.anthropic.com` before fetching; for egress-restricted deployments | `true` |
| `spinnerTipsEnabled` | Default `true`. Show tips in the spinner while Claude is working | `false` |
| `spinnerTipsOverride` | Override spinner tips with custom strings (`tips` array, `excludeDefault` boolean) | `{ "excludeDefault": true, "tips": ["Use our internal tool X"] }` |
| `spinnerVerbs` | Customize action verbs shown during a turn (`mode`: `"replace"` or `"append"`) | `{"mode": "append", "verbs": ["Pondering", "Crafting"]}` |
| `sshConfigs` | SSH connections shown in the Desktop environment dropdown (`id`, `name`, `sshHost`, optional `sshPort`/`sshIdentityFile`/`startDirectory`). Managed/user settings only | `[{"id": "dev-vm", "name": "Dev VM", "sshHost": "user@dev.example.com"}]` |
| `statusLine` | Configure a custom status line (`padding`, `refreshInterval`, `hideVimModeIndicator`) | `{"type": "command", "command": "~/.claude/statusline.sh"}` |
| `strictKnownMarketplaces` | (Managed only) Allowlist of plugin marketplace sources | `[{ "source": "github", "repo": "acme-corp/plugins" }]` |
| `strictPluginOnlyCustomization` | (Managed only) Block skills/agents/hooks/MCP servers from user and project sources; `true` locks all four, array locks named ones | `["skills", "hooks"]` |
| `switchModelsOnFlag` | Default `true`. Auto-switch to the fallback model when a safety classifier flags a request; `false` pauses to choose instead | `false` |
| `syntaxHighlightingDisabled` | Disable syntax highlighting in diffs, code blocks, file previews | `true` |
| `teammateMode` | Default `in-process`. Agent team teammate display: `in-process`, `auto`, `tmux`, `iterm2` | `"auto"` |
| `terminalProgressBarEnabled` | Default `true`. Show the terminal progress bar (ConEmu, Ghostty 1.2+, iTerm2 3.6.6+) | `false` |
| `theme` | Default `"dark"`. `"auto"`, `"dark"`, `"light"`, `"dark-daltonized"`, `"light-daltonized"`, `"dark-ansi"`, `"light-ansi"`, or `"custom:<slug>"` | `"dark"` |
| `tui` | Terminal UI renderer: `"fullscreen"` (flicker-free alt-screen) or `"default"` (classic). Set via `/tui` | `"fullscreen"` |
| `ultracode` | Turn on ultracode for the current session. Not read from `settings.json` directly — set via `/effort ultracode`, `--settings`, or an Agent SDK control request | `true` |
| `useAutoModeDuringPlan` | Default `true`. Whether plan mode uses auto mode semantics when auto mode is available. Not read from shared project settings | `false` |
| `verbose` | Default `false`. Show full tool output instead of truncated summaries. `--verbose` flag overrides for one session | `true` |
| `viewMode` | Default transcript view mode on startup: `"default"`, `"verbose"`, `"focus"` | `"verbose"` |
| `vimInsertModeRemaps` | Map two-key INSERT-mode sequences to Escape in vim editor mode. User/`--settings`/managed settings only | `{"jj": "<Esc>"}` |
| `voice` | Voice dictation settings: `enabled`, `mode` (`"hold"`/`"tap"`), `autoSubmit` | `{ "enabled": true, "mode": "tap" }` |
| `voiceEnabled` | Legacy alias for `voice.enabled`; prefer the `voice` object | `true` |
| `wheelScrollAccelerationEnabled` | Default `true`. Accelerate mouse-wheel scroll speed during fast scrolls in fullscreen rendering | `false` |
| `workflowKeywordTriggerEnabled` | Default `true`. Whether the keyword `ultracode` in a prompt triggers a dynamic workflow | `false` |
| `workflowSizeGuideline` | Default `medium`. Agent-count guidance for dynamic workflows Claude writes: `unrestricted`, `small`, `medium`, `large` | `"small"` |
| `wslInheritsWindowsSettings` | (Windows managed settings only) `true` makes Claude Code on WSL also read managed settings from the Windows policy chain | `true` |
## Global config settings
Stored in `~/.claude.json` rather than `settings.json`; adding these keys to `settings.json` is silently ignored at startup.
| Key | Description | Example |
| --- | --- | --- |
| `autoConnectIde` | Default `false`. Auto-connect to a running IDE when Claude Code starts from an external terminal | `true` |
| `autoInstallIdeExtension` | Default `true`. Auto-install the Claude Code IDE extension when running from a VS Code terminal | `false` |
| `diffTool` | Default `auto`. Where to display file diffs when an IDE is connected: `auto` (IDE diff viewer) or `terminal` | `"terminal"` |
| `externalEditorContext` | Default `false`. Prepend Claude's previous response as `#`-commented context when opening the external editor (Ctrl+G) | `true` |
| `permissionExplainerEnabled` | Default `true`. Show a model-generated command explanation on Ctrl+E at a Bash/PowerShell permission prompt | `false` |
| `teammateDefaultModel` | Default model for agent team teammates when the spawn prompt doesn't specify one; `null` inherits the lead's `/model` selection | `"sonnet"` |
## Worktree settings
Configure how `--worktree` creates and manages git worktrees.
| Key | Description | Example |
| --- | --- | --- |
| `worktree.baseRef` | Which ref new worktrees branch from: `"fresh"` (default, `origin/<default-branch>`) or `"head"` (current local `HEAD`) | `"head"` |
| `worktree.symlinkDirectories` | Directories to symlink from the main repository into each worktree (avoid duplicating large dirs) | `["node_modules", ".cache"]` |
| `worktree.sparsePaths` | Directories to check out per worktree via git sparse-checkout | `["packages/my-app", "shared/utils"]` |
| `worktree.bgIsolation` | Isolation mode for background sessions: `"worktree"` (default, blocks Edit/Write in main checkout until `EnterWorktree`) or `"none"` | `"none"` |
To copy gitignored files like `.env` into new worktrees, use a `.worktreeinclude` file in the project root instead of a setting.
## Permission settings
The `permissions` key's structure:
| Key | Description | Example |
| --- | --- | --- |
| `allow` | Array of permission rules to allow tool use. See Permission rule syntax (permissions docs) | `[ "Bash(git diff *)" ]` |
| `ask` | Array of permission rules to ask for confirmation | `[ "Bash(git push *)" ]` |
| `deny` | Array of permission rules to deny tool use; `"*"` denies every tool, `"mcp__*"` denies every MCP tool | `[ "WebFetch", "Bash(curl *)", "Read(./.env)", "Read(./secrets/**)" ]` |
| `additionalDirectories` | Additional working directories for file access (most `.claude/` configuration is not discovered from these) | `[ "../docs/" ]` |
| `defaultMode` | Default permission mode on open: `default`, `acceptEdits`, `plan`, `auto`, `dontAsk`, `bypassPermissions`, `manual` (alias for `default`). `auto` is ignored in project/local settings | `"acceptEdits"` |
| `disableAutoMode` | `"disable"` prevents auto mode activation (same as the top-level setting) | `"disable"` |
| `disableBypassPermissionsMode` | `"disable"` prevents `bypassPermissions` mode (disables `--dangerously-skip-permissions`) | `"disable"` |
| `skipDangerousModePermissionPrompt` | Skip the confirmation prompt before entering bypass permissions mode. Ignored in project settings | `true` |
## Attribution settings
`attribution` customizes git commit and pull request attribution text, for example `{"commit": "Generated with Claude Code", "pr": ""}` (empty string omits the PR attribution line).
## Related
- [env-vars.md](./env-vars.md): the environment-variable counterparts and precedence rules
- [claude-directory.md](./claude-directory.md): where each settings file lives on disk
- [debug-your-config.md](./debug-your-config.md): `/status`, `/doctor`, and other inspection commands
- [auto-mode-config.md](./auto-mode-config.md): the full `autoMode` reference
- [model-config.md](./model-config.md), [statusline.md](./statusline.md), [keybindings.md](./keybindings.md): the pages dedicated to `model`/`modelOverrides`, `statusLine`, and keybindings respectively
references/settings/statusline.md
<!-- source: https://code.claude.com/docs/en/statusline.md / last verified: 2026-08-07 -->
# Customize your status line
A customizable bar at the bottom of Claude Code that runs a shell script you configure. It receives JSON session data on stdin and displays whatever the script prints stdout — context usage, costs, git status, or anything else.
## Signature / Usage
```json ~/.claude/settings.json
{
"statusLine": {
"type": "command",
"command": "~/.claude/statusline.sh",
"padding": 2
}
}
```
Or generate one from natural language: `/statusline show model name and context percentage with a progress bar`.
Minimal script (`~/.claude/statusline.sh`, then `chmod +x`):
```bash
#!/bin/bash
input=$(cat)
MODEL=$(echo "$input" | jq -r '.model.display_name')
DIR=$(echo "$input" | jq -r '.workspace.current_dir')
PCT=$(echo "$input" | jq -r '.context_window.used_percentage // 0' | cut -d. -f1)
echo "[$MODEL] 📁 ${DIR##*/} | ${PCT}% context"
```
## Options / Props
| Field | Description |
| --- | --- |
| `type` | `"command"` — run the shell command in `command` |
| `command` | Script path or inline shell command (runs in a shell) |
| `padding` | Extra horizontal spacing in characters, default `0`, in addition to built-in interface spacing |
| `refreshInterval` | Re-run the command every N seconds (min `1`) in addition to event-driven updates; needed for time-based data or when background subagents change git state while idle |
| `hideVimModeIndicator` | `true` suppresses the built-in `-- INSERT --` text when the script already renders `vim.mode` |
Disable: `/statusline delete` (or `clear`/`remove it`), or delete the `statusLine` key manually.
## How status lines work
Claude Code pipes JSON to the script's stdin; the script prints to stdout. Runs once at session start/resume, then again on: a new assistant message, `/compact` finishing, permission mode change, vim mode toggle, or a `refreshInterval` tick. Debounced at 300ms; an in-flight script is cancelled if a new trigger fires. Multi-line output (`echo` per line), ANSI color codes, and OSC 8 hyperlinks are all supported. Read `COLUMNS`/`LINES` env vars for terminal size (stdout is captured, so `tput cols` doesn't work). Runs locally, consumes no API tokens.
## Available data (JSON fields on stdin)
| Field | Description |
| --- | --- |
| `model.id`, `model.display_name` | Current model |
| `cwd`, `workspace.current_dir` | Current working directory |
| `workspace.project_dir` | Directory Claude Code was launched from |
| `workspace.added_dirs` | Dirs added via `/add-dir` |
| `workspace.git_worktree` | Worktree name (absent in main tree) |
| `workspace.repo.host/owner/name` | Parsed from `origin` remote |
| `cost.total_cost_usd` | Estimated session cost (resets on `/clear`) |
| `cost.total_duration_ms`, `cost.total_api_duration_ms` | Wall-clock / API-wait time |
| `cost.total_lines_added`, `cost.total_lines_removed` | Lines changed |
| `context_window.total_input_tokens`, `.total_output_tokens` | Current context usage (not cumulative, since v2.1.132) |
| `context_window.context_window_size` | 200000 default, or 1000000 for extended-context models |
| `context_window.used_percentage`, `.remaining_percentage` | Pre-calculated, input-tokens-only |
| `context_window.current_usage` | `{input_tokens, output_tokens, cache_creation_input_tokens, cache_read_input_tokens}`; `null` before first API call and right after `/compact` |
| `exceeds_200k_tokens` | Fixed 200k threshold regardless of actual window size |
| `fast_mode` | Whether fast mode is on |
| `effort.level` | `low`/`medium`/`high`/`xhigh`/`max` (ultracode reports as `xhigh`); absent if unsupported |
| `thinking.enabled` | Extended thinking on/off |
| `rate_limits.five_hour`/`.seven_day` `.used_percentage`/`.resets_at` | Pro/Max subscription rate limits, present only after first API response |
| `session_id`, `session_name` | Session identity; `session_name` absent unless custom-named or AI-titled |
| `prompt_id` | UUID of current prompt (absent until first input; v2.1.196+) |
| `transcript_path`, `version` | Transcript file path, Claude Code version |
| `output_style.name` | Current output style |
| `vim.mode` | `NORMAL`/`INSERT`/`VISUAL`/`VISUAL LINE` when vim mode enabled |
| `agent.name` | Set with `--agent` or agent settings |
| `pr.number`, `.url`, `.review_state` | Open PR for current branch (absent once merged/closed) |
| `worktree.name`, `.path`, `.branch`, `.original_cwd`, `.original_branch` | Present only during `--worktree` sessions |
`context_window.used_percentage` is calculated from `input_tokens + cache_creation_input_tokens + cache_read_input_tokens` only (not output tokens).
## Examples
Common patterns (Bash/Python/Node.js snippets in the source): context-window progress bar, git status with ANSI colors, cost/duration tracking, multi-line output, OSC 8 clickable links (e.g. to a GitHub repo), rate-limit display, and caching slow `git` calls to a temp file keyed by `session_id` (not PID, which changes per invocation).
### Subagent status lines
```json
{ "subagentStatusLine": { "type": "command", "command": "~/.claude/subagent-statusline.sh" } }
```
Renders a custom row per subagent shown in the agent panel. Receives base hook fields + `columns` + a `tasks` array (`id`, `name`, `type`, `status`, `description`, `label`, `startTime`, `model`, `effort`, `contextWindowSize`, `tokenCount`, `tokenSamples`, `cwd`). Write one JSON line per row to override: `{"id": "<task id>", "content": "<row body>"}`; omit `id` to keep default rendering, emit empty `content` to hide the row.
### Windows configuration
Runs through Git Bash if installed, else PowerShell. Use forward slashes in `command` paths (Git Bash treats unquoted backslashes as escapes). To run a PowerShell script explicitly: `"command": "powershell -NoProfile -File C:/Users/username/.claude/statusline.ps1"`.
## Notes
- Status line only runs after workspace trust is accepted for the directory (it executes a shell command, same trust gate as hooks); `claude --debug` logs `Status line command skipped: workspace trust not accepted` otherwise.
- `disableAllHooks: true` also disables the status line.
- Scripts that exit non-zero or hang leave the status line blank/stale; a slow script blocks updates until it completes or is cancelled by the next trigger.
- Test with mock input: `echo '{"model":{"display_name":"Opus"},...}' | ./statusline.sh`.
- Community projects `ccstatusline` and `starship-claude` provide pre-built configurations.
## Related
- [model-config.md](./model-config.md): `effort.level` and `fast_mode` semantics shown in the status line
- [terminal-config.md](./terminal-config.md): OSC 8 hyperlink support (`FORCE_HYPERLINK`) and color theme matching
references/settings/terminal-config.md
<!-- source: https://code.claude.com/docs/en/terminal-config.md / last verified: 2026-08-07 -->
# Configure your terminal for Claude Code
Fixes for terminal-specific quirks: Shift+Enter for newlines, terminal bell/notifications, tmux, color theme matching, and Vim mode. This page is about getting the *terminal* to send the right signals; to change which keys Claude Code itself responds to, see keybindings.
## Enter multiline prompts
Enter submits; Ctrl+J or `\` + Enter always inserts a newline. Shift+Enter works natively in Ghostty/Kitty/iTerm2/WezTerm/Warp/Apple Terminal/Windows Terminal; run `/terminal-setup` once for VS Code/Cursor/Devin Desktop/Alacritty/Zed; not available in gnome-terminal or JetBrains IDEs. `/terminal-setup` also sets `terminal.integrated.gpuAcceleration: "off"` and tunes `mouseWheelScrollSensitivity` in VS Code-family editors. Run it in the host terminal, not inside tmux/screen. Inside tmux, Shift+Enter also needs the tmux config below.
## Enable Option key shortcuts on macOS
Most macOS terminals don't send Option as a modifier by default ("Use Option as Meta Key").
| Terminal | Fix |
| --- | --- |
| Apple Terminal | Settings → Profiles → Keyboard → "Use Option as Meta Key" (done automatically by first-run `/terminal-setup`) |
| iTerm2 | Settings → Profiles → Keys → General → Left/Right Option key → "Esc+"; `/terminal-setup` also enables clipboard access |
| VS Code | Add `"terminal.integrated.macOptionIsMeta": true` |
## Get a terminal bell or notification
Desktop notification is sent by default only in Ghostty/Kitty/iTerm2. Elsewhere, set `preferredNotifChannel: "terminal_bell"`:
```json ~/.claude/settings.json
{ "preferredNotifChannel": "terminal_bell" }
```
iTerm2 requires enabling: Settings → Profiles → Terminal → "Notification Center Alerts" → Filter Alerts → "Send escape sequence-generated alerts".
### Play a sound with a Notification hook
```json ~/.claude/settings.json
{
"hooks": {
"Notification": [
{ "hooks": [{ "type": "command", "command": "afplay /System/Library/Sounds/Glass.aiff" }] }
]
}
}
```
## Configure tmux
Inside tmux, Shift+Enter and desktop notifications/progress bar break by default. Add to `~/.tmux.conf`, then `tmux source-file ~/.tmux.conf`:
```bash ~/.tmux.conf
set -g allow-passthrough on
set -s extended-keys on
set -as terminal-features 'xterm*:extkeys'
```
## Match the color theme
`/theme` (or the picker in `/config`) selects a built-in theme, a custom theme, or one from an installed plugin; "auto" follows the terminal's light/dark background.
### Create a custom theme
Each custom theme is a JSON file in `~/.claude/themes/`; filename (minus `.json`) is the slug, stored as `custom:<slug>`.
```json ~/.claude/themes/dracula.json
{
"name": "Dracula",
"base": "dark",
"overrides": { "claude": "#bd93f9", "error": "#ff5555", "success": "#50fa7b" }
}
```
| Field | Type | Description |
| --- | --- | --- |
| `name` | string | Display label in `/theme` (default: filename slug) |
| `base` | string | `dark`, `light`, `dark-daltonized`, `light-daltonized`, `dark-ansi`, `light-ansi` (default `dark`) |
| `overrides` | object | Color-token → value map (unset tokens fall through to `base`) |
Color values: `#rrggbb`, `#rgb`, `rgb(r,g,b)`, `ansi256(n)`, `ansi:<name>` (16 standard ANSI names). Unknown tokens/invalid values are ignored (won't break rendering). Files in `~/.claude/themes/` hot-reload (restart once if the folder didn't exist at startup).
Token groups: text/accent (`claude`, `text`, `inverseText`, `inactive`, `subtle`, `suggestion`, `permission`, `remember`), status (`success`, `error`, `warning`, `merged`), input/mode (`promptBorder`, `planMode`, `autoAccept`, `bashBorder`, `ide`, `fastMode`), diff (`diffAdded`, `diffRemoved`, `diffAddedDimmed`, `diffRemovedDimmed`, `diffAddedWord`, `diffRemovedWord`), fullscreen-only (`userMessageBackground`, `userMessageBackgroundHover`, `bashMessageBackgroundColor`, `memoryBackgroundColor`, `selectionBg`), usage/labels (`rate_limit_fill`, `rate_limit_empty`, `briefLabelYou`, `briefLabelClaude`), plus shimmer pairs (e.g. `claude`/`claudeShimmer`), 8 named subagent colors (`<color>_FOR_SUBAGENTS_ONLY`), and 7 `rainbow_<color>` tokens for the `ultrathink` gradient.
## Switch to fullscreen rendering
`/tui fullscreen` (or `CLAUDE_CODE_NO_FLICKER=1` at launch) switches to a dedicated full-screen buffer instead of scrollback, keeping memory flat and adding mouse support. Scroll with mouse/PageUp inside Claude Code rather than terminal scrollback. If only flicker is the issue and synchronized output isn't auto-detected (e.g. Emacs `eat`), set `CLAUDE_CODE_FORCE_SYNC_OUTPUT=1` instead. Not available in screen reader mode.
## Paste large content
Pastes over 800 characters or 2 lines collapse to a placeholder like `[Pasted text #1 +120 lines]`; full content is still sent on submit. VS Code's integrated terminal can drop characters on very large pastes — prefer writing to a file and asking Claude to read it.
## Edit prompts with Vim keybindings
`/config` → Editor mode, or `editorMode: "vim"` in settings. Supports a subset of NORMAL/VISUAL motions and operators (`hjkl`, `v`/`V`, `d`/`c`/`y` + text objects). Not remappable via the keybindings file — use `vimInsertModeRemaps` for INSERT-mode sequences like `jj`→Escape. Enter still submits in INSERT mode (unlike standard Vim); use `o`/`O` or Ctrl+J for a newline.
## Notes
- `CLAUDE_CODE_FORCE_SYNC_OUTPUT`, `CLAUDE_CODE_NO_FLICKER`, and `FORCE_HYPERLINK` are environment variables documented in `env-vars.md`.
## Related
- [keybindings.md](./keybindings.md): remapping any Claude Code shortcut, including Enter/Shift+Enter
- [statusline.md](./statusline.md): OSC 8 hyperlink support and terminal width detection (`COLUMNS`/`LINES`)
references/troubleshooting/README.md
# Troubleshooting
| Name | Description | Path |
|------|-------------|------|
| Troubleshoot installation and login | `command not found`、PATH、パーミッション、ネットワーク、TLS、認証エラーの修正。インストール・ログイン失敗対応 | [troubleshoot-install.md](./troubleshoot-install.md) |
| Troubleshooting | CPU・メモリ使用率高騰、ハング、auto-compact thrashing、検索問題の修正。Claude Code 実行時の問題対応 | [troubleshooting.md](./troubleshooting.md) |
references/troubleshooting/troubleshoot-install.md
<!-- source: https://code.claude.com/docs/en/troubleshoot-install / last verified: 2026-08-07 -->
# Troubleshoot installation and login
Fixes for `command not found`, PATH, permission, network, TLS, and authentication errors when installing or signing in to Claude Code. For runtime issues after Claude Code is working, see Troubleshooting; for settings/hooks/MCP not applying, see Debug your configuration.
## Signature / Usage
```bash
# Diagnostics
curl -sI https://downloads.claude.ai/claude-code-releases/latest # network reachability (expect HTTP/2 200)
echo $PATH | tr ':' '\n' | grep -Fx "$HOME/.local/bin" # PATH check (macOS/Linux)
which -a claude # find conflicting installs
ldd "$(command -v claude)" | grep "not found" # missing shared libs (Linux)
claude doctor # automated installer/config check
# Alternative installers
brew install --cask claude-code # macOS
winget install Anthropic.ClaudeCode # Windows
```
## Options / Props
| Symptom | Cause / fix |
|---------|-------------|
| `command not found: claude` / `not recognized` | Install dir (`~/.local/bin` or `%USERPROFILE%\.local\bin`) isn't on PATH — add it and restart the terminal |
| `syntax error near unexpected token '<'` or HTML in `iex` output | Install script returned an HTML page or 403 — check region/proxy, retry, or use `brew`/`winget` |
| `curl: (23)` / `curl: (56) Failure writing output to destination` | Download interrupted — check connectivity, retry, or use an alternative installer |
| `Killed` / exit code 137 during install | OOM killer on a low-memory Linux server — add swap (needs ~512 MB free) |
| `TLS connect error` / `unable to get local issuer certificate` | Update CA certs; corporate proxy TLS inspection — use `--cacert`/`NODE_EXTRA_CA_CERTS` |
| `irm`/`&&`/`-fsSL` errors on Windows | Wrong shell for the command — use the PowerShell (`irm ... \| iex`) or CMD installer as appropriate |
| `running scripts is disabled on this system` | PowerShell execution policy blocks npm's `.ps1` shims — `Set-ExecutionPolicy RemoteSigned -Scope CurrentUser`, use `.cmd` launchers, or the native installer |
| `Error loading shared library libstdc++.so.6` | musl/glibc binary mismatch — check `ldd --version`, reinstall, or `apk add libgcc libstdc++` on Alpine |
| `Illegal instruction` | Wrong CPU architecture, or missing AVX (pre-2013 CPU / hypervisor not passing AVX through) |
| `dyld: cannot load` / `Symbol not found ... libicucore` (macOS) | macOS older than 13.0 — update macOS |
| `Exec format error` (WSL1) | Native-binary regression on WSL1 — convert to WSL2 (`wsl --set-version <Distro> 2`) or wrap with `ld-linux` |
| `Error: claude native binary not installed` | npm optional dependency/postinstall skipped — remove `--omit=optional`/`--ignore-scripts`, or run `install.cjs` manually |
| `OAuth error: Invalid code` | Login code expired/truncated — retry, or press `c` to copy the URL |
| `This organization has been disabled` despite active subscription | A stale `ANTHROPIC_API_KEY` env var overrides subscription OAuth — `unset ANTHROPIC_API_KEY` |
| OAuth login fails in WSL2/SSH/containers | Browser redirect can't reach the local callback — paste the printed code, or set `BROWSER` |
| `Could not load credentials` (Bedrock/Agent Platform/Foundry) | Cloud provider CLI not authenticated in the current shell — `aws sts get-caller-identity`, `gcloud auth application-default login`, `az login` |
## Notes
- The installer needs write access to `~/.local/bin/` and `~/.claude/`; on Windows this is rarely an issue since `%USERPROFILE%` is user-writable by default.
- `claude update` / `claude doctor` can hang (pre-v2.1.214) if a shell rc file path (`~/.zshrc`, `~/.bashrc`, etc.) is actually a directory.
- Prebuilt binaries exist only for `darwin-arm64`, `darwin-x64`, `linux-x64`/`arm64` (glibc and musl), and `win32-x64`/`arm64` — other platforms (e.g. FreeBSD) are unsupported.
- Parallel local sessions share and coordinate OAuth token renewal; on macOS, login can also fail if the Keychain is locked or out of sync (`claude doctor` checks this).
## Related
- [Troubleshooting](./troubleshooting.md): runtime performance, stability, and search issues once Claude Code is running
references/troubleshooting/troubleshooting.md
<!-- source: https://code.claude.com/docs/en/troubleshooting / last verified: 2026-08-07 -->
# Troubleshooting
Fixes for high CPU/memory usage, hangs, auto-compact thrashing, and search problems once Claude Code is running. For install/login issues see Troubleshoot installation and login; for settings/hooks/MCP not applying see Debug your configuration; for API error codes see the Error reference.
## Signature / Usage
```bash
/doctor # automated setup checkup with proposed fixes
/mcp # check MCP server status
claude --safe-mode # restart with all plugins/MCP/hooks disabled to isolate the cause
/heapdump # write a heap snapshot + diagnostics to ~/Desktop for memory leaks
/compact # reduce context size
/terminal-setup # fix garbled rendering in VS Code/Cursor integrated terminals
```
## Options / Props
| Symptom | Fix |
|---------|-----|
| High CPU / memory | `/compact` regularly, restart between major tasks, gitignore large build dirs, `claude --safe-mode` to isolate a plugin/MCP/hook, `/heapdump` if memory stays high |
| Large Markdown tables cut off | Display caps at 200 rows (`… N more rows not shown`); the full table stays in context and `/copy` copies every row — ask Claude to write it to a file instead |
| `Autocompact is thrashing: the context refilled to the limit...` | A file/tool output immediately refills context after compaction — read files in smaller chunks, `/compact` with a narrow focus, delegate to a subagent, or `/clear` |
| Command hangs or freezes | `Ctrl+C` to cancel; if unresponsive, close the terminal and `claude --resume` in the same directory |
| Garbled/corrupted text in editor terminal | GPU renderer issue — run `/terminal-setup` to disable `terminal.integrated.gpuAcceleration` |
| Search / `@file` / skills not finding files | Bundled `ripgrep` may not run on your system — install a native `ripgrep` package and set `USE_BUILTIN_RIPGREP=0` |
| Fewer search results than expected on WSL | Cross-filesystem read penalty — narrow searches, move the project to the Linux filesystem (`/home/`), or run natively on Windows |
## Notes
- `/doctor` proposes fixes it can apply after confirmation; if `claude` won't start at all, run `claude doctor` from the shell instead.
- `.heapsnapshot` files contain the full process memory including conversation content and credentials — never attach them to a public issue; only share the `-diagnostics.json` summary.
- `/compact` returns `Not enough messages to compact.` when the conversation has too few turns to summarize, which can happen even with a full context if a single large paste filled it.
- For account/billing/subscription problems (not install or runtime issues), contact Anthropic support directly rather than filing a GitHub issue.
## Related
- [Troubleshoot installation and login](./troubleshoot-install.md): install, PATH, and login failures
samples/cli-usage.md
<!-- source: https://code.claude.com/docs/en/cli-reference.md, https://code.claude.com/docs/en/quickstart.md / last verified: 2026-08-07 -->
# CLI Startup Patterns
Common ways to launch and control the `claude` CLI from a terminal or shell pipeline.
```bash
claude --version # confirm install
claude # start interactive session, prompts login on first use
claude "task" # run a one-time task
claude "explain this project" # start interactive session with an initial prompt
claude -p "explain this function" # query via SDK, then exit (non-interactive)
cat logs.txt | claude -p "explain" # process piped content
claude -c # continue most recent conversation in current directory
claude -c -p "query" # continue, then run one query non-interactively
claude -r # resume a previous conversation (picker)
claude -r "<session>" "query" # resume a session by ID or name
claude --continue # resume most recent session
claude --resume auth-refactor # resume a named/ID session
```
## Notes
- `claude -p` (`--print`) runs in print/non-interactive mode and exits after responding.
- `-c` is short for `--continue`; `-r` is short for `--resume`. `--resume` without an argument shows a session picker.
- Session-scoped flags (`--model`, `--effort`, `--fallback-model`) apply only to the session they're passed to and don't persist; use `/model`, `/effort`, or the matching `settings.json` key to persist a choice.
- `claude --help` does not list every flag; absence from `--help` doesn't mean the flag is unavailable.
- Example from the Claude Code docs (code.claude.com) `cli-reference` and `quickstart` pages.
samples/common-workflows.md
<!-- source: https://code.claude.com/docs/en/common-workflows.md / last verified: 2026-08-07 -->
# Common Workflows
Typical prompt recipes for exploring a codebase, fixing a bug, and reviewing recent commits with Claude Code.
```bash
cd /path/to/project
claude
```
```text
give me an overview of this codebase
```
```text
explain the main architecture patterns used here
what are the key data models?
how is authentication handled?
```
```text
find the files that handle user authentication
how do these authentication files work together?
trace the login process from front-end to database
```
```text
I'm seeing an error when I run npm test
suggest a few ways to fix the @ts-ignore in user.ts
update user.ts to add the null check you suggested
```
```bash
claude --worktree feature-auth # isolated parallel session
claude --permission-mode plan # plan before editing
claude --continue # resume most recent session in this directory
git log --oneline -20 | claude -p "summarize these recent commits"
```
## Notes
- `@file` and `@directory` reference files/directories without waiting for a full read; `@server:resource` fetches an MCP resource (for example `@github:repos/owner/repo/issues`).
- `claude --from-pr 1234` opens the session picker filtered to sessions linked to that PR after `gh pr create`.
- Delegate research with "use a subagent to investigate how our auth system handles token refresh" to keep large file reads out of the main context.
- `claude --continue` resumes the most recent session in the current directory; if there isn't one yet it prints `No conversation found to continue` and exits.
- Example from the Claude Code docs (code.claude.com) `common-workflows` page, sections "Get a quick codebase overview", "Find relevant code", "Fix bugs efficiently", "Resume previous conversations", "Run parallel sessions with worktrees", "Plan before editing", and "Pipe Claude into scripts".
samples/keybindings-terminal.md
<!-- source: https://code.claude.com/docs/en/keybindings.md / last verified: 2026-08-07 -->
# Custom Keybindings and Terminal Setup
Rebind a keyboard shortcut in `~/.claude/keybindings.json` and configure a terminal (tmux) so Shift+Enter and notifications work correctly.
```json ~/.claude/keybindings.json
{
"$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
}
}
]
}
```
```bash ~/.tmux.conf
# Fix Shift+Enter and desktop notifications inside tmux
set -g allow-passthrough on
set -s extended-keys on
set -as terminal-features 'xterm*:extkeys'
```
## Notes
- Run `/keybindings` to create or open `~/.claude/keybindings.json`; changes are auto-detected without restarting.
- Setting an action to `null` unbinds a default shortcut in that context (`Global`, `Chat`, `Settings`, etc.).
- Run `/terminal-setup` once (in the host terminal, not inside tmux/screen) to enable Shift+Enter in VS Code/Cursor/Alacritty/Zed and tune editor terminal settings.
- Reserved shortcuts cannot be rebound: Ctrl+C (interrupt), Ctrl+D (exit), Ctrl+M (Enter), Caps Lock.
- Example from the Claude Code docs (code.claude.com) `keybindings` and `terminal-config` pages.
samples/memory-claude-md.md
<!-- source: https://code.claude.com/docs/en/memory.md / last verified: 2026-08-07 -->
# CLAUDE.md Memory Import Syntax
Give Claude persistent, user-written project instructions via CLAUDE.md, including `@path` imports of other files.
```markdown
See @README for project overview and @package.json for available npm commands for this project.
# Additional Instructions
- git workflow @docs/git-instructions.md
```
```bash
/init # generate a starting CLAUDE.md from the codebase
/memory # browse and edit CLAUDE.md / auto memory files
/context # verify which memory files loaded
```
## Notes
- `@path/to/import` expands the file's content into context at launch; imported files can recursively import other files, up to a maximum depth of four hops.
- All discovered CLAUDE.md files are concatenated (not overridden), ordered broadest-to-most-specific: managed policy (e.g. `/etc/claude-code/CLAUDE.md`) → user (`~/.claude/CLAUDE.md`) → project (`./CLAUDE.md` or `./.claude/CLAUDE.md`) → local (`./CLAUDE.local.md`, gitignore this one).
- Claude Code reads `CLAUDE.md`, not `AGENTS.md`; import an existing AGENTS.md with `@AGENTS.md` or symlink `CLAUDE.md -> AGENTS.md`.
- Target under 200 lines per CLAUDE.md; move task-specific content to `.claude/rules/` or to skills instead of growing a single file.
- Project-root CLAUDE.md survives `/compact` (re-read from disk); nested CLAUDE.md files and path-scoped rules do not reload automatically, only the next time Claude reads a matching file.
- Example from the Claude Code docs (code.claude.com) `memory` page.
samples/README.md
# samples
| Name | Description | Path |
| --- | --- | --- |
| common-workflows | コードベース理解・バグ修正・worktree・コミットログ要約の代表的プロンプト | [common-workflows.md](./common-workflows.md) |
| memory-claude-md | CLAUDE.md の `@path` インポート記法と階層読み込み順序 | [memory-claude-md.md](./memory-claude-md.md) |
| cli-usage | claude コマンドの代表的な起動パターン(-p, -c, -r, --continue, --resume 等) | [cli-usage.md](./cli-usage.md) |
| settings-json | permissions / env を含む最小構成の settings.json | [settings-json.md](./settings-json.md) |
| statusline-config | statusLine 設定とモデル・ディレクトリ・context 使用率を表示するスクリプト例 | [statusline-config.md](./statusline-config.md) |
| keybindings-terminal | keybindings.json でのキー再割り当てと tmux 用ターミナル設定 | [keybindings-terminal.md](./keybindings-terminal.md) |
samples/settings-json.md
<!-- source: https://code.claude.com/docs/en/settings.md / last verified: 2026-08-07 -->
# Minimal settings.json
A minimal project `settings.json` combining permission rules and environment variables.
```json .claude/settings.json
{
"$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",
"OTEL_EXPORTER_OTLP_PROTOCOL": "http/protobuf"
},
"companyAnnouncements": ["Welcome to Acme Corp! Review our code guidelines at docs.acme.com"]
}
```
## Notes
- `.claude/settings.json` is checked into source control (shared with the team); `.claude/settings.local.json` is for personal, gitignored overrides at the same repo root.
- Precedence, highest to lowest: managed settings > command-line arguments > local > project > user.
- Permission rules merge across scopes rather than override each other.
- Most keys (including `permissions` and `env`) reload live without a restart; `model` and `outputStyle` apply only on next restart or `/clear`.
- Run `/config` for an interactive settings UI, or `/config key=value` to change one option directly.
- Example from the Claude Code docs (code.claude.com) `settings` page.
samples/statusline-config.md
<!-- source: https://code.claude.com/docs/en/statusline.md / last verified: 2026-08-07 -->
# Custom Status Line
Configure a status line that runs a shell script and shows model, directory, and context usage at the bottom of the terminal.
```json ~/.claude/settings.json
{
"statusLine": {
"type": "command",
"command": "~/.claude/statusline.sh",
"padding": 2
}
}
```
```bash
#!/bin/bash
# ~/.claude/statusline.sh (chmod +x)
input=$(cat)
MODEL=$(echo "$input" | jq -r '.model.display_name')
DIR=$(echo "$input" | jq -r '.workspace.current_dir')
PCT=$(echo "$input" | jq -r '.context_window.used_percentage // 0' | cut -d. -f1)
echo "[$MODEL] ${DIR##*/} | ${PCT}% context"
```
## Notes
- Or generate one from natural language: `/statusline show model name and context percentage with a progress bar`.
- The script receives JSON session data on stdin (`model`, `workspace`, `cost`, `context_window`, etc.) and must print to stdout; it re-runs on new assistant messages, `/compact`, permission-mode changes, vim-mode toggles, and any `refreshInterval` tick.
- `context_window.used_percentage` is calculated from `input_tokens + cache_creation_input_tokens + cache_read_input_tokens` only.
- Disable with `/statusline delete` or by removing the `statusLine` key; `disableAllHooks: true` also disables it.
- Test locally with mock input: `echo '{"model":{"display_name":"Opus"},...}' | ./statusline.sh`.
- Example from the Claude Code docs (code.claude.com) `statusline` page.
scripts/cli-commands.md
<!-- source: https://code.claude.com/docs/en/cli-reference.md / last verified: 2026-08-07 -->
<!-- source: https://code.claude.com/docs/en/quickstart.md / last verified: 2026-08-07 -->
# cli-commands
Interactive/print-mode session start, session continuation, auth, and diagnostic commands for the `claude` CLI. `claude --help` doesn't list every flag, so absence from `--help` doesn't mean unavailable.
## 対話セッションの開始
```bash
claude
claude "explain this project"
```
## 印字モード(print mode)で一度だけ問い合わせて終了
```bash
claude -p "explain this function"
```
## パイプ入力を処理
```bash
cat logs.txt | claude -p "explain"
```
## 直前の会話を継続
```bash
claude --continue
claude -c
claude -c -p "query"
```
## セッションを ID / 名前で再開
```bash
claude --resume auth-refactor
claude -r "<session>" "query"
```
## バージョン確認
```bash
claude --version
claude -v
```
## インストール・設定の診断(セッションを開始しない)
```bash
claude doctor
```
## 最新バージョンへ更新
```bash
claude update
```
## 認証(ブラウザログイン)
```bash
claude auth login
claude auth login --sso
claude auth login --console
```
`--email` is also listed as a sign-in option (argument syntax not documented in the official reference).
## ログアウト
```bash
claude auth logout
```
## 認証状態の確認
```bash
claude auth status
claude auth status --text
```
## CI / スクリプト用の長期 OAuth トークン発行
```bash
claude setup-token
```
## MCP サーバーの設定
```bash
claude mcp
claude mcp login <name>
claude mcp logout <name>
```
## プラグイン管理
```bash
claude plugin
claude plugins
```
## バックグラウンドセッション
```bash
claude agents # open agent view for background sessions
claude attach <id> # attach to a background session in this terminal
claude logs <id> # print recent output from a background session
claude respawn <id> # restart a background session, keeping conversation intact
claude rm <id> # remove a background session from the list (transcript stays on disk)
claude stop <id> # stop a background session
claude kill <id> # alias for claude stop
```
## デーモン(バックグラウンドセッションのスーパーバイザー)
```bash
claude daemon status
claude daemon stop --any
claude daemon stop --any --keep-workers
```
## Remote Control サーバー
```bash
claude remote-control
```
## ultrareview の非対話実行
```bash
claude ultrareview
claude ultrareview <target>
claude ultrareview --json
claude ultrareview --timeout 30
```
## 代表的な CLI フラグ
```bash
claude --model sonnet
claude --permission-mode plan
claude --dangerously-skip-permissions
claude --add-dir ../docs
claude --output-format json -p "query"
claude --allowedTools "Bash(git diff *)"
claude --mcp-config ./mcp.json
claude --worktree '#123'
```
> **警告**: `--dangerously-skip-permissions` (equivalent to `--permission-mode bypassPermissions`) skips every permission prompt, so file edits and command execution happen without confirmation. Only use it in a trusted environment.
## セッション内スラッシュコマンド
```text
/clear
/help
/exit
```
Ctrl+D twice also exits, as an alternative to `/exit`.
## Notes
- `claude --help` doesn't list every flag; the full flag reference is `references/settings/cli-reference.md`.
- `--enable-auto-mode` was removed in v2.1.111; use `--permission-mode auto` instead.
scripts/env-setup.md
<!-- source: https://code.claude.com/docs/en/env-vars.md / last verified: 2026-08-07 -->
<!-- source: https://code.claude.com/docs/en/settings.md / last verified: 2026-08-07 -->
<!-- source: https://code.claude.com/docs/en/troubleshoot-install.md / last verified: 2026-08-07 -->
# env-setup
Representative environment-variable setups for authentication, model routing, and network/proxy configuration. Full variable list is covered by `references/settings/env-vars.md`; this file only holds runnable setup examples.
## シェルでの一時設定(そのターミナルセッションのみ)
```bash
export API_TIMEOUT_MS="1200000"
claude
```
## 設定ファイルでの永続設定(`claude` 実行のたびに適用)
```json ~/.claude/settings.json
{
"env": {
"API_TIMEOUT_MS": "1200000",
"BASH_DEFAULT_TIMEOUT_MS": "300000"
}
}
```
## API キー認証
```bash
export ANTHROPIC_API_KEY="sk-ant-..."
```
To use a Pro/Max/Team/Enterprise subscription instead, unset the API key:
```bash
unset ANTHROPIC_API_KEY
```
If you see `This organization has been disabled` despite an active subscription, a stale `ANTHROPIC_API_KEY` is likely overriding subscription OAuth — the same `unset` resolves it.
## カスタム Authorization ヘッダー
```bash
export ANTHROPIC_AUTH_TOKEN="<token>"
```
Sent as `Authorization: Bearer <token>`.
## API エンドポイントのオーバーライド(プロキシ・ゲートウェイ)
```bash
export ANTHROPIC_BASE_URL="https://your-proxy.example.com"
```
Setting a host other than `api.anthropic.com` disables Remote Control.
## モデルの指定
```bash
export ANTHROPIC_MODEL="claude-sonnet-5"
export ANTHROPIC_DEFAULT_OPUS_MODEL="claude-opus-4-6"
export ANTHROPIC_DEFAULT_SONNET_MODEL="claude-sonnet-5"
export ANTHROPIC_DEFAULT_HAIKU_MODEL="claude-haiku-4-5"
```
## HTTP / HTTPS プロキシ
```bash
export HTTP_PROXY="http://proxy.example.com:8080"
export HTTPS_PROXY="http://proxy.example.com:8080"
export NO_PROXY="localhost,127.0.0.1"
```
## Amazon Bedrock 経由の利用
```bash
export CLAUDE_CODE_USE_BEDROCK=1
export AWS_BEARER_TOKEN_BEDROCK="<token>"
```
## Google Cloud(Agent Platform / Vertex)経由の利用
```bash
export CLAUDE_CODE_USE_VERTEX=1
export ANTHROPIC_VERTEX_PROJECT_ID="<project-id>"
```
## Microsoft Foundry 経由の利用
```bash
export CLAUDE_CODE_USE_FOUNDRY=1
export ANTHROPIC_FOUNDRY_API_KEY="<key>"
export ANTHROPIC_FOUNDRY_RESOURCE="<resource-name>"
```
## テレメトリ・自動更新の無効化(オフライン/制限環境向け)
```bash
export CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1
export DISABLE_AUTOUPDATER=1
export DISABLE_TELEMETRY=1
```
## OpenTelemetry の有効化
```bash
export CLAUDE_CODE_ENABLE_TELEMETRY=1
export OTEL_METRICS_EXPORTER="otlp"
export OTEL_EXPORTER_OTLP_PROTOCOL="http/protobuf"
```
## TLS 証明書の追加(社内プロキシの TLS インスペクション対策)
```bash
export NODE_EXTRA_CA_CERTS="/path/to/corp-ca.pem"
```
Use this when hitting `unable to get local issuer certificate`.
## Notes
- When a variable is set in both a settings file `env` block and a shell export, the settings file value takes precedence.
- The full variable list and precedence rules are covered by `references/settings/env-vars.md`.
scripts/install.md
<!-- source: https://code.claude.com/docs/en/setup.md / last verified: 2026-08-07 -->
<!-- source: https://code.claude.com/docs/en/quickstart.md / last verified: 2026-08-07 -->
<!-- source: https://code.claude.com/docs/en/troubleshoot-install.md / last verified: 2026-08-07 -->
<!-- source: https://code.claude.com/docs/en/claude-directory.md / last verified: 2026-08-07 -->
# install
Install, verify, update, and uninstall Claude Code across macOS, Linux, WSL, and Windows.
## ネイティブインストーラー(macOS / Linux / WSL)
```bash
# Step 1 - download to an exclusive temp file and print it for review. Nothing is executed here;
# if any step fails the temp file is removed and the chain stops.
installer="$(mktemp "${TMPDIR:-/tmp}/claude-install.XXXXXX")" \
&& curl -fsSL https://claude.ai/install.sh -o "${installer}" \
&& cat "${installer}" \
|| { rm -f -- "${installer:-}"; unset installer; echo "download failed; nothing was executed" >&2; false; }
```
Read the script printed above. Run the next block only if you have reviewed it and decided to proceed — it is a separate step so that copying the block above never executes anything.
```bash
# Step 2 - only after you have read the script above and decided to proceed, run it yourself.
# The temp file is removed afterwards; the final status is the installer's own exit status.
if [ -s "${installer:-}" ]; then
bash "${installer}"; status=$?; rm -f -- "${installer}"; unset installer
else
echo "no downloaded installer to run (Step 1 failed or was not run)" >&2; status=1
fi
(exit "${status}")
```
## Homebrew(macOS)
```bash
brew install --cask claude-code # stable channel
brew install --cask claude-code@latest # latest channel
```
## WinGet(Windows)
```bash
winget install Anthropic.ClaudeCode
```
## npm 経由のインストール
```bash
npm install -g @anthropic-ai/claude-code
```
Requires Node.js 22+ for the package manager itself; the package installs a native binary that doesn't use Node.js at runtime. Never use `sudo npm install -g`.
## インストール確認
```bash
claude --version
```
## インストール診断(読み取り専用、セッションを開始しない)
```bash
claude doctor
```
## ネットワーク疎通確認
```bash
curl -sI https://downloads.claude.ai/claude-code-releases/latest # expect HTTP/2 200
```
## PATH 確認(macOS / Linux)
```bash
echo $PATH | tr ':' '\n' | grep -Fx "$HOME/.local/bin"
```
## 競合インストールの検出
```bash
which -a claude
```
## アップデート
```bash
claude update
```
Native installations auto-update in the background; Homebrew, WinGet, and apt/dnf/apk installs require manual updates unless `CLAUDE_CODE_PACKAGE_MANAGER_AUTO_UPDATE=1` (Homebrew/WinGet only). `DISABLE_AUTOUPDATER=1` stops only the background check; `DISABLE_UPDATES=1` blocks all update paths including manual ones.
## バージョンを指定してインストール/再インストール
```bash
claude install stable
claude install latest
claude install 2.1.118
```
## プロジェクトのローカルデータ削除
> **警告**: `--all` deletes `history.jsonl` across every project. Not reversible.
```bash
claude project purge <path> # delete transcript/memory/tasks/debug/file-history for one project
claude project purge --dry-run # preview the deletion plan without deleting
claude project purge -y # skip the confirmation prompt
claude project purge --all # purge every project, including history.jsonl
```
`shell-snapshots/` and `backups/` are never touched (not project-scoped).
## アンインストール
> **警告**: Removing `~/.claude`, `~/.claude.json`, the project's `.claude/`, and `.mcp.json` deletes all settings, allowed tools, MCP configuration, and session history. Not reversible. These four paths are only safe to delete as part of an explicit uninstall (per setup.md's Notes) — during normal operation, manually deleting `~/.claude.json`, `~/.claude/settings.json`, or `~/.claude/plugins/` is explicitly discouraged (claude-directory.md).
Uninstalling requires removing the binary/version files first, then optionally the four paths below. Do not run a blanket recursive delete on these paths. Save the following as a script (for example `uninstall-claude-config.sh`) and run it with the target repository as its argument: it verifies the repository root first, creates a fresh exclusive backup directory, preflights all four paths (no symlinks, no pre-existing destination, writable parent) before touching anything, then moves (never deletes) each path — and if any move fails or the script is interrupted (Ctrl+C / SIGTERM), it rolls back the moves already made so the live configuration is never left half-removed.
```bash
#!/usr/bin/env bash
# Usage: bash uninstall-claude-config.sh /path/to/target-repo
set -euo pipefail
target="${1:?usage: $0 /path/to/target-repo}"
# 1. Validate the target before touching anything: it must be an existing git repository root
cd -- "${target}"
# --show-prefix is empty exactly at the repository root. Assigning it (rather than testing the
# substitution inline) lets set -e abort when this is not a git repository at all, and avoids
# comparing path spellings, which differ between git and pwd on Windows / symlinked paths
prefix="$(git rev-parse --show-prefix)"
if [ -n "${prefix}" ]; then
echo "not at a repository root: $(pwd) is inside $(git rev-parse --show-toplevel)" >&2
exit 1
fi
# 2. Create an exclusive, fresh backup directory (mktemp fails instead of reusing an existing one)
backup="$(mktemp -d "${HOME}/claude-uninstall-backup-XXXXXX")"
echo "backup directory: ${backup}"
# The four paths, user-level first, then project-side (we are at the verified repository root)
sources=("${HOME}/.claude" "${HOME}/.claude.json" "${PWD}/.claude" "${PWD}/.mcp.json")
names=(dot-claude dot-claude.json project-dot-claude project-mcp.json)
# 3. Preflight every path BEFORE any move: refuse symlinks, refuse to overwrite, require a writable parent
for i in "${!sources[@]}"; do
src="${sources[$i]}"; dest="${backup}/${names[$i]}"
if [ -L "${src}" ]; then
echo "refusing to move symlink: ${src}" >&2
exit 1
fi
[ -e "${src}" ] || continue
if [ -e "${dest}" ]; then
echo "backup destination already exists: ${dest}" >&2
exit 1
fi
if [ ! -w "$(dirname -- "${src}")" ]; then
echo "cannot move ${src}: parent directory is not writable" >&2
exit 1
fi
done
# 4. Move with rollback: if any mv fails, or the script is interrupted (Ctrl+C / SIGTERM),
# everything moved so far is put back in reverse order
moved_src=(); moved_dest=()
pending_src=""; pending_dest="" # the move in flight (bash runs traps only after it finishes)
restore_one() {
if [ -e "$1" ]; then
echo "ROLLBACK SKIPPED: $1 exists again; check $2 manually" >&2
elif [ ! -e "$2" ]; then
: # never moved
elif mv -- "$2" "$1"; then
echo "restored $1" >&2
else
echo "ROLLBACK FAILED: restore $2 -> $1 manually" >&2
fi
}
rollback() {
local i
echo "move aborted; restoring already-moved paths" >&2
if [ -n "${pending_src}" ]; then
restore_one "${pending_src}" "${pending_dest}"
fi
for (( i = ${#moved_src[@]} - 1; i >= 0; i-- )); do
restore_one "${moved_src[$i]}" "${moved_dest[$i]}"
done
}
on_signal() { trap - ERR INT TERM; rollback; exit 130; }
trap rollback ERR
trap on_signal INT TERM
for i in "${!sources[@]}"; do
src="${sources[$i]}"; dest="${backup}/${names[$i]}"
[ -e "${src}" ] || continue
pending_src="${src}"; pending_dest="${dest}"
mv -- "${src}" "${dest}"
moved_src+=("${src}"); moved_dest+=("${dest}")
pending_src=""; pending_dest=""
echo "moved ${src} -> ${dest}"
done
trap - ERR INT TERM
# 5. Nothing has been deleted. Remove the backup explicitly once you are sure it is no longer needed:
echo "done. To discard the backup later, run: rm -r -- \"${backup}\""
```
> **Note**: The official docs do not document a command for removing the native binary/version files themselves — the location differs by install method (native installer / Homebrew / WinGet / npm) and isn't specified.
scripts/README.md
# scripts
| Name | Description | Path |
| --- | --- | --- |
| install | インストール・バージョン確認・アップデート・アンインストール | [install.md](./install.md) |
| cli-commands | claude CLI の主要コマンド・フラグ例 | [cli-commands.md](./cli-commands.md) |
| env-setup | 認証・モデル指定・プロキシ等の環境変数設定例 | [env-setup.md](./env-setup.md) |
SKILL.md
---
name: anthropic-claude-code
description: >
Claude Code (code.claude.com) の CLI 本体リファレンス。
CLAUDE.md memory, settings.json, env-vars, model config, keybindings, statusline,
terminal config, cli-reference (-p / --continue / --resume), sessions, checkpointing,
worktrees, remote control, channels, deep links, troubleshooting。
user-invocable: false
---
# anthropic-claude-code
Claude Code (code.claude.com) — ターミナル上で動くエージェント型コーディングツール CLI 本体のリファレンス。
インストール・quickstart・agentic loop の仕組み・CLAUDE.md memory・settings.json / 環境変数 / モデル設定・
keybindings / statusline / ターミナル設定・`cli-reference`(`-p` / `--continue` / `--resume` 等のフラグ)・
セッション管理(resume, checkpointing, worktrees, remote control, channels, deep links)・
トラブルシューティングをカバーする。
Skills / MCP / subagents / hooks / plugins の拡張機能は `anthropic-claude-code-extend`、
Agent SDK(ライブラリとして組み込む場合)は `anthropic-agent-sdk`、Messages API 直接呼び出しは
`anthropic-api-core` を参照(本スキルは Claude Code CLI 本体の使い方・設定・運用を担当)。
## ディレクトリ構成
```text
skills/anthropic-claude-code/
SKILL.md
references/
getting-started/
README.md
overview.md
quickstart.md
how-claude-code-works.md
best-practices.md
common-workflows.md
features-overview.md
feature-availability.md
glossary.md
memory.md
goal.md
context-window.md
prompt-caching.md
setup.md
settings/
README.md
settings.md
env-vars.md
model-config.md
keybindings.md
statusline.md
terminal-config.md
debug-your-config.md
cli-reference.md
claude-directory.md
auto-mode-config.md
fast-mode.md
errors.md
sessions/
README.md
sessions.md
remote-control.md
channels.md
channels-reference.md
deep-links.md
worktrees.md
checkpointing.md
troubleshooting/
README.md
troubleshoot-install.md
troubleshooting.md
samples/
README.md
common-workflows.md
memory-claude-md.md
cli-usage.md
settings-json.md
statusline-config.md
keybindings-terminal.md
scripts/
README.md
install.md
cli-commands.md
env-setup.md
```
## 探索手順
タスクからカテゴリを引き、カテゴリの README.md で目的のページを特定する:
1. 下記マッピング表でタスクに対応するカテゴリを探す
2. そのカテゴリの `references/{category}/README.md`(`samples/` `scripts/` は直下の README.md)を参照して目的のページを特定する
3. 該当ページの `.md` を Read して詳細を確認する
## タスク → カテゴリ マッピング
| タスク | カテゴリ | 参照 README |
|--------|---------|------------|
| Claude Code の概要・インストール・quickstart・agentic loop の仕組み・ベストプラクティス・典型ワークフロー・機能一覧・用語集・CLAUDE.md memory・`/goal`・context window・prompt caching を知りたい | getting-started | [references/getting-started/README.md](references/getting-started/README.md) |
| `settings.json` / 環境変数 / モデル設定・エイリアス・keybindings・statusline・ターミナル設定・`cli-reference`(コマンド・フラグ)・`.claude` ディレクトリ構成・auto mode・fast mode・エラーメッセージを知りたい | settings | [references/settings/README.md](references/settings/README.md) |
| セッション管理(resume / branch)・remote control・channels(MCP イベントプッシュ)・deep links・worktree 並行実行・checkpointing(`/rewind`)を扱いたい | sessions | [references/sessions/README.md](references/sessions/README.md) |
| インストール・ログイン失敗、CPU/メモリ高騰・ハング・auto-compact thrashing などランタイム問題を診断したい | troubleshooting | [references/troubleshooting/README.md](references/troubleshooting/README.md) |
| 典型的な使い方を知りたい(common workflows, CLAUDE.md `@path` インポート, CLI 起動パターン, settings.json 最小構成, statusline スクリプト, keybindings/tmux 設定) | samples | [samples/README.md](samples/README.md) |
| インストール・バージョン確認・アップデート・アンインストール・`claude` CLI コマンド例・認証/モデル/プロキシ環境変数設定を知りたい | scripts | [scripts/README.md](scripts/README.md) |