Follow Discord
Sweep 20 Nov 2026 · 19:55Z Build v2.1.330 547 read Stable v2.1.323 Latest v2.1.330 Next v2.1.330 Feeds RSS JSON llms.txt llms-full.txt Unofficial
One capture · claude-code

One read of Claude Code CLIclaude-code-20261116T220701Z

9 pages moved out of 205 read.

Pages moved 9 significant first
Pages read 205 in this capture
Captured 22:07 UTC
Corpus hash 2492e0b9357a corpus-hash

What this read moved

1-9 of 9

agent-sdk/configuration Changed · +3 / -2 lines

from line 136
136136 
137137## Limit turns and spend
138138 
139Cap turns and spend with `maxTurns` / `max_turns` and `maxBudgetUsd` / `max_budget_usd`. Both caps are off when unset. When a session hits a cap, the run ends with a result message whose subtype names the cap, `error_max_turns` or `error_max_budget_usd`. What happens next differs by input mode:
139Cap turns and spend with `maxTurns` / `max_turns` and `maxBudgetUsd` / `max_budget_usd`. Both caps are off when unset. When a session hits a cap, the run ends with a result message. The result's subtype is `error_max_turns` for the turn cap and `error_max_budget_usd` for the spend cap. Single-shot and streaming input handle a cap result differently:
140140 
141141* **Single-shot `query()`**: the SDK yields the cap result and then raises, so wrap the loop in a try block to continue past the error
142* **Streaming input**: the session stays alive past a cap result, and the max-turns count starts over for each queued message. The budget total accumulates across messages, and once spend reaches the cap, later messages in the same conversation end with the same budget result. A [`/clear`](https://code.claude.com/docs/en/agent-sdk/cost-tracking) starts the budget over
142* **Streaming input**: the session stays alive past a cap result, and the max-turns count starts over for each queued message. The budget total accumulates across messages, and once spend reaches the cap, later messages in the same conversation end with the same budget result. A [`/clear`](https://code.claude.com/docs/en/agent-sdk/cost-tracking) starts the budget over.
143* **Streaming input in TypeScript**: the loop throws when the last response ends in an error result, such as `error_max_turns`. Wrap the loop in a try block to continue past it.
143144 
144145The two caps treat `0` differently:
145146 

agent-sdk/skills Changed · +4 / -1 lines

from line 165
165165 
166166> [!NOTE]
167167>
168> A command can hit the `maxTurns` / `max_turns` limit like any other prompt, ending the query with an error result instead of `success`. For the error-result contract, see [Handle the result](https://code.claude.com/docs/en/agent-sdk/agent-loop.md#handle-the-result). If your command might hit the limit, wrap the loop in a `try`/`catch` in TypeScript or `try`/`except` in Python, as shown in [Single Message Input](https://code.claude.com/docs/en/agent-sdk/streaming-vs-single-mode.md#single-message-input), or set `maxTurns` high enough for the work to complete.
168> When a command reaches the `maxTurns` / `max_turns` limit, the query ends with an error result instead of `success`. For the error-result contract, see [Handle the result](https://code.claude.com/docs/en/agent-sdk/agent-loop.md#handle-the-result). If your command might hit the limit, do one of these:
169>
170> * Set `maxTurns` high enough for the work to complete.
171> * Wrap the `query()` loop in `try`/`catch` in TypeScript or `try`/`except` in Python.
169172 
170173### Compact history with `/compact`
171174 

agent-sdk/streaming-output Changed · +6 / -3 lines

from line 4
44 
55By default, the Agent SDK yields a complete `AssistantMessage` for each non-empty content block, such as a text block or a tool call, after Claude finishes generating that block. To receive incremental updates as text and tool calls are generated, enable partial message streaming.
66 
7> [!TIP]
7> [!NOTE]
88>
9> This page covers output streaming (receiving tokens in real-time). For input modes (how you send messages), see [Send messages to agents](https://code.claude.com/docs/en/agent-sdk/streaming-vs-single-mode.md). You can also [stream responses using the Agent SDK via the CLI](https://code.claude.com/docs/en/headless.md).
9> These cases are covered on other pages:
10>
11> * **Sending messages to a running session**: see [Send messages to a running agent](https://code.claude.com/docs/en/agent-sdk/streaming-vs-single-mode.md)
12> * **Streaming responses from the CLI**: see [stream responses using the Agent SDK via the CLI](https://code.claude.com/docs/en/headless.md)
1013 
1114## Enable streaming output
1215 
from line 326
323326 
324327Now that you can stream text and tool calls in real-time, explore these related topics:
325328 
326* [Interactive vs one-shot queries](https://code.claude.com/docs/en/agent-sdk/streaming-vs-single-mode.md): choose between input modes for your use case
329* [Send messages to a running agent](https://code.claude.com/docs/en/agent-sdk/streaming-vs-single-mode.md): interrupt Claude's response or attach an image to a message
327330* [Structured outputs](https://code.claude.com/docs/en/agent-sdk/structured-outputs.md): get typed JSON responses from the agent
328331* [Permissions](https://code.claude.com/docs/en/agent-sdk/permissions.md): control which tools the agent can use
329332 

agent-sdk/streaming-vs-single-mode Changed · +274 / -215 lines

# Send messages to a running agent ## Choose single-shot or streaming input ## Send more than one message to a session ### Send a follow-up with an image ### Feed messages from a chat interface in TypeScript ## Read each response ## Interrupt Claude's response ## Next steps # Streaming Input ## Overview ## Streaming Input Mode (Recommended) ### Benefits ### Implementation Example ## Single Message Input ### When to Use Single Message Input ### Limitations ### Implementation Example

from line 1
1# Streaming Input
1# Send messages to a running agent
22 
3> Understanding the two input modes for Claude Agent SDK and when to use each
3> Send follow-up messages and images to one Agent SDK session with streaming input, read each response, and interrupt a response to redirect Claude.
44 
5## Overview
5Streaming input keeps an Agent SDK session open so your application can send it more than one message while it runs. You can also attach images to a message and stop a response partway through to redirect Claude.
66 
7The Claude Agent SDK supports two distinct input modes for interacting with agents:
7> [!NOTE]
8>
9> Streaming input covers the messages you send. To show Claude's response as it's generated, see [Stream responses in real-time](https://code.claude.com/docs/en/agent-sdk/streaming-output.md).
810 
9* **Streaming Input Mode**: a persistent, interactive session
10* **Single Message Input**: one-shot queries that use session state and resuming
11## Choose single-shot or streaming input
1112 
12## Streaming Input Mode (Recommended)
13Choose streaming input for an application that holds a conversation with Claude, such as a chat interface. Use streaming input to attach images to a message, interrupt a response, or [switch the model or permission mode](https://code.claude.com/docs/en/agent-sdk/configuration.md#change-configuration-mid-session) while the session runs.
1314 
14Streaming input mode is the **preferred** way to use the Claude Agent SDK. It provides full access to the agent's capabilities and enables rich, interactive experiences.
15A single-shot call passes one prompt string to `query()`. The call ends after Claude answers it. Single-shot fits a single task, such as a serverless function. To follow up after that call ends, start a new call that resumes the session. For more information, see [Continue, resume, and fork](https://code.claude.com/docs/en/agent-sdk/sessions.md#continue-resume-and-fork).
1516 
16It allows the agent to operate as a long lived process that takes in user input, handles interruptions, surfaces permission requests, and handles session management.
17## Send more than one message to a session
1718 
18### Benefits
19* **TypeScript**: write an [async generator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function%2A) that yields [`SDKUserMessage`](https://code.claude.com/docs/en/agent-sdk/typescript#sdkusermessage) objects, and pass it as the `prompt` of `query()`. Make the generator wait between yields for the next message from your user.
20* **Python**: open a `ClaudeSDKClient` and pass each message to `client.query()`. Pass a string for a text message. To attach an image, pass an [async generator](https://docs.python.org/3/glossary.html#term-asynchronous-generator) that yields user message dicts.
1921 
20In streaming input mode, you work in a persistent session with these capabilities:
22To have Claude answer each message in its own response, wait for the previous response's [result message](#read-each-response) before you send the next one:
2123 
22* **Image uploads**: attach images directly to messages for visual analysis and understanding
23* **Queued messages**: send multiple messages that process sequentially, with ability to interrupt
24* **Tool integration**: full access to all tools and custom MCP servers during the session
25* **Real-time feedback**: see responses as they're generated, not just final results
26* **Context persistence**: maintain conversation context across multiple turns naturally
24* **TypeScript**: have your generator await a promise. Resolve it in your `for await` loop over `query()` when the result message arrives.
25* **Python**: call `client.query()` with the next message after your [`receive_response()`](https://code.claude.com/docs/en/agent-sdk/python#claudesdkclient) loop ends.
2726 
28### Implementation Example
27> [!NOTE]
28>
29> A message you send during tool calls reaches Claude after those tool calls finish. Claude then answers it and your earlier message in one response. If the turn ends first, Claude starts a new turn for it. For details, see [Turns and budget](https://code.claude.com/docs/en/agent-sdk/agent-loop.md#turns-and-budget).
2930 
30These examples read an image named `diagram.png` from the working directory. Create one there first, or change the filename to point at your own image.
31### Send a follow-up with an image
3132 
33This example sends a text question, then a follow-up with an image, and prints Claude's response to each. Before you run it, save a PNG image as `diagram.png` in your working directory:
34 
3235```typescript TypeScript theme={null}
36import { readFile } from "node:fs/promises";
3337import { query, type SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";
34import { readFile } from "fs/promises";
3538 
36async function* generateMessages(): AsyncGenerator<SDKUserMessage> {
37 // First message
39let firstResponseDone!: () => void;
40const firstResponseFinished = new Promise<void>((resolve) => {
41 firstResponseDone = resolve;
42});
43 
44async function* messages(): AsyncGenerator<SDKUserMessage> {
3845 yield {
3946 type: "user",
4047 message: {
4148 role: "user",
42 content: "Analyze this codebase for security issues"
49 content: "Explain in two sentences what a message queue does.",
4350 },
44 parent_tool_use_id: null
51 parent_tool_use_id: null,
4552 };
4653 
47 // Wait for conditions or user input
48 await new Promise((resolve) => setTimeout(resolve, 2000));
54 await firstResponseFinished;
4955 
50 // Follow-up with image
56 const image = await readFile("diagram.png");
5157 yield {
5258 type: "user",
5359 message: {
5460 role: "user",
5561 content: [
62 { type: "text", text: "Describe this image in one sentence." },
5663 {
57 type: "text",
58 text: "Review this architecture diagram"
59 },
60 {
6164 type: "image",
6265 source: {
6366 type: "base64",
6467 media_type: "image/png",
65 data: await readFile("diagram.png", "base64")
66 }
67 }
68 ]
68 data: image.toString("base64"),
69 },
70 },
71 ],
6972 },
70 parent_tool_use_id: null
73 parent_tool_use_id: null,
7174 };
7275}
7376 
74// Process streaming responses
75for await (const message of query({
76 prompt: generateMessages(),
77 options: {
78 maxTurns: 10,
79 allowedTools: ["Read", "Grep"]
77let responses = 0;
78for await (const message of query({ prompt: messages() })) {
79 if (message.type === "assistant") {
80 for (const block of message.message.content) {
81 if (block.type === "text") {
82 console.log(block.text);
83 }
84 }
85 } else if (message.type === "result") {
86 responses += 1;
87 console.log(`Response ${responses} finished: ${message.subtype}`);
88 if (responses === 1) {
89 firstResponseDone();
90 }
8091 }
81})) {
82 if (message.type === "result" && message.subtype === "success") {
83 console.log(message.result);
84 }
8592}
8693```
8794 
8895```python Python theme={null}
89from claude_agent_sdk import (
90 ClaudeSDKClient,
91 ClaudeAgentOptions,
92 AssistantMessage,
93 TextBlock,
94)
9596import asyncio
9697import base64
98from pathlib import Path
9799 
100from claude_agent_sdk import AssistantMessage, ClaudeSDKClient, ResultMessage, TextBlock
98101 
99async def streaming_analysis():
100 async def message_generator():
101 # First message
102 yield {
103 "type": "user",
104 "message": {
105 "role": "user",
106 "content": "Analyze this codebase for security issues",
107 },
108 }
109102 
110 # Wait for conditions
111 await asyncio.sleep(2)
112 
113 # Follow-up with image
114 with open("diagram.png", "rb") as f:
115 image_data = base64.b64encode(f.read()).decode()
116 
117 yield {
118 "type": "user",
119 "message": {
120 "role": "user",
121 "content": [
122 {"type": "text", "text": "Review this architecture diagram"},
123 {
124 "type": "image",
125 "source": {
126 "type": "base64",
127 "media_type": "image/png",
128 "data": image_data,
129 },
103async def image_message():
104 image_data = base64.b64encode(Path("diagram.png").read_bytes()).decode()
105 yield {
106 "type": "user",
107 "message": {
108 "role": "user",
109 "content": [
110 {"type": "text", "text": "Describe this image in one sentence."},
111 {
112 "type": "image",
113 "source": {
114 "type": "base64",
115 "media_type": "image/png",
116 "data": image_data,
130117 },
131 ],
132 },
133 }
118 },
119 ],
120 },
121 }
134122 
135 # Use ClaudeSDKClient for streaming input
136 options = ClaudeAgentOptions(max_turns=10, allowed_tools=["Read", "Grep"])
137123 
138 async with ClaudeSDKClient(options) as client:
139 # Send streaming input
140 await client.query(message_generator())
124async def main():
125 async with ClaudeSDKClient() as client:
126 await client.query("Explain in two sentences what a message queue does.")
127 async for message in client.receive_response():
128 if isinstance(message, AssistantMessage):
129 for block in message.content:
130 if isinstance(block, TextBlock):
131 print(block.text)
132 elif isinstance(message, ResultMessage):
133 print(f"Response 1 finished: {message.subtype}")
141134 
142 # Process responses
135 await client.query(image_message())
143136 async for message in client.receive_response():
144137 if isinstance(message, AssistantMessage):
145138 for block in message.content:
146139 if isinstance(block, TextBlock):
147140 print(block.text)
141 elif isinstance(message, ResultMessage):
142 print(f"Response 2 finished: {message.subtype}")
148143 
149144 
150asyncio.run(streaming_analysis())
145asyncio.run(main())
151146```
152147 
153When you run the example, the TypeScript version prints each response as it completes. The Python version's `receive_response()` loop ends at the first result message, so it prints the security analysis; to read both responses, use one `query()` and `receive_response()` pair per message as shown in the [Python reference's example of continuing a conversation](https://code.claude.com/docs/en/agent-sdk/python.md#example-continuing-a-conversation).
148When you run either version, the example prints `Response 1 finished: success` and `Response 2 finished: success`.
154149 
155If an image block's `source` is missing or isn't an object, the SDK doesn't report an error. Claude Code sends Claude a text note in place of the image, such as `[Image could not be processed: image block has no source object]`, and the session continues.
150If Claude didn't see your image, see [Image could not be processed](https://code.claude.com/docs/en/agent-sdk/troubleshooting.md#image-could-not-be-processed).
156151 
157> [!NOTE]
158>
159> In the TypeScript SDK, if your message generator throws, for example when a file it reads is missing, the stream ends with an error that reads `Claude Code process aborted by user` instead of the original error, so check the code inside your generator first when you see that message. The error may also be preceded by a long minified line of bundled SDK source, so read to the end of the output for the error text.
160>
161> In the Python SDK, a generator exception is logged at debug level and the session stalls without raising, so if a streaming session hangs with no output, enable debug logging and check your generator.
152### Feed messages from a chat interface in TypeScript
162153 
163## Single Message Input
154Feed your user's messages to your prompt generator through a queue:
164155 
165Single message input is simpler but more limited.
156* **`pushMessage()`**: your interface's input handler calls this for each message the user sends.
157* **`closeInput()`**: the handler calls this when the user closes the chat.
158* **`userMessages()`**: the generator you pass as the `prompt` of `query()`.
166159 
167### When to Use Single Message Input
160`pushMessage()` adds each message to an array, and the generator reads from that array. When the array is empty, the generator waits until a message arrives or the chat closes:
168161 
169Use single message input when:
162```typescript theme={null}
163import type { SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";
170164 
171* You need a one-shot response
172* You do not need image attachments or mid-session control methods
173* You need to operate in a stateless environment, such as a lambda function
165const pending: string[] = [];
166let wake: (() => void) | null = null;
167let closed = false;
174168 
175### Limitations
169// The interface's input handler calls this with each message the user sends.
170function pushMessage(text: string): void {
171 pending.push(text);
172 wake?.();
173}
176174 
177> [!WARNING]
178>
179> Single message input mode does **not** support:
180>
181> * Direct image attachments in messages
182> * Dynamic message queueing
183> * Real-time interruption
184> * Natural multi-turn conversations
175// The interface calls this when the user closes the chat.
176function closeInput(): void {
177 closed = true;
178 wake?.();
179}
185180 
186If a query ends with an error result, such as `error_max_turns`, a single message `query()` call raises an error that includes the failure text after yielding the final result message, so wrap the loop in a try block if your code needs to continue. See [Handle the result](https://code.claude.com/docs/en/agent-sdk/agent-loop.md#handle-the-result) for the result subtypes.
181async function* userMessages(): AsyncGenerator<SDKUserMessage> {
182 while (true) {
183 const text = pending.shift();
184 if (text !== undefined) {
185 yield { type: "user", message: { role: "user", content: text }, parent_tool_use_id: null };
186 } else if (closed) {
187 return;
188 } else {
189 await new Promise<void>((resolve) => (wake = resolve));
190 wake = null;
191 }
192 }
193}
194```
187195 
188### Implementation Example
196Messages you push during a response can share one response. To choose when Claude reads a message you push during a response, set the message's [`priority`](https://code.claude.com/docs/en/agent-sdk/typescript#sdkusermessage) field.
189197 
198## Read each response
199 
200Claude ends each response with a result message.
201 
202* **TypeScript**: the `for await` loop over `query()` yields each response's messages in order. The loop ends after the last response's result message, once your generator has returned. To match a result to the messages it answers, set a `uuid` on each message you send, and read the result's [`user_message_uuids`](https://code.claude.com/docs/en/agent-sdk/typescript#user_message_uuids).
203* **Python**: start a `receive_response()` loop for each response, because each loop stops after the next [`ResultMessage`](https://code.claude.com/docs/en/agent-sdk/python#resultmessage). The client keeps the conversation's context from one message to the next. For more information, see [Automatic session management](https://code.claude.com/docs/en/agent-sdk/sessions.md#automatic-session-management).
204 
205The result message's `subtype` field reports how the response ended, such as `success` or `error_during_execution`.
206 
207If the last response ends in an error result:
208 
209* **TypeScript**: the loop over `query()` yields that result and then throws. Wrap the loop in `try`/`catch` to handle the exception. To keep the conversation going after the throw, start a new `query()` call that [resumes the session](https://code.claude.com/docs/en/agent-sdk/sessions.md#continue-resume-and-fork). While your generator still has messages to send, an error result for an earlier response doesn't throw.
210* **Python**: `receive_response()` on a `ClaudeSDKClient` yields the error result without raising.
211 
212For what each result subtype means, see [Handle the result](https://code.claude.com/docs/en/agent-sdk/agent-loop.md#handle-the-result).
213 
214## Interrupt Claude's response
215 
216To stop a response partway through and keep the session open, call `interrupt()` on the object that runs the session:
217 
218* **TypeScript**: pass an async generator as `prompt`, save the [`Query` object](https://code.claude.com/docs/en/agent-sdk/typescript#query-object) returned by `query()`, and call `interrupt()` on it.
219* **Python**: call `interrupt()` on the `ClaudeSDKClient`. If a `receive_response()` loop is reading the response, that loop ends at the interrupted response's `ResultMessage`. Send your next message after that result arrives.
220 
221When you call `interrupt()` during a response, that response ends with an `error_during_execution` result. Messages you sent before the interrupt that Claude hadn't read yet still reach Claude once the interrupted response ends. For what the TypeScript loop does when the last response is an error result, see [Read each response](#read-each-response).
222 
223This example asks Claude for a long essay. The example calls `interrupt()` three seconds after the session starts, then sends a second message to the same session once the interrupted response ends:
224 
190225```typescript TypeScript theme={null}
191import { query } from "@anthropic-ai/claude-agent-sdk";
226import { query, type SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";
192227 
193// Simple one-shot query
194// query() throws after an error result, such as error_max_turns
195try {
196 for await (const message of query({
197 prompt: "Explain the authentication flow",
198 options: {
199 maxTurns: 5,
200 allowedTools: ["Read", "Grep"]
201 }
202 })) {
203 if (message.type === "result" && message.subtype === "success") {
204 console.log(message.result);
205 }
206 }
207} catch (error) {
208 console.error(`Query failed: ${error}`);
228let firstResponseDone!: () => void;
229const firstResponseFinished = new Promise<void>((resolve) => {
230 firstResponseDone = resolve;
231});
232 
233async function* messages(): AsyncGenerator<SDKUserMessage> {
234 yield {
235 type: "user",
236 message: {
237 role: "user",
238 content: "Write a 2,000-word essay on the history of the printing press.",
239 },
240 parent_tool_use_id: null,
241 };
242 
243 await firstResponseFinished;
244 
245 yield {
246 type: "user",
247 message: {
248 role: "user",
249 content: "In one sentence, what is a prime number?",
250 },
251 parent_tool_use_id: null,
252 };
209253}
210254 
211// Continue conversation with session management
212try {
213 for await (const message of query({
214 prompt: "Now explain the authorization process",
215 options: {
216 continue: true,
217 maxTurns: 5
255const conversation = query({ prompt: messages() });
256 
257let responses = 0;
258for await (const message of conversation) {
259 if (message.type === "system" && message.subtype === "init" && responses === 0) {
260 setTimeout(async () => {
261 await conversation.interrupt();
262 console.log("Interrupt sent");
263 }, 3000);
264 } else if (message.type === "assistant") {
265 for (const block of message.message.content) {
266 if (block.type === "text") {
267 console.log(block.text);
268 }
218269 }
219 })) {
220 if (message.type === "result" && message.subtype === "success") {
221 console.log(message.result);
270 } else if (message.type === "result") {
271 responses += 1;
272 console.log(`Response ${responses} finished: ${message.subtype}`);
273 if (responses === 1) {
274 firstResponseDone();
222275 }
223276 }
224} catch (error) {
225 console.error(`Query failed: ${error}`);
226277}
227278```
228279 
229280```python Python theme={null}
230from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
231281import asyncio
232282 
283from claude_agent_sdk import AssistantMessage, ClaudeSDKClient, ResultMessage, TextBlock
233284 
234async def single_message_example():
235 # Simple one-shot query using query() function
236 # query() raises ResultError after an error result, such as error_max_turns
237 try:
238 async for message in query(
239 prompt="Explain the authentication flow",
240 options=ClaudeAgentOptions(max_turns=5, allowed_tools=["Read", "Grep"]),
241 ):
242 if isinstance(message, ResultMessage) and message.subtype == "success":
243 print(message.result)
244 except Exception as e:
245 print(f"Query failed: {e}")
246285 
247 # Continue conversation with session management
248 try:
249 async for message in query(
250 prompt="Now explain the authorization process",
251 options=ClaudeAgentOptions(continue_conversation=True, max_turns=5),
252 ):
253 if isinstance(message, ResultMessage) and message.subtype == "success":
254 print(message.result)
255 except Exception as e:
256 print(f"Query failed: {e}")
286async def main():
287 async with ClaudeSDKClient() as client:
288 await client.query("Write a 2,000-word essay on the history of the printing press.")
289 await asyncio.sleep(3)
290 await client.interrupt()
291 print("Interrupt sent")
292 async for message in client.receive_response():
293 if isinstance(message, AssistantMessage):
294 for block in message.content:
295 if isinstance(block, TextBlock):
296 print(block.text)
297 elif isinstance(message, ResultMessage):
298 print(f"Response 1 finished: {message.subtype}")
257299 
300 await client.query("In one sentence, what is a prime number?")
301 async for message in client.receive_response():
302 if isinstance(message, AssistantMessage):
303 for block in message.content:
304 if isinstance(block, TextBlock):
305 print(block.text)
306 elif isinstance(message, ResultMessage):
307 print(f"Response 2 finished: {message.subtype}")
258308 
259asyncio.run(single_message_example())
309 
310asyncio.run(main())
260311```
261312 
262When you run the example, each query prints its final result text: first the authentication explanation, then the authorization explanation.
313When you run either version, the first response stops partway through the essay, and the example prints `Response 1 finished: error_during_execution`. Claude then answers the second message. The output ends with `Response 2 finished: success`.
314 
315## Next steps
316 
317* [Stream responses in real-time](https://code.claude.com/docs/en/agent-sdk/streaming-output.md): show text and tool calls as Claude generates them
318* [Handle approvals and user input](https://code.claude.com/docs/en/agent-sdk/user-input.md): answer Claude's permission requests and clarifying questions
319* [Change configuration mid-session](https://code.claude.com/docs/en/agent-sdk/configuration.md#change-configuration-mid-session): switch the model or permission mode while the session runs
320* [`Query` object](https://code.claude.com/docs/en/agent-sdk/typescript#query-object) in TypeScript and [`ClaudeSDKClient`](https://code.claude.com/docs/en/agent-sdk/python#claudesdkclient) in Python: the methods that send messages to a running session or control it
321* [Work with sessions](https://code.claude.com/docs/en/agent-sdk/sessions.md): resume, continue, or fork a conversation
263322 

agent-sdk/troubleshooting Changed · +43 / -5 lines

## Streaming input ### Operation aborted ### Prompt stream failed; closing stdin ### Image could not be processed

from line 1
11# Troubleshoot the Agent SDK
22 
3> Fix Agent SDK errors: the Claude Code CLI fails to start or exits, a tool message is too large, or a result arrives without structured output.
3> Fix Agent SDK errors: the Claude Code CLI fails to start or exits, your prompt generator throws, a tool message is too large, or structured output is missing.
44 
5This page covers Agent SDK errors in CLI startup, CLI process exit, large tool calls and results, and structured outputs. Entries on this page are keyed to the error you see. Each entry names the cause and what to do.
5This page covers Agent SDK errors in CLI startup, CLI process exit, large tool calls and results, streaming input, and structured outputs. Entries on this page are keyed to the error you see. Each entry names the cause and what to do.
66 
7Symptoms tied to a feature, such as a hook not firing or a skill not being used, have a troubleshooting section on that feature's page. The table names the section or page that covers each symptom:
7Symptoms tied to a feature, such as a hook not firing or a skill not being used, have a troubleshooting section on that feature's page. Look up your symptom in this table to find the section or page that covers it:
88 
99| Symptom | Go to |
1010| :- | :- |
from line 17
1717| An agent that works on your machine fails in a deployed service or container | [Troubleshoot deployment failures](https://code.claude.com/docs/en/agent-sdk/hosting.md#troubleshoot-deployment-failures) |
1818| `Not logged in`, `Invalid API key`, `API Error`, `429`, `There's an issue with the selected model` | [Error reference](https://code.claude.com/docs/en/errors.md#find-your-error) |
1919| `CLINotFoundError`, `CLIConnectionError`, `ProcessError`, `Claude Code process exited with code N`, `Claude Code returned an error result`, `CLIJSONDecodeError`, `structured_output` is `None` | [CLI startup](#cli-startup), [CLI process exit](#cli-process-exit), [Large tool calls and results](#large-tool-calls-and-results), and [Structured outputs](#structured-outputs) on this page |
20| `Operation aborted`, `Claude Code process aborted by user`, `Prompt stream failed; closing stdin`, or a Python `query()` loop that stops, with no exception, before all your messages are answered | [Streaming input](#streaming-input) on this page |
21| `Image could not be processed` | [Image could not be processed](#image-could-not-be-processed) on this page |
2022 
2123## CLI startup
2224 
from line 161
159161 
1601621. If you hold a `ClaudeSDKClient` open, call `disconnect()`. The client receives no more messages after this error, but Claude Code keeps running and can still make changes.
1611632. Start a new `query()` or `ClaudeSDKClient` with the larger limit and [`continue_conversation=True`](https://code.claude.com/docs/en/agent-sdk/sessions#continue-resume-and-fork), which picks the most recent session in the working directory. To pick a specific session, set `resume` to `data["session_id"]` from the init [`SystemMessage`](https://code.claude.com/docs/en/agent-sdk/python#systemmessage).
164 
165## Streaming input
166 
167### Operation aborted
168 
169In TypeScript, your `for await` loop over `query()` throws one of these messages as an `AbortError`. Either one means the query was aborted:
170 
171```text theme={null}
172Operation aborted
173Claude Code process aborted by user
174```
175 
176Check for these causes:
177 
178* **Your code aborted the query**: if your code calls `abort()` on the `AbortController` you passed as the [`abortController`](https://code.claude.com/docs/en/agent-sdk/typescript#options) option, the loop throws one of these errors. If you didn't intend the abort, check where your code calls `abort()`.
179* **Your async generator threw**: the error doesn't include your generator's own error message. To see that message, wrap the generator's body in `try`/`catch`, log the caught error, and rethrow it. Then fix the error you logged.
180 
181### Prompt stream failed; closing stdin
182 
183In Python, when the async generator you passed to the `query()` function raises an exception, your `async for` loop over `query()` ends with no exception. The SDK logs this line at `ERROR` level. If you haven't configured logging, Python prints the line to stderr:
184 
185```text theme={null}
186Prompt stream failed; closing stdin: <your exception's message>
187```
188 
189To see the exception's traceback, wrap the generator's body in `try`/`except`. Log the exception with its traceback and raise it again. Then fix the exception you logged.
190 
191### Image could not be processed
192 
193When an image block in your message has no `source` object, no error reaches your code. Claude receives this text note in place of the image:
194 
195```text theme={null}
196[Image could not be processed: image block has no source object]
197```
198 
199Claude answers without the image. Check that each image block has a `source` object, as in [Send a follow-up with an image](https://code.claude.com/docs/en/agent-sdk/streaming-vs-single-mode.md#send-a-follow-up-with-an-image).
162200 
163201## Structured outputs
164202 

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

from line 333
333333>
334334> * A single-shot `query()` call yields the final result message, then raises an error that includes the failure text, such as `Reached maximum number of turns`. The raise is intentional. Wrap the loop in a try block if your code needs to continue past it. The underlying Claude Code process also exits with a nonzero code.
335335> * A streaming input session stays alive, and you can keep sending messages, except after a session crash, which emits a final `error_during_execution` result and exits the process.
336> * In TypeScript, the loop over `query()` in a streaming input session throws when the last response ends in an error result. Wrap the loop in a try block if your code needs to continue past it.
336337 
337338The result also includes a `stop_reason` field (`string | null` in TypeScript, `str | None` in Python) indicating why the model stopped generating on its final turn. Common values are `end_turn` (model finished normally), `max_tokens` (hit the output token limit), and `refusal` (the model declined the request). On error results that the loop produced, `stop_reason` carries the value from the last assistant response before the loop ended; the result Claude Code synthesizes after a session crash carries `null`.
338339 

agent-sdk/cost-tracking Changed · +1 / -1 lines

from line 87
8787| `total_cost_usd` | Included. Counts subagent requests alongside the top-level loop |
8888| `modelUsage` / `model_usage` | Included. Counts subagent requests alongside the top-level loop, broken down by model |
8989 
90In [single message input mode](https://code.claude.com/docs/en/agent-sdk/streaming-vs-single-mode.md#single-message-input), when background subagents are still running at the end of the final turn, Claude Code waits for them, up to the cap described in [background tasks at exit](https://code.claude.com/docs/en/headless.md#background-tasks-at-exit), before emitting the result. The result's `total_cost_usd`, `duration_api_ms`, and `modelUsage`, or `model_usage` in Python, include the work done during that wait.
90In [single message input mode](https://code.claude.com/docs/en/agent-sdk/streaming-vs-single-mode.md#choose-single-shot-or-streaming-input), Claude Code waits for background subagents still running at the end of the final turn before emitting the result. The wait lasts up to the cap described in [background tasks at exit](https://code.claude.com/docs/en/headless.md#background-tasks-at-exit). The result's `total_cost_usd`, `duration_api_ms`, and `modelUsage`, or `model_usage` in Python, include the work done during that wait.
9191 
9292The following examples iterate over the message stream from a `query()` call and print the total cost when the `result` message arrives:
9393 

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

from line 214
214214 
215215> [!NOTE]
216216>
217> This example uses streaming to show progress in real-time. If you don't need live output (for example, for background jobs or CI pipelines), you can collect all messages at once. See [Streaming vs. single-turn mode](https://code.claude.com/docs/en/agent-sdk/streaming-vs-single-mode.md) for details.
217> This example prints Claude's text and tool calls as the loop receives them. If you don't need live output, collect the messages in the loop and read them after the loop ends. To choose between a single-shot `query()` and streaming input, see [Choose single-shot or streaming input](https://code.claude.com/docs/en/agent-sdk/streaming-vs-single-mode.md#choose-single-shot-or-streaming-input).
218218 
219219### Run your agent
220220 

agent-sdk/todo-tracking Changed · +1 / -1 lines

from line 367
367367 
368368* [Agent SDK reference - TypeScript](https://code.claude.com/docs/en/agent-sdk/typescript.md): the options, types, and tool schemas for the TypeScript SDK, including the Task tool input and output types
369369* [Agent SDK reference - Python](https://code.claude.com/docs/en/agent-sdk/python.md): the options, types, and tool documentation for the Python SDK
370* [Streaming Input](https://code.claude.com/docs/en/agent-sdk/streaming-vs-single-mode.md): the two input modes, and when to use streaming input instead of the single-shot calls these examples use
370* [Send messages to a running agent](https://code.claude.com/docs/en/agent-sdk/streaming-vs-single-mode.md): use streaming input in place of the single-shot calls these examples use
371371* [Give Claude custom tools](https://code.claude.com/docs/en/agent-sdk/custom-tools.md): define your own tools with the SDK's in-process MCP server
372372 
Feedback