Sweep 22 Sep 2026 · 17:19Z Build v2.1.280 501 read Stable v2.1.267 Latest v2.1.280 Next v2.1.280 Feeds RSS JSON llms.txt Unofficial
One capture · claude-code

One read of Claude Code CLI

11 pages moved out of 191 read.

claude-code-20260828T190702Z

Pages moved 11 significant first
Pages read 191 in this capture
Captured 19:07 UTC
Corpus hash 02e9a1d7d1cf corpus-hash

What this read moved

1–11 of 11

agent-sdk/hosting Changed · +8 / -8 lines

## Troubleshoot deployment failures

from line 8
88 
99If you do not need infrastructure control, custom isolation, or your own data plane, consider [Managed Agents](https://platform.claude.com/docs/en/managed-agents/overview) instead: a hosted REST API where Anthropic runs the agent and the sandbox, so your application sends events and streams back results with no hosting infrastructure to operate.
1010 
11<Info>
12 For security hardening beyond basic sandboxing, including network controls, credential management, and isolation options, see [Secure Deployment](/docs/en/agent-sdk/secure-deployment).
13</Info>
14 
1511## The subprocess model
1612 
1713Every hosting decision on this page follows from how the SDK runs the agent. When your code calls `query()`, the SDK spawns a separate `claude` CLI process and talks to it over stdio. That subprocess owns the shell, the working directory, and the JSONL session transcripts on local disk.
from line 141
145141 ```
146142</CodeGroup>
147143 
148See [Session storage](/docs/en/agent-sdk/session-storage) for the full `SessionStore` interface and reference adapters.
149 
150144### Multi-agent container
151145 
152146Run multiple SDK subprocesses inside one container. Best for agents that must collaborate closely, for example multi-agent simulations where the agents interact with each other in a shared environment.
from line 306
312306 ```
313307</CodeGroup>
314308 
315For per-tenant network controls, see [Secure Deployment](/docs/en/agent-sdk/secure-deployment).
316 
317309## Known limitations
318310 
319311Plan around these in your deployment design.
from line 316
324316| Memory growth over long sessions | Cap session length or recycle subprocesses periodically. See [Scaling and concurrency](#scaling-and-concurrency). |
325317| Large parallel-subagent fanouts can hit rate limits | Break work into smaller batches rather than issuing one wide dispatch. |
326318| No per-subagent wall-clock deadline | Cap each [subagent](/docs/en/agent-sdk/subagents) with `maxTurns` in its `AgentDefinition`. For background subagents only, `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS` sets a stall watchdog that fires when a `run_in_background` subagent stops producing output; it is not a total-runtime deadline. |
319 
320## Troubleshoot deployment failures
321 
322Use this section when an agent that works on your machine fails in a deployed service. Each item below names a failure and links the entry that covers it:
323 
324* **CLI not found at service start**: a container or service manager runs your application with a different `PATH` than your shell, so an install that works locally isn't visible to the process. See [Claude Code not found](/docs/en/agent-sdk/troubleshooting#clinotfounderror-claude-code-not-found).
325* **CLI present in the image but won't launch**: Claude Code can't start from a binary that doesn't match the container's architecture or libc, or from a file that lost its execute permission in the image build. See [Failed to start Claude Code](/docs/en/agent-sdk/troubleshooting#cliconnectionerror-failed-to-start-claude-code).
326* **Claude Code process exits mid-run**: the error your application receives depends on the SDK language and on whether the CLI reported an error result first. The entries under [CLI process exit](/docs/en/agent-sdk/troubleshooting#cli-process-exit) cover each message.
327327 
328328## Next steps
329329 

agent-sdk/migration-guide Changed · +3 / -71 lines

from line 42
4242import { query, tool, createSdkMcpServer } from "@anthropic-ai/claude-agent-sdk";
4343```
4444 
45**4. Update package.json dependencies:**
45**4. Update package.json:**
4646 
47If you have the package listed in your `package.json`, update it:
47If `@anthropic-ai/claude-code` is still listed in your `package.json`, replace it with `@anthropic-ai/claude-agent-sdk` and update the version range as well, for example from `"^0.0.42"` to `"^0.3.0"`.
4848 
49Before:
50 
51```json theme={null}
52{
53 "dependencies": {
54 "@anthropic-ai/claude-code": "^0.0.42"
55 }
56}
57```
58 
59After:
60 
61```json theme={null}
62{
63 "dependencies": {
64 "@anthropic-ai/claude-agent-sdk": "^0.3.0"
65 }
66}
67```
68 
6949**5. Review [breaking changes](#breaking-changes)**
7050 
7151Make any code changes needed to complete the migration.
from line 171
191171 ```
192172</CodeGroup>
193173 
194**Why this changed:** Provides better control and isolation for SDK applications. You can now build agents with custom behavior without inheriting Claude Code's CLI-focused instructions.
195 
196174### Settings sources default
197175 
198176This default was briefly changed in v0.1.0 to load no filesystem settings and then reverted, so no migration action is needed.
from line 177
199177 
200178**Current behavior:** Omitting `settingSources` on `query()` loads user, project, and local filesystem settings, matching the CLI. This includes `~/.claude/settings.json`, `.claude/settings.json`, `.claude/settings.local.json`, CLAUDE.md files, and custom commands.
201179 
202To run isolated from filesystem settings, pass an empty array:
203 
204<CodeGroup>
205 ```typescript TypeScript theme={null}
206 import { query } from "@anthropic-ai/claude-agent-sdk";
207 
208 const isolatedResult = query({
209 prompt: "Hello",
210 options: {
211 settingSources: [] // Skip user, project, and local settings
212 }
213 });
214 
215 // Or load only specific sources:
216 const projectOnlyResult = query({
217 prompt: "Hello",
218 options: {
219 settingSources: ["project"] // Only project settings
220 }
221 });
222 ```
223 
224 ```python Python theme={null}
225 from claude_agent_sdk import query, ClaudeAgentOptions
226 import asyncio
227 
228 
229 async def main():
230 async for message in query(
231 prompt="Hello",
232 options=ClaudeAgentOptions(setting_sources=[]), # Skip user, project, and local settings
233 ):
234 print(message)
235 
236 # Or load only specific sources:
237 async for message in query(
238 prompt="Hello",
239 options=ClaudeAgentOptions(
240 setting_sources=["project"] # Only project settings
241 ),
242 ):
243 print(message)
244 
245 
246 asyncio.run(main())
247 ```
248</CodeGroup>
180To run isolated from filesystem settings, pass `settingSources: []`, or `setting_sources=[]` in Python. See [Control filesystem settings with settingSources](/docs/en/agent-sdk/claude-code-features#control-filesystem-settings-with-settingsources) for what each source loads.
249181 
250182Isolation is especially important for CI/CD pipelines, deployed applications, test environments, and multi-tenant systems where local customizations should not leak in.
251183 

agent-sdk/python Changed · +13 / -234 lines

## Build a continuous conversation interface ## Error handling ## Advanced Features with ClaudeSDKClient ### Building a Continuous Conversation Interface ### Using Hooks for Behavior Modification ### Real-time Progress Monitoring ## Example Usage ### Basic file operations (using query) ### Error handling ### Using custom tools with ClaudeSDKClient

from line 1846
18461846 
18471847## Error Types
18481848 
1849The types below define what your code catches. For entries keyed to the error messages these types raise, with the cause and fix for each, see [Troubleshooting](/docs/en/agent-sdk/troubleshooting).
1850 
18491851### `ClaudeSDKError`
18501852 
18511853Base exception class for all SDK errors.
from line 1971
19691971* `tool_use_id`: Optional tool use identifier (for tool-related hooks)
19701972* `context`: Hook context with additional information
19711973 
1972Returns a [`HookJSONOutput`](#hookjsonoutput) that may contain:
1974Returns a [`HookJSONOutput`](#hookjsonoutput).
19731975 
1974* `decision`: `"block"` to block the action
1975* `systemMessage`: warning message shown to the user
1976* `hookSpecificOutput`: Hook-specific output data
1977 
19781976### `HookContext`
19791977 
19801978Context information passed to hook callbacks.
from line 2860
28622860**Tool name:** `TodoWrite`
28632861 
28642862<Note>
2865 On Python Agent SDK 0.2.139 and later, the following tools aren't available on Opus 4.8, Sonnet 5, Fable 5, Mythos 5, or later versions of those families unless you opt in:
2863 On Python Agent SDK 0.2.139 and later, the following restriction applies.
28662864 
2865 The following tools aren't available on Opus 4.8, Sonnet 5, Fable 5, Mythos 5, or later versions of those families unless you opt in:
2866 
28672867 * `TodoWrite`
28682868 * `TaskCreate`
28692869 * `TaskGet`
from line 3129
31293129}
31303130```
31313131 
3132## Advanced Features with ClaudeSDKClient
3132## Build a continuous conversation interface
31333133 
3134### Building a Continuous Conversation Interface
3134The following example keeps one `ClaudeSDKClient` connected across turns, so Claude remembers earlier messages. Type `new` to disconnect and reconnect for a fresh session, or `exit` to end the conversation.
31353135 
31363136```python theme={null}
31373137from claude_agent_sdk import (
from line 3210
32103210asyncio.run(main())
32113211```
32123212 
3213### Using Hooks for Behavior Modification
3213## Error handling
32143214 
3215```python theme={null}
3216from claude_agent_sdk import (
3217 ClaudeSDKClient,
3218 ClaudeAgentOptions,
3219 HookMatcher,
3220 HookContext,
3221)
3222import asyncio
3223from typing import Any
3215The following example wraps a `query()` call in handlers for four of the [error types](#error-types) the SDK raises.
32243216 
3225 
3226async def pre_tool_logger(
3227 input_data: dict[str, Any], tool_use_id: str | None, context: HookContext
3228) -> dict[str, Any]:
3229 """Log all tool usage before execution."""
3230 tool_name = input_data.get("tool_name", "unknown")
3231 print(f"[PRE-TOOL] About to use: {tool_name}")
3232 
3233 # You can modify or block the tool execution here
3234 if tool_name == "Bash" and "rm -rf" in str(input_data.get("tool_input", {})):
3235 return {
3236 "hookSpecificOutput": {
3237 "hookEventName": "PreToolUse",
3238 "permissionDecision": "deny",
3239 "permissionDecisionReason": "Dangerous command blocked",
3240 }
3241 }
3242 return {}
3243 
3244 
3245async def post_tool_logger(
3246 input_data: dict[str, Any], tool_use_id: str | None, context: HookContext
3247) -> dict[str, Any]:
3248 """Log results after tool execution."""
3249 tool_name = input_data.get("tool_name", "unknown")
3250 print(f"[POST-TOOL] Completed: {tool_name}")
3251 return {}
3252 
3253 
3254async def user_prompt_modifier(
3255 input_data: dict[str, Any], tool_use_id: str | None, context: HookContext
3256) -> dict[str, Any]:
3257 """Add context to user prompts."""
3258 original_prompt = input_data.get("prompt", "")
3259 
3260 # Add a timestamp as additional context for Claude to see
3261 from datetime import datetime
3262 
3263 timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
3264 
3265 return {
3266 "hookSpecificOutput": {
3267 "hookEventName": "UserPromptSubmit",
3268 "additionalContext": f"[Submitted at {timestamp}] Original prompt: {original_prompt}",
3269 }
3270 }
3271 
3272 
3273async def main():
3274 options = ClaudeAgentOptions(
3275 hooks={
3276 "PreToolUse": [
3277 HookMatcher(hooks=[pre_tool_logger]),
3278 HookMatcher(matcher="Bash", hooks=[pre_tool_logger]),
3279 ],
3280 "PostToolUse": [HookMatcher(hooks=[post_tool_logger])],
3281 "UserPromptSubmit": [HookMatcher(hooks=[user_prompt_modifier])],
3282 },
3283 allowed_tools=["Read", "Write", "Bash"],
3284 )
3285 
3286 async with ClaudeSDKClient(options=options) as client:
3287 await client.query("List files in current directory")
3288 
3289 async for message in client.receive_response():
3290 # Hooks will automatically log tool usage
3291 pass
3292 
3293 
3294asyncio.run(main())
3295```
3296 
3297### Real-time Progress Monitoring
3298 
3299```python theme={null}
3300from claude_agent_sdk import (
3301 ClaudeSDKClient,
3302 ClaudeAgentOptions,
3303 AssistantMessage,
3304 ToolUseBlock,
3305 ToolResultBlock,
3306 TextBlock,
3307)
3308import asyncio
3309 
3310 
3311async def monitor_progress():
3312 options = ClaudeAgentOptions(
3313 allowed_tools=["Write", "Bash"], permission_mode="acceptEdits"
3314 )
3315 
3316 async with ClaudeSDKClient(options=options) as client:
3317 await client.query("Create 5 Python files with different sorting algorithms")
3318 
3319 # Monitor progress in real-time
3320 async for message in client.receive_response():
3321 if isinstance(message, AssistantMessage):
3322 for block in message.content:
3323 if isinstance(block, ToolUseBlock):
3324 if block.name == "Write":
3325 file_path = block.input.get("file_path", "")
3326 print(f"Creating: {file_path}")
3327 elif isinstance(block, ToolResultBlock):
3328 print("Completed tool execution")
3329 elif isinstance(block, TextBlock):
3330 print(f"Claude says: {block.text[:100]}...")
3331 
3332 print("Task completed!")
3333 
3334 
3335asyncio.run(monitor_progress())
3336```
3337 
3338## Example Usage
3339 
3340### Basic file operations (using query)
3341 
3342```python theme={null}
3343from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ToolUseBlock
3344import asyncio
3345 
3346 
3347async def create_project():
3348 options = ClaudeAgentOptions(
3349 allowed_tools=["Read", "Write", "Bash"],
3350 permission_mode="acceptEdits",
3351 )
3352 
3353 async for message in query(
3354 prompt="Create a Python project structure with setup.py", options=options
3355 ):
3356 if isinstance(message, AssistantMessage):
3357 for block in message.content:
3358 if isinstance(block, ToolUseBlock):
3359 print(f"Using tool: {block.name}")
3360 
3361 
3362asyncio.run(create_project())
3363```
3364 
3365### Error handling
3366 
33673217This example catches [`ResultError`](#resulterror), which requires Python Agent SDK 0.2.140 or later.
33683218 
33693219```python theme={null}
from line 3253
34033253asyncio.run(main())
34043254```
34053255 
3406### Using custom tools with ClaudeSDKClient
3407 
3408```python theme={null}
3409from claude_agent_sdk import (
3410 ClaudeSDKClient,
3411 ClaudeAgentOptions,
3412 tool,
3413 create_sdk_mcp_server,
3414 AssistantMessage,
3415 TextBlock,
3416)
3417import asyncio
3418from typing import Any
3419 
3420 
3421# Define custom tools with @tool decorator
3422@tool("calculate", "Perform mathematical calculations", {"expression": str})
3423async def calculate(args: dict[str, Any]) -> dict[str, Any]:
3424 try:
3425 result = eval(args["expression"], {"__builtins__": {}})
3426 return {"content": [{"type": "text", "text": f"Result: {result}"}]}
3427 except Exception as e:
3428 return {
3429 "content": [{"type": "text", "text": f"Error: {str(e)}"}],
3430 "is_error": True,
3431 }
3432 
3433 
3434@tool("get_time", "Get current time", {})
3435async def get_time(args: dict[str, Any]) -> dict[str, Any]:
3436 from datetime import datetime
3437 
3438 current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
3439 return {"content": [{"type": "text", "text": f"Current time: {current_time}"}]}
3440 
3441 
3442async def main():
3443 # Create SDK MCP server with custom tools
3444 my_server = create_sdk_mcp_server(
3445 name="utilities", version="1.0.0", tools=[calculate, get_time]
3446 )
3447 
3448 # Configure options with the server
3449 options = ClaudeAgentOptions(
3450 mcp_servers={"utils": my_server},
3451 allowed_tools=["mcp__utils__calculate", "mcp__utils__get_time"],
3452 )
3453 
3454 # Use ClaudeSDKClient for interactive tool usage
3455 async with ClaudeSDKClient(options=options) as client:
3456 await client.query("What's 123 * 456?")
3457 
3458 # Process calculation response
3459 async for message in client.receive_response():
3460 if isinstance(message, AssistantMessage):
3461 for block in message.content:
3462 if isinstance(block, TextBlock):
3463 print(f"Calculation: {block.text}")
3464 
3465 # Follow up with time query
3466 await client.query("What time is it now?")
3467 
3468 async for message in client.receive_response():
3469 if isinstance(message, AssistantMessage):
3470 for block in message.content:
3471 if isinstance(block, TextBlock):
3472 print(f"Time: {block.text}")
3473 
3474 
3475asyncio.run(main())
3476```
3477 
34783256## Sandbox Configuration
34793257 
34803258### `SandboxSettings`
from line 3450
36723450 
36733451* [SDK overview](/docs/en/agent-sdk/overview) - General SDK concepts
36743452* [TypeScript SDK reference](/docs/en/agent-sdk/typescript) - TypeScript SDK documentation
3453* [Custom tools](/docs/en/agent-sdk/custom-tools) - Define in-process MCP tools for Claude to call
36753454* [CLI reference](/docs/en/cli-reference) - Command-line interface
36763455* [Common workflows](/docs/en/common-workflows) - Step-by-step guides
36773456 

agent-sdk/streaming-vs-single-mode Changed · +0 / -38 lines

### How It Works

from line 15
1515 
1616It allows the agent to operate as a long lived process that takes in user input, handles interruptions, surfaces permission requests, and handles session management.
1717 
18### How It Works
19 
20```mermaid theme={null}
21sequenceDiagram
22 participant App as Your Application
23 participant Agent as Claude Agent
24 participant Tools as Tools/Hooks
25 participant FS as Environment/<br/>File System
26 
27 App->>Agent: Initialize with AsyncGenerator
28 activate Agent
29 
30 App->>Agent: Yield Message 1
31 Agent->>Tools: Execute tools
32 Tools->>FS: Read files
33 FS-->>Tools: File contents
34 Tools->>FS: Write/Edit files
35 FS-->>Tools: Success/Error
36 Agent-->>App: Stream partial response
37 Agent-->>App: Stream more content...
38 Agent->>App: Complete Message 1
39 
40 App->>Agent: Yield Message 2 + Image
41 Agent->>Tools: Process image & execute
42 Tools->>FS: Access filesystem
43 FS-->>Tools: Operation results
44 Agent-->>App: Stream response 2
45 
46 App->>Agent: Queue Message 3
47 App->>Agent: Interrupt/Cancel
48 Agent->>App: Handle interruption
49 
50 Note over App,Agent: Session stays alive
51 Note over Tools,FS: Persistent file system<br/>state maintained
52 
53 deactivate Agent
54```
55 
5618### Benefits
5719 
5820In streaming input mode, you work in a persistent session with these capabilities:

agent-sdk/structured-outputs Changed · +1 / -8 lines

from line 243
243243 ```
244244</CodeGroup>
245245 
246**Benefits:**
247 
248* Full type inference (TypeScript) and type hints (Python)
249* Runtime validation with `safeParse()` or `model_validate()`
250* Better error messages
251* Composable, reusable schemas
252 
253246## Output format configuration
254247 
255248The `outputFormat` (TypeScript) or `output_format` (Python) option accepts an object with:
from line 383
390383| `success` | Output was generated and validated successfully |
391384| `error_max_structured_output_retries` | No valid output remained after multiple attempts (validation failures, or a model-fallback retraction with no successful retry) |
392385 
393A result can also end with subtype `success` but no `structured_output` value, for example when the run completes without the agent producing a structured output. Treat that case as a failure as well. The example below treats a result as successful only when the `subtype` is `success` and `structured_output` is present, and handles every other result as a failure:
386A result can also end with subtype `success` but no `structured_output` value, for example when the run completes without the agent producing a structured output. Treat that case as a failure as well. The troubleshooting entry [structured\_output is None but the result says success](/docs/en/agent-sdk/troubleshooting#structured_output-is-none-but-the-result-says-success) covers this case. The example below treats a result as successful only when the `subtype` is `success` and `structured_output` is present, and handles every other result as a failure:
394387 
395388<CodeGroup>
396389 ```typescript TypeScript theme={null}

agent-sdk/troubleshooting Changed · +69 / -0 lines

### CLIConnectionError: Failed to start Claude Code ### CLIConnectionError: Not connected ## CLI process exit ### ProcessError: Command failed with exit code ### Claude Code process exited with code N ### Claude Code returned an error result

from line 22
2222* If you set `cli_path`, confirm the file exists and is the `claude` executable.
2323* If you rely on `PATH` resolution, confirm `claude --version` works in the same environment your application runs in. Processes you launch outside your shell, such as from an IDE or a service manager, often run with a different `PATH`.
2424 
25The TypeScript SDK reports a missing executable as `Claude Code native binary not found at <path>` or `Claude Code executable not found at <path>. Is options.pathToClaudeCodeExecutable set?`. It looks for the CLI in only two places, its bundled platform package and the path you set in `pathToClaudeCodeExecutable`. Reinstall `@anthropic-ai/claude-agent-sdk` without skipping optional dependencies so the bundled binary is present, or point `pathToClaudeCodeExecutable` at a [native install](/docs/en/setup#install-claude-code).
26 
2527### CLIConnectionError: Refusing to execute batch script
2628 
2729On Windows, connecting fails with a `CLIConnectionError` when the CLI path the Python SDK uses is a `.bat` or `.cmd` batch script, including the `claude.cmd` shim that an npm install creates:
from line 46
4446* On x64 Windows, install the `claude-agent-sdk` wheel, which bundles `claude.exe`.
4547 
4648Before `claude-agent-sdk` 0.2.124, the Python SDK spawned batch scripts through `cmd.exe` without this check.
49 
50### CLIConnectionError: Failed to start Claude Code
51 
52The SDK found a file at the configured path but couldn't launch it. Python raises these failures as a `CLIConnectionError`. TypeScript rejects the message iteration with an error carrying no SDK class. The table below maps each message to what it tells you. Match the message you see:
53 
54| Message | SDK | What it tells you |
55| ----------------------------------------------------------------- | ---------- | -------------------------------------------------------------------- |
56| `Failed to start Claude Code: <detail>` | Python | The rest of the message is the operating system's own error |
57| `Claude Code executable at <path> exists but failed to launch` | TypeScript | The script at the configured path can't run |
58| `Claude Code native binary at <path> exists but failed to launch` | TypeScript | The binary can't run, with a libc suggestion appended to the message |
59| `Failed to spawn Claude Code process: <detail>` | TypeScript | Any other launch failure |
60 
61In both SDKs, the usual cause is a configured path that points at something that can't run, such as a text file, a directory, or a file without execute permission. Read the native-binary message's libc suggestion as one possible cause.
62 
63To fix it in either SDK:
64 
65* Confirm the configured path points at the `claude` executable itself and that the file has execute permission.
66* If you don't need a custom path, remove `cli_path` in Python or `pathToClaudeCodeExecutable` in TypeScript so the SDK finds a CLI on its own, preferring its bundled copy.
67 
68### CLIConnectionError: Not connected
69 
70Calling a `ClaudeSDKClient` method in Python before the client has connected, or after it has disconnected, raises a `CLIConnectionError` with this message:
71 
72```
73Not connected. Call connect() first.
74```
75 
76Do what the message says. Either call `await client.connect()` before any other client method, or open the client with `async with ClaudeSDKClient() as client:`, which connects on entry.
77 
78## CLI process exit
79 
80The entries in this section mean the Claude Code process ended while your application was using it. Which error you see depends on the SDK language and on whether the CLI reported an error result before it exited.
81 
82### ProcessError: Command failed with exit code
83 
84The Python SDK raises a `ProcessError` when the Claude Code process exits with a nonzero code:
85 
86```
87Command failed with exit code 1 (exit code: 1)
88Error output: Check stderr output for details
89```
90 
91The message states the exit code twice, and the `Error output` line is fixed text rather than your process's error output. The same fixed text fills the exception's `stderr` attribute. The exception's `exit_code` attribute carries the code. To capture what the CLI actually wrote to stderr, pass a `stderr` callback in `ClaudeAgentOptions` and log what it receives.
92 
93A bare `ProcessError` means the CLI exited without reporting an error result. When the CLI did report one, the SDK raises [`ResultError`](/docs/en/agent-sdk/python#resulterror) instead, covered in [Claude Code returned an error result](#claude-code-returned-an-error-result). `ResultError` subclasses `ProcessError`, so `except ProcessError` catches both. To handle them differently, put the `except ResultError` clause first.
94 
95Before `claude-agent-sdk` 0.2.140, the Python SDK raised error-result exits as a plain `Exception` rather than a `ResultError`.
96 
97### Claude Code process exited with code N
98 
99IDE wrappers print this message too, and the [error reference](/docs/en/errors#claude-code-process-exited-with-code-n) covers it for VS Code and other launchers. This entry covers what your TypeScript SDK code receives. The SDK surfaces a nonzero CLI exit as a plain `Error` that rejects the `for await` loop over `query()`'s messages. There's no SDK error class to catch, so wrap the loop in `try`/`catch` and match on the message:
100 
101```
102Claude Code process exited with code 1. stderr: <tail of the CLI's stderr>
103```
104 
105When the CLI wrote to stderr, the message ends with the tail of it. To capture the full stream, pass a `stderr` callback in the query options. A process killed by a signal reports `Claude Code process terminated by signal <name>` in the same form.
106 
107### Claude Code returned an error result
108 
109Both SDKs replace the process-exit error with this message when the CLI reported an error result before exiting:
110 
111```
112Claude Code returned an error result: <the CLI's own error report>
113```
114 
115The text after the colon is the CLI's report of what went wrong, so start there rather than with the exit itself. Python raises this as a [`ResultError`](/docs/en/agent-sdk/python#resulterror), whose `data` attribute carries the full error result. TypeScript rejects the message loop with a plain `Error` carrying the same message shape.
47116 
48117## Structured outputs
49118 

agent-sdk/typescript Changed · +12 / -28 lines

This page is larger than the 256 KiB this site keeps, so one side of the diff below stops where the stored text does.

from line 905
905905});
906906```
907907 
908**Loading CLAUDE.md project instructions:**
908To load CLAUDE.md project instructions, include `"project"` in `settingSources`. See [Modify system prompts](/docs/en/agent-sdk/modifying-system-prompts#claude-md-files-for-project-level-instructions) for how CLAUDE.md loading interacts with the system prompt options.
909909 
910```typescript theme={null}
911import { query } from "@anthropic-ai/claude-agent-sdk";
912 
913// Load project settings to include CLAUDE.md files
914const result = query({
915 prompt: "Add a new feature following project conventions",
916 options: {
917 systemPrompt: {
918 type: "preset",
919 preset: "claude_code" // Use Claude Code's system prompt
920 },
921 settingSources: ["project"], // Loads CLAUDE.md from project directory
922 allowedTools: ["Read", "Write", "Edit"]
923 }
924});
925```
926 
927910#### Settings precedence
928911 
929912When multiple sources are loaded, settings are merged with this precedence (highest to lowest):
from line 2669
26862669Creates and manages a structured task list for tracking progress.
26872670 
26882671<Note>
2689 On TypeScript Agent SDK 0.3.233 and later, the following tools aren't available on Opus 4.8, Sonnet 5, Fable 5, Mythos 5, or later versions of those families unless you opt in:
2672 On TypeScript Agent SDK 0.3.233 and later, the following restriction applies.
26902673 
2674 The following tools aren't available on Opus 4.8, Sonnet 5, Fable 5, Mythos 5, or later versions of those families unless you opt in:
2675 
26912676 * `TodoWrite`
26922677 * `TaskCreate`
26932678 * `TaskGet`
from line 3622
36373622Returns the previous and updated task lists.
36383623 
36393624<Note>
3640 On TypeScript Agent SDK 0.3.233 and later, the following tools aren't available on Opus 4.8, Sonnet 5, Fable 5, Mythos 5, or later versions of those families unless you opt in:
3625 On TypeScript Agent SDK 0.3.233 and later, the following restriction applies.
36413626 
3627 The following tools aren't available on Opus 4.8, Sonnet 5, Fable 5, Mythos 5, or later versions of those families unless you opt in:
3628 
36423629 * `TodoWrite`
36433630 * `TaskCreate`
36443631 * `TaskGet`
from line 3780
37933780 
37943781```typescript theme={null}
37953782type ExitWorktreeOutput = {
3796 action: "keep" | "remo
3783 action: "keep" | "remove";
3784 originalCwd: string;
3785 worktreePath: string;
3786 worktreeBranch?: string;
3787 tmuxSessionName?: string;
3788 discardedFiles?: number;
3789 discardedCommits?: number;
3790 message: st

agent-sdk/user-input Changed · +0 / -20 lines

from line 213
213213 
214214When denying, provide a message explaining why. Claude sees this message and may adjust its approach.
215215 
216<CodeGroup>
217 ```python Python theme={null}
218 from claude_agent_sdk.types import PermissionResultAllow, PermissionResultDeny
219 
220 # Allow the tool to execute
221 return PermissionResultAllow(updated_input=input_data)
222 
223 # Block the tool
224 return PermissionResultDeny(message="User rejected this action")
225 ```
226 
227 ```typescript TypeScript theme={null}
228 // Allow the tool to execute
229 return { behavior: "allow", updatedInput: input };
230 
231 // Block the tool
232 return { behavior: "deny", message: "User rejected this action" };
233 ```
234</CodeGroup>
235 
236216Beyond allowing or denying, you can modify the tool's input or provide context that helps Claude adjust its approach:
237217 
238218* **Approve**: let the tool execute as Claude requested

agent-sdk/claude-code-features Changed · +0 / -2 lines

from line 6
66 
77When you omit `settingSources`, `query()` reads the same filesystem settings as the Claude Code CLI: user, project, and local settings, CLAUDE.md files, and `.claude/` skills, agents, and commands. To run without these, pass `settingSources: []`, which limits the agent to what you configure programmatically. Managed policy settings and the global `~/.claude.json` config are read regardless of this option. See [What settingSources does not control](#what-settingsources-does-not-control).
88 
9For a conceptual overview of what each feature does and when to use it, see [Extend Claude Code](/docs/en/features-overview).
10 
119## Control filesystem settings with settingSources
1210 
1311The setting sources option ([`setting_sources`](/docs/en/agent-sdk/python#claudeagentoptions) in Python, [`settingSources`](/docs/en/agent-sdk/typescript#settingsource) in TypeScript) controls which filesystem-based settings the SDK loads. Pass an explicit list to opt in to specific sources, or pass an empty array to disable user, project, and local settings.

agent-sdk/quickstart Changed · +1 / -0 lines

from line 360
360360* **[MCP servers](/docs/en/agent-sdk/mcp)**: connect to databases, browsers, APIs, and other external systems
361361* **[Hosting](/docs/en/agent-sdk/hosting)**: deploy agents to Docker, cloud, and CI/CD
362362* **[Example agents](https://github.com/anthropics/claude-agent-sdk-demos)**: see complete examples: email assistant, research agent, and more
363* **[Troubleshooting](/docs/en/agent-sdk/troubleshooting)**: fix Agent SDK errors by the exact message you see
363364 

errors Changed · +1 / -0 lines

This page is larger than the 256 KiB this site keeps, so one side of the diff below stops where the stored text does.

Nothing in the body moved in this read. What changed is above.