SpyBara
Go Premium

Documentation 2026-07-16 22:59 UTC to 2026-07-17 01:01 UTC

30 files changed +283 −85. View all changes and history on the product overview
2026
Fri 17 01:01 Thu 16 22:59 Wed 15 22:00 Tue 14 23:01 Mon 13 23:57 Sat 11 19:03 Fri 10 17:00 Thu 9 23:58 Wed 8 16:02 Tue 7 16:02 Mon 6 23:57 Sat 4 03:01 Fri 3 23:00 Thu 2 23:59 Wed 1 21:01
Details

298 ```298 ```

299 299 

300 ```typescript TypeScript theme={null}300 ```typescript TypeScript theme={null}

301 import { tool } from "@anthropic-ai/claude-agent-sdk";

302 import { z } from "zod";

303 

301 tool(304 tool(

302 "get_temperature",305 "get_temperature",

303 "Get the current temperature at a location",306 "Get the current temperature at a location",


353 import httpx356 import httpx

354 from typing import Any357 from typing import Any

355 358 

359 from claude_agent_sdk import tool

360 

356 361 

357 @tool(362 @tool(

358 "fetch_data",363 "fetch_data",


388 ```393 ```

389 394 

390 ```typescript TypeScript theme={null}395 ```typescript TypeScript theme={null}

396 import { tool } from "@anthropic-ai/claude-agent-sdk";

397 import { z } from "zod";

398 

391 tool(399 tool(

392 "fetch_data",400 "fetch_data",

393 "Fetch data from an API",401 "Fetch data from an API",


458 import base64466 import base64

459 import httpx467 import httpx

460 468 

469 from claude_agent_sdk import tool

470 

461 471 

462 # Define a tool that fetches an image from a URL and returns it to Claude472 # Define a tool that fetches an image from a URL and returns it to Claude

463 @tool("fetch_image", "Fetch an image from a URL and return it to Claude", {"url": str})473 @tool("fetch_image", "Fetch an image from a URL and return it to Claude", {"url": str})


481 ```491 ```

482 492 

483 ```typescript TypeScript theme={null}493 ```typescript TypeScript theme={null}

494 import { tool } from "@anthropic-ai/claude-agent-sdk";

495 import { z } from "zod";

496 

484 tool(497 tool(

485 "fetch_image",498 "fetch_image",

486 "Fetch an image from a URL and return it to Claude",499 "Fetch an image from a URL and return it to Claude",


774 ]787 ]

775 788 

776 for prompt in prompts:789 for prompt in prompts:

790 try:

777 async for message in query(prompt=prompt, options=options):791 async for message in query(prompt=prompt, options=options):

778 if isinstance(message, AssistantMessage):792 if isinstance(message, AssistantMessage):

779 for block in message.content:793 for block in message.content:


781 print(f"[tool call] {block.name}({block.input})")795 print(f"[tool call] {block.name}({block.input})")

782 elif isinstance(message, ResultMessage) and message.subtype == "success":796 elif isinstance(message, ResultMessage) and message.subtype == "success":

783 print(f"Q: {prompt}\nA: {message.result}\n")797 print(f"Q: {prompt}\nA: {message.result}\n")

798 except Exception as error:

799 # A single-shot query() raises after yielding an error result. Only success

800 # results are printed above, so handle the failure here and continue with

801 # the next prompt.

802 print(f"Call failed: {error}")

784 803 

785 804 

786 asyncio.run(main())805 asyncio.run(main())


796 ];815 ];

797 816 

798 for (const prompt of prompts) {817 for (const prompt of prompts) {

818 try {

799 for await (const message of query({819 for await (const message of query({

800 prompt,820 prompt,

801 options: {821 options: {


813 console.log(`Q: ${prompt}\nA: ${message.result}\n`);833 console.log(`Q: ${prompt}\nA: ${message.result}\n`);

814 }834 }

815 }835 }

836 } catch (error) {

837 // A single-shot query() throws after yielding an error result. Only success

838 // results are logged above, so handle the failure here and continue with

839 // the next prompt.

840 console.error(`Call failed: ${error}`);

841 }

816 }842 }

817 ```843 ```

818</CodeGroup>844</CodeGroup>

Details

118 let sessionId: string | undefined;118 let sessionId: string | undefined;

119 119 

120 // Step 2: Capture checkpoint UUID from the first user message120 // Step 2: Capture checkpoint UUID from the first user message

121 try {

121 for await (const message of response) {122 for await (const message of response) {

122 if (message.type === "user" && message.uuid && !checkpointId) {123 if (message.type === "user" && message.uuid && !checkpointId) {

123 checkpointId = message.uuid;124 checkpointId = message.uuid;


126 sessionId = message.session_id;127 sessionId = message.session_id;

127 }128 }

128 }129 }

130 } catch (error) {

131 // A single-shot query() throws after yielding an error result. If the

132 // failure was an error result, sessionId and checkpointId were already

133 // captured by the loop above; connection or process failures yield no

134 // result message.

135 console.error(`Session ended with an error: ${error}`);

136 }

129 137 

130 // Step 3: Later, rewind by resuming the session with an empty prompt138 // Step 3: Later, rewind by resuming the session with an empty prompt

131 if (checkpointId && sessionId) {139 if (checkpointId && sessionId) {


229 ) as client:237 ) as client:

230 await client.query("") # Empty prompt to open the connection238 await client.query("") # Empty prompt to open the connection

231 async for message in client.receive_response():239 async for message in client.receive_response():

240 if checkpoint_id:

232 await client.rewind_files(checkpoint_id)241 await client.rewind_files(checkpoint_id)

233 break242 break

234 ```243 ```


240 });249 });

241 250 

242 for await (const msg of rewindQuery) {251 for await (const msg of rewindQuery) {

252 if (checkpointId) {

243 await rewindQuery.rewindFiles(checkpointId);253 await rewindQuery.rewindFiles(checkpointId);

254 }

244 break;255 break;

245 }256 }

246 ```257 ```


430 const checkpoints: Checkpoint[] = [];441 const checkpoints: Checkpoint[] = [];

431 let sessionId: string | undefined;442 let sessionId: string | undefined;

432 443 

444 try {

433 for await (const message of response) {445 for await (const message of response) {

434 if (message.type === "user" && message.uuid) {446 if (message.type === "user" && message.uuid) {

435 checkpoints.push({447 checkpoints.push({


442 sessionId = message.session_id;454 sessionId = message.session_id;

443 }455 }

444 }456 }

457 } catch (error) {

458 // A single-shot query() throws after yielding an error result. If the

459 // failure was an error result, sessionId and the checkpoints array were

460 // already populated by the loop above; connection or process failures

461 // yield no result message.

462 console.error(`Session ended with an error: ${error}`);

463 }

445 464 

446 // Later: rewind to any checkpoint by resuming the session465 // Later: rewind to any checkpoint by resuming the session

447 if (checkpoints.length > 0 && sessionId) {466 if (checkpoints.length > 0 && sessionId) {


612 options: opts631 options: opts

613 });632 });

614 633 

634 try {

615 for await (const message of response) {635 for await (const message of response) {

616 // Capture the first user message UUID - this is our restore point636 // Capture the first user message UUID - this is our restore point

617 if (message.type === "user" && message.uuid && !checkpointId) {637 if (message.type === "user" && message.uuid && !checkpointId) {


622 sessionId = message.session_id;642 sessionId = message.session_id;

623 }643 }

624 }644 }

645 } catch (error) {

646 // A single-shot query() throws after yielding an error result. If the

647 // failure was an error result, checkpointId and sessionId were already

648 // captured by the loop above; connection or process failures yield no

649 // result message.

650 console.error(`Session ended with an error: ${error}`);

651 }

625 652 

626 console.log("Done! Open utils.ts to see the added doc comments.\n");653 console.log("Done! Open utils.ts to see the added doc comments.\n");

627 654 


760 ) as client:787 ) as client:

761 await client.query("")788 await client.query("")

762 async for message in client.receive_response():789 async for message in client.receive_response():

790 if checkpoint_id:

763 await client.rewind_files(checkpoint_id)791 await client.rewind_files(checkpoint_id)

764 break792 break

765 ```793 ```


771 options: { ...opts, resume: sessionId }799 options: { ...opts, resume: sessionId }

772 });800 });

773 801 

802 try {

774 for await (const msg of rewindQuery) {803 for await (const msg of rewindQuery) {

804 if (checkpointId) {

775 await rewindQuery.rewindFiles(checkpointId);805 await rewindQuery.rewindFiles(checkpointId);

806 }

776 break;807 break;

777 }808 }

809 } catch (error) {

810 // An error here means the rewind didn't complete, for example the checkpoint

811 // wasn't found or the session couldn't be resumed.

812 console.error(`Rewind session ended with an error: ${error}`);

813 }

778 ```814 ```

779</CodeGroup>815</CodeGroup>

780 816 

Details

650 650 

651Each notification includes a `message` field with a human-readable description and optionally a `title`.651Each notification includes a `message` field with a human-readable description and optionally a `title`.

652 652 

