Every behavior you see in Claude Code comes from one of two places. Either the model chose it (which file to read, what to edit, when to stop), or the harness did it (built the request, checked a permission rule, snapshotted a file, compacted the context, cut a log down to a preview). If you can tell which one is acting, you can predict what Claude Code will do, debug it when it misbehaves, and put each rule where it will actually hold.
This session takes the engine apart. You'll trace one task event by event through the agent loop, learn the built-in tools and their sharp edges, see how aliases, effort and fallbacks pick the model, map the limits that cause confident wrong answers, choose between the seven surfaces, run a first session the way the docs intend, and read the bill. Facts are as of 2026-10-24 · v2.1.310. Version-gated features say "requires v2.1.xxx+" next to them.
After this session you can explain any line of a stream-json transcript, predict which permission mode a session starts in, choose a model and effort level per task on any provider, and keep the prompt cache warm. Core 2 (Context Engineering) builds on this with memory, settings and /context; Agents 1 (Inside the Agent Loop) goes from using the loop to building on it.
Anatomy
Claude Code is a loop with two parts. A model decides what to do next; a harness turns each decision into a real action, feeds the result back, and enforces every rule the model can't be trusted to keep. Learn where the line between them sits and most of Claude Code's behavior becomes predictable.
The Agent Loop
The docs describe the agentic loop as three phases: gather context, take action and verify results. "These phases blend together." A question about the codebase may only gather context. A bug fix cycles through all three several times. Claude "decides what each step requires based on what it learned from the previous step, chaining dozens of actions together and course-correcting along the way" (How Claude Code works).
Mechanically, one iteration is one API request. The harness sends the system prompt, the tool definitions, your CLAUDE.md and the whole conversation so far. The model streams back text and zero or more tool_use blocks. If there are tool calls, Claude Code checks hooks and permissions, runs the tools, appends the results as a tool_result message, and sends the next request. When the model answers without a tool call, the loop ends, Stop hooks run, and the turn is over. The API itself is stateless: Claude Code re-sends the transcript every time, and the prompt cache makes that affordable (see Costs).
The model owns one station of the loop (the thin arc); the harness owns the other four (the thick band), and every rule is enforced there. Hover or tab to a station, light one owner at a time, or run one iteration around the ring. You sit outside it: a prompt starts the turn, Esc stops it, Enter queues a correction.
You're part of the loop too. Esc stops Claude mid-turn ("Claude keeps the work done so far"). Typing a correction and pressing Enter without stopping queues it: if Claude is running tool calls, "it reads the message as soon as those calls finish, within the same turn". That's usually the cheaper way to steer, because nothing already done is thrown away.
The cleanest way to watch the loop is headless mode with stream-json. Each line is one event: system/init first, then assistant events (one per content block), user events carrying tool results, and a final result event.
# read-only tools only, capped at $0.25 (costs money; the first request alone carries the harness)
claude -p "Which module computes tax? Answer in one sentence." \
--output-format stream-json --verbose \
--permission-mode dontAsk --tools Read,Grep,Glob --allowedTools Read,Grep,Glob \
--max-turns 4 --max-budget-usd 0.25 \
| jq -c '{type, subtype, tool: (.message.content[0].name // null)}'
Step through the run: each line lands in the terminal, the gutter marks who produced it (❯ you, ◆ harness, ● model, ▸ tool) and the brackets on the right mark gather, act and verify. Illustrative replay of a claude -p run on the labs' tiny-app sample. Event types and field names follow the documented stream-json shapes and recorded v2.1.303 runs; ids, token counts and costs are illustrative.
Pitfall: counting turns yourselfThe word "turn" means three different things. Don't hard-code its arithmetic: in recorded runs, one tool call plus an answer reported num_turns: 2, and --max-turns 2 stopped at 3. Per-step stop_reason is null and per-step output_tokens is a placeholder. Read num_turns, stop_reason and token totals from the result event.
Three meanings of "turn", and what fires on each
User turn. One prompt and everything Claude does until it stops. "Every prompt you send that starts a turn creates a new checkpoint" (checkpointing). Hooks with per-turn cadence are UserPromptSubmit, Stop and StopFailure.
API round trip. One model request. A single response that contains a text block and a tool call is streamed as two assistant lines that share message.id; deduplicate by that id when you count model responses, as the cost-tracking page also advises. PreToolUse and PostToolUse fire on every tool call (except EndConversation).
SDK/CLI num_turns. The docs say "A turn is one round trip" and that max_turns "counts tool-use turns only". Recorded runs don't line up with naive arithmetic, so treat the field as authoritative and opaque.
Ordering inside a response. In a real run with two parallel tool calls, the stream went tool_use #1, its result, tool_use #2, its result. Don't assume every tool_use of a response arrives before any tool_result. In the Agent SDK loop, read-only tools (Read, Glob, Grep, read-only MCP tools) can run concurrently, while Edit, Write and Bash run sequentially (agent loop).
What you build: a replay of a recorded stream-json run broken into the system/init harness configuration, request 1's prompt size (the system prompt you can't see, measured), one block per model response grouped by message.id with its cache reads and writes, every tool call, and the result line, with total_cost_usd recomputed from usage at list prices.
cd labs && python3 core-1/session_anatomy.py
cd labs && python3 core-1/session_anatomy.py --all # every recorded fixture side by side
# opt-in real run: costs money; read-only tools, capped, in a temp copy of the sample repo
cd labs && python3 core-1/session_anatomy.py --real --model haiku --max-budget-usd 0.05
Observe: request 1 already carries about 9.8K prompt tokens with only three tools enabled (the system prompt, tool definitions, the sample's CLAUDE.md and your message, almost all of it harness); two Read calls in one response share a message.id; the recomputed cost matches total_cost_usd; in --all, the summary table reads stop_reason first (a refusal arrives as subtype success), then terminal_reason, then subtype, and the max-turns run ends with stop_reasontool_use, terminal_reasonmax_turns and error_max_turns, with no result text.
"Tools are what make Claude Code agentic. Without tools, Claude can only respond with text." The docs (How Claude Code works) group the built-in tools into five kinds of agency, plus orchestration tools. The tool names are the exact strings you write in permission rules, subagent tools lists and hook matchers (tools reference).
Kind
Tools
Prompts in Manual?
What bites
File operations
Read, Edit, Write, NotebookEdit
Read no; the rest yes
Edit is exact string replacement; old_string must match once. Read returns at most 25,000 tokens per call.
Search
Glob, Grep
No
Absent by default on macOS, Linux and WSL. Search runs through Bash.
Execution
Bash, PowerShell, Monitor
Yes (built-in read-only commands don't)
Separate process per command; env vars don't persist; 2-minute default timeout.
Web
WebFetch, WebSearch
Yes (preapproved doc domains don't)
WebFetch returns a model's extraction of the page, not the page.
This is the fact most older guides get wrong. "On macOS, Linux, and WSL, Claude Code leaves Glob and Grep out of the default tool set, and Claude searches with find and grep through the Bash tool instead. In Claude's shell those two commands run embedded versions of bfs and ugrep, and the searches reach your hooks and permission rules as Bash calls." On Windows they're part of the default set. You get the Glob and Grep tools back when you name either in --tools or --allowedTools at launch (an allow rule in a settings file doesn't count), when a deny rule, --disallowedTools or --restricted removes Bash, or for a subagent whose tools lists them and leaves out Bash.
Why it matters: a PreToolUse hook with matcher Grep never fires on a Mac. Match Bash and inspect tool_input.command instead. A search with grep or find is in the built-in read-only set, so it doesn't prompt unless a Read deny or ask rule matches the path; in auto mode the classifier may still review it.
A shadow board: every tool has a painted outline, and a removed tool leaves only its outline and a tag naming what removed it (the platform default, --tools, a deny rule or --restricted). Pick a platform and flags. Applies the documented Glob/Grep rules to a simplified tool list. --restricted also removes other command-running tools and WebFetch; only the tools shown here are modelled.
The tools you'll reason about most
Bash runs each command in a separate process. A cd carries over while it stays inside the project or an added directory; an export doesn't survive to the next command. Aliases and functions from your shell startup file are captured at session start. BASH_DEFAULT_TIMEOUT_MS (2 minutes) and BASH_MAX_TIMEOUT_MS (10 minutes) bound foreground commands, and a command that hits its timeout moves to the background instead of dying (unless it starts with sleep).
Agent spawns a subagent in its own context window; the parent sees only its final result. "In version 2.1.63, the Task tool was renamed to Agent"; Task(...) still works as an alias in rules. Since v2.1.198 subagents run in the background by default. Launching one doesn't prompt; its own tool calls are checked against your rules.
Edit needs an exact, unique match for old_string. Opus 4.6, Haiku 4.5 and older models always require a prior read of the file; newer models can edit an unread file when reading it wouldn't need a permission prompt and the Read tool is available. Claude can also edit after viewing a file with cat, head, sed -n or grep on one file with no pipes.
WebFetch converts the page to Markdown and "runs the prompt against the content in a separate model call, and Claude receives the result of that call rather than the raw page." It refuses localhost and dotless hostnames and caches responses for 15 minutes.
Exercise: list your own session's tools
Print the tool list Claude Code gives a headless session on your machine, then repeat with --allowedTools Grep. Which tools appear or disappear?
Show a solution
claude -p "Say ok." --output-format stream-json --verbose \
--permission-mode plan --max-turns 1 | head -1 | jq '.tools'
claude -p "Say ok." --output-format stream-json --verbose \
--permission-mode plan --max-turns 1 --allowedTools Grep | head -1 | jq '.tools'
On macOS, Linux or WSL the first list has no Glob or Grep; the second has both, because naming either in --allowedTools restores both. On native Windows both lists include them. Your exact list also depends on your plan, provider, plugins and MCP servers, which is why the init event is the source of truth. Expect the subagent tool to appear as "Task" in this list even though tool calls and rules call it Agent.
Tool names you'll see in the wild, and the ones that changed
The tools reference lists more than forty built-ins, including Monitor (streams lines from a background command, added 2.1.98), CronCreate/CronList/CronDelete (session-scoped scheduled prompts), ScheduleWakeup (self-paced /loop), RemoteTrigger (cloud scheduled tasks), EnterWorktree/ExitWorktree, SendUserFile, PushNotification and EndConversation. Removed or renamed: Task → Agent (2.1.63); TaskOutput removed in 2.1.277 (Claude reads a background task's output file with Read). TodoWrite is disabled by default in favor of TaskCreate/TaskGet/TaskList/TaskUpdate, which are on by default only on some models.
One naming trap: the Agent tool "appears as "Agent" in tool_use blocks but as "Task" in the system:init tools list" (SDK subagents). The CLI's own stream-json does the same: a real claude -p run on v2.1.303 listed "Task" in init. Match both if you parse init events, and use Agent(...) in rules.
--tools controls which tools exist in a session; --allowedTools only pre-approves calls. A bare tool name in a deny rule ("Bash") "removes the tool from Claude's context entirely", while a scoped deny (Bash(rm *)) leaves the tool visible and blocks matching calls (permissions).
The Model
"When this guide says 'Claude chooses' or 'Claude decides,' it's the model doing the reasoning." The model reads the request, decides which tool to call with which input, writes the code, interprets the results and decides when it's done. On most plans and providers the account default is Opus 5.5; the next topic covers how aliases, effort and fallbacks choose the model for a request.
Three properties of current models shape how Claude Code drives them:
No memory between requests. Everything the model knows about your session is in that request's context. "Each new session starts with a fresh context window, without the conversation history from previous sessions." Persistence comes from files: CLAUDE.md, auto memory, your specs.
Reasoning is adaptive and always on. On Opus 5.5, Sonnet 5.5, Haiku 5.5 and the Fable models, extended thinking can't be turned off; the effort level controls how much the model thinks. "You are charged for all thinking tokens generated, even when collapsed or redacted."
No sampling knobs. There's no temperature setting in Claude Code or the Agent SDK, and current models reject non-default sampling parameters on the API. You steer with context and effort, not randomness.
The practical consequence: the model's choices are as good as its context. If Claude reads the wrong file, it usually didn't know the right one existed. If it claims success, that claim is text the model generated, which is why verification habits matter.
Pitfall: blaming the model for a harness rule"Claude refused to touch .git/config" isn't model caution. .git is a protected directory, and writes there are "never auto-approved except in bypassPermissions mode and in plan-mode sessions where bypass permissions are available" (permission modes). Prompting harder won't change it; your approval will (in auto mode the classifier reviews such writes instead).
The Context Window
"Claude Code's context window holds everything Claude knows about your session: your instructions, the files it reads, its own responses, and content that never appears in your terminal" (context window). Current models have a 1M-token window. Before you type anything, the request already carries:
the system prompt (Claude Code's instructions plus tool definitions; "Claude Code's system prompt isn't published"),
your CLAUDE.md files, which are "delivered as a user message after the system prompt, not as part of the system prompt itself",
auto memory (the first 200 lines or 25KB of MEMORY.md), skill descriptions, MCP tool names (definitions load on demand through tool search), and your output style.
Then the conversation grows: your prompts, every tool call and result, Claude's replies, and system reminders. Claude Code adds context on its own: your CLAUDE.md files, output-style instructions, "a note when a file Claude read earlier changes on disk", and the commit and PR attribution lines. If Claude follows a rule you didn't write, such as a Co-Authored-By trailer, it probably came from there (attribution and includeGitInstructions control it).
Order matters twice: the cache matches an exact prefix (layers on the left change least), and compaction rewrites only the conversation. The ruler marks where the cached part ends and the new turn is written; pick an action in Prompt Caching and it moves to where the cache breaks. Hover a segment for what it holds. Widths are illustrative, not measured; the docs' cache-layer table lists only CLAUDE.md, auto memory and unscoped rules in project context, so where skill and MCP listings sit is approximate.
When the window fills, Claude Code "compacts the conversation into a summary." On native-1M models auto-compaction starts at about 967K tokens by default. Your requests and key code survive; "detailed instructions from early in the conversation may be lost", so put persistent rules in CLAUDE.md. Core 2 covers /context, compaction and fresh starts in depth (Session Context).
Pitfall: editing CLAUDE.md mid-sessionThe edit doesn't break the cache, but "the edit also doesn't apply. Claude keeps working with the version that was loaded at session start" until /clear, /compact or a restart (prompt caching).
Harness Responsibilities
"Claude Code is the layer around the model that provides the tools and manages the context the model sees. This surrounding layer is what the term agentic harness refers to." Here's what each side owns:
The harness (Claude Code)
Builds every request: system prompt, tools, CLAUDE.md, reminders, history
Runs tools, applies their output limits and saves overflow to files
Enforces permission rules: "Rules are evaluated in order: deny, then ask, then allow"
Runs hooks at lifecycle events; runs the auto-mode classifier (a second model)
Snapshots files before edits (checkpoints); records sessions as JSONL under ~/.claude/projects/
Compacts context, manages the prompt cache and its TTL, estimates cost
Starts subagents in separate contexts and scans what they return
The model (Claude)
Decides which tool to call, with what input, in what order
Reads results and changes approach
Writes code, plans, commit messages, explanations
Follows CLAUDE.md and skills (as context, not as enforcement)
Decides when the task is done, and says so
"Permission rules are enforced by Claude Code, not by the model." That sentence is the design principle. (One caveat on personal setups: without managed settings or a Team/Enterprise /login, an installed mod "can approve a call that a deny rule refuses or a PreToolUse hook blocked"; vet mods like any code you run.) Anything that must happen belongs in the harness's configuration: a deny rule, a hook, the sandbox. Anything that should usually happen can be guidance in CLAUDE.md. CLAUDE.md files are "context, not enforced configuration. To block an action regardless of what Claude decides, use a PreToolUse hook instead" (memory).
A project .claude/settings.json: the harness reads it, the model never sees it. Deny beats ask beats allow regardless of specificity. A Bash deny pattern "isn't a security boundary around the program" (bash -c or /bin/rm slip past). The boundary is the sandbox or a container; a PreToolUse hook adds defense in depth, but a hook that inspects command text has the same bypass surface (Core 5: Security).
Pick who is responsible for each behavior. Feedback cites the mechanism, so a wrong answer still teaches where to look.
The same harness everywhere: CLI, IDE, cloud, SDK
"Each surface connects to the same underlying Claude Code engine, so your repo's CLAUDE.md files, settings, and MCP servers work across all of them" (overview). The Agent SDK is that harness as a library: "the same tools, agent loop, and context management that power Claude Code", with one big default difference: "The SDK no longer uses Claude Code's system prompt by default" (opt in with the claude_code preset).
The harness records the system prompt on the first request and reuses it until compaction, even across --resume and --continue (CLI reference), which is part of why a resumed session keeps its cache. --bare strips the harness to its core for scripts: no hooks, skills, plugins, MCP, auto memory or CLAUDE.md, and only Bash and file tools. "--bare is the recommended mode for scripted and SDK calls, and will become the default for -p in a future release" (headless).
Portability note: other harnesses (Codex CLI, Gemini CLI, Cursor) split the same responsibilities differently. claude import (v2.1.213+) brings their instruction files, MCP servers and commands over, but enforcement semantics don't translate; re-check rules after migrating.
Key takeaways
One loop iteration is one API request; the harness re-sends the whole transcript every time and the model stops the loop by answering without a tool call.
On macOS, Linux and WSL, search runs as Bash (find/grep): write hooks and rules for Bash, not Grep.
The subagent tool is Agent; Task(...) is only an alias.
CLAUDE.md is context the model may follow; deny rules, hooks and the sandbox are what the harness enforces.
Read cost, turns and stop reasons from the result event, never from per-step events.
Models and Effort
The model answering a request is the product of an alias, a provider, a precedence chain and sometimes a fallback. Effort is a second dial with its own precedence. Get both right at the top of a session, because changing either later can cost you the cache.
Model Aliases
A model alias picks a model without a version number. "Aliases point to the recommended version for your provider and update over time" (model configuration). The set: best, fable, opus, sonnet, haiku, sonnet[1m], opus[1m], opusplan, opusplan[1m]. default isn't an alias; it "clears any model override and reverts to the runtime default for your account". best uses Fable where it's available to you, otherwise the same model as opus. opusplan "uses opus during plan mode, then switches to sonnet for execution".
Provider
opus
sonnet
haiku
Account default
Anthropic API (subscription or Console)
Opus 5.5
Sonnet 5.5
Haiku 5.5
Opus 5.5
Claude Platform on AWS
Opus 5.5
Sonnet 4.6
Haiku 4.5
Opus 5.5
Amazon Bedrock, Google Cloud's Agent Platform
Opus 5.5
Sonnet 4.5
Haiku 4.5
Opus 5.5
Microsoft Foundry
Opus 4.6
Sonnet 4.5
Haiku 4.5
Sonnet 4.5
Minimum versions: Fable 5.1 v2.1.257+, Opus 5.5 v2.1.280+, Sonnet 5.5 v2.1.284+, Haiku 5.5 v2.1.293+. "Neither Fable model is the account-type default on any plan or provider."
On third-party providers an unpinned alias resolves to Claude Code's built-in default, "which can lag the newest release and may not yet be enabled in your account". Pin each family with ANTHROPIC_DEFAULT_OPUS_MODEL, ANTHROPIC_DEFAULT_SONNET_MODEL, ANTHROPIC_DEFAULT_HAIKU_MODEL and ANTHROPIC_DEFAULT_FABLE_MODEL. (ANTHROPIC_SMALL_FAST_MODEL is deprecated in favor of the Haiku variable.)
Tick which sources are set: the first set source in the chain wins and carries the highlight, and everything after it is overridden. The account default (dashed) always waits at the end. Environment variables aren't a settings level, so ANTHROPIC_MODEL beats any file's model key. ANTHROPIC_DEFAULT_MODEL requires v2.1.236+.
/model saves the pick "as your default for new sessions"; press s on a row to apply it to this session only. Resumed sessions keep their saved model, and the switch "also reaches subagents that inherit the main conversation's model". "The model setting is an initial selection, not enforcement": admins restrict choices with availableModels, enforceAvailableModels and deniedModels (Autonomy 2).
Pick a provider and the cables re-patch: every alias jack is wired to the model it resolves to there. Click a jack or use the menu; pinning plugs your own cable over the built-in default. Socket badges show the context window, effort levels and auto mode on that provider. Encodes the documented alias table, effort support, 1M-context rules and auto-mode model requirements as of October 2026. Pinning assumes the pinned ID is enabled in your account.
Pitfall: "sonnet" on BedrockOn Bedrock and Agent Platform, plain sonnet is Sonnet 4.5: a 200K window, no effort control, and no auto mode. Auto mode on those providers needs Sonnet 5+, Opus 4.7+, Haiku 5.5 or Fable, so a session on the unpinned alias starts in Manual even though the built-in start mode is auto.
Effort Levels
"Effort levels control adaptive reasoning, which lets the model decide whether and how much to think on each step." Levels are low, medium, high, xhigh and max (Opus 4.6 and Sonnet 4.6 have no xhigh; models not listed in the docs, such as Sonnet 4.5, don't support effort). Defaults: medium on Opus 5.5, Sonnet 5.5 and Haiku 5.5, xhigh on Opus 4.7, high elsewhere. If you set a level the model doesn't support, Claude Code "falls back to the highest supported level at or below the one you set".
Resolution order: (1) an explicit choice, meaning CLAUDE_CODE_EFFORT_LEVEL, --effort or /effort; (2) your settings, a per-model level saved under modelSettings or an effortLevel key; (3) the model's default. A maxEffortLevel cap then clamps anything above it. Two traps: max "applies to the current session only" unless set through the environment variable, and a top-level effortLevel in your user settings "doesn't count for Opus 5.5" and later models (it's the older form; project, local and managed values still apply to every model).
modelSettings (v2.1.251+) is what /effort writes when you press Enter; press s instead for this session only (v2.1.257+). maxEffortLevel requires v2.1.267+, and across scopes the lowest cap applies.
ultrathink is the only keyword: "Include ultrathink anywhere in your prompt to request deeper reasoning on that turn without changing your session effort setting." From v2.1.311, typed in the terminal prompt, it can also run that turn at xhigh effort on Opus 5.5, Sonnet 5.5, Haiku 5.5 or Fable 5.1 through Anthropic's API; the word shows in rainbow colors when it can (model config). "think", "think hard" and "think more" are ordinary text. Ultracode is different again: a setting (/effort ultracode, "ultracode": true) that makes Claude orchestrate dynamic workflows for substantive tasks; it isn't an effort level.
Each source drops a marker on the level it asks for; the first one set wins, a maxEffortLevel ceiling pushes it down, and hatched notches are levels the model doesn't support. Follows the documented resolution order, the maxEffortLevel cap and per-model level support. "Explicit" stands for whichever of the env var, --effort or /effort you used.
Calibrate effort before changing modelsMedium is the Opus 5.5 default for a reason. Raise effort for edge-case-heavy work (concurrency, migrations, security reviews), but effort "does not fix when the model has the wrong approach" (Spending your effort, official blog). And from the docs: "max may show diminishing returns and is prone to overthinking, so test before adopting it broadly".
Effort, the cache, and what carries over
On most models each effort level has its own cache, so changing effort mid-session rebuilds the whole request. On Opus 5.5, Sonnet 5.5, Haiku 5.5 and Fable 5.1 (v2.1.260+ for Fable) with an API key or a Claude subscription, the cache stays intact by default. That exception doesn\'t hold on Bedrock, Agent Platform or a Claude apps gateway, with CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS set, or under a HIPAA configuration (prompt caching). Where the exception holds you can move effort mid-session cheaply; elsewhere, pick it at the top.
After an automatic content fallback, "it keeps the effort level the flagged request ran at": an Opus 5.5 session at medium that falls back to Opus 4.8 stays at medium, although Opus 4.8 defaults to high. Check the level in effect with /effort status.
Subagents resolve effort separately: per-invocation effort (v2.1.292+) beats the agent's effort frontmatter, which beats the session; CLAUDE_CODE_EFFORT_LEVEL beats both (subagents). MAX_THINKING_TOKENS is ignored as a number on adaptive-reasoning models; it isn't how you tune current models.
Fallback Chains
Claude Code has two unrelated fallbacks, and confusing them is a common source of "why is it on a different model?"
Availability fallback (fallback chains). "When the primary model is overloaded, unavailable, or returns another non-retryable server error, Claude Code can switch to a fallback model instead of failing the request." Configure --fallback-model sonnet,haiku for a session or a fallbackModel array in settings. Rules: models are tried in order; "Claude Code caps chains at three models after duplicate removal"; "The switch lasts for the current turn only"; /status doesn't show the chain; compaction never falls back to a smaller context window. Authentication, billing, rate-limit, request-size and transport errors "never trigger a switch". A switch "means one turn with a cold prompt cache on the fallback model". fallbackModel takes its whole value from the highest settings file that sets it; lists don't merge.
Content fallback (automatic model fallback). Fable, Opus 5.5, Sonnet 5.5 and Opus 5 run with safety classifiers that most often flag biology and cybersecurity content. Fable and Opus 5.5: biology re-runs on Opus 5, cybersecurity on Opus 4.8. Sonnet 5.5: cybersecurity re-runs on Sonnet 5; biology ends in a refusal. Unlike the availability chain, "After a fallback, the session continues on the fallback model. To return to your original model, run /model." Set switchModelsOnFlag: false to be asked each time; requires v2.1.219+ for category-based targets.
Availability fallback is a transfer switch: on overload or unavailability it moves this turn to the first healthy fallbackModel entry, and on the next turn it switches back to the primary. Rate-limit and auth errors are faults on the shared line, so no source helps. Content fallback is a separate selector that latches. Simulates one turn and the next under the documented rules for both fallback kinds; entries that resolve to the primary model fail the same way and pass to the next.
A fallback on the very first requestThe first request carries your CLAUDE.md and git status, so "a repository that contains security or biology material can trip the classifier on that context alone." To check whether your customizations are the trigger, start with claude --safe-mode, which disables CLAUDE.md, skills, MCP servers and hooks.
Providers
The provider is where your requests go and who bills you. Subscriptions (Pro, Max, Team, Enterprise) and Console API keys go to the Anthropic API. Third-party providers are switched on with one environment variable each: CLAUDE_CODE_USE_BEDROCK=1, CLAUDE_CODE_USE_VERTEX=1 (Google Cloud's Agent Platform, "formerly Vertex AI"; identifiers keep VERTEX), CLAUDE_CODE_USE_FOUNDRY=1, CLAUDE_CODE_USE_ANTHROPIC_AWS=1 (Claude Platform on AWS). A gateway set with ANTHROPIC_BASE_URL "changes where requests are sent, not which model answers them".
export CLAUDE_CODE_USE_BEDROCK=1
export AWS_REGION=us-east-1 # order: AWS_REGION, AWS_DEFAULT_REGION, profile, us-east-1
# pin the families so aliases don't lag; Invoke API IDs are inference profiles
# (us. / eu. / apac. / global. per region; the profile must be enabled in your account)
export ANTHROPIC_DEFAULT_SONNET_MODEL='us.anthropic.claude-sonnet-5-5'
# or keep the built-in defaults and only change the prefix:
# export ANTHROPIC_BEDROCK_REGION_PREFIX=global
claude
export CLAUDE_CODE_USE_VERTEX=1
export CLOUD_ML_REGION=us-east5
export ANTHROPIC_VERTEX_PROJECT_ID=my-gcp-project
export ANTHROPIC_DEFAULT_SONNET_MODEL='claude-sonnet-5-5'
claude
export CLAUDE_CODE_USE_FOUNDRY=1
export ANTHROPIC_FOUNDRY_RESOURCE=my-foundry-resource # resource name only
export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-5-5' # alias opus is Opus 4.6 here
claude
export ANTHROPIC_BASE_URL=https://llm-gateway.example.internal
export ANTHROPIC_AUTH_TOKEN="$(my-token-helper)" # sent as Authorization: Bearer
claude # /status shows the base URL, auth source and proxy rows
Claude Code calls the Bedrock Invoke API, so Bedrock pins use cross-region inference-profile IDs such as the docs' us.anthropic.claude-opus-4-8; the built-in Opus default is us.anthropic.claude-opus-5-5 in a us-* region. The bare anthropic.claude-… form without a version suffix is the Mantle endpoint's ID, which Claude Code routes only with CLAUDE_CODE_USE_MANTLE=1 (Bedrock). Agent Platform and Foundry IDs follow the models overview. Bedrock and Agent Platform also have a login wizard (claude → "3rd-party platform").
What the provider changes, beyond billing:
Alias resolution and auto mode, as above.
Cache TTL: on an API key or a cloud provider, every request bucket defaults to a 5-minute TTL (see Prompt Caching).
Features: Remote Control, Claude in Chrome, cloud scheduled tasks and phone push notifications aren't available on Bedrock, Agent Platform or Foundry; WebSearch isn't available on Bedrock; claude import isn't available on third-party providers.
Background tasks: on Bedrock and Agent Platform they use Sonnet; on Foundry the primary model.
Provider plumbing that bites in practice
Bedrock resolves the region as AWS_REGION → AWS_DEFAULT_REGION → profile → us-east-1. AWS_BEARER_TOKEN_BEDROCK short-circuits the credential chain; awsAuthRefresh and awsCredentialExport run your SSO refresh. Claude Code "uses the Amazon Bedrock Invoke API and does not support the Converse API", so IAM policies and proxies must allow the Invoke API. WebSearch and /logout aren't available (Bedrock).
Agent Platform reads CLOUD_ML_REGION (falls back to us-east5), ANTHROPIC_VERTEX_PROJECT_ID and per-model VERTEX_REGION_CLAUDE_* overrides; gcpAuthRefresh has a 3-minute timeout; the role needed is roles/aiplatform.user.
Foundry takes ANTHROPIC_FOUNDRY_RESOURCE (the resource name only) or ANTHROPIC_FOUNDRY_BASE_URL, and ANTHROPIC_FOUNDRY_API_KEY or ANTHROPIC_FOUNDRY_AUTH_TOKEN (which wins). It "has no startup model check", so a wrong pin fails on the first request, not at launch.
Gateways.ANTHROPIC_AUTH_TOKEN is sent as Authorization: Bearer, ANTHROPIC_API_KEY as x-api-key, and an apiKeyHelper output as both (cached 5 minutes). The base URL alone "doesn't replace the subscription". Part of the 1-hour cache request travels in the anthropic-beta header, so configure the gateway to forward that header unchanged. Claude Code assumes each recognized model's API context window behind a gateway; if the gateway enforces 200K, set CLAUDE_CODE_AUTO_COMPACT_WINDOW=200000.
Content fallback on third-party providers resolves its targets through your pinned IDs: from Fable, Opus 5.5 or Opus 5, a pinned ANTHROPIC_DEFAULT_OPUS_MODEL becomes the fallback for every flagged category that has one, and the fallback model's context window must be at least the session's (model configuration).
Admins can pin the destinations a fleet may use with the managed allowedProviders key (v2.1.285+). Gateways and providers at fleet scale are covered in Autonomy 2: Environment.
Choosing a Model per Task
Start from the docs' own guidance: "Sonnet handles most coding tasks well. Opus provides stronger reasoning for complex architectural decisions." On the Anthropic API the default is already Opus 5.5 at medium effort, which is a strong general choice. Then adjust per task, measuring cost per task rather than per token: a stronger model that finishes in fewer turns can cost less overall.
Task
Starting point
Why
Everyday feature work, bug fixes
Account default (Opus 5.5, medium)
Strong default; raise effort before switching models
Edge-case-heavy logic, concurrency, migrations
Opus 5.5 at high/xhigh, or ultrathink for one turn
More reasoning per step where mistakes are expensive
Hardest, longest-running tasks
fable / best
"for your hardest and longest-running tasks"
Plan with depth, execute cheaply
opusplan
Opus in plan mode, Sonnet after approval (one model switch)
Lookups and searches in subagents
model: haiku or sonnet on the subagent
"Move down to Sonnet or Haiku for lookups, not for writing code"
Route the cheap work, not the main session. A read-only scout subagent on a smaller model keeps the main conversation on the strong model and its cache warm:
---
name: repo-scout
description: Finds where something is defined or used and reports file:line hits. Use for lookups, not for edits.
tools: Read, Glob, Grep
model: haiku
---
Search the repository for what the parent asked about. Report each hit as
`path:line: one-line context`, grouped by file, then stop. Don't edit anything.
Saved as .claude/agents/repo-scout.md. Listing Glob and Grep while leaving out Bash gives this subagent the dedicated search tools even on macOS. CLAUDE_CODE_SUBAGENT_MODEL sets one model for all subagents instead. Subagents and their design are covered in Core 2 and Agents 4.
Pitfall: switching models mid-task"Each model has its own cache." A mid-session /model means the next request re-processes your whole context at cache-write prices; /model asks you to confirm while the cache is warm (v2.1.238+). "Pick your model and effort level at the top of a session, then save /compact for natural breaks between tasks."
Exercise: measure one task on two configurations
Pick a small, real task in a scratch branch. Run it once with the default model at medium and once with --effort high. Compare /usage totals, the number of corrections you had to make, and whether the result passed your tests.
Show a solution
git switch -c effort-a && claude --effort medium # do the task, then /usage
git switch main && git switch -c effort-b && claude --effort high
Record total cost, wall time, corrections and test result for each. Most people find medium fine for routine work and high worth it only where they had to correct medium's reasoning. A single run is anecdote; repeat on three or four tasks before you change your default. Note the /usage dollar figure is an estimate at list price, and on a subscription the plan usage bars matter more.
Key takeaways
Aliases resolve per provider: on Bedrock and Agent Platform sonnet is Sonnet 4.5 unless you pin ANTHROPIC_DEFAULT_SONNET_MODEL.
Model precedence: /model → --model → ANTHROPIC_MODEL → model → ANTHROPIC_DEFAULT_MODEL; it's a starting choice, not enforcement.
Effort defaults to medium on the 5.5 models; max is session-only, ultrathink is a one-turn request (from v2.1.311, typed in the terminal, that turn can run at xhigh), and "think hard" is just text.
Availability fallback lasts one turn; content fallback keeps the session on the fallback model until /model.
Choose model and effort at the start of a session; route lookups to cheaper subagents.
Limits
The model is fluent whether or not it's right, it knows nothing after its cutoff, and it only sees what fits through each tool's output limit. Most "Claude was confidently wrong" incidents trace to one of those three. The fix is a habit: make every claim point at evidence in the transcript.
Confabulation
Confabulation is a fluent claim with nothing under it. The general mechanism: a model predicts plausible text, and plausible isn't the same as true. In Claude Code the expensive confabulations are claims about the state of your world:
"Tests pass." when the last test run predates the last edit, or never happened.
"Nothing else calls this." when the search covered src/ but not tests/ or the scripts directory.
"The docs say X." after a WebFetch. WebFetch "is lossy by design. The extraction prompt determines what reaches Claude, so a result that says a page doesn't mention something may only mean the prompt didn't ask about it."
"The build log shows one warning." when the log was 200,000 characters and Claude saw a 2,000-character preview plus a file path it never opened.
"The subagent verified it." The parent "doesn't see the subagent's intermediate tool calls or outputs, only that final result."
What good behavior looks like, from a recorded run where Bash was denied: "I couldn't run python3 -m unittest: Bash was denied by this session's permission mode, so I have no test results." That's the standard to hold Claude to: say what was checked, with what, and what wasn't.
Mark each claim as backed by a tool result in the transcript or not. Each answer prints a stamp citing the event that backs the claim, or why nothing does; hover a stamped claim to light that event. The transcript is illustrative, built on the labs' tiny-app sample.
Knowledge Cutoff
Opus 5.5, Sonnet 5.5, Haiku 5.5 and Fable 5.1 all have a reliable knowledge cutoff of June 2026 (models overview). Claude Code ships roughly weekly. So the model is routinely wrong about its own harness: features, flags and defaults that changed after June 2026 are invisible to it unless they're in context.
Release dates from the docs changelog. The cutoff is drawn as all of June 2026, because the models overview gives a month, not a day. Everything in the fog reaches the model only through context: docs it fetches, release notes, your CLAUDE.md. Hover a release for its note.
The same applies to every library you use. Practical defenses:
For Claude Code itself, ask a question that triggers the built-in claude-code-guide subagent, which the subagents table lists for "When you ask questions about Claude Code features" (subagents), or point Claude at the docs: every page serves Markdown at https://code.claude.com/docs/en/<page>.md, indexed at llms.txt. /release-notes shows what changed.
For dependencies, have Claude read the installed source or lockfile (node_modules/, site-packages/, go.sum) rather than recall the API, and fetch the version-specific docs.
For "current" facts (prices, model IDs, deprecations), require a fetched source in the answer.
Pitfall: outdated advice that looks authoritativeTraining data and older blog posts carry stale Claude Code advice: "press # to add a memory" (removed in 2.0.70), "Shift+Tab toggles auto-accept" (the cycle changed; auto is the start mode since v2.1.283), "spawn subagents with Task(...)" (the tool is Agent), "Claude Code SDK" (it's the Claude Agent SDK), "use --dangerously-skip-permissions to go fast" (auto mode is the middle ground). Treat a confident answer about Claude Code from memory as a hypothesis.
Context Limits
Two limits shape what the model sees. The first is the window itself: 1M tokens on current models, with auto-compaction at about 967K on native-1M models. You can lower the threshold with /autocompact 500k (v2.1.221+), autoCompactWindow, --autocompact or CLAUDE_CODE_AUTO_COMPACT_WINDOW, which takes precedence, in a range of 100K to 1M. Mind the unit trap: "CLAUDE_CODE_AUTO_COMPACT_WINDOW=200 means 200 tokens even though /autocompact 200 means 200,000." (Claude Code warns and treats such a value as the 100K minimum; v2.1.304+ also accepts 200k.) If one huge output refills the window right after each summary, Claude Code "stops auto-compacting after a few attempts and shows an error instead of looping".
The second, and more often the cause of a wrong answer, is per-tool output limits. Each tool passes the model a bounded slice of its output:
Tool
What reaches Claude inline
Past the limit
Bash, valid result
Up to about 30,000 characters
A file path in the session directory plus a preview of the first 2,000 characters
Bash, failure
Up to about 10,000 characters
A head-and-tail excerpt, no file path
Read
Up to 25,000 tokens per call
First page with a PARTIAL view notice; whole files over 256 KB are refused (read in pages, or allow_large on v2.1.296+)
MCP tool
Warning above 10,000 tokens; capped at 25,000 (MAX_MCP_OUTPUT_TOKENS). "Tools that return image data are still subject to the token limit."
Text results over 50,000 characters are saved to a file
WebFetch
An extraction from up to 100,000 characters of the page
On v2.1.290+ the result says how much went unread
Glob
Up to 100 file paths, sorted by modification time
A truncation flag
Exit code 1 counts as a valid result only for commands where it's benign (grep, rg, find, diff, test, git diff, git grep…). A failing pytest is a failure, so its log is cut to about 10,000 characters of head and tail. bashOutputMaxChars (v2.1.261+, up to 128,000) raises the inline ceiling. Source: tools reference, MCP.
One failing pytest run (exit 1) printed on a tape, line by line; the bar down the left edge is the whole log to scale, with the error marked. A failure reaches Claude inline up to about 10,000 characters. Past that Claude gets a head-and-tail excerpt of that size and no file path, so whatever sat in the torn-out middle, here the traceback, never arrives. The log is illustrative and stays inside the default 30,000-character read-back window; the even head/tail split is drawn for clarity, since the docs give only the excerpt's total. Token figures use about 2.5 characters per token, from Anthropic's models overview ("1M tokens is roughly 555k words or 2.5M Unicode characters on the current tokenizer", models overview), so they're approximate.
The habit this suggests: filter before Claude reads. Ask for pytest -q --maxfail=1 instead of the full verbose suite, grep the log for the error, or add a preprocessing hook (the costs page ships a filter-test-output.sh example). It saves tokens and puts the error inside the inline window.
Output Limits
One response is also bounded. Current models allow up to 128K output tokens. CLAUDE_CODE_MAX_OUTPUT_TOKENS sets "the maximum number of output tokens for most requests"; a value above the model's cap is lowered to the cap, and "Increasing this value reduces the effective context window available before auto-compaction triggers." Thinking counts as output, both for the limit and the bill.
When a reply hits the limit you see one of these (errors):
API Error: Claude's response exceeded the ... output token maximum. To configure this behavior, set the CLAUDE_CODE_MAX_OUTPUT_TOKENS environment variable.
API Error: Claude's response exceeded the 64000 output token maximum for a request sent without streaming. The CLAUDE_CODE_MAX_OUTPUT_TOKENS environment variable cannot raise this limit.
The second form means a streaming request failed and Claude Code re-sent it without streaming, which caps the reply at 64,000 tokens (before v2.1.299 that truncation was silent). Recovery: in an interactive session reply continue (the partial text stays in the conversation), or ask for the output in smaller pieces, one file or one section per reply. In unattended runs, a StopFailure hook can match max_output_tokens to flag truncated turns instead of treating them as success.
Note: the spinner isn't your contextThe ↓ 5.5k tokens beside the spinner "is a live, approximate count of the output the current turn has produced so far". It leaves out everything sent to the model and resets every turn and on compaction, so it won't match /usage.
Verification Habits
The best-practices page reduces this to two moves: "Give Claude something it can run that comes back pass or fail", and whichever check you use, "ask Claude for evidence: the command it ran and its output, or the screenshot" (best practices). Both turn the model's claim of success into a tool result you can read.
✗ Assertion-shaped prompt
"Make discount codes case-insensitive and make sure everything works."
Claude decides what "works" means and reports it. You get a sentence, not evidence.
✓ Evidence-shaped prompt
"Make discount codes case-insensitive. Add a test for a lower-case code. Done means python3 -m unittest passes after your last edit. In your summary, quote the command and its final line, and list anything you didn't check."
Habits that scale from one prompt to a team:
Write "done" into CLAUDE.md as runnable commands, not adjectives.
Run the bundled checks yourself./verify (user-invoked only since v2.1.215, so Claude won't run it for you) builds and runs your app to confirm a change "without falling back to tests or type checks"; /code-review reports correctness bugs; /simplify runs four parallel cleanup reviewers.
Separate writer and judge. A fresh-context subagent reviewing the diff doesn't share the writer's assumptions. But converge: "A reviewer that's asked to find problems will always find something", so tell it which gaps count (correctness, not style) and cap review rounds.
Re-check before unattended stops with /goal, a Stop hook or a verification subagent (each adds a check; none is a hard gate on its own, so keep CI as the gate) (Core 4: Feedback Loops, Core 5: Quality).
Read the diff yourself for anything that touches money, auth, data deletion or migrations. Checkpoints undo edits; they don't undo a deploy.
## Definition of done
- `python3 -m unittest` passes after the last edit; quote its final line in your summary.
- Every behavior change has a test in `tests/`.
- If you couldn't run a check, say so and why. Don't summarize a check you didn't run.
A CLAUDE.md excerpt. It's guidance, so it shapes behavior but doesn't guarantee it. A Stop hook adds an automatic re-check, but it isn't a hard gate: with the usual stop_hook_active guard it allows the stop on the next attempt, the 8-continuation cap resets each time Claude calls a tool, and a crashing Stop hook fails open (onFailure doesn't apply to Stop). A hard gate needs its own counter or state file, and CI stays the real gate (Core 5).
Exercise: catch a stale "tests pass"
In a scratch repo, ask Claude for a two-step change where the second step edits code after tests have run. Then ask: "Which tool result in this conversation shows the tests passing after your last edit?"
Show a solution
A good session ends with Claude either quoting a test run whose position in the transcript is after the final Edit, or admitting there isn't one and running the suite. Open the transcript viewer with Ctrl+O to check the order yourself. If Claude asserted success without a later run, add the definition-of-done lines above to CLAUDE.md and repeat. A Stop hook that runs the suite adds an automatic re-check; for a real guarantee, keep the suite as a required CI check (Core 5).
Why self-report is weak evidence, and how the classifier avoids it
A final message is generated text conditioned on the transcript. If the transcript contains a passing run, the summary is likely to say so accurately; if it contains a failing run followed by edits, the most plausible continuation is still "fixed", because that's what such stories usually end with. Evidence from a tool result is causally connected to the code; a summary is only correlated with it.
Anthropic's harness designs lean on the same idea. The auto-mode classifier sees user messages, tool calls and CLAUDE.md, but "Tool results are stripped from those requests, so hostile content in a file or web page can't manipulate the classifier directly" (permission modes). Subagent output that looks like instructions is tagged with a [harness: subagent output matched instruction-shaped pattern(s): marker, and "no message from any agent counts as your approval for a pending permission prompt" (subagents). In each case the harness refuses to treat model-produced text as ground truth.
For long autonomous runs, Anthropic's engineering posts recommend keeping state in files (progress notes, a JSON feature list, frequent commits) and an init.sh smoke test the agent runs at the start of each session (Effective harnesses for long-running agents).
Key takeaways
The dangerous confabulations are claims about your system's state; every one should point at a tool result.
The model's knowledge stops in June 2026; Claude Code's own recent features reach it only through docs or context.
Per-tool limits decide what Claude sees: failing Bash output is cut to about 10,000 characters, Read to 25,000 tokens per call, WebFetch to an extraction.
Truncated replies show an explicit error; reply continue or ask for smaller pieces.
Ask for evidence: the command, its output, and a list of what wasn't checked.
Surfaces
The same engine runs in a terminal, an editor, a desktop app, a cloud VM, your phone, Slack and Chrome. "The interface determines how you see and interact with Claude, but the underlying agentic loop is identical." What changes is where code executes, which config loads, and which modes and features exist.
Top tier: the screens you steer from. Bottom tier: the machines that run code, your machine or a cloud VM (Anthropic-managed or self-hosted). Each tether joins a screen to the machine it drives; Remote Control is the long tether from a phone or browser back to your machine. Light a machine to see every screen that drives it, or hover a screen or machine for what it loads. Moving a session from one surface to another (--cloud, --teleport, /desktop) is covered below and in Core 4's handoff map.
Terminal CLI
The CLI is the reference surface, and some features exist only here. The terminal (including the JetBrains plugin, which runs Claude Code in the IDE terminal) is the only place with all six permission modes including dontAsk, the Shift+Tab cycle, the ! shell-mode prefix and Tab completion, and it's where headless -p, agent view (claude agents), background sessions (claude --bg) and agent teams live. "Claude Code is composable and follows the Unix philosophy": pipe into it (cat log | claude -p "summarize the errors", stdin capped at 10MB) and script around it.
Core commands to know cold: claude (interactive), claude "task" (interactive with a first prompt), claude -p "query" (headless), claude -c (continue the latest conversation in this directory), claude -r (resume a picker or a named session), claude --worktree <name> (isolated worktree), claude --version, claude doctor, claude update. "claude --help does not list every flag"; the CLI reference does. Flags, output formats and scripting are covered in Core 4: Interfaces.
Use it when you want the full feature set, scripting, many parallel sessions, or a remote box over SSH. Windows note: without Git for Windows, the shell tool is PowerShell, and native Windows has no sandbox (WSL 2 does).
IDE Extensions
VS Code (1.94.0+) is "the recommended way to use Claude Code in VS Code". The extension bundles a private CLI that "does not put claude on your shell PATH", and "The extension's version number is the Claude Code version it bundles." What you gain: side-by-side diffs with accept/reject in Manual mode, plans opened as Markdown you can comment inline, @terminal:name and @browser mentions, Option+K / Alt+K to insert @file.ts#5-10 from a selection. "The extension and CLI share the same conversation history", so you can resume one in the other. What you lose: the ! shortcut and Tab completion are CLI-only. Starting mode is set by claudeCode.initialPermissionMode, which "doesn't accept auto", and the extension "never reads a project's .claude/settings.json or .claude/settings.local.json for the starting permission mode".
JetBrains (IntelliJ, PyCharm, WebStorm, GoLand and others): the plugin "does not bundle its own copy of the CLI", so install the CLI first. Cmd+Esc / Ctrl+Esc launches it, and because it runs Claude Code in the IDE terminal, modes and Shift+Tab work as in the CLI. A caution from the docs: in acceptEdits mode Claude "may be able to modify IDE configuration files that can be automatically executed by your IDE".
Both connect through a built-in, hidden MCP server named ide, which gives Claude mcp__ide__getDiagnostics (type errors and warnings after edits) and, in VS Code, mcp__ide__executeCode for Jupyter cells. From an external terminal, /ide connects a CLI session to a running IDE.
Desktop App
In the Claude Desktop app, "Claude Code is the Code tab. The app also has chat and Cowork, which handles Dispatch and longer agentic work" (Desktop; macOS, Windows x64/ARM64, Linux beta; paid plan). The Code tab "runs its own copy of Claude Code, which has its own version number", so it can differ from your terminal's claude --version.
It adds a visual layer: preview servers declared in .claude/launch.json, worktrees under .claude/worktrees/, scheduled tasks that run locally, an Open in menu that can send a local Code-tab session to the cloud, and (research preview, Pro or Max) computer use. It removes some CLI features: no dontAsk, no Shift+Tab cycling (a mode selector instead, remembered per folder, with Plan session-only), no -p, no agent teams.
Hand a terminal session to Desktop with /desktop (alias /app; claude.ai subscription; macOS and x64 Windows) or start from a shell with claude --desktop --continue (v2.1.285+).
Cloud Sessions
A cloud session runs on Anthropic-managed (or your organization's self-hosted) infrastructure and "keeps running after you close your laptop". Start one from claude.ai/code, the Claude app, Desktop's Cloud option, or the CLI: claude --cloud "fix the flaky checkout test". In a GitHub repo with the Claude GitHub App installed, that command "clones your current directory's GitHub remote at your current branch, not your local checkout, so push first if you have local commits". With no git remote, or on a github.com repo without the app, Claude Code instead bundles your local repository (history plus uncommitted changes to tracked files) and uploads it; CCR_FORCE_BUNDLE=1 forces a bundle. On macOS, Linux and WSL the bundle leaves out uncommitted changes to credential-like files such as .env and *.pem; on native Windows they upload as they are. (--remote is a deprecated alias.) The Anthropic blog (Claude Code in the cloud) describes the VM as "about 4 vCPUs, 16 GB of RAM, and 30 GB of disk" and notes "Your GitHub token never enters the VM".
Config is the big difference. Cloud sessions read only the shared project .claude/settings.json and server-managed settings, not your user or local files, and don't install plugins, not even the ones the repo's settings enable (what carries over).
Anthropic's launch post sums it up: "CLAUDE.md, rules, skills, agents, and commands travel with the repo, and your ~/.claude stays on your laptop" (Claude Code in the cloud). Commit what the cloud needs. Modes offered: Accept edits, Plan, Auto.
Moving between surfaces: "session handoff is one-way". claude --teleport or /teleport (/tp) pulls a cloud session into your terminal (clean git state, branch pushed, same claude.ai account); nothing pushes a terminal session up. To steer an existing cloud session from a script, claude -p "also update the changelog" --cloud <session-id> queues one follow-up and exits.
Plans and limits: "Cloud sessions are available on Pro, Max, and Team plans, and for Enterprise users with premium seats or Chat + Claude Code seats"; ZDR, HIPAA and CMEK organizations can't use them. Security note: "When running with network access disabled, Claude Code can still communicate with the Anthropic API, which may allow data to exit the VM."
Remote Control
Remote Control is the inverse of a cloud session: the session and your files stay on your machine, and claude.ai/code or the Claude mobile app steers it. "Your local Claude Code session makes outbound HTTPS requests only and never opens inbound ports on your machine." Entry points: /remote-control (/rc) inside a session, claude --remote-control (--rc) at launch, or claude remote-control as a server that can spawn sessions (--spawn same-dir|worktree|session, --capacity default 32). /mobile shows a QR code for the app.
Requirements and trade-offs: "available on Pro, Max, Team, and Enterprise plans. API keys are not supported"; off by default on Team and Enterprise until an Owner enables it; unavailable on Bedrock, Agent Platform, Foundry, a non-Anthropic ANTHROPIC_BASE_URL, or with CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC set. "While Remote Control is connected, the session transcript ... is stored on Anthropic servers." Modes offered: Manual, Accept edits, Plan, Auto. remoteControlAtStartup: true in project or local settings is ignored, so a repo can't turn it on for you; the --sandbox flags were removed in v2.1.300.
Use it to approve a permission prompt or nudge a long local run from your phone, when the work needs your machine's files, credentials or hardware.
Slack and Chrome
Slack now has two products. Claude Tag (public beta, Team and Enterprise, first-party only): "Claude Tag runs @Claude as your organization's shared identity with admin-configured access" (Claude Code in Slack). It runs as that shared identity, anyone in the paired workspace can tag @Claude by default, and channel work bills to the organization's usage balance under an Owner-set spend limit. The earlier Claude Code in Slack runs each task as a cloud session under an individual Pro or Max account, in channels only, and only in a workspace "Not connected to Claude Tag by any organization"; in Tag-connected workspaces "The legacy Claude in Slack bot is retired effective October 5, 2026". /install-slack-app starts the OAuth flow. The Slack docs warn "Claude may follow directions from other messages in the context": treat a busy channel as untrusted input.
Claude in Chrome lets a CLI or VS Code session drive your real browser through the extension (version 1.0.36 or later; Chrome, Edge and other Chromium browsers): claude --chrome, /chrome, or @browser in VS Code. Claude "shares your browser's login state, so it can access any site you're already signed into", and pauses at login pages and CAPTCHAs. Requirements: a direct Anthropic plan and /login (API keys and claude setup-token tokens keep it off); not on WSL; not through Bedrock, Agent Platform or Foundry. A project can't turn it on (CLAUDE_CODE_ENABLE_CFC in project settings is ignored). Site permissions come from the extension; in auto mode a classifier-approved browser call skips the extension's per-site check, which is worth knowing before you point it at a logged-in admin console. Screenshot-driven loops are covered in Core 5: User Interfaces.
Surface
Code runs on
Permission modes
Config it reads
Needs
Terminal CLI
Your machine
All six
Managed, user, project, local, CLI
Any account or provider
VS Code extension
Your machine
Manual, Edit automatically, Plan, Auto, Bypass
Same as CLI (start mode: extension rules)
VS Code 1.94+
JetBrains plugin
Your machine (IDE terminal)
All six, Shift+Tab as in the CLI
Same as CLI
CLI installed separately
Desktop Code tab
Your machine (or send to cloud)
Manual, Accept edits, Plan, Auto, Bypass
Same as CLI
Paid plan
Cloud session
Anthropic or self-hosted VM
Accept edits, Plan, Auto
Project settings + server-managed only
Pro, Max, Team; Enterprise premium seats
Remote Control
Your machine
Manual, Accept edits, Plan, Auto
Same as CLI
Subscription; no API keys or cloud providers
Slack (Claude Tag / earlier app)
Cloud
Set by the product
Org config / your cloud setup
Team, Enterprise / Pro, Max
Tick what the task needs and pick your account. Every ticked constraint strikes out the surfaces with a documented blocker (✕); ✓ marks documented support and ~ a caveat. The survivors stay lit, and the first pick is the survivor with the most ✓. Blockers and support come from the docs pages linked in this topic; there are no fit scores.
Version skew, config scope and data paths across surfaces
Three version numbers can disagree. Your terminal's claude --version, the VS Code extension ("The extension's version number is the Claude Code version it bundles") and the Desktop Code tab ("runs its own copy of Claude Code, which has its own version number"). A feature marked "requires v2.1.xxx+" can work in one and not another on the same laptop. The Agent SDK bundles a CLI too: "updating the SDK is how you update the CLI".
Config scope follows where the process runs. Local surfaces read managed, user, project and local settings. Cloud sessions read only the project's .claude/settings.json and server-managed settings, and don't install plugins, not even the ones the repo's settings enable. Remote Control steers a local process, so it sees your full local config; but a repo can't switch it on, because remoteControlAtStartup: true in project or local settings is ignored. The same pattern protects Chrome: CLAUDE_CODE_ENABLE_CFC in project settings is ignored.
Data paths differ. Local sessions write JSONL transcripts under ~/.claude/projects/. "While Remote Control is connected, the session transcript ... is stored on Anthropic servers." Cloud sessions run in a VM where, per Anthropic's launch post (Claude Code in the cloud), "Your GitHub token never enters the VM", but "When running with network access disabled, Claude Code can still communicate with the Anthropic API, which may allow data to exit the VM", and organization IP allowlisting breaks every Anthropic-hosted cloud session (cloud sessions).
Scripting the handoffs.claude -p "msg" --cloud <session-id> --output-format json returns {ok, session_id, url} (stream-json isn't supported there). Inside a cloud session, typing /teleport replies with the exact claude --teleport <session-id> command (v2.1.223+ in the session's environment). After you teleport, "new work there stays local and doesn't appear in the cloud session", so run /remote-control locally if you want to keep steering from your phone.
Exercise: one task across three surfaces
On a scratch repo with a GitHub remote: push a branch, start a cloud session on it with claude --cloud, watch it at claude.ai/code, pull it into your terminal with claude --teleport, then keep steering it from your phone with /remote-control. Note which configuration each surface loaded.
Show a solution
git switch -c try-cloud && git push -u origin try-cloud
claude --cloud "add a test for lower-case discount codes and run the suite"
# watch it at claude.ai/code; when it finishes, from a clean checkout of the repo:
claude --teleport # pick the session; uncommitted changes must be stashed first
# inside the teleported session:
/remote-control # then open it from the Claude mobile app
What you should notice: the cloud session ran on the pushed branch (it cloned from GitHub; with no remote or no Claude GitHub App it would have uploaded a local bundle instead) and didn't see your ~/.claude hooks or rules, only the project's .claude/settings.json. Teleport checked out the session's branch and loaded its history, and new work there stays local. Remote Control kept execution on your machine while the phone steered. You need Pro, Max or Team (or an Enterprise premium seat) and a GitHub connection (/web-setup).
Key takeaways
One engine, three execution environments: local, cloud, and Remote Control (local, steered remotely).
The terminal CLI (including the JetBrains plugin's IDE terminal) is the only place with every mode and feature; the VS Code extension bundles its own CLI and its own start-mode rules.
claude --cloud clones your pushed branch when it clones from GitHub (otherwise it uploads a local bundle) and reads only project settings; teleport only pulls down.
Remote Control and Chrome need a direct Anthropic subscription login; neither works through cloud providers.
Claude Tag is the Team/Enterprise Slack product; the earlier Claude Code in Slack serves Pro/Max in unconnected workspaces.
First Session
A first session done right takes ten minutes: a native install, a login, a trusted folder, a curated CLAUDE.md, a plan before the first real change, and knowing how to rewind and diagnose. Most of the habits that make Claude Code feel reliable are set here.
Each station links to its concept below. The two spurs are the recovery paths to know before you need them: /doctor off Log in, and Esc Esc · /rewind looping back from Implement to /plan.
Install and Authentication
Prefer the native installer: it auto-updates in the background ("then take effect the next time you start Claude Code"), keeps the two newest versions, and puts a launcher at ~/.local/bin/claude. Homebrew and WinGet don't auto-update; the claude-code cask tracks the stable channel ("typically about a week behind"), claude-code@latest the latest.
curl -fsSL https://claude.ai/install.sh | bash
claude --version # prints a version followed by (Claude Code)
claude doctor # read-only install and settings diagnostics
irm https://claude.ai/install.ps1 | iex
claude --version
brew install --cask claude-code # stable channel; upgrade yourself
winget install Anthropic.ClaudeCode # no background updates either
# Node.js 22+; never sudo; upgrade with @latest, not `npm update -g`
npm install -g @anthropic-ai/claude-code
npm install -g @anthropic-ai/claude-code@latest
Requirements: macOS 13.0+, Windows 10 1809+ or Server 2019+, Ubuntu 20.04+, Debian 10+, Alpine 3.19+, "4 GB+ RAM, x64 or ARM64 processor". Pin a channel with autoUpdatesChannel ("latest" or "stable") and a floor with minimumVersion.
Authentication. "Claude Code requires a Pro, Max, Team, Enterprise, or Console account. The free claude.ai plan does not include Claude Code access." Run claude and follow the login, or use claude auth login [--email|--sso|--console]; check with claude auth status ("Exits with code 0 if logged in, 1 if not"); switch inside a session with /login. An ANTHROPIC_API_KEY in the environment skips the login once you approve it, and the first Console login creates a "Claude Code" workspace for cost tracking. For CI, claude setup-token creates a long-lived OAuth token (CLAUDE_CODE_OAUTH_TOKEN). Credentials go to the macOS Keychain, a 0600 file on Linux, or user-profile ACLs on Windows.
Workspace trust. The first launch in a folder asks whether you trust it. Until you do, the project's permissions.allow rules and additionalDirectories don't apply; deny and ask rules apply immediately. "A claude -p run or an SDK session never shows it", which is why headless runs in untrusted repos deserve --bare (Core 4).
Pitfall: two installsAn old npm global plus a native install means two claude binaries on your PATH and confusing version reports. /doctor checks for "duplicate or leftover installs, PATH problems". Pick one method.
/init
/init generates a starter CLAUDE.md from the codebase. "If a CLAUDE.md already exists, /init suggests improvements rather than overwriting it." It also reads .cursor/rules/, .cursorrules and .github/copilot-instructions.md, and if it finds OpenAI Codex or Google Gemini CLI configuration it offers /import. Set CLAUDE_CODE_NEW_INIT=1 for a multi-phase flow that also walks through skills, hooks and personal memory and "presents a reviewable proposal before writing any files". The docs' sequence: "Run /init to generate a starter CLAUDE.md, then /memory to refine it."
Treat the output as a draft. The rules for curating it:
"target under 200 lines per CLAUDE.md file. Longer files consume more context and reduce adherence."
Keep what Claude can't derive from the code: commands, invariants, non-obvious conventions, things not to do. Delete the directory tour it can rediscover with ls. Before you add a line, ask the docs' two questions: "Could it find this by reading the code?" and "Would it actually go and look?" If both are yes, leave it out.
Skip IMPORTANT and capitals. Current models "follow a plainly worded line, and piling on emphasis mostly makes Claude over-apply the rule." A line that keeps getting missed belongs in a hook, or the file needs to be shorter.
Must-hold rules go in permissions or hooks; CLAUDE.md is advisory.
# tiny-app
Shopping-cart library (`tinyapp/`) with a receipt CLI. Stdlib only, Python 3.9+.
## Commands
- Test: `python3 -m unittest`
- Try the CLI: `python3 -m tinyapp.cli --region CA --code WELCOME10 apple:120:3`
## Conventions
- All amounts are integer cents. Never introduce floats for money.
- Tax applies after the discount; rounding is half up (see `tax_for`).
- Add or update a test for every behavior change, and run the suite before finishing.
## Don't
- Don't add third-party dependencies.
A curated CLAUDE.md (the labs' sample repo uses a version of this). Short, concrete, and every line changes behavior. CLAUDE.md design is covered in depth in Core 2: Memory and Core 3: Repository Knowledge.
Permission Modes
A permission mode sets the baseline for what runs without asking; rules and hooks layer on top, and "Deny rules block in every mode, including bypassPermissions" (permission modes).
Config value
Status bar
Runs without asking
Best for
default (alias manual)
⏸ manual mode on
Reads only
Sensitive work, unfamiliar code
acceptEdits
⏵⏵ accept edits on
Reads, edits, mkdirtouchrmrmdirmvcpsed in scope
Iterating on code you're reviewing
plan
⏸ plan mode on
Reads, plus classifier-approved commands when auto is available
Exploring before changing
auto
⏵⏵ auto mode on
"Everything, with background safety checks"
Long tasks, less prompt fatigue
dontAsk
⏵⏵ don't ask on
Reads, built-in read-only commands and pre-approved tools; anything that would prompt is denied
Locked-down CI and scripts
bypassPermissions
⏵⏵ bypass permissions on
Everything
"Isolated containers and VMs only"
The naming trap: the mode every UI calls Manual has the config value default; hooks and the SDK always see "default".
Which mode a session starts in. The first of: the --permission-mode flag (or --dangerously-skip-permissions), then permissions.defaultMode in settings, then the built-in default. "With Claude Code v2.1.283 or later, auto mode is the built-in starting permission mode for interactive terminal and VS Code sessions." claude -p and Agent SDK runs with no mode set start in Manual (v2.1.302+), so calls needing approval are denied unless an allow rule, hook or --permission-prompt-tool approves them. The SDK follows the CLI version it bundles (Python claude-agent-sdk 0.2.168 bundles CLI 2.1.301), so always pass permission_mode explicitly. Edge cases: "auto" or "bypassPermissions" as defaultMode in project or local settings don't take effect; any settings file with disableAutoMode: "disable" forces Manual; and "When the flag, a settings file, or the built-in default selects auto but auto mode isn't available to the session, Claude Code starts the session in Manual instead."
Switching. Shift+Tab (or Alt+M): "From auto, the first press switches to default, and the cycle then runs default → acceptEdits → plan". bypassPermissions joins the cycle only if you launched with it enabled; dontAsk "never appears in the cycle".
One settings panel, four surfaces: each status bar shows the mode that surface starts in and which source decided it. Click a bar for its full trace. Implements the documented start order and built-in default table for the terminal, -p, the SDK and the VS Code extension (v2.1.302+ behavior). Then shows where Shift+Tab goes from there.
Auto mode, honestly. A classifier model ("By default, classifier requests go to Claude Sonnet 5") reviews each call and blocks "anything irreversible, destructive, or aimed outside your environment". Explicit ask rules still prompt; on entering auto, broad allow rules such as Bash(*) or Bash(python*) are dropped. Three blocks in a row or twenty in total pause it back to prompting. "Auto mode reduces permission prompts but does not guarantee safety." And "Boundaries are not stored as rules": a "don't push to main" said in chat "can be lost if context compaction removes the message that stated it. For a hard guarantee, add a deny rule instead."
~/.claude/settings.json for someone who prefers reviewing edits as they land. Note the space before *: Bash(ls*) without one "matches lsof too". Rules and precedence across settings files are covered in Core 2: Settings.
Pitfall: bypass as a speed settingbypassPermissions "offers no protection against prompt injection or unintended actions". Only use it inside a container or VM you can throw away, as a non-root user (it refuses root on Linux and macOS). For fewer prompts on your laptop, auto mode or the sandbox's auto-allow mode is the documented middle ground.
What you build: a decision table of sample tool calls across all six modes under a sample set of team rules, with a trace for each cell in the documented order: PreToolUse hooks, deny rules, critical-path removals, ask rules, protected paths, then allow rules and the mode's baseline. Auto mode's classifier isn't simulated; those cells say "classifier".
cd labs && python3 core-1/mode_simulator.py
cd labs && python3 core-1/mode_simulator.py --explain --mode auto
cd labs && python3 core-1/mode_simulator.py --headless # claude -p: prompts become denials
cd labs && python3 core-1/mode_simulator.py --self-test # asserts the docs' own rule examples
Observe:Read: .env and Bash: cat .env are denied in every column, bypassPermissions included (Read deny rules reach recognized file commands such as cat, but not grep -r); git push prompts even in bypass and auto because of an explicit ask rule, and is denied in dontAsk; npm run build is allowed by a rule everywhere except auto, which drops package-manager run rules; /usr/bin/curl slips past Bash(curl *).
Project auto doesn't fall back to your user setting. If .claude/settings.json sets "auto", it "doesn't take effect, and Claude Code then uses the built-in default rather than a defaultMode from ~/.claude/settings.json". Project "bypassPermissions" starts the session in Manual.
HIPAA. Eligible sessions in an organization with the HIPAA configuration start in default (v2.1.285+), with auto still available to switch to.
Providers and models. Auto needs a supported model: on the Anthropic API and Claude Platform on AWS, Opus 4.6+, Sonnet 4.6+, Haiku 5.5 or Fable; on Bedrock, Agent Platform, Foundry and the apps gateway, Sonnet 5+, Opus 4.7+, Haiku 5.5 or Fable. Sonnet 4.5, Opus 4.5 and Haiku 4.5 aren't supported anywhere.
Headless. In -p under auto mode without --permission-prompt-tool, a blocked action is denied and "Claude keeps working"; repeated blocks don't end the run.
Protected paths. Writes to .git, .claude, .vscode, .husky and similar, and files like .gitconfig, shell rc files and .mcp.json, are never auto-approved outside bypass and plan-mode sessions where bypass is available (auto mode sends them to the classifier even when an allow rule matches); rm of critical paths (root, home, the working directory and its parents) can't be approved by any rule or hook.
Plan Mode
"Plan mode tells Claude to research and propose changes without making them. Claude reads files, runs shell commands to explore, and writes a plan, but does not edit your source." Enter it with /plan [description] (for example /plan add lower-case discount codes), Shift+Tab, or claude --permission-mode plan. From auto it's three Shift+Tab presses, so /plan is the reliable habit; the older "press Shift+Tab twice" tip is only true from Manual.
It isn't strictly read-only: when auto mode is available and useAutoModeDuringPlan is on (the default), the classifier approves exploratory shell commands instead of prompting. When the plan is ready you choose Yes, and use auto mode, Yes, manually approve edits, or No, keep planning. Ctrl+G opens the plan in your editor so you can change it before approving; plans are saved under plansDirectory (default ~/.claude/plans) and the plan is re-injected after compaction.
you/plan make discount codes case-insensitive and add a test
assistant (plan)1. In pricing.apply_discount, look up code.upper(). 2. Add test_lowercase_code to tests/test_pricing.py. 3. Run python3 -m unittest. Out of scope: Cart stores the raw code; display stays unchanged.
Claude CodeWould you like to proceed? · Yes, and use auto mode · Yes, manually approve edits · No, keep planning
Illustrative transcript. Note the explicit out-of-scope line: asking the plan to say what it won't change is a cheap way to catch scope surprises before any edit.
When to skip it: when you could describe the diff in one sentence. When to insist on it: anything touching several modules, data, or an API contract. To make plan the default for a project's terminal sessions, set "defaultMode": "plan" in .claude/settings.json; VS Code users set claudeCode.initialPermissionMode instead.
Checkpoints and /rewind
"Every prompt you send that starts a turn creates a new checkpoint." Claude Code snapshots files before Claude's edits, keeps the 100 most recent checkpoints per session, keeps them across resume, and deletes them "about 30 days after the session last saved one". Open the menu with /rewind (aliases /checkpoint, /undo) or Esc Esc on empty input, pick a point, then pick an action: Restore code and conversation, Restore conversation, Restore code, Summarize from here, Summarize up to here, or Never mind. "Summarize keeps you in the same session and compresses context, like a targeted /compact." Rewinding reuses an already-cached prefix, so it's cheap.
Bash changes count only on files Claude already edited. "Once Claude has edited a file with its file editing tools in your conversation, /rewind undoes changes that Bash commands make to that file afterward. A file that only Bash commands changed isn't tracked and stays as it is." So a formatter run on a file Claude edited is undone, while a file that only an mv, a cp or a codegen script touched isn't restored.
Subagent edits come back only on files Claude itself had already edited in your conversation; a foreground context: fork skill's edits restore as usual. Changes from outside the session are normally not captured unless they touch files the session edited, and symlinked or hard-linked files are skipped.
"Actions that affect remote systems (databases, APIs, deployments) can't be checkpointed" (How Claude Code works).
"Checkpoints are separate from git" (How Claude Code works). Commit early; use git for history and collaboration.
A four-prompt session with two Bash changes: one renames a file Claude never edited (the hatched lane), the other reformats a file Claude already edited. Drag the playhead to a checkpoint (or press one) and pick an action: tracked changes after it rewind (↺), the Bash-only lane stays. The lanes follow the documented tracking rules.
/doctor
/doctor "runs a setup checkup that diagnoses installation and configuration issues and can fix them" (alias /checkup; it became a fixing checkup in 2.1.205). It's a bundled skill: "Claude reports its findings first and asks for confirmation before changing anything." It covers installation health (duplicate installs, PATH problems, unparseable settings, a newer version on your channel), extensions (unused skills, MCP servers and plugins against their context cost, slow hooks), CLAUDE.md files (duplicates, content Claude could derive from the codebase, always-loaded guidance it can move into skills), and permissions (an offer to make auto your default and to pre-approve read-only commands that you frequently deny).
Its relatives:
claude doctor in a shell: "read-only installation and settings diagnostics without starting a session". Use it in scripts and when Claude Code won't start.
/doctor prompt-audit [path] (v2.1.283+): audits CLAUDE.md, skills, agents and commands for outdated or conflicting instructions, including patterns written for older models.
/status: shows the "Setting sources" line, the provider and auth rows, and the model. First stop for "why is it using that model or mode?"
claude --safe-mode: disables customizations but keeps auth, model, built-in tools and permissions. "If a problem disappears in safe mode, one of those surfaces is the cause."
/debug [description] and claude --debug / --debug-file <path>: runtime diagnosis and logs.
Exercise: a first session, done right
In a repo you know well (or the labs' tiny-app copied to a temp dir): verify your install, check auth, trust the folder, run /init and cut its output to the lines that matter, plan one small change with /plan, implement it, then deliberately rewind it. Finish with /doctor and /usage.
Show a solution
claude --version && claude auth status --text && claude doctor
cp -r labs/common/samples/tiny-app /tmp/tiny-app && cd /tmp/tiny-app
git init -q && git add -A && git commit -qm init
claude
# /init → edit CLAUDE.md down to commands, invariants, don'ts
# /plan make discount codes case-insensitive and add a test
# approve → let it implement → check the test run is after the last edit
# Esc Esc → pick the checkpoint before the change → Restore code and conversation
# /doctor → read findings, decline anything you don't understand
# /usage → note cost, cache line, and duration
Check yourself: after the rewind, git status should show only your CLAUDE.md edits (if you made the code change through Edit). If anything remained, only Bash touched that file: a file Claude never edited with its file tools isn't tracked, so restore it with git.
Key takeaways
Native install for auto-updates; one install method only; claude auth status and claude doctor are your scriptable checks.
Project allow rules wait for workspace trust; -p never asks for trust.
/init writes a draft; curate it under 200 lines of things Claude can't derive.
Interactive sessions start in auto (v2.1.283+), -p in Manual (v2.1.302+); the SDK follows its bundled CLI, so pass permission_mode explicitly. Project files can't set auto or bypass as the default.
Use /plan for multi-file changes; rewind is per prompt, undoes Bash changes only on files Claude already edited, and never covers remote effects.
Costs
"Claude Code charges by API token consumption." Every request re-sends the whole context, so cost is dominated by context size times request count, discounted by the prompt cache. Learn to read /usage, keep the cache warm, cap unattended runs, and know which controls your setup gives you.
/usage
/usage (aliases /cost and /stats; /cost isn't a separate command) shows the session's numbers. Claude Code computes the dollar figure "locally from token counts at list price" unless a managed modelPricing table is in effect, so it's an estimate. "These totals reset when /clear starts a new session" (v2.1.211+).
Total cost: $0.55
Total duration (API): 6m 20s
Total duration (wall): 6h 33m 10s
Total code changes: 0 lines added, 0 lines removed
Usage by model:
claude-sonnet-4-6: 1.2k input, 5.3k output, 940.0k cache read, 50.0k cache write ($0.55)
Prompt cache (main): 14 requests · 91% of input tokens from cache · 2 misses (last 6m 10s ago, 310.2k tokens re-cached) · 1 expected rebuild (compaction or tool-result clearing) · warm (1h TTL, last activity 40s ago)
The docs' own example (costs). The Prompt cache (main) line requires v2.1.251+; since v2.1.260 it can name a likely cause for the last miss, such as tool definitions changed.
How to read it: cache read dwarfing input is healthy (history re-read at the cheap rate). Repeated misses after breaks mean your TTL is shorter than your pauses. For Pro and Max subscribers the session cost figure "isn't relevant for billing purposes"; on Pro, Max, Team and Enterprise the plan usage bars matter, and /usage adds an attribution breakdown (skills, subagents, plugins, MCP servers), behavior flags for anything over 10% of recent usage (long context, cache misses), and the heaviest /loop tasks.
Elsewhere: headless runs report total_cost_usd and a per-model modelUsage breakdown in the result event; the status line receives cost.total_cost_usd and prompt_cache.*; /insights analyzes up to 200 new sessions per run into ~/.claude/usage-data/report.html. All of these are client-side estimates; the Console usage page and your cloud bill are authoritative.
Prompt Caching
Prompt caching is automatic. Requests are layered system prompt and tools, then project context (CLAUDE.md, auto memory, unscoped rules), then conversation, and "The match is exact, so a change anywhere in the prefix recomputes everything after it. There is no per-file or per-segment caching." "Each model has its own cache." Scope is "effectively scoped to one machine and directory"; a fork's first request reads the parent's cache, a subagent's doesn't.
TTL rules. A cache TTL is how long a prefix survives idle time; "Each request that hits the cache resets the timer." Claude Code puts every request in one of two buckets (prompt caching):
One wick per bucket, as long as its TTL (an hour or five minutes). It burns while the bucket sits idle, each cache hit relights it to full length, and a wick that burns out means the next request misses and writes the prefix again. Drag the idle time, switch billing and the overrides, or replay a session; the six gaps are illustrative. "Main conversation" covers interactive turns, -p runs and SDK turns; "everything else" covers subagents, workflows, in-process teammates, forks, compaction and session titles. Drawing on usage credits drops a subscription's main conversation to 5 minutes.
Override per bucket (v2.1.242+): promptCacheTtl / CLAUDE_CODE_PROMPT_CACHE_TTL for the main conversation, subagentPromptCacheTtl / CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL for the rest, each 5m or 1h. Precedence: FORCE_PROMPT_CACHING_5M=1 → the bucket's env var → the bucket's setting → a subagent's experimental.cacheTtl → ENABLE_PROMPT_CACHING_1H=1 → the default. Verify what you got:
Prices (Anthropic API list prices, pricing page, October 2026): cache writes cost 1.25× base input at 5 minutes and 2× at 1 hour; cache reads cost 0.05× on Opus 5.5 and Sonnet 5.5, 0.025× on Fable 5.1, 0.1× on other models. Opus 5.5 is $4 / $20 per MTok input/output, so a 5-minute write is $5, a 1-hour write $8 and a read $0.20 per MTok.
Every request re-sends the whole prefix, so the receipt prints one block per request at Anthropic API list prices for Opus 5.5 (Sonnet 5.5 after a model switch): each block reads the prompt the previous request cached (the tiny lines) and writes the previous reply plus the new turn, and a break longer than the TTL prints a REWRITE of the whole prefix. Send turns, take a break, switch model or edit CLAUDE.md, and change billing or promptCacheTtl (shared with the calculator below). Token counts are illustrative.
Your TTL is the solid line, the other TTL the dashed one; the first misses are labelled where the line jumps. Hover or arrow-key along the chart for both values; the table view has the totals. Billing and promptCacheTtl are shared with the receipt above. Toy model at list prices: each request reads from the cache the prompt the previous request wrote and writes what's new since then, the previous reply plus the new turn (a reply is cached by the request after it); a gap longer than the TTL turns the next request into a full rewrite. Real sessions add subagents, compaction and tool-result clearing. Illustrative, not a bill.
What breaks the cache, and what doesn't, decides how you work:
Pick an action: it topples the cache layer it breaks and every layer after it, because the prefix match is exact; cache-safe actions leave the dominoes standing. The prefix strip in The Context Window follows along. Each verdict quotes or paraphrases the documented list of invalidating and cache-safe actions.
The working rule from the docs: "Pick your model and effort level at the top of a session, then save /compact for natural breaks between tasks." From Anthropic's cost post (What a task costs on Opus 5.5): "compact before a break, not after one", because after the break the cache is cold and compaction reads the whole conversation at full price. On a 1-hour TTL, Claude Code can compact an idle session near expiry on its own (turn off with idleCompaction: false, v2.1.290+).
What you build: a per-turn cost model that sizes what each request carries (harness, CLAUDE.md, MCP tool names or upfront schemas, the skill listing), applies the documented TTL buckets and their precedence, and replays mid-session events such as a model switch or compaction.
cd labs && python3 core-1/cost_model.py # Opus 5.5, API key, a 20-minute break every 10 turns
cd labs && python3 core-1/cost_model.py --billing subscription # main conversation gets the 1-hour TTL
cd labs && python3 core-1/cost_model.py --event 10:model-switch --event 20:compact
Observe: the turn after a break is a full rewrite under 5m and a cheap read under 1h; with --break-every 0 the 1-hour TTL loses because every write costs 2× instead of 1.25×; an effort change keeps the cache on the 5.5 models with an API key or subscription, but not on a cloud provider.
Take Opus 5.5 on an API key with a context averaging about 200K tokens over 100 requests that each add about 5K new tokens. Toy numbers, list prices.
Writes. 100 × 5K = 0.5 MTok of new tokens. At 5 minutes that's 0.5 × $5 = $2.50; at 1 hour, 0.5 × $8 = $4.00. The 1-hour TTL costs $1.50 more if you never pause.
A miss. Coming back after a 10-minute break on a 5-minute TTL rewrites the whole 200K prefix: 0.2 × $5 = $1.00, instead of a read at 0.2 × $0.20 = $0.04.
Break-even. The 1-hour TTL pays for itself once you'd otherwise take about two such misses ($1.50 ÷ $0.96). With a bigger context, a miss costs proportionally more; with no pauses, 5 minutes wins.
That's why the defaults differ by billing: on a subscription within plan usage the main conversation already gets 1 hour, and once you draw on usage credits Claude Code "drops the main conversation to the five-minute TTL, which charges a lower rate for cache writes". If you work in bursts with long pauses on an API key, set promptCacheTtl: "1h"; if you work continuously, leave it.
Haiku 5.5 adds a wrinkle: prompts over 100,000 tokens pay higher rates ($0.50 vs $0.10 input), and the prompt length "counts all of its input tokens, including cache reads and cache writes" (pricing).
Token Budgets
Budgets come in two kinds: hard caps on unattended runs, and habits that keep interactive context small.
Hard caps for headless and SDK runs.--max-turns ("No limit by default") and --max-budget-usd, which is checked "against its client-side cost estimate, which can differ from your bill" and can overshoot by one response. Combine them with a narrow mode and tool list:
claude -p "Triage the failing tests and write findings to triage.md" \
--permission-mode dontAsk \
--allowedTools "Read" "Bash(python3 -m pytest *)" "Edit(./triage.md)" \
--max-turns 25 --max-budget-usd 2.00 \
--output-format json > run.json
jq '{stop_reason, terminal_reason, subtype, num_turns, total_cost_usd, permission_denials}' run.json
# gate in this order: a refusal first, then how the run ended, then the subtype
jq -e '.stop_reason != "refusal" and .terminal_reason == "completed" and .subtype == "success"' run.json > /dev/null || exit 1
"To tell failures apart, check data["stop_reason"] first, then terminal_reason, then subtype" (Agent SDK reference). A declined response has stop_reason: "refusal", usually with subtype: "success", and its terminal_reason doesn't single it out: it can read completed or api_error. Real v2.1.303 runs also reported an API failure as subtype: "success" with terminal_reason: "api_error", and a budget stop as terminal_reason: "budget_exhausted". So the gate above fails the job on a refusal, then unless terminal_reason is completed and subtype is success (other subtypes: error_max_turns, error_max_budget_usd, error_during_execution). Edit(...) path rules also cover Write, so Edit(./triage.md) lets Claude create that one file. Headless permissions are covered in Core 4.
Caps on reasoning and output.maxEffortLevel clamps effort everywhere, including subagents and skills; CLAUDE_CODE_MAX_OUTPUT_TOKENS bounds each response; /autocompact keeps the window smaller than 1M if your work doesn't need it.
Context habits (each from the costs page):
"Clear between tasks: Use /clear to start fresh when switching to unrelated work. Stale context wastes tokens on every subsequent message." /clear costs nothing; "/compact reads the conversation it summarizes, so compacting a large context is itself a large request."
Delegate verbose operations (log trawls, broad searches) to subagents, which return a summary. But "Running several sessions or subagents at once multiplies token usage"; agent teams use "approximately 7x more tokens than standard sessions when teammates run in plan mode".
Prefer CLIs over MCP servers where both exist: tools like gh, aws, gcloud and sentry-cli "are still more context-efficient than MCP servers because they don't add any per-tool listing", even though MCP tool definitions are deferred by default through tool search (costs).
Move rarely needed instructions from CLAUDE.md into skills, which load only when used.
Filter tool output with hooks or flags before Claude reads it.
Why long sessions climb even when you're idle: each request carries the whole conversation; the first message after a break past the TTL misses; session-scoped scheduled tasks, cross-session messages and goal check-ins all start turns that send full context. Background housekeeping is "typically under $0.04 per session".
Cost Controls
Which controls you have depends on how your organization reaches Claude Code (costs):
Setup
See spend
Cap spend
Per-user numbers
Claude for Teams / Enterprise
Spend report in org analytics
Seat allowance (5-hour and weekly windows); usage-credit spend limits per org, group or member
Spend report CSV; Enterprise Analytics API
Claude Console (API)
Console usage page
Workspace spend limits on the auto-created "Claude Code" workspace
Console dashboard; Claude Code Analytics API
Bedrock, Agent Platform, Foundry
Your cloud billing console
Your cloud's budget controls
OpenTelemetry, or a gateway
OpenTelemetry "works on every setup" and streams claude_code.cost.usage and claude_code.token.usage into your own stack (Agents 5). Calibration numbers from the docs: enterprise usage averages "around $13 per developer per active day and $150-250 per developer per month, with costs remaining below $30 per active day for 90% of users". For API organizations, the docs recommend per-user rate limits that fall with team size, from 200k–300k TPM per user for 1–5 users down to 10k–15k for 500+.
Fleet-level settings (managed settings; see Autonomy 2):
availableModels restricts what /model, --model and the model key can pick (pair with enforceAvailableModels to cover the Default option). modelPricing (managed only, v2.1.242+) "changes what Claude Code reports, not what Anthropic charges": it makes /usage, the status line, --max-budget-usd and OpenTelemetry match contracted rates.
When a developer hits a limit, the message tells you which one: "You've hit your session limit" or "weekly limit" is a seat window "shared across all models, so the developer can't restore access by switching models with /model"; a model-specific Opus or Sonnet limit can be worked around by switching family; a spend-limit message points to usage credits; and a context or auto-compact warning is "not a usage limit". autoContinueAtUsageLimit (on by default for subscriptions, v2.1.234+) resumes the interrupted task after the reset.
Exercise: find your cache misses
Work normally for an hour, including one break longer than five minutes. Then run /usage and read the Prompt cache (main) line. How many misses, when, and what TTL? Decide whether to change promptCacheTtl.
Show a solution
On a subscription within plan usage you should see 1h TTL and few misses unless you switched model or effort or added an MCP server. On an API key or cloud provider you'll see 5m TTL and a miss after each long break; each miss re-cached roughly your whole context. If misses after breaks dominate, set "promptCacheTtl": "1h" in user settings and compare the next day. If the line names a likely cause such as tool definitions changed, fix that first: it's a habit problem, not a TTL problem.
Key takeaways
/usage (= /cost) is a list-price estimate; on subscriptions the plan bars matter, and the Prompt cache (main) line is the best single diagnostic.
Default TTL: main conversation 1 hour on a subscription within plan usage (other requests 5 minutes, except server-controlled helpers at 1 hour); 5 minutes for everything on usage credits, API keys and cloud providers. Either bucket can be set to 1 hour with promptCacheTtl / subagentPromptCacheTtl.
Model switches, most effort changes, tool or MCP changes, compaction and the first new conversation after an upgrade rebuild the cache; editing files, mode changes, skills and /rewind don't.
Cap unattended runs with --max-turns, --max-budget-usd and a narrow tool list; gate on stop_reason first (a refusal arrives as subtype success), then terminal_reason, then subtype, and read total_cost_usd.
/clear is free; compact before a break, not after one.
Session wrap-up
Claude Code is a model in a loop inside a harness. The model chooses actions; the harness assembles every request, runs the tools, bounds their output, enforces permissions, snapshots edits, compacts context and keeps the cache. Aliases, providers, effort and fallbacks decide which model answers and how hard it thinks. The model's knowledge, context and output are all bounded, so evidence beats assertion. Seven surfaces share one engine but differ in where code runs and which config loads. A good first session sets the habits (curated CLAUDE.md, a plan for real changes, rewind and doctor as reflexes), and the bill follows context size, request count and cache hits.
Where this connects
Core 2: Context Engineering: CLAUDE.md hierarchy, settings precedence, permission rules, /context, compaction, skills and subagents from the user side.
Core 4: Interfaces: CLI flags, headless output formats and scripts; Parallel Work for worktrees, background sessions and cloud.
Core 5: Quality: turning verification habits into checklists, hooks and review subagents.
Agents 1: Agent Loop: turns, stop conditions, interrupts and budgets from the builder's side; Agents 2 for the same harness as a library.
Permission mode × rule × tool call decisions, following the docs
cd labs && python3 core-1/mode_simulator.py
All three run offline with recorded fixtures. Where a lab supports --real, it drives your installed claude read-only, capped with --max-turns and --max-budget-usd, in a temp copy of the sample repo, and says up front that it costs money.
What to do next
Run the first-session exercise in a real repo and keep the CLAUDE.md you end up with.
Read one stream-json transcript of your own (session_anatomy.py --real or the jq one-liner) and name every event.
Check /status and /usage at the end of tomorrow's work: which model, which mode, how many cache misses.