653This example forwards every notification to a Slack channel. It requires a [Slack incoming webhook URL](https://api.slack.com/messaging/webhooks), which you create by adding an app to your Slack workspace and enabling incoming webhooks:653This example forwards every notification to a Slack channel. It requires a [Slack incoming webhook URL](https://docs.slack.dev/messaging/sending-messages-using-incoming-webhooks/), which you create by adding an app to your Slack workspace and enabling incoming webhooks:

654 654 

655<CodeGroup>655<CodeGroup>

656 ```python Python theme={null}656 ```python Python theme={null}

agent-sdk/mcp.md +23 −18

Details

643 643 

644### Query a database644### Query a database

645 645 

646This example uses the [Postgres MCP server](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/postgres) to query a database. The reference server is archived but still runs with `npx`. The connection string is passed as an argument to the server. The agent automatically discovers the database schema, writes the SQL query, and returns the results.646This example uses [DBHub](https://github.com/bytebase/dbhub) to query a Postgres database. The agent automatically discovers the database schema, writes the SQL query, and returns the results.

647 647 

648Before running, set the `DATABASE_URL` environment variable to your connection string. Replace the placeholder values with your own database details:648DBHub's `execute_sql` tool runs whatever SQL the agent emits, including writes, unless you restrict it. Setting `readonly = true` in the [DBHub configuration file](https://dbhub.ai/config/toml) makes DBHub reject `INSERT`, `UPDATE`, `DELETE`, and DDL statements, so the example cannot modify your data even if the agent emits a write. DBHub resolves `${DATABASE_URL}` from the process environment when it loads the config, so the connection string stays out of the file. Create this `dbhub.toml` next to your script:

649 

650```toml dbhub.toml theme={null}

651[[sources]]

652id = "production"

653dsn = "${DATABASE_URL}"

654 

655[[tools]]

656name = "execute_sql"

657source = "production"

658readonly = true

659```

660 

661The script then points DBHub at the config file instead of passing a connection string directly. Before running, set the `DATABASE_URL` environment variable to your connection string. Replace the placeholder values with your own database details:

649 662 

650```bash theme={null}663```bash theme={null}

651export DATABASE_URL=postgresql://user:password@localhost:5432/mydb664export DATABASE_URL=postgresql://user:password@localhost:5432/mydb


655 ```typescript TypeScript theme={null}668 ```typescript TypeScript theme={null}

656 import { query } from "@anthropic-ai/claude-agent-sdk";669 import { query } from "@anthropic-ai/claude-agent-sdk";

657 670 

658 // Connection string from environment variable

659 const connectionString = process.env.DATABASE_URL;

660 

661 for await (const message of query({671 for await (const message of query({

662 // Natural language query - Claude writes the SQL672 // Natural language query - Claude writes the SQL

663 prompt: "How many users signed up last week? Break it down by day.",673 prompt: "How many users signed up last week? Break it down by day.",


665 mcpServers: {675 mcpServers: {

666 postgres: {676 postgres: {

667 command: "npx",677 command: "npx",

668 // Pass connection string as argument to the server678 // dbhub.toml sets readonly = true, so execute_sql rejects writes

669 args: ["-y", "@modelcontextprotocol/server-postgres", connectionString]679 args: ["-y", "@bytebase/dbhub", "--config", "dbhub.toml"]

670 }680 }

671 },681 },

672 // Allow only read queries, not writes682 allowedTools: ["mcp__postgres__execute_sql"]

673 allowedTools: ["mcp__postgres__query"]

674 }683 }

675 })) {684 })) {

676 if (message.type === "result" && message.subtype === "success") {685 if (message.type === "result" && message.subtype === "success") {


681 690 

682 ```python Python theme={null}691 ```python Python theme={null}

683 import asyncio692 import asyncio

684 import os

685 from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage693 from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage

686 694 

687 695 

688 async def main():696 async def main():

689 # Connection string from environment variable

690 connection_string = os.environ["DATABASE_URL"]

691 

692 options = ClaudeAgentOptions(697 options = ClaudeAgentOptions(

693 mcp_servers={698 mcp_servers={

694 "postgres": {699 "postgres": {

695 "command": "npx",700 "command": "npx",

696 # Pass connection string as argument to the server701 # dbhub.toml sets readonly = true, so execute_sql rejects writes

697 "args": [702 "args": [

698 "-y",703 "-y",

699 "@modelcontextprotocol/server-postgres",704 "@bytebase/dbhub",

700 connection_string,705 "--config",

706 "dbhub.toml",

701 ],707 ],

702 }708 }

703 },709 },

704 # Allow only read queries, not writes710 allowed_tools=["mcp__postgres__execute_sql"],

705 allowed_tools=["mcp__postgres__query"],

706 )711 )

707 712 

708 # Natural language query - Claude writes the SQL713 # Natural language query - Claude writes the SQL

Details

455 session_id = None455 session_id = None

456 456 

457 # First query: capture the session ID457 # First query: capture the session ID

458 try:

458 async for message in query(459 async for message in query(

459 prompt="Read the authentication module",460 prompt="Read the authentication module",

460 options=ClaudeAgentOptions(allowed_tools=["Read", "Glob"]),461 options=ClaudeAgentOptions(allowed_tools=["Read", "Glob"]),

461 ):462 ):

462 if isinstance(message, SystemMessage) and message.subtype == "init":463 if isinstance(message, SystemMessage) and message.subtype == "init":

463 session_id = message.data["session_id"]464 session_id = message.data["session_id"]

465 except Exception as error:

466 # A single-shot query() raises after yielding an error result. If

467 # the failure was an error result, session_id was already captured

468 # by the loop above; connection or process failures yield no

469 # result message.

470 print(f"Session ended with an error: {error}")

464 471 

465 # Resume with full context from the first query472 # Resume with full context from the first query

466 async for message in query(473 async for message in query(


480 let sessionId: string | undefined;487 let sessionId: string | undefined;

481 488 

482 // First query: capture the session ID489 // First query: capture the session ID

490 try {

483 for await (const message of query({491 for await (const message of query({

484 prompt: "Read the authentication module",492 prompt: "Read the authentication module",

485 options: { allowedTools: ["Read", "Glob"] }493 options: { allowedTools: ["Read", "Glob"] }


488 sessionId = message.session_id;496 sessionId = message.session_id;

489 }497 }

490 }498 }

499 } catch (error) {

500 // A single-shot query() throws after yielding an error result. If the

501 // failure was an error result, sessionId was already captured by the

502 // loop above; connection or process failures yield no result message.

503 console.error(`Session ended with an error: ${error}`);

504 }

491 505 

492 // Resume with full context from the first query506 // Resume with full context from the first query

493 for await (const message of query({507 for await (const message of query({

Details

112 const store = new InMemorySessionStore();112 const store = new InMemorySessionStore();

113 113 

114 let sessionId: string | undefined;114 let sessionId: string | undefined;

115 try {

115 for await (const message of query({116 for await (const message of query({

116 prompt: "List the TypeScript files under src/",117 prompt: "List the TypeScript files under src/",

117 options: { sessionStore: store },118 options: { sessionStore: store },


120 sessionId = message.session_id;121 sessionId = message.session_id;

121 }122 }

122 }123 }

124 } catch (error) {

125 // A single-shot query() throws after yielding an error result. If the

126 // failure was an error result, sessionId was already captured by the loop

127 // above; connection or process failures yield no result message.

128 console.error(`Session ended with an error: ${error}`);

129 }

123 130 

124 // Resume from the store. The agent has full context from the first call.131 // Resume from the store. The agent has full context from the first call.

125 for await (const message of query({132 for await (const message of query({


146 153 

147 async def main():154 async def main():

148 session_id = None155 session_id = None

156 try:

149 async for message in query(157 async for message in query(

150 prompt="List the Python files under src/",158 prompt="List the Python files under src/",

151 options=ClaudeAgentOptions(session_store=store),159 options=ClaudeAgentOptions(session_store=store),

152 ):160 ):

153 if isinstance(message, ResultMessage):161 if isinstance(message, ResultMessage):

154 session_id = message.session_id162 session_id = message.session_id

163 except Exception as error:

164 # A single-shot query() raises after yielding an error result. If the

165 # failure was an error result, session_id was already captured by the

166 # loop above; connection or process failures yield no result message.

167 print(f"Session ended with an error: {error}")

155 168 

156 # Resume from the store. The agent has full context from the first call.169 # Resume from the store. The agent has full context from the first call.

157 async for message in query(170 async for message in query(


228 241 

229@pytest.mark.asyncio242@pytest.mark.asyncio

230async def test_my_store_conformance():243async def test_my_store_conformance():

231 await run_session_store_conformance(MyRedisStore)244 await run_session_store_conformance(MyRedisStore) # Your adapter class

232```245```

233 246 

234## Behavior notes247## Behavior notes

Details

110import { query } from "@anthropic-ai/claude-agent-sdk";110import { query } from "@anthropic-ai/claude-agent-sdk";

111 111 

112// First query: creates a new session112// First query: creates a new session

113for await (const message of query({113try {

114 for await (const message of query({

114 prompt: "Analyze the auth module",115 prompt: "Analyze the auth module",

115 options: { allowedTools: ["Read", "Glob", "Grep"] }116 options: { allowedTools: ["Read", "Glob", "Grep"] }

116})) {117 })) {

117 if (message.type === "result" && message.subtype === "success") {118 if (message.type === "result" && message.subtype === "success") {

118 console.log(message.result);119 console.log(message.result);

119 }120 }

121 }

122} catch (error) {

123 // A single-shot query() throws after yielding an error result,

124 // so the follow-up query below still runs.

125 console.error(`Session ended with an error: ${error}`);

120}126}

121 127 

122// Second query: continue: true resumes the most recent session128// Second query: continue: true resumes the most recent session


213Pass a session ID to `resume` to return to that specific session. The agent picks up with full context from wherever the session left off. Common reasons to resume:219Pass a session ID to `resume` to return to that specific session. The agent picks up with full context from wherever the session left off. Common reasons to resume:

214 220 

215* **Follow up on a completed task.** The agent already analyzed something; now you want it to act on that analysis without re-reading files.221* **Follow up on a completed task.** The agent already analyzed something; now you want it to act on that analysis without re-reading files.

216* **Recover from a limit.** The first run ended with `error_max_turns` or `error_max_budget_usd` (see [Handle the result](/en/agent-sdk/agent-loop#handle-the-result)); resume with a higher limit.222* **Recover from a limit.** The first run ended with `error_max_turns` or `error_max_budget_usd` (see [Handle the result](/en/agent-sdk/agent-loop#handle-the-result)); resume with a higher limit. In a single-shot `query()` call the SDK raises after yielding that error result, so catch the error before resuming.

217* **Restart your process.** You captured the ID before shutdown and want to restore the conversation.223* **Restart your process.** You captured the ID before shutdown and want to restore the conversation.

218 224 

219This example resumes the session from [Capture the session ID](#capture-the-session-id) with a follow-up prompt. Because you're resuming, the agent already has the prior analysis in context:225This example resumes the session from [Capture the session ID](#capture-the-session-id) with a follow-up prompt. Because you're resuming, the agent already has the prior analysis in context:


291 async def main():297 async def main():

292 # Fork: branch from session_id into a new session298 # Fork: branch from session_id into a new session

293 forked_id = None299 forked_id = None

300 try:

294 async for message in query(301 async for message in query(

295 prompt="Instead of JWT, outline how OAuth2 would work for the auth module",302 prompt="Instead of JWT, outline how OAuth2 would work for the auth module",

296 options=ClaudeAgentOptions(303 options=ClaudeAgentOptions(


303 forked_id = message.session_id # The fork's ID, distinct from session_id310 forked_id = message.session_id # The fork's ID, distinct from session_id

304 if message.subtype == "success":311 if message.subtype == "success":

305 print(message.result)312 print(message.result)

313 except Exception as error:

314 # A single-shot query() raises after yielding an error result. If the

315 # failure was an error result, forked_id was already captured by the

316 # loop above; connection or process failures yield no result message.

317 print(f"Session ended with an error: {error}")

306 318 

307 print(f"Forked session: {forked_id}")319 print(f"Forked session: {forked_id}")

308 320 

309 # Original session is untouched; resuming it continues the JWT thread321 # Original session is untouched; resuming it continues the JWT thread

322 try:

310 async for message in query(323 async for message in query(

311 prompt="Continue with the JWT approach",324 prompt="Continue with the JWT approach",

312 options=ClaudeAgentOptions(resume=session_id),325 options=ClaudeAgentOptions(resume=session_id),

313 ):326 ):

314 if isinstance(message, ResultMessage) and message.subtype == "success":327 if isinstance(message, ResultMessage) and message.subtype == "success":

315 print(message.result)328 print(message.result)

329 except Exception as error:

330 # A single-shot query() raises after yielding an error result.

331 print(f"Session ended with an error: {error}")

316 332 

317 333 

318 asyncio.run(main())334 asyncio.run(main())


326 // Fork: branch from sessionId into a new session342 // Fork: branch from sessionId into a new session

327 let forkedId: string | undefined;343 let forkedId: string | undefined;

328 344 

345 try {

329 for await (const message of query({346 for await (const message of query({

330 prompt: "Instead of JWT, outline how OAuth2 would work for the auth module",347 prompt: "Instead of JWT, outline how OAuth2 would work for the auth module",

331 options: {348 options: {


341 console.log(message.result);358 console.log(message.result);

342 }359 }

343 }360 }

361 } catch (error) {

362 // A single-shot query() throws after yielding an error result. If the

363 // failure was an error result, forkedId was already captured by the loop

364 // above; connection or process failures yield no result message.

365 console.error(`Session ended with an error: ${error}`);

366 }

344 367 

345 console.log(`Forked session: ${forkedId}`);368 console.log(`Forked session: ${forkedId}`);

346 369 

347 // Original session is untouched; resuming it continues the JWT thread370 // Original session is untouched; resuming it continues the JWT thread

371 try {

348 for await (const message of query({372 for await (const message of query({

349 prompt: "Continue with the JWT approach",373 prompt: "Continue with the JWT approach",

350 options: { resume: sessionId }374 options: { resume: sessionId }


353 console.log(message.result);377 console.log(message.result);

354 }378 }

355 }379 }

380 } catch (error) {

381 // A single-shot query() throws after yielding an error result.

382 console.error(`Session ended with an error: ${error}`);

383 }

356 ```384 ```

357</CodeGroup>385</CodeGroup>

358 386 

Details

250 import { query } from "@anthropic-ai/claude-agent-sdk";250 import { query } from "@anthropic-ai/claude-agent-sdk";

251 251 

252 // Simple one-shot query252 // Simple one-shot query

253 // query() throws after an error result, such as error_max_turns

254 try {

253 for await (const message of query({255 for await (const message of query({

254 prompt: "Explain the authentication flow",256 prompt: "Explain the authentication flow",

255 options: {257 options: {


261 console.log(message.result);263 console.log(message.result);

262 }264 }

263 }265 }

266 } catch (error) {

267 console.error(`Query failed: ${error}`);

268 }

264 269 

265 // Continue conversation with session management270 // Continue conversation with session management

271 try {

266 for await (const message of query({272 for await (const message of query({

267 prompt: "Now explain the authorization process",273 prompt: "Now explain the authorization process",

268 options: {274 options: {


274 console.log(message.result);280 console.log(message.result);

275 }281 }

276 }282 }

283 } catch (error) {

284 console.error(`Query failed: ${error}`);

285 }

277 ```286 ```

278 287 

279 ```python Python theme={null}288 ```python Python theme={null}


283 292 

284 async def single_message_example():293 async def single_message_example():

285 # Simple one-shot query using query() function294 # Simple one-shot query using query() function

295 # query() raises after an error result, such as error_max_turns

296 try:

286 async for message in query(297 async for message in query(

287 prompt="Explain the authentication flow",298 prompt="Explain the authentication flow",

288 options=ClaudeAgentOptions(max_turns=5, allowed_tools=["Read", "Grep"]),299 options=ClaudeAgentOptions(max_turns=5, allowed_tools=["Read", "Grep"]),

289 ):300 ):

290 if isinstance(message, ResultMessage):301 if isinstance(message, ResultMessage) and message.subtype == "success":

291 print(message.result)302 print(message.result)

303 # The SDK raises a plain Exception for error results, so match Exception here

304 except Exception as e:

305 print(f"Query failed: {e}")

292 306 

293 # Continue conversation with session management307 # Continue conversation with session management

308 try:

294 async for message in query(309 async for message in query(

295 prompt="Now explain the authorization process",310 prompt="Now explain the authorization process",

296 options=ClaudeAgentOptions(continue_conversation=True, max_turns=5),311 options=ClaudeAgentOptions(continue_conversation=True, max_turns=5),

297 ):312 ):

298 if isinstance(message, ResultMessage):313 if isinstance(message, ResultMessage) and message.subtype == "success":

299 print(message.result)314 print(message.result)

315 except Exception as e:

316 print(f"Query failed: {e}")

300 317 

301 318 

302 asyncio.run(single_message_example())319 asyncio.run(single_message_example())

Details

73 required: ["company_name"]73 required: ["company_name"]

74 };74 };

75 75 

76 try {

76 for await (const message of query({77 for await (const message of query({

77 prompt: "Research Anthropic and provide key company information",78 prompt: "Research Anthropic and provide key company information",

78 options: {79 options: {


88 // { company_name: "Anthropic", founded_year: 2021, headquarters: "San Francisco, CA" }89 // { company_name: "Anthropic", founded_year: 2021, headquarters: "San Francisco, CA" }

89 }90 }

90 }91 }

92 } catch (error) {

93 // A single-shot query() throws after yielding an error result, such as

94 // error_max_structured_output_retries; see the Error handling section.

95 console.error(`Session ended with an error: ${error}`);

96 }

91 ```97 ```

92 98 

93 ```python Python theme={null}99 ```python Python theme={null}


107 113 

108 114 

109 async def main():115 async def main():

116 try:

110 async for message in query(117 async for message in query(

111 prompt="Research Anthropic and provide key company information",118 prompt="Research Anthropic and provide key company information",

112 options=ClaudeAgentOptions(119 options=ClaudeAgentOptions(


117 if isinstance(message, ResultMessage) and message.structured_output:124 if isinstance(message, ResultMessage) and message.structured_output:

118 print(message.structured_output)125 print(message.structured_output)

119 # {'company_name': 'Anthropic', 'founded_year': 2021, 'headquarters': 'San Francisco, CA'}126 # {'company_name': 'Anthropic', 'founded_year': 2021, 'headquarters': 'San Francisco, CA'}

127 except Exception as error:

128 # A single-shot query() raises after yielding an error result, such as

129 # error_max_structured_output_retries; see the Error handling section.

130 print(f"Session ended with an error: {error}")

120 131 

121 132 

122 asyncio.run(main())133 asyncio.run(main())


154 const schema = z.toJSONSchema(FeaturePlan);165 const schema = z.toJSONSchema(FeaturePlan);

155 166 

156 // Use in query167 // Use in query

168 try {

157 for await (const message of query({169 for await (const message of query({

158 prompt:170 prompt:

159 "Plan how to add dark mode support to a React app. Break it into implementation steps.",171 "Plan how to add dark mode support to a React app. Break it into implementation steps.",


177 }189 }

178 }190 }

179 }191 }

192 } catch (error) {

193 // A single-shot query() throws after yielding an error result, such as

194 // error_max_structured_output_retries; see the Error handling section.

195 console.error(`Session ended with an error: ${error}`);

196 }

180 ```197 ```

181 198 

182 ```python Python theme={null}199 ```python Python theme={null}


199 216 

200 217 

201 async def main():218 async def main():

219 try:

202 async for message in query(220 async for message in query(

203 prompt="Plan how to add dark mode support to a React app. Break it into implementation steps.",221 prompt="Plan how to add dark mode support to a React app. Break it into implementation steps.",

204 options=ClaudeAgentOptions(222 options=ClaudeAgentOptions(


217 print(235 print(

218 f"{step.step_number}. [{step.estimated_complexity}] {step.description}"236 f"{step.step_number}. [{step.estimated_complexity}] {step.description}"

219 )237 )

238 except Exception as error:

239 # A single-shot query() raises after yielding an error result, such as

240 # error_max_structured_output_retries; see the Error handling section.

241 print(f"Session ended with an error: {error}")

220 242 

221 243 

222 asyncio.run(main())244 asyncio.run(main())


277 };299 };

278 300 

279 // Agent uses Grep to find TODOs, Bash to get git blame info301 // Agent uses Grep to find TODOs, Bash to get git blame info

302 try {

280 for await (const message of query({303 for await (const message of query({

281 prompt: "Find all TODO comments in this codebase and identify who added them",304 prompt: "Find all TODO comments in this codebase and identify who added them",

282 options: {305 options: {


297 });320 });

298 }321 }

299 }322 }

323 } catch (error) {

324 // A single-shot query() throws after yielding an error result, such as

325 // error_max_structured_output_retries; see the Error handling section.

326 console.error(`Session ended with an error: ${error}`);

327 }

300 ```328 ```

301 329 

302 ```python Python theme={null}330 ```python Python theme={null}


329 357 

330 async def main():358 async def main():

331 # Agent uses Grep to find TODOs, Bash to get git blame info359 # Agent uses Grep to find TODOs, Bash to get git blame info

360 try:

332 async for message in query(361 async for message in query(

333 prompt="Find all TODO comments in this codebase and identify who added them",362 prompt="Find all TODO comments in this codebase and identify who added them",

334 options=ClaudeAgentOptions(363 options=ClaudeAgentOptions(


342 print(f"{todo['file']}:{todo['line']} - {todo['text']}")371 print(f"{todo['file']}:{todo['line']} - {todo['text']}")

343 if "author" in todo:372 if "author" in todo:

344 print(f" Added by {todo['author']} on {todo['date']}")373 print(f" Added by {todo['author']} on {todo['date']}")

374 except Exception as error:

375 # A single-shot query() raises after yielding an error result, such as

376 # error_max_structured_output_retries; see the Error handling section.

377 print(f"Session ended with an error: {error}")

345 378 

346 379 

347 asyncio.run(main())380 asyncio.run(main())

Details

547* [Amazon Bedrock pricing](https://aws.amazon.com/bedrock/pricing/)547* [Amazon Bedrock pricing](https://aws.amazon.com/bedrock/pricing/)

548* [Amazon Bedrock inference profiles](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html)548* [Amazon Bedrock inference profiles](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html)

549* [Amazon Bedrock token burndown and quotas](https://docs.aws.amazon.com/bedrock/latest/userguide/quotas-token-burndown.html)549* [Amazon Bedrock token burndown and quotas](https://docs.aws.amazon.com/bedrock/latest/userguide/quotas-token-burndown.html)

550* [Claude Code on Amazon Bedrock: Quick Setup Guide](https://community.aws/content/2tXkZKrZzlrlu0KfH8gST5Dkppq/claude-code-on-amazon-bedrock-quick-setup-guide)550* [Claude Code on Amazon Bedrock: Quick Setup Guide](https://builder.aws.com/content/2tXkZKrZzlrlu0KfH8gST5Dkppq/claude-code-on-amazon-bedrock-quick-setup-guide)

551* [Claude Code Monitoring Implementation (Amazon Bedrock)](https://github.com/aws-solutions-library-samples/guidance-for-claude-code-with-amazon-bedrock/blob/main/assets/docs/MONITORING.md)551* [Claude Code Monitoring Implementation (Amazon Bedrock)](https://github.com/aws-solutions-library-samples/guidance-for-claude-code-with-amazon-bedrock/blob/main/assets/docs/MONITORING.md)

Details

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

10 10 

11<Note>11<Note>

12 Auto mode is available to all users on every provider, including the Anthropic API, Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, and signed-in [Claude apps gateway](/en/claude-apps-gateway) sessions. If Claude Code reports auto mode as unavailable for your account, check the [full requirements](/en/permission-modes#eliminate-prompts-with-auto-mode), which also cover the supported models and Owner enablement on Team and Enterprise plans. {/* min-version: 2.1.207 */}In v2.1.158 through v2.1.206, auto mode on Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, and Claude apps gateway sessions required setting `CLAUDE_CODE_ENABLE_AUTO_MODE=1`; v2.1.207 removed the requirement.12 Auto mode is available to all users on every provider, including the Anthropic API, [Claude Platform on AWS](/en/claude-platform-on-aws), Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, and signed-in [Claude apps gateway](/en/claude-apps-gateway) sessions. If Claude Code reports auto mode as unavailable for your account, check the [full requirements](/en/permission-modes#eliminate-prompts-with-auto-mode), which also cover the supported models and Owner enablement on Team and Enterprise plans. {/* min-version: 2.1.207 */}In v2.1.158 through v2.1.206, auto mode on Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, and Claude apps gateway sessions required setting `CLAUDE_CODE_ENABLE_AUTO_MODE=1`; v2.1.207 removed the requirement.

13</Note>13</Note>

14 14 

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

Details

189 189 

190## Server options190## Server options

191 191 

192A channel sets these options in the [`Server`](https://modelcontextprotocol.io/docs/concepts/servers) constructor. The `instructions` and `capabilities.tools` fields are [standard MCP](https://modelcontextprotocol.io/docs/concepts/servers); `capabilities.experimental['claude/channel']` and `capabilities.experimental['claude/channel/permission']` are the channel-specific additions:192A channel sets these options in the [`Server`](https://modelcontextprotocol.io/docs/learn/server-concepts) constructor. The `instructions` and `capabilities.tools` fields are [standard MCP](https://modelcontextprotocol.io/docs/learn/server-concepts); `capabilities.experimental['claude/channel']` and `capabilities.experimental['claude/channel/permission']` are the channel-specific additions:

193 193 

194| Field | Type | Description |194| Field | Type | Description |

195| :------------------------------------------------------- | :------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |195| :------------------------------------------------------- | :------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

Details

19* Every user prompt creates a new checkpoint19* Every user prompt creates a new checkpoint

20* Claude Code keeps file snapshots for the 100 most recent checkpoints in a session. Discarding an older checkpoint deletes the snapshot files that no remaining checkpoint references, except each file's first snapshot, which the VS Code extension uses as the baseline for its session diffs. {/* min-version: 2.1.208 */}Before v2.1.208, those superseded snapshot files stayed on disk until the session was cleaned up.20* Claude Code keeps file snapshots for the 100 most recent checkpoints in a session. Discarding an older checkpoint deletes the snapshot files that no remaining checkpoint references, except each file's first snapshot, which the VS Code extension uses as the baseline for its session diffs. {/* min-version: 2.1.208 */}Before v2.1.208, those superseded snapshot files stayed on disk until the session was cleaned up.

21* Checkpoints are saved with the conversation, so a resumed session can still `/rewind` to them21* Checkpoints are saved with the conversation, so a resumed session can still `/rewind` to them

22* Automatically cleaned up along with sessions after 30 days (configurable)22* Automatically cleaned up along with sessions after 30 days, configurable via [`cleanupPeriodDays`](/en/settings#available-settings)

23 23 

24### Rewind and summarize24### Rewind and summarize

25 25 


38* **Summarize up to here**: compress the conversation before this point into a summary, keeping later messages intact38* **Summarize up to here**: compress the conversation before this point into a summary, keeping later messages intact

39* **Never mind**: return to the message list without making changes39* **Never mind**: return to the message list without making changes

40 40 

41The two code restore options appear only when the selected checkpoint has tracked file changes to revert. If no file edits were captured after that point, the menu offers only **Restore conversation**, the summarize options, and **Never mind**.

42 

41After restoring the conversation or choosing Summarize from here, the original prompt from the selected message is restored into the input field so you can re-send or edit it.43After restoring the conversation or choosing Summarize from here, the original prompt from the selected message is restored into the input field so you can re-send or edit it.

42 44 

43Choosing Summarize up to here leaves you at the end of the conversation with the input empty.45Choosing Summarize up to here leaves you at the end of the conversation with the input empty. With either summarize option, a **Summarized conversation** marker appears in the conversation where the compressed messages were.

44 46 

45#### Rewind past a cleared conversation47#### Rewind past a cleared conversation

46 48 


53* **Summarize from here**: messages before the selected message stay intact. The selected message and everything after it are replaced with a summary. Use this to discard a side discussion while keeping early context in full detail.55* **Summarize from here**: messages before the selected message stay intact. The selected message and everything after it are replaced with a summary. Use this to discard a side discussion while keeping early context in full detail.

54* **Summarize up to here**: messages before the selected message are replaced with a summary. The selected message and everything after it stay intact, and you remain at the end of the conversation. Use this to compress early setup discussion while keeping recent work in full detail.56* **Summarize up to here**: messages before the selected message are replaced with a summary. The selected message and everything after it stay intact, and you remain at the end of the conversation. Use this to compress early setup discussion while keeping recent work in full detail.

55 57 

56In both cases the original messages are preserved in the session transcript, so Claude can reference the details if needed. You can type optional instructions to guide what the summary focuses on. This is similar to `/compact`, but targeted: instead of summarizing the entire conversation, you choose which side of the selected message to compress.58In both cases the original messages are preserved in the session transcript, so Claude can reference the details if needed. To guide what the summary focuses on, highlight a **Summarize** option with the arrow keys and type instructions inline where the row reads **add context (optional)**, then press `Enter` to summarize; selecting the option by its number key summarizes immediately without instructions. This is similar to `/compact`, but targeted: instead of summarizing the entire conversation, you choose which side of the selected message to compress.

57 59 

58<Note>60<Note>

59 Summarize keeps you in the same session and compresses context. If you want to branch off and try a different approach while preserving the original session intact, use [fork](/en/sessions#branch-a-session) instead (`claude --continue --fork-session`).61 Summarize keeps you in the same session and compresses context. If you want to branch off and try a different approach while preserving the original session intact, use [fork](/en/sessions#branch-a-session) instead (`claude --continue --fork-session`).

Details

62 oneLiner: 'Project-scoped MCP servers, shared with your team',62 oneLiner: 'Project-scoped MCP servers, shared with your team',

63 when: <>Servers connect when the session begins. Tool schemas are deferred by default and load on demand via <A href="/en/mcp#scale-with-mcp-tool-search">tool search</A></>,63 when: <>Servers connect when the session begins. Tool schemas are deferred by default and load on demand via <A href="/en/mcp#scale-with-mcp-tool-search">tool search</A></>,

64 description: <>Configures Model Context Protocol (MCP) servers that give Claude access to external tools: databases, APIs, browsers, and more. This file holds the project-scoped servers your whole team uses. Personal servers you want to keep to yourself go in <C>~/.claude.json</C> instead.</>,64 description: <>Configures Model Context Protocol (MCP) servers that give Claude access to external tools: databases, APIs, browsers, and more. This file holds the project-scoped servers your whole team uses. Personal servers you want to keep to yourself go in <C>~/.claude.json</C> instead.</>,

65 tips: [<>Use environment variable references for secrets: <C>{'${GITHUB_TOKEN}'}</C></>, <>Lives at the project root, not inside <C>.claude/</C></>, <>For servers only you need, run <C>claude mcp add --scope user</C>. This writes to <C>~/.claude.json</C> instead of <C>.mcp.json</C></>],65 tips: [<>Use environment variable references for secrets: <C>{'${NOTION_TOKEN}'}</C></>, <>Lives at the project root, not inside <C>.claude/</C></>, <>For servers only you need, run <C>claude mcp add --scope user</C>. This writes to <C>~/.claude.json</C> instead of <C>.mcp.json</C></>],

66 exampleIntro: <>This example configures the GitHub MCP server so Claude can read issues and open pull requests. The <C>{'${GITHUB_TOKEN}'}</C> reference is read from your shell environment when Claude Code starts the server, so the token never lands in the file.</>,66 exampleIntro: <>This example configures the Notion MCP server so Claude can read and update pages in your workspace. The <C>{'${NOTION_TOKEN}'}</C> reference is read from your shell environment when Claude Code starts the server, so the token never lands in the file.</>,

67 example: `{67 example: `{

68 "mcpServers": {68 "mcpServers": {

69 "github": {69 "notion": {

70 "command": "npx",70 "command": "npx",

71 "args": ["-y", "@modelcontextprotocol/server-github"],71 "args": ["-y", "@notionhq/notion-mcp-server"],

72 "env": {72 "env": {

73 "GITHUB_TOKEN": "\${GITHUB_TOKEN}"73 "NOTION_TOKEN": "\${NOTION_TOKEN}"

74 }74 }

75 }75 }

76 }76 }

env-vars.md +1 −1

Details

294| `CLAUDE_CODE_RETRY_WATCHDOG` | {/* min-version: 2.1.186 */}Set to `1` for unattended sessions such as eval harnesses, CI jobs, or remote workers. Retries `429` and `529` capacity errors indefinitely instead of failing after `CLAUDE_CODE_MAX_RETRIES` attempts. The watchdog backs off up to 5 minutes between attempts, or until the limit resets when the response carries a rate-limit reset time, so a session that hits a usage limit waits out the remaining window. {/* min-version: 2.1.199 */}As of v2.1.199 it also raises the default retry count for other transient errors, such as server errors, timeouts, and dropped connections, to 300, roughly three hours of backoff, and removes the cap of 15 on `CLAUDE_CODE_MAX_RETRIES` if you set that variable explicitly. Requires Claude Code v2.1.186 or later |294| `CLAUDE_CODE_RETRY_WATCHDOG` | {/* min-version: 2.1.186 */}Set to `1` for unattended sessions such as eval harnesses, CI jobs, or remote workers. Retries `429` and `529` capacity errors indefinitely instead of failing after `CLAUDE_CODE_MAX_RETRIES` attempts. The watchdog backs off up to 5 minutes between attempts, or until the limit resets when the response carries a rate-limit reset time, so a session that hits a usage limit waits out the remaining window. {/* min-version: 2.1.199 */}As of v2.1.199 it also raises the default retry count for other transient errors, such as server errors, timeouts, and dropped connections, to 300, roughly three hours of backoff, and removes the cap of 15 on `CLAUDE_CODE_MAX_RETRIES` if you set that variable explicitly. Requires Claude Code v2.1.186 or later |

295| `CLAUDE_CODE_SAFE_MODE` | Set to `1` to start in safe mode: CLAUDE.md, skills, plugins, hooks, MCP servers, custom commands and agents, output styles, workflows, custom themes, custom keybindings, status line and file-suggestion commands, LSP servers, and auto-memory do not load, for troubleshooting a broken configuration. Managed settings policy still applies, including policy-configured hooks, status line, and file-suggestion commands; managed plugins, managed skills, managed CLAUDE.md, and policy-configured MCP servers do not. Equivalent to passing [`--safe-mode`](/en/cli-reference#cli-flags). Directly spawned child processes inherit the variable |295| `CLAUDE_CODE_SAFE_MODE` | Set to `1` to start in safe mode: CLAUDE.md, skills, plugins, hooks, MCP servers, custom commands and agents, output styles, workflows, custom themes, custom keybindings, status line and file-suggestion commands, LSP servers, and auto-memory do not load, for troubleshooting a broken configuration. Managed settings policy still applies, including policy-configured hooks, status line, and file-suggestion commands; managed plugins, managed skills, managed CLAUDE.md, and policy-configured MCP servers do not. Equivalent to passing [`--safe-mode`](/en/cli-reference#cli-flags). Directly spawned child processes inherit the variable |

296| `CLAUDE_CODE_SCRIPT_CAPS` | JSON object limiting how many times specific scripts may be invoked per session when `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB` is set. Keys are substrings matched against the command text; values are integer call limits. For example, `{"deploy.sh": 2}` allows `deploy.sh` to be called at most twice. Matching is substring-based so shell-expansion tricks like `./scripts/deploy.sh $(evil)` still count against the cap. Runtime fan-out via `xargs` or `find -exec` is not detected; this is a defense-in-depth control |296| `CLAUDE_CODE_SCRIPT_CAPS` | JSON object limiting how many times specific scripts may be invoked per session when `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB` is set. Keys are substrings matched against the command text; values are integer call limits. For example, `{"deploy.sh": 2}` allows `deploy.sh` to be called at most twice. Matching is substring-based so shell-expansion tricks like `./scripts/deploy.sh $(evil)` still count against the cap. Runtime fan-out via `xargs` or `find -exec` is not detected; this is a defense-in-depth control |

297| `CLAUDE_CODE_SCROLL_SPEED` | Set the mouse wheel scroll multiplier in [fullscreen rendering](/en/fullscreen#mouse-wheel-scrolling). Accepts values from 1 to 20, and fractional values below 1 such as `0.5` to slow accelerated trackpad and wheel scrolling in terminals that already amplify wheel events. Set to `3` to match `vim` if your terminal sends one wheel event per notch without amplification. Ignored in the JetBrains IDE terminal, where Claude Code uses its own scroll handling |297| `CLAUDE_CODE_SCROLL_SPEED` | Set the mouse wheel scroll multiplier in [fullscreen rendering](/en/fullscreen#mouse-wheel-scrolling). Accepts any positive value up to 20, including fractional values below 1 such as `0.5` to slow accelerated trackpad and wheel scrolling in terminals that already amplify wheel events. Set to `3` to match `vim` if your terminal sends one wheel event per notch without amplification. Ignored in the JetBrains IDE terminal, where Claude Code uses its own scroll handling |

298| `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS` | Override the time budget in milliseconds for [SessionEnd](/en/hooks#sessionend) hooks. Applies to session exit, `/clear`, and switching sessions via interactive `/resume`. By default the budget is 1.5 seconds, automatically raised to the highest per-hook `timeout` configured in settings files, up to 60 seconds. Timeouts on plugin-provided hooks do not raise the budget |298| `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS` | Override the time budget in milliseconds for [SessionEnd](/en/hooks#sessionend) hooks. Applies to session exit, `/clear`, and switching sessions via interactive `/resume`. By default the budget is 1.5 seconds, automatically raised to the highest per-hook `timeout` configured in settings files, up to 60 seconds. Timeouts on plugin-provided hooks do not raise the budget |

299| `CLAUDE_CODE_SESSION_ID` | Set automatically to the current session ID in Bash and PowerShell tool subprocesses, [hook command](/en/hooks) subprocesses, and stdio [MCP server](/en/mcp) subprocesses. For Bash, PowerShell, and hooks this matches the `session_id` field in the hook JSON input and is updated on `/clear`. An MCP server subprocess retains the ID it was spawned with. On `--resume <session-id>` it receives the resumed ID, matching hooks and Bash. On `--continue` or `--resume` without an explicit ID it may receive the initial startup ID instead. Use to correlate scripts and external tools with the Claude Code session that launched them |299| `CLAUDE_CODE_SESSION_ID` | Set automatically to the current session ID in Bash and PowerShell tool subprocesses, [hook command](/en/hooks) subprocesses, and stdio [MCP server](/en/mcp) subprocesses. For Bash, PowerShell, and hooks this matches the `session_id` field in the hook JSON input and is updated on `/clear`. An MCP server subprocess retains the ID it was spawned with. On `--resume <session-id>` it receives the resumed ID, matching hooks and Bash. On `--continue` or `--resume` without an explicit ID it may receive the initial startup ID instead. Use to correlate scripts and external tools with the Claude Code session that launched them |

300| `CLAUDE_CODE_SHELL` | Set the shell Claude Code uses to run Bash tool commands. Accepts a path to a `bash` or `zsh` binary, for example `/opt/homebrew/bin/bash`. Other shells such as `fish` are not supported. If the value is not a working `bash` or `zsh` path, Claude Code ignores it and falls back to auto-detection. Auto-detection uses your `$SHELL` when it points to `bash` or `zsh`, otherwise it picks the first working `zsh` then `bash` found on your `PATH` and standard install locations |300| `CLAUDE_CODE_SHELL` | Set the shell Claude Code uses to run Bash tool commands. Accepts a path to a `bash` or `zsh` binary, for example `/opt/homebrew/bin/bash`. Other shells such as `fish` are not supported. If the value is not a working `bash` or `zsh` path, Claude Code ignores it and falls back to auto-detection. Auto-detection uses your `$SHELL` when it points to `bash` or `zsh`, otherwise it picks the first working `zsh` then `bash` found on your `PATH` and standard install locations |

fullscreen.md +5 −4

Details

108export CLAUDE_CODE_SCROLL_SPEED=3108export CLAUDE_CODE_SCROLL_SPEED=3

109```109```

110 110 

111A value of `3` matches the default in `vim` and similar applications. The setting accepts values from 1 to 20, and fractional values below 1 such as `0.5` to slow accelerated trackpad and wheel scrolling in terminals that already amplify wheel events.111A value of `3` matches the default in `vim` and similar applications. The setting accepts any positive value up to 20, including fractional values below 1 such as `0.25` to slow accelerated trackpad and wheel scrolling in terminals that already amplify wheel events.

112 112 

113To adjust scroll speed interactively, run `/scroll-speed`. The dialog shows a ruler you can scroll while it is open so you can feel the change immediately. Press `←` and `→` to adjust, `r` to reset to the auto-detected default, and `Enter` to save.113To adjust scroll speed interactively, run `/scroll-speed`. The dialog shows a ruler you can scroll while it is open so you can feel the change immediately. Press `←` and `→` to adjust the speed, `r` to reset to the auto-detected default, and `Enter` to save. The dialog steps in whole numbers up to 10, and on terminals that support finer control it also offers quarter steps down to 0.25. {/* min-version: 2.1.172 */}Quarter steps require Claude Code v2.1.172 or later.

114 114 

115The command writes the same value the `CLAUDE_CODE_SCROLL_SPEED` environment variable sets, persisted to `~/.claude/settings.json`. The command isn't available in the JetBrains IDE terminal.115The command writes the same value the `CLAUDE_CODE_SCROLL_SPEED` environment variable sets, persisted to `~/.claude/settings.json`. The dialog's maximum is 10: if you set a higher value through the environment variable, the dialog shows 10, and saving from the dialog persists 10. The command isn't available in the JetBrains IDE terminal.

116 116 

117Separately from the base speed, Claude Code accelerates the scroll rate when you spin the wheel quickly, so a fast spin covers more distance than the same number of slow notches. {/* min-version: 2.1.174 */}To turn acceleration off and keep a constant rate per notch, set `wheelScrollAccelerationEnabled` to `false` in [`settings.json`](/en/settings#available-settings). This setting requires Claude Code v2.1.174 or later.117Separately from the base speed, Claude Code accelerates the scroll rate when you spin the wheel quickly, so a fast spin covers more distance than the same number of slow notches. {/* min-version: 2.1.174 */}To turn acceleration off and keep a constant rate per notch, set `wheelScrollAccelerationEnabled` to `false` in [`settings.json`](/en/settings#available-settings). This setting requires Claude Code v2.1.174 or later.

118 118 


136| `n` / `N` | Jump to next or previous match. Works after you've closed the search bar |136| `n` / `N` | Jump to next or previous match. Works after you've closed the search bar |

137| `j` / `k` or `↑` / `↓` | Scroll one line |137| `j` / `k` or `↑` / `↓` | Scroll one line |

138| `g` / `G` or `Home` / `End` | Jump to top or bottom |138| `g` / `G` or `Home` / `End` | Jump to top or bottom |

139| `{` / `}` | Jump to the previous or next prompt |

139| `Ctrl+u` / `Ctrl+d` | Scroll half a page |140| `Ctrl+u` / `Ctrl+d` | Scroll half a page |

140| `Ctrl+b` / `Ctrl+f` or `Space` / `b` | Scroll a full page |141| `Ctrl+b` / `Ctrl+f` or `Space` / `b` | Scroll a full page |

141| `Ctrl+o`, `Esc`, or `q` | Exit transcript mode and return to the prompt |142| `Ctrl+o`, `Esc`, or `q` | Exit transcript mode and return to the prompt |


235 236 

236If you encounter a problem, run `/feedback` inside Claude Code to report it, or open an issue on the [claude-code GitHub repo](https://github.com/anthropics/claude-code/issues). Include your terminal emulator name and version.237If you encounter a problem, run `/feedback` inside Claude Code to report it, or open an issue on the [claude-code GitHub repo](https://github.com/anthropics/claude-code/issues). Include your terminal emulator name and version.

237 238 

238To turn fullscreen rendering off, run `/tui default`, or unset `CLAUDE_CODE_NO_FLICKER` if you enabled it that way. To force the classic renderer regardless of the saved `tui` setting, set `CLAUDE_CODE_DISABLE_ALTERNATE_SCREEN=1`. The classic renderer keeps the conversation in your terminal's native scrollback so `Cmd+f` and tmux copy mode work as usual.239To turn fullscreen rendering off, run `/tui default`, or unset `CLAUDE_CODE_NO_FLICKER` if you enabled it that way. When you switch back with `/tui default`, Claude Code may first show an optional feedback prompt asking what made you switch. Type a reason and press `Enter` to send it, or press `Esc` to skip. The CLI relaunches into the classic renderer either way. To force the classic renderer regardless of the saved `tui` setting, set `CLAUDE_CODE_DISABLE_ALTERNATE_SCREEN=1`. The classic renderer keeps the conversation in your terminal's native scrollback so `Cmd+f` and tmux copy mode work as usual.

239 240 

240Background sessions opened from [agent view](/en/agent-view) or `claude attach` always use fullscreen rendering. The attaching terminal enters the alternate screen buffer to show the session, and the classic renderer has no scrollback or mouse handling there, so the `tui` setting and `CLAUDE_CODE_DISABLE_ALTERNATE_SCREEN` don't apply to them.241Background sessions opened from [agent view](/en/agent-view) or `claude attach` always use fullscreen rendering. The attaching terminal enters the alternate screen buffer to show the session, and the classic renderer has no scrollback or mouse handling there, so the `tui` setting and `CLAUDE_CODE_DISABLE_ALTERNATE_SCREEN` don't apply to them.

headless.md +2 −2

Details

127If the value isn't a valid JSON Schema, `claude` exits with `Error: --json-schema is not a valid JSON Schema` followed by the validator's diagnostic. Claude Code accepts schemas that use the `format` keyword, such as `"format": "email"`, but treats `format` as an annotation and doesn't enforce it. Before v2.1.205, Claude Code silently ignored an invalid schema and returned unstructured text, and treated any schema containing `format` as invalid.127If the value isn't a valid JSON Schema, `claude` exits with `Error: --json-schema is not a valid JSON Schema` followed by the validator's diagnostic. Claude Code accepts schemas that use the `format` keyword, such as `"format": "email"`, but treats `format` as an annotation and doesn't enforce it. Before v2.1.205, Claude Code silently ignored an invalid schema and returned unstructured text, and treated any schema containing `format` as invalid.

128 128 

129<Tip>129<Tip>

130 Use a tool like [jq](https://jqlang.github.io/jq/) to parse the response and extract specific fields:130 Use a tool like [jq](https://jqlang.org/) to parse the response and extract specific fields:

131 131 

132 ```bash theme={null}132 ```bash theme={null}

133 # Extract the text result133 # Extract the text result


155 155 

156By default, Claude Code emits only subagent `tool_use` and `tool_result` blocks. {/* min-version: 2.1.211 */}Pass [`--forward-subagent-text`](/en/cli-reference#cli-flags) or set [`CLAUDE_CODE_FORWARD_SUBAGENT_TEXT`](/en/env-vars) to also emit subagent text and thinking blocks, so you can reconstruct each subagent's transcript. This requires Claude Code v2.1.211 or later.156By default, Claude Code emits only subagent `tool_use` and `tool_result` blocks. {/* min-version: 2.1.211 */}Pass [`--forward-subagent-text`](/en/cli-reference#cli-flags) or set [`CLAUDE_CODE_FORWARD_SUBAGENT_TEXT`](/en/env-vars) to also emit subagent text and thinking blocks, so you can reconstruct each subagent's transcript. This requires Claude Code v2.1.211 or later.

157 157 

158The following example uses [jq](https://jqlang.github.io/jq/) to filter for text deltas and display just the streaming text. The `-r` flag outputs raw strings (no quotes) and `-j` joins without newlines so tokens stream continuously:158The following example uses [jq](https://jqlang.org/) to filter for text deltas and display just the streaming text. The `-r` flag outputs raw strings (no quotes) and `-j` joins without newlines so tokens stream continuously:

159 159 

160```bash theme={null}160```bash theme={null}

161claude -p "Write a poem" --output-format stream-json --verbose --include-partial-messages | \161claude -p "Write a poem" --output-format stream-json --verbose --include-partial-messages | \

hooks.md +1 −1

Details

1579If the deferred tool is no longer available when you resume, the process exits with `stop_reason: "tool_deferred_unavailable"` and `is_error: true` before the hook fires. This happens when an MCP server that provided the tool is not connected for the resumed session. The `deferred_tool_use` payload is still included so you can identify which tool went missing.1579If the deferred tool is no longer available when you resume, the process exits with `stop_reason: "tool_deferred_unavailable"` and `is_error: true` before the hook fires. This happens when an MCP server that provided the tool is not connected for the resumed session. The `deferred_tool_use` payload is still included so you can identify which tool went missing.

1580 1580 

1581<Note>1581<Note>

1582 `--resume` restores the permission mode that was active when the tool was deferred, so you don't need to pass `--permission-mode` again. The exceptions are `plan` and `bypassPermissions`, which are never carried over. Passing `--permission-mode` explicitly on resume overrides the restored value.1582 `--resume` restores the permission mode that was active when the tool was deferred, so you don't need to pass `--permission-mode` again. The exceptions are `plan` and `bypassPermissions`, which are never carried over, and `auto`, which is restored only when your account still meets the [auto mode requirements](/en/permission-modes#eliminate-prompts-with-auto-mode). Passing `--permission-mode` explicitly on resume overrides the restored value.

1583</Note>1583</Note>

1584 1584 

1585### PermissionRequest1585### PermissionRequest

hooks-guide.md +2 −2

Details

186 186 

187Automatically run [Prettier](https://prettier.io/) on every file Claude edits, so formatting stays consistent without manual intervention.187Automatically run [Prettier](https://prettier.io/) on every file Claude edits, so formatting stays consistent without manual intervention.

188 188 

189This hook uses the `PostToolUse` event with an `Edit|Write` matcher, so it runs only after file-editing tools. The command extracts the edited file path with [`jq`](https://jqlang.github.io/jq/) and passes it to Prettier. Add this to `.claude/settings.json` in your project root:189This hook uses the `PostToolUse` event with an `Edit|Write` matcher, so it runs only after file-editing tools. The command extracts the edited file path with [`jq`](https://jqlang.org/) and passes it to Prettier. Add this to `.claude/settings.json` in your project root:

190 190 

191```json theme={null}191```json theme={null}

192{192{


209On Claude Code v2.1.191 or later you can also write the matcher as `Edit,Write`, since `|` and `,` are interchangeable list separators for tool-name matchers on those versions.209On Claude Code v2.1.191 or later you can also write the matcher as `Edit,Write`, since `|` and `,` are interchangeable list separators for tool-name matchers on those versions.

210 210 

211<Note>211<Note>

212 The Bash examples on this page use `jq` for JSON parsing. Install it with `brew install jq` on macOS, `apt-get install jq` on Debian and Ubuntu, or see [`jq` downloads](https://jqlang.github.io/jq/download/).212 The Bash examples on this page use `jq` for JSON parsing. Install it with `brew install jq` on macOS, `apt-get install jq` on Debian and Ubuntu, or see [`jq` downloads](https://jqlang.org/download/).

213</Note>213</Note>

214 214 

215### Block edits to protected files215### Block edits to protected files

Details

11<Note>11<Note>

12 Keyboard shortcuts may vary by platform and terminal. In [fullscreen rendering](/en/fullscreen), press `?` in the transcript viewer to see available shortcuts there.12 Keyboard shortcuts may vary by platform and terminal. In [fullscreen rendering](/en/fullscreen), press `?` in the transcript viewer to see available shortcuts there.

13 13 

14 **macOS users**: Option/Alt key shortcuts (`Alt+B`, `Alt+F`, `Alt+Y`, `Alt+M`, `Alt+P`) require configuring Option as Meta in your terminal:14 **macOS users**: Option/Alt key shortcuts (`Alt+B`, `Alt+F`, `Alt+Y`, `Alt+P`) require configuring Option as Meta in your terminal:

15 15 

16 * **iTerm2**: Settings → Profiles → Keys → General → set Left/Right Option key to "Esc+"16 * **iTerm2**: Settings → Profiles → Keys → General → set Left/Right Option key to "Esc+"

17 * **Apple Terminal**: Settings → Profiles → Keyboard → check "Use Option as Meta Key"17 * **Apple Terminal**: Settings → Profiles → Keyboard → check "Use Option as Meta Key"


23### General controls23### General controls

24 24 

25| Shortcut | Description | Context |25| Shortcut | Description | Context |

26| :-------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |26| :------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

27| `Ctrl+C` | Interrupt, or clear input | Interrupts a running operation. If nothing is running, the first press clears the prompt input and a second press exits Claude Code |27| `Ctrl+C` | Interrupt, or clear input | Interrupts a running operation. If nothing is running, the first press clears the prompt input and a second press exits Claude Code |

28| `Ctrl+X Ctrl+K` | Stop all running [background subagents](/en/sub-agents#run-subagents-in-foreground-or-background) in this session. Press twice within 3 seconds to confirm | Subagent control |28| `Ctrl+X Ctrl+K` | Stop all running [background subagents](/en/sub-agents#run-subagents-in-foreground-or-background) in this session. Press twice within 3 seconds to confirm | Subagent control |

29| `Ctrl+D` | Exit Claude Code session | The first press shows a confirmation hint and a second press within 800ms exits. When the prompt has text, `Ctrl+D` deletes the character after the cursor instead |29| `Ctrl+D` | Exit Claude Code session | The first press shows a confirmation hint and a second press within 800ms exits. When the prompt has text, `Ctrl+D` deletes the character after the cursor instead |


34| `Ctrl+V` or `Cmd+V` (iTerm2) or `Alt+V` (Windows and WSL) | Paste image from clipboard | Inserts an `[Image #N]` chip at the cursor so you can reference it positionally in your prompt. On WSL, both `Ctrl+V` and `Alt+V` are bound; use `Alt+V` if your terminal intercepts `Ctrl+V` |34| `Ctrl+V` or `Cmd+V` (iTerm2) or `Alt+V` (Windows and WSL) | Paste image from clipboard | Inserts an `[Image #N]` chip at the cursor so you can reference it positionally in your prompt. On WSL, both `Ctrl+V` and `Alt+V` are bound; use `Alt+V` if your terminal intercepts `Ctrl+V` |

35| `Ctrl+B` | Background running tasks | Backgrounds Bash commands and agents. Tmux users press twice |35| `Ctrl+B` | Background running tasks | Backgrounds Bash commands and agents. Tmux users press twice |

36| `Ctrl+T` | Toggle Claude's task checklist | Show or hide [Claude's to-do checklist](#task-list) in the status area. This is not the background-task view; use [`/tasks`](/en/commands) to see running shells and subagents |36| `Ctrl+T` | Toggle Claude's task checklist | Show or hide [Claude's to-do checklist](#task-list) in the status area. This is not the background-task view; use [`/tasks`](/en/commands) to see running shells and subagents |

37| `Ctrl+S` | Stash or restore prompt | With text in the input, stashes it and clears the prompt. Pressed again on an empty prompt, restores the stashed text, cursor position, and pasted content |

38| `Ctrl+Z` | Suspend Claude Code | Unix only. Suspends the process to your shell; run `fg` to resume |

37| `Left/Right arrows` | Cycle through dialog tabs | Navigate between tabs in permission dialogs and menus |39| `Left/Right arrows` | Cycle through dialog tabs | Navigate between tabs in permission dialogs and menus |

38| `Up/Down arrows` or `Ctrl+P`/`Ctrl+N` | Move cursor or navigate command history | When the input spans more than one visual row, whether wrapped or multiline, first moves the cursor within the prompt. Once the cursor is on the first or last visual row, pressing again navigates command history. {/* min-version: 2.1.169 */}As of v2.1.169, wrapped single-line input behaves the same as multiline |40| `Up/Down arrows` or `Ctrl+P`/`Ctrl+N` | Move cursor or navigate command history | When the input spans more than one visual row, whether wrapped or multiline, first moves the cursor within the prompt. Once the cursor is on the first or last visual row, pressing again navigates command history. {/* min-version: 2.1.169 */}As of v2.1.169, wrapped single-line input behaves the same as multiline |

39| `Esc` | Interrupt Claude, or close a dialog | Stop the current response or tool call mid-turn so you can redirect. Claude keeps the work done so far. When a dialog such as a permission prompt is open, `Esc` closes the dialog rather than interrupting Claude. {/* min-version: 2.1.202 */}Before v2.1.202, `Esc` on some dialogs interrupted Claude and left the dialog open |41| `Esc` | Interrupt Claude, or close a dialog | Stop the current response or tool call mid-turn so you can redirect. Claude keeps the work done so far. When a dialog such as a permission prompt is open, `Esc` closes the dialog rather than interrupting Claude. {/* min-version: 2.1.202 */}Before v2.1.202, `Esc` on some dialogs interrupted Claude and left the dialog open |

40| `Esc` + `Esc` | Clear input draft, or rewind | When the prompt input contains text, double `Esc` clears it and saves the draft to history so `Up` recalls it. When the input is empty, double `Esc` opens the [rewind menu](/en/checkpointing) to restore or summarize code and conversation from a previous point |42| `Esc` + `Esc` | Clear input draft, or rewind | When the prompt input contains text, double `Esc` clears it and saves the draft to history so `Up` recalls it. When the input is empty, double `Esc` opens the [rewind menu](/en/checkpointing) to restore or summarize code and conversation from a previous point |

41| `Shift+Tab` or `Alt+M` (some configurations) | Cycle permission modes | Cycle through `default` (labeled Manual in the mode indicator), `acceptEdits`, `plan`, and any modes you have enabled, such as `auto` or `bypassPermissions`. See [permission modes](/en/permission-modes). |43| `Shift+Tab`, or `Alt+M` on Windows when the Node or Bun runtime doesn't enable VT input mode | Cycle permission modes | Cycle through `default` (labeled Manual in the mode indicator), `acceptEdits`, `plan`, and any modes you have enabled, such as `auto` or `bypassPermissions`. See [permission modes](/en/permission-modes). |

42| `Option+P` (macOS) or `Alt+P` (Windows/Linux) | Switch model | Switch models without clearing your prompt |44| `Option+P` (macOS) or `Alt+P` (Windows/Linux) | Switch model | Switch models without clearing your prompt |

43| `Option+T` (macOS) or `Alt+T` (Windows/Linux) | Toggle extended thinking | Enable or disable extended thinking mode. Has no effect on Fable 5, which always uses extended thinking. {/* min-version: 2.1.132 */}As of v2.1.132 this shortcut works on macOS without configuring Option as Meta |45| `Option+T` (macOS) or `Alt+T` (Windows/Linux) | Toggle extended thinking | Enable or disable extended thinking mode. Has no effect on Fable 5, which always uses extended thinking. {/* min-version: 2.1.132 */}As of v2.1.132 this shortcut works on macOS without configuring Option as Meta |

44| `Option+O` (macOS) or `Alt+O` (Windows/Linux) | Toggle fast mode | Enable or disable [fast mode](/en/fast-mode) |46| `Option+O` (macOS) or `Alt+O` (Windows/Linux) | Toggle fast mode | Enable or disable [fast mode](/en/fast-mode) |


46### Text editing48### Text editing

47 49 

48| Shortcut | Description | Context |50| Shortcut | Description | Context |

49| :----------------------- | :----------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |51| :------------------------- | :----------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

50| `Ctrl+A` | Move cursor to start of current line | In multiline input, moves to the start of the current logical line |52| `Ctrl+A` | Move cursor to start of current line | In multiline input, moves to the start of the current logical line |

51| `Ctrl+E` | Move cursor to end of current line | In multiline input, moves to the end of the current logical line |53| `Ctrl+E` | Move cursor to end of current line | In multiline input, moves to the end of the current logical line |

52| `Ctrl+K` | Delete to end of line | Stores deleted text for pasting |54| `Ctrl+K` | Delete to end of line | Stores deleted text for pasting |


56| `Alt+Y` (after `Ctrl+Y`) | Cycle paste history | After pasting, cycle through previously deleted text. Requires [Option as Meta](#keyboard-shortcuts) on macOS |58| `Alt+Y` (after `Ctrl+Y`) | Cycle paste history | After pasting, cycle through previously deleted text. Requires [Option as Meta](#keyboard-shortcuts) on macOS |

57| `Alt+B` | Move cursor back one word | Word navigation. Requires [Option as Meta](#keyboard-shortcuts) on macOS |59| `Alt+B` | Move cursor back one word | Word navigation. Requires [Option as Meta](#keyboard-shortcuts) on macOS |

58| `Alt+F` | Move cursor forward one word | Word navigation. Requires [Option as Meta](#keyboard-shortcuts) on macOS |60| `Alt+F` | Move cursor forward one word | Word navigation. Requires [Option as Meta](#keyboard-shortcuts) on macOS |

61| `Ctrl+_` or `Ctrl+Shift+-` | Undo last input edit | Restores the previous input text and cursor position |

59 62 

60### Theme and display63### Theme and display

61 64 


88 91 

89### Transcript viewer92### Transcript viewer

90 93 

91When the transcript viewer is open (toggled with `Ctrl+O`), these shortcuts are available. In [fullscreen rendering](/en/fullscreen), press `?` to show the full shortcut reference panel inside the viewer. `Ctrl+E` can be rebound via [`transcript:toggleShowAll`](/en/keybindings).94When the transcript viewer is open (toggled with `Ctrl+O`), these shortcuts are available. Run `/tui` with no argument to check which renderer is active. In [fullscreen rendering](/en/fullscreen), press `?` to show the full shortcut reference panel inside the viewer. `Ctrl+E` can be rebound via [`transcript:toggleShowAll`](/en/keybindings).

92 95 

93| Shortcut | Description |96| Shortcut | Description |

94| :------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |97| :------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

95| `?` | Toggle the keyboard shortcut help panel. Requires [fullscreen rendering](/en/fullscreen) |98| `?` | Toggle the keyboard shortcut help panel. Requires [fullscreen rendering](/en/fullscreen) |

96| `{` / `}` | Jump to the previous or next user prompt, like vim paragraph motion. Requires [fullscreen rendering](/en/fullscreen) |99| `{` / `}` | Jump to the previous or next user prompt, like vim paragraph motion. Requires [fullscreen rendering](/en/fullscreen) |

97| `Ctrl+E` | Toggle show all content |100| `Ctrl+E` | Toggle show all content. Available in the default renderer only, not in [fullscreen rendering](/en/fullscreen) |

98| `[` | Write the full conversation to your terminal's native scrollback so `Cmd+F`, tmux copy mode, and other native tools can search it. Requires [fullscreen rendering](/en/fullscreen#search-and-review-the-conversation) |101| `[` | Write the full conversation to your terminal's native scrollback so `Cmd+F`, tmux copy mode, and other native tools can search it. Requires [fullscreen rendering](/en/fullscreen#search-and-review-the-conversation) |

99| `v` | Write the conversation to a temporary file and open it in `$VISUAL` or `$EDITOR`. Requires [fullscreen rendering](/en/fullscreen) |102| `v` | Write the conversation to a temporary file and open it in `$VISUAL` or `$EDITOR`. Requires [fullscreen rendering](/en/fullscreen) |

100| `q`, `Ctrl+C`, `Esc` | Exit transcript view. All three can be rebound via [`transcript:exit`](/en/keybindings) |103| `q`, `Ctrl+C`, `Esc` | Exit transcript view. All three can be rebound via [`transcript:exit`](/en/keybindings) |


245 248 

246### Reverse search with Ctrl+R249### Reverse search with Ctrl+R

247 250 

248Press `Ctrl+R` to interactively search through your command history:251Press `Ctrl+R` to interactively search through your command history. In [fullscreen rendering](/en/fullscreen), `Ctrl+R` opens a search dialog instead: type to filter, press `Up` and `Down` to move through matches, and press `Ctrl+S` to cycle the scope through this session, this project, and all projects. Press `Enter` or `Tab` to place a match in the prompt input, or `Esc` to cancel. The steps below describe the default inline search:

249 252 

2501. **Start search**: press `Ctrl+R` to activate reverse history search2531. **Start search**: press `Ctrl+R` to activate reverse history search

2512. **Type query**: enter text to search for in previous commands. The search term is highlighted in matching results2542. **Type query**: enter text to search for in previous commands. The search term is highlighted in matching results

2523. **Navigate matches**: press `Ctrl+R` again to cycle through older matches2553. **Navigate matches**: press `Ctrl+R` again to cycle through older matches

2534. **Change scope**: search defaults to prompts from all projects. Press `Ctrl+S` to cycle the scope through this session, this project, and all projects2564. **Search scope**: the inline search always searches prompts from all projects

2545. **Accept match**:2575. **Accept match**:

255 * Press `Tab` or `Esc` to accept the current match and continue editing258 * Press `Tab` or `Esc` to accept the current match and continue editing

256 * Press `Enter` to accept and execute the command immediately259 * Press `Enter` to accept and execute the command immediately


258 * Press `Ctrl+C` to cancel and restore your original input261 * Press `Ctrl+C` to cancel and restore your original input

259 * Press `Backspace` on empty search to cancel262 * Press `Backspace` on empty search to cancel

260 263 

261The search loads the 100 most recent unique prompts in the selected scope, with duplicates collapsed to the newest occurrence. Matching prompts display with the search term highlighted, so you can find and reuse previous inputs.264The inline search scans your full prompt history, newest first, with duplicates collapsed to the newest occurrence. The fullscreen dialog lists the 100 most recent unique prompts in the selected scope. Matching prompts display with the search term highlighted, so you can find and reuse previous inputs.

262 265 

263Accepting a match or canceling the search takes effect immediately, even while Claude Code is still loading the history. Before v2.1.202, accepting or canceling during that load could report an internal error.266Accepting a match or canceling the search takes effect immediately, even while Claude Code is still loading the history. Before v2.1.202, accepting or canceling during that load could report an internal error.

264 267 


331 334 

332Suggestions are automatically skipped after the first turn of a conversation and in plan mode.335Suggestions are automatically skipped after the first turn of a conversation and in plan mode.

333 336 

334In print mode they are off by default. Pass [`--prompt-suggestions`](/en/cli-reference#cli-flags) with `--output-format stream-json --verbose` to emit a `prompt_suggestion` message after each turn instead.337In print mode they are off by default. Pass [`--prompt-suggestions`](/en/cli-reference#cli-flags) with `-p "<prompt>" --output-format stream-json --verbose` to emit a `prompt_suggestion` message after each turn instead.

335 338 

336To disable prompt suggestions entirely, set the environment variable or toggle the setting in `/config`:339To disable prompt suggestions entirely, set the environment variable or toggle the setting in `/config`:

337 340 

jetbrains.md +3 −1

Details

77 77 

781. Run `claude`781. Run `claude`

792. Enter the `/config` command792. Enter the `/config` command

803. Set the diff tool to `auto` to show diffs in the IDE, or `terminal` to keep them in the terminal803. Set **Diff tool** to `auto` to show diffs in the IDE, or `terminal` to keep them in the terminal

81 

82The **Diff tool** entry appears in `/config` only when Claude Code is connected to the IDE, so run `claude` from the JetBrains terminal or run [`/ide`](/en/commands) first from an external terminal. See [`diffTool`](/en/settings#global-config-settings) for the underlying setting.

81 83 

82### Plugin settings84### Plugin settings

83 85 

keybindings.md +4 −0

Details

159| `transcript:toggleShowAll` | Ctrl+E | Toggle show all content |159| `transcript:toggleShowAll` | Ctrl+E | Toggle show all content |

160| `transcript:exit` | q, Ctrl+C, Escape | Exit transcript view |160| `transcript:exit` | q, Ctrl+C, Escape | Exit transcript view |

161 161 

162`transcript:toggleShowAll` applies in the default renderer only; in [fullscreen rendering](/en/fullscreen), the transcript viewer doesn't offer a show-all toggle.

163 

162### History search actions164### History search actions

163 165 

164Actions available in the `HistorySearch` context:166Actions available in the `HistorySearch` context:


171| `historySearch:execute` | Enter | Execute selected command |173| `historySearch:execute` | Enter | Execute selected command |

172| `historySearch:cycleScope` | Ctrl+S | Cycle scope: session, project, everywhere |174| `historySearch:cycleScope` | Ctrl+S | Cycle scope: session, project, everywhere |

173 175 

176The `historySearch:next`, `historySearch:accept`, `historySearch:cancel`, and `historySearch:execute` defaults apply to the inline history search in the default renderer, which always searches prompts from all projects. `historySearch:cycleScope` takes effect only in [fullscreen rendering](/en/fullscreen), where `Ctrl+R` opens a search dialog instead and `Ctrl+S` cycles its scope. The dialog's other keys are fixed and can't be rebound: `Enter` or `Tab` places the highlighted match in the prompt input and `Esc` cancels.

177 

174### Task actions178### Task actions

175 179 

176Actions available in the `Task` context:180Actions available in the `Task` context:

model-config.md +1 −1

Details

100 100 

101Prices in the `/model` picker appear when Claude Code talks to the Anthropic API, directly or through an [LLM gateway](/en/llm-gateway) that proxies it, and the price on a row is the price of the model that row selects. On [third-party providers](/en/third-party-integrations) such as Amazon Bedrock and on the [Claude apps gateway](/en/claude-apps-gateway), your provider or gateway determines what you pay, so picker rows show no price. The price is a display label only; it doesn't affect which model a row selects or what your provider bills. Before v2.1.206, [Claude Platform on AWS](/en/claude-platform-on-aws) and gateway sessions showed Anthropic list prices, and a row could show the price of a different model than the one it selected.101Prices in the `/model` picker appear when Claude Code talks to the Anthropic API, directly or through an [LLM gateway](/en/llm-gateway) that proxies it, and the price on a row is the price of the model that row selects. On [third-party providers](/en/third-party-integrations) such as Amazon Bedrock and on the [Claude apps gateway](/en/claude-apps-gateway), your provider or gateway determines what you pay, so picker rows show no price. The price is a display label only; it doesn't affect which model a row selects or what your provider bills. Before v2.1.206, [Claude Platform on AWS](/en/claude-platform-on-aws) and gateway sessions showed Anthropic list prices, and a row could show the price of a different model than the one it selected.

102 102 

103Resumed sessions started with `claude --resume`, `--continue`, or the `/resume` picker keep the model they were using when the transcript was saved, regardless of the current `model` setting. If the restored model has been retired or is excluded by [`availableModels`](#restrict-model-selection), the session falls through to the normal precedence order. This prevents another session's `/model` choice from changing the model on resume.103Resumed sessions started with `claude --resume`, `--continue`, or the `/resume` picker keep the model they were using when the transcript was saved, regardless of the current `model` setting. If the restored model has been retired or is excluded by [`availableModels`](#restrict-model-selection), the session falls through to the normal precedence order. This prevents another session's `/model` choice from changing the model on resume. On providers that use provider-specific deployment IDs rather than Anthropic model IDs, such as Amazon Bedrock, Google Cloud's Agent Platform, and Microsoft Foundry, the transcript model isn't restored at all and the session resolves its model through the normal precedence order.

104 104 

105A model you pick for the new launch with `--model` or `ANTHROPIC_MODEL` still takes precedence over the restored model. {/* min-version: 2.1.195 */}As of v2.1.195, so does an [`ANTHROPIC_DEFAULT_OPUS_MODEL`](#environment-variables) family variable.105A model you pick for the new launch with `--model` or `ANTHROPIC_MODEL` still takes precedence over the restored model. {/* min-version: 2.1.195 */}As of v2.1.195, so does an [`ANTHROPIC_DEFAULT_OPUS_MODEL`](#environment-variables) family variable.

106 106 

Details

38 Not every mode is in the default cycle:38 Not every mode is in the default cycle:

39 39 

40 * `auto`: appears when your account meets the [auto mode requirements](#eliminate-prompts-with-auto-mode); cycling to it switches modes without a confirmation prompt40 * `auto`: appears when your account meets the [auto mode requirements](#eliminate-prompts-with-auto-mode); cycling to it switches modes without a confirmation prompt

41 * `bypassPermissions`: appears after you start with `--permission-mode bypassPermissions`, `--dangerously-skip-permissions`, or `--allow-dangerously-skip-permissions`; the `--allow-` variant adds the mode to the cycle without activating it41 * `bypassPermissions`: appears after you start with `--permission-mode bypassPermissions`, `--dangerously-skip-permissions`, `--allow-dangerously-skip-permissions`, or `permissions.defaultMode: "bypassPermissions"` in [settings](/en/settings#permission-settings); the `--allow-` variant adds the mode to the cycle without activating it

42 * `dontAsk`: never appears in the cycle; set it with `--permission-mode dontAsk`42 * `dontAsk`: never appears in the cycle; set it with `--permission-mode dontAsk`

43 43 

44 Enabled optional modes slot in after `plan`, with `bypassPermissions` first and `auto` last. If you have both enabled, you will cycle through `bypassPermissions` on the way to `auto`.44 Enabled optional modes slot in after `plan`, with `bypassPermissions` first and `auto` last. If you have both enabled, you will cycle through `bypassPermissions` on the way to `auto`.


49 claude --permission-mode plan49 claude --permission-mode plan

50 ```50 ```

51 51 

52 **As a default**: set `defaultMode` in [settings](/en/settings#settings-files).52 **As a default**: set `defaultMode` in a [settings file](/en/settings#settings-files) such as `~/.claude/settings.json`:

53 53 

54 ```json theme={null}54 ```json theme={null}

55 {55 {


157 157 

158### Review and approve a plan158### Review and approve a plan

159 159 

160When the plan is ready, Claude presents it and asks how to proceed. From that prompt you can:160When the plan is ready, Claude presents it and asks how to proceed. From that prompt you can choose:

161 161 

162* Approve and start in auto mode162* **Yes, and use auto mode**: approve and start in [auto mode](#eliminate-prompts-with-auto-mode). When auto mode is unavailable, this option reads **Yes, auto-accept edits**. Sessions started with bypass permissions enabled show **Yes, and bypass permissions** instead.

163* Approve and accept edits163* **Yes, manually approve edits**: approve and review each edit individually.

164* Approve and review each edit manually164* **No, refine with Ultraplan on Claude Code on the web**: send the plan to [Ultraplan](/en/ultraplan) for browser-based review.

165* Keep planning with feedback165* **No, keep planning**: stay in plan mode and tell Claude what to change.

166* Refine with [Ultraplan](/en/ultraplan) for browser-based review

167 166 

168Approving a plan exits plan mode and switches the session to the permission mode each approve option describes, so Claude starts editing. To plan again, cycle back to plan mode with `Shift+Tab`, or prefix your next prompt with `/plan`.167Approving a plan exits plan mode and switches the session to the permission mode each approve option describes, so Claude starts editing. To plan again, cycle back to plan mode with `Shift+Tab`, or prefix your next prompt with `/plan`.

169 168 

170Press `Ctrl+G` to open the proposed plan in your default text editor and edit it directly before Claude proceeds. When [`showClearContextOnPlanAccept`](/en/settings#available-settings) is enabled, each approve option also offers to clear the planning context first.169Press `Ctrl+G` to open the proposed plan in your default text editor and edit it directly before Claude proceeds. When [`showClearContextOnPlanAccept`](/en/settings#available-settings) is enabled, the list gains a first option that approves the plan and clears the planning context.

171 170 

172Accepting a plan also names the session from the plan content automatically, unless you've already set a name with `--name` or `/rename`.171Accepting a plan also names the session from the plan content automatically, unless you've already set a name with `--name` or `/rename`.

173 172 


201 200 

202* **Plan**: All plans.201* **Plan**: All plans.

203* **Owner**: on Team and Enterprise, an Owner must enable it in [Claude Code admin settings](https://claude.ai/admin-settings/claude-code) before users can turn it on. Administrators can also turn auto mode off by setting `permissions.disableAutoMode` to `"disable"` in [managed settings](/en/permissions#managed-settings). For the desktop app's Code tab, `disableAutoMode` is the organization-level control, and the admin settings toggle doesn't apply.202* **Owner**: on Team and Enterprise, an Owner must enable it in [Claude Code admin settings](https://claude.ai/admin-settings/claude-code) before users can turn it on. Administrators can also turn auto mode off by setting `permissions.disableAutoMode` to `"disable"` in [managed settings](/en/permissions#managed-settings). For the desktop app's Code tab, `disableAutoMode` is the organization-level control, and the admin settings toggle doesn't apply.

204* **Model**: on the Anthropic API, Claude Opus 4.6 or later, Sonnet 4.6 or later, or [Fable 5](/en/model-config#work-with-fable-5). On Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, and signed-in [Claude apps gateway](/en/claude-apps-gateway) sessions, only Claude Sonnet 5, Opus 4.7, Opus 4.8, and Fable 5. Older models, including Sonnet 4.5, Opus 4.5, Haiku, and claude-3 models, are not supported on any provider.203* **Model**: on the Anthropic API and [Claude Platform on AWS](/en/claude-platform-on-aws), Claude Opus 4.6 or later, Sonnet 4.6 or later, or [Fable 5](/en/model-config#work-with-fable-5). On Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, and signed-in [Claude apps gateway](/en/claude-apps-gateway) sessions, only Claude Sonnet 5, Opus 4.7, Opus 4.8, and Fable 5. Older models, including Sonnet 4.5, Opus 4.5, Haiku, and claude-3 models, are not supported on any provider.

205* **Provider**: available by default on the Anthropic API, Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, and signed-in Claude apps gateway sessions. {/* min-version: 2.1.207 */}In v2.1.158 through v2.1.206, auto mode was off on all of these providers except the Anthropic API until you set `CLAUDE_CODE_ENABLE_AUTO_MODE=1`; v2.1.207 removed the requirement.204* **Provider**: available by default on the Anthropic API, Claude Platform on AWS, Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, and signed-in Claude apps gateway sessions. {/* min-version: 2.1.207 */}In v2.1.158 through v2.1.206, auto mode was off on all of these providers except the Anthropic API and Claude Platform on AWS until you set `CLAUDE_CODE_ENABLE_AUTO_MODE=1`; v2.1.207 removed the requirement.

206 205 

207If Claude Code reports auto mode as unavailable, one of these requirements is unmet; this is not a transient outage. A separate message that names a model and says auto mode "cannot determine the safety" of an action is a transient classifier outage; see the [error reference](/en/errors#auto-mode-cannot-determine-the-safety-of-an-action).206If Claude Code reports auto mode as unavailable, one of these requirements is unmet; this is not a transient outage. A separate message that names a model and says auto mode "cannot determine the safety" of an action is a transient classifier outage; see the [error reference](/en/errors#auto-mode-cannot-determine-the-safety-of-an-action).

208 207 


307* In [non-interactive mode](/en/headless) and Agent SDK sessions there is no turn boundary, so a deny is reused for the rest of the run306* In [non-interactive mode](/en/headless) and Agent SDK sessions there is no turn boundary, so a deny is reused for the rest of the run

308* Changing your permission mode or rules drops all cached verdicts307* Changing your permission mode or rules drops all cached verdicts

309 308 

310Run `claude auto-mode defaults` to see the full rule lists. If routine actions get blocked, an administrator can add trusted repos, buckets, and services via the `autoMode.environment` setting: see [Configure auto mode](/en/auto-mode-config).309Run `claude auto-mode defaults` to print the full rule lists as JSON. If routine actions get blocked, an administrator can add trusted repos, buckets, and services via the `autoMode.environment` setting: see [Configure auto mode](/en/auto-mode-config).

311 310 

312{/* min-version: 2.1.211 */}Pushing to any branch of the repository you're working in and creating a pull request that matches your request run without a prompt, with the two exceptions the lists above cover: the classifier judges a push to a deploy-named branch such as `production` or `gh-pages` on its own terms, and still blocks a push whose content carries risk. To require a human checkpoint before these actions while staying in auto mode, add `permissions.ask` rules: see [Common boundaries](/en/auto-mode-config#common-boundaries).311{/* min-version: 2.1.211 */}Pushing to any branch of the repository you're working in and creating a pull request that matches your request run without a prompt, with the two exceptions the lists above cover: the classifier judges a push to a deploy-named branch such as `production` or `gh-pages` on its own terms, and still blocks a push whose content carries risk. To require a human checkpoint before these actions while staying in auto mode, add `permissions.ask` rules: see [Common boundaries](/en/auto-mode-config#common-boundaries).

313 312 


395 Only use this mode in isolated environments like containers, VMs, or dev containers without internet access, where Claude Code cannot damage your host system.394 Only use this mode in isolated environments like containers, VMs, or dev containers without internet access, where Claude Code cannot damage your host system.

396</Warning>395</Warning>

397 396 

398You cannot enter `bypassPermissions` from a session that was started without one of the enabling flags; restart with one to enable it:397You can't enter `bypassPermissions` from a session that was started without it enabled. Enable it at launch with `permissions.defaultMode: "bypassPermissions"` in [settings](/en/settings#permission-settings) or with an enabling flag:

399 398 

400```bash theme={null}399```bash theme={null}

401claude --permission-mode bypassPermissions400claude --permission-mode bypassPermissions


403 402 

404The `--dangerously-skip-permissions` flag is equivalent.403The `--dangerously-skip-permissions` flag is equivalent.

405 404 

405The first time you start an interactive session with this mode enabled, Claude Code shows a warning dialog asking you to accept responsibility for actions taken without permission checks. Claude Code saves your acceptance to user settings, so the dialog appears only once. If you decline, Claude Code exits. In [non-interactive mode](/en/headless) no dialog is shown, and a [background session](/en/agent-view) started with `--bg` is refused until you've accepted the dialog in an interactive session.

406 

406On Linux and macOS, Claude Code refuses to start in this mode when running as root or under `sudo`:407On Linux and macOS, Claude Code refuses to start in this mode when running as root or under `sudo`:

407 408 

408```text theme={null}409```text theme={null}

permissions.md +1 −1

Details

206 206 

207 * Options before URL: `curl -X GET http://github.com/...`207 * Options before URL: `curl -X GET http://github.com/...`

208 * Different protocol: `curl https://github.com/...`208 * Different protocol: `curl https://github.com/...`

209 * Redirects: `curl -L http://bit.ly/xyz`, which redirects to GitHub209 * Redirects: `curl -L http://short.example.com/xyz`, which redirects to GitHub

210 * Variables: `URL=http://github.com && curl $URL`210 * Variables: `URL=http://github.com && curl $URL`

211 * Extra spaces: `curl http://github.com`211 * Extra spaces: `curl http://github.com`

212 212 

quickstart.md +5 −5

Details

29 <Tab title="Native Install (Recommended)">29 <Tab title="Native Install (Recommended)">

30 **macOS, Linux, WSL:**30 **macOS, Linux, WSL:**

31 31 

32 ```bash theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null}32 ```bash theme={null}

33 curl -fsSL https://claude.ai/install.sh | bash33 curl -fsSL https://claude.ai/install.sh | bash

34 ```34 ```

35 35 

36 **Windows PowerShell:**36 **Windows PowerShell:**

37 37 

38 ```powershell theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null}38 ```powershell theme={null}

39 irm https://claude.ai/install.ps1 | iex39 irm https://claude.ai/install.ps1 | iex

40 ```40 ```

41 41 

42 **Windows CMD:**42 **Windows CMD:**

43 43 

44 ```batch theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null}44 ```batch theme={null}

45 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd45 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

46 ```46 ```

47 47 


57 </Tab>57 </Tab>

58 58 

59 <Tab title="Homebrew">59 <Tab title="Homebrew">

60 ```bash theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null}60 ```bash theme={null}

61 brew install --cask claude-code61 brew install --cask claude-code

62 ```62 ```

63 63 


69 </Tab>69 </Tab>

70 70 

71 <Tab title="WinGet">71 <Tab title="WinGet">

72 ```powershell theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null}72 ```powershell theme={null}

73 winget install Anthropic.ClaudeCode73 winget install Anthropic.ClaudeCode

74 ```74 ```

75 75 

sessions.md +12 −0

Details

24 24 

25Sessions created with [`claude -p`](/en/headless) or the [Agent SDK](/en/agent-sdk/overview) do not appear in the session picker, but you can still resume one by passing its session ID to `claude --resume <session-id>`. Run this from the directory the session was started in: session ID lookup is scoped to the current project directory and its git worktrees, so a session created elsewhere reports `No conversation found with session ID: <session-id>`.25Sessions created with [`claude -p`](/en/headless) or the [Agent SDK](/en/agent-sdk/overview) do not appear in the session picker, but you can still resume one by passing its session ID to `claude --resume <session-id>`. Run this from the directory the session was started in: session ID lookup is scoped to the current project directory and its git worktrees, so a session created elsewhere reports `No conversation found with session ID: <session-id>`.

26 26 

27### What a resumed session restores

28 

29A resumed session restores the conversation along with the state saved in it:

30 

31* Conversation history: the full history, including tool calls and results.

32* Model: the session continues on the model it was using. The model isn't restored when it has been retired or isn't allowed by `availableModels`, when a `--model` flag or `ANTHROPIC_MODEL`-family environment variable picks one at launch, or on providers that use provider-specific deployment IDs, such as [Amazon Bedrock, Google Cloud's Agent Platform, and Microsoft Foundry](/en/third-party-integrations); see [model configuration](/en/model-config#setting-your-model) for the resolution order.

33* Permission mode: the mode the session was in. `plan` and `bypassPermissions` are never restored; [bypassing permissions](/en/permission-modes#skip-all-checks-with-bypasspermissions-mode) must be enabled again at launch, with one of its launch flags or `permissions.defaultMode: "bypassPermissions"` in [settings](/en/settings#permission-settings). `auto` is restored only when your account still meets the [auto mode requirements](/en/permission-modes#eliminate-prompts-with-auto-mode). Pass `--permission-mode` to override the restored mode.

34* Active goal: a [goal](/en/goal#resume-with-an-active-goal) that was still active when the session ended carries over; its turn count, timer, and token-spend baseline reset.

35* Scheduled tasks: [tasks that haven't expired](/en/scheduled-tasks#limitations) are restored. Background Bash and monitor tasks aren't.

36 

37Not every configuration flag from the original launch is restored. If the session depended on `--mcp-config`, `--settings`, `--plugin-dir`, `--fallback-model`, or directories added with `--add-dir`, pass them again when you resume; directories added mid-session with `/add-dir` aren't restored either, though the session picker still uses them to locate the session. The standard settings files, such as `settings.json` and `settings.local.json`, are re-read at launch, so configuration that lives in them doesn't need to be passed again.

38 

27### Where the session picker looks39### Where the session picker looks

28 40 

29Sessions are stored per project directory. By default the session picker shows interactive sessions from the current worktree, plus sessions started elsewhere that added the current directory with `/add-dir`. Use `Ctrl+W` to widen to all worktrees of the repository or `Ctrl+A` to widen to every project on this machine.41Sessions are stored per project directory. By default the session picker shows interactive sessions from the current worktree, plus sessions started elsewhere that added the current directory with `/add-dir`. Use `Ctrl+W` to widen to all worktrees of the repository or `Ctrl+A` to widen to every project on this machine.

settings.md +2 −1

Details

347</Note>347</Note>

348 348 

349| Key | Description | Example |349| Key | Description | Example |

350| :--------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------- |350| :--------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------- |

351| `autoConnectIde` | **Default**: `false`. Automatically connect to a running IDE when Claude Code starts from an external terminal. Appears in `/config` as **Auto-connect to IDE (external terminal)** when running outside a VS Code or JetBrains terminal. The [`CLAUDE_CODE_AUTO_CONNECT_IDE`](/en/env-vars) environment variable overrides this when set | `true` |351| `autoConnectIde` | **Default**: `false`. Automatically connect to a running IDE when Claude Code starts from an external terminal. Appears in `/config` as **Auto-connect to IDE (external terminal)** when running outside a VS Code or JetBrains terminal. The [`CLAUDE_CODE_AUTO_CONNECT_IDE`](/en/env-vars) environment variable overrides this when set | `true` |

352| `autoInstallIdeExtension` | **Default**: `true`. Automatically install the Claude Code IDE extension when running from a VS Code terminal. Appears in `/config` as **Auto-install IDE extension** when running inside a VS Code or JetBrains terminal. You can also set the [`CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL`](/en/env-vars) environment variable to `1` | `false` |352| `autoInstallIdeExtension` | **Default**: `true`. Automatically install the Claude Code IDE extension when running from a VS Code terminal. Appears in `/config` as **Auto-install IDE extension** when running inside a VS Code or JetBrains terminal. You can also set the [`CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL`](/en/env-vars) environment variable to `1` | `false` |

353| `diffTool` | **Default**: `auto`. Where to display file diffs when an IDE is connected: `auto` opens diffs in the IDE's diff viewer, `terminal` keeps them in the terminal. Appears in `/config` as **Diff tool** only when Claude Code is connected to a VS Code or JetBrains IDE | `"terminal"` |

353| `externalEditorContext` | **Default**: `false`. Prepend Claude's previous response as `#`-commented context when you open the external editor with `Ctrl+G`. Appears in `/config` as **Show last response in external editor** | `true` |354| `externalEditorContext` | **Default**: `false`. Prepend Claude's previous response as `#`-commented context when you open the external editor with `Ctrl+G`. Appears in `/config` as **Show last response in external editor** | `true` |

354| `permissionExplainerEnabled` | **Default**: `true`. Show a model-generated [explanation of the command](/en/permissions#permission-system) when you press `Ctrl+E` on a Bash or PowerShell permission prompt. Set to `false` to turn the shortcut off | `false` |355| `permissionExplainerEnabled` | **Default**: `true`. Show a model-generated [explanation of the command](/en/permissions#permission-system) when you press `Ctrl+E` on a Bash or PowerShell permission prompt. Set to `false` to turn the shortcut off | `false` |

355| `teammateDefaultModel` | Default model for [agent team](/en/agent-teams) teammates when the spawn prompt doesn't specify one. Set to a model alias such as `"sonnet"`, or `null` to inherit the lead's current `/model` selection. Appears in `/config` as **Default teammate model** | `"sonnet"` |356| `teammateDefaultModel` | Default model for [agent team](/en/agent-teams) teammates when the spawn prompt doesn't specify one. Set to a model alias such as `"sonnet"`, or `null` to inherit the lead's current `/model` selection. Appears in `/config` as **Default teammate model** | `"sonnet"` |

setup.md +5 −5

Details

41 <Tab title="Native Install (Recommended)">41 <Tab title="Native Install (Recommended)">

42 **macOS, Linux, WSL:**42 **macOS, Linux, WSL:**

43 43 

44 ```bash theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null}44 ```bash theme={null}

45 curl -fsSL https://claude.ai/install.sh | bash45 curl -fsSL https://claude.ai/install.sh | bash

46 ```46 ```

47 47 

48 **Windows PowerShell:**48 **Windows PowerShell:**

49 49 

50 ```powershell theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null}50 ```powershell theme={null}

51 irm https://claude.ai/install.ps1 | iex51 irm https://claude.ai/install.ps1 | iex

52 ```52 ```

53 53 

54 **Windows CMD:**54 **Windows CMD:**

55 55 

56 ```batch theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null}56 ```batch theme={null}

57 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd57 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

58 ```58 ```

59 59 


69 </Tab>69 </Tab>

70 70 

71 <Tab title="Homebrew">71 <Tab title="Homebrew">

72 ```bash theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null}72 ```bash theme={null}

73 brew install --cask claude-code73 brew install --cask claude-code

74 ```74 ```

75 75 


81 </Tab>81 </Tab>

82 82 

83 <Tab title="WinGet">83 <Tab title="WinGet">

84 ```powershell theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null} theme={null}84 ```powershell theme={null}

85 winget install Anthropic.ClaudeCode85 winget install Anthropic.ClaudeCode

86 ```86 ```

87 87 

statusline.md +2 −2

Details

86 86 

87<Steps>87<Steps>

88 <Step title="Create a script that reads JSON and prints output">88 <Step title="Create a script that reads JSON and prints output">

89 Claude Code sends JSON data to your script via stdin. This script uses [`jq`](https://jqlang.github.io/jq/), a command-line JSON parser you may need to install, to extract the model name, directory, and context percentage, then prints a formatted line.89 Claude Code sends JSON data to your script via stdin. This script uses [`jq`](https://jqlang.org/), a command-line JSON parser you may need to install, to extract the model name, directory, and context percentage, then prints a formatted line.

90 90 

91 Save this to `~/.claude/statusline.sh` (where `~` is your home directory, such as `/Users/username` on macOS or `/home/username` on Linux):91 Save this to `~/.claude/statusline.sh` (where `~` is your home directory, such as `/Users/username` on macOS or `/home/username` on Linux):

92 92 


3322. Make it executable: `chmod +x ~/.claude/statusline.sh`3322. Make it executable: `chmod +x ~/.claude/statusline.sh`

3333. Add the path to your [settings](#manually-configure-a-status-line)3333. Add the path to your [settings](#manually-configure-a-status-line)

334 334 

335The Bash examples use [`jq`](https://jqlang.github.io/jq/) to parse JSON. Python and Node.js have built-in JSON parsing.335The Bash examples use [`jq`](https://jqlang.org/) to parse JSON. Python and Node.js have built-in JSON parsing.

336 336 

337### Context window usage337### Context window usage

338 338