claude_codes/io/result.rs
1use serde::{Deserialize, Deserializer, Serialize, Serializer};
2use serde_json::Value;
3use std::fmt;
4
5/// Result message for completed queries
6#[derive(Debug, Clone, Serialize, Deserialize)]
7pub struct ResultMessage {
8 pub subtype: ResultSubtype,
9 pub is_error: bool,
10 pub duration_ms: u64,
11 pub duration_api_ms: u64,
12
13 /// Time to first token, in milliseconds.
14 #[serde(skip_serializing_if = "Option::is_none")]
15 pub ttft_ms: Option<u64>,
16
17 /// Time to first streamed token, in milliseconds.
18 #[serde(skip_serializing_if = "Option::is_none")]
19 pub ttft_stream_ms: Option<u64>,
20
21 /// Time from session start until the first request was issued, in milliseconds.
22 #[serde(skip_serializing_if = "Option::is_none")]
23 pub time_to_request_ms: Option<u64>,
24
25 /// How [`time_to_request_ms`](Self::time_to_request_ms) was spent, in
26 /// integer milliseconds per phase, summing to it exactly (CLI 2.1.285+):
27 /// `system_prompt`, `system_prompt_rebuild` (a second assembly of the
28 /// system prompt, run when the tool pool re-read after the message was
29 /// handled differs from the turn-start pool; CLIs before 2.1.287 report
30 /// it inside `system_prompt`), `resume_other` (settling, before the
31 /// turn's own prompt, tool calls that an earlier run left open or the
32 /// session's client handed over — see
33 /// [`turn_start_resume_kind`](Self::turn_start_resume_kind) — excluding
34 /// four parts that have keys of their own: `resume_store_confirm`,
35 /// `resume_staged_files_wait`, `resume_connector_wait` and
36 /// `turn_start_tool_run`; CLIs before 2.1.287 report these five as one
37 /// `turn_start_resume` key), `process_user_input` (excluding
38 /// `input_images`, `input_attachments`, `input_command` and
39 /// `input_hooks`, which have keys of their own on 2.1.287+),
40 /// `transcript_persist`, `init_message`, `engine_pickup`,
41 /// `memory_recall_wait`, `memory_context_wait`, `autocompact`,
42 /// `query_setup`, `tool_schema_build`, `message_normalization`,
43 /// `client_creation` and `other` (the remainder no phase covers). A phase
44 /// that did not run is absent; `other` is always present. Open set —
45 /// keep unrecognized phase names. Present where `time_to_request_ms` is,
46 /// on `CLAUDE_CODE_REMOTE` sessions and hosts that set
47 /// `CLAUDE_CODE_EMIT_STARTUP_TIMING`; absent elsewhere.
48 #[serde(default, skip_serializing_if = "Option::is_none")]
49 pub time_to_request_phases_ms: Option<std::collections::BTreeMap<String, u64>>,
50
51 /// What the turn was given to settle before its own prompt; the
52 /// `resume_*` phases and `turn_start_tool_run` in
53 /// [`time_to_request_phases_ms`](Self::time_to_request_phases_ms) say how
54 /// long that took (CLI 2.1.287+). A turn given more than one kind reports
55 /// the first in [`TurnStartResumeKind`] order. Present where
56 /// `time_to_request_phases_ms` is.
57 #[serde(default, skip_serializing_if = "Option::is_none")]
58 pub turn_start_resume_kind: Option<TurnStartResumeKind>,
59
60 /// On a turn the session's client handed over (`turn_start_resume_kind`
61 /// is `turn_handoff`), how long its `turn_handoff` control request waited
62 /// from its arrival on the session server's SSE stream until the input
63 /// loop read it, in integer ms, split into `startup_wait`,
64 /// `control_requests_ahead` and `user_frames_ahead` (each absent when 0)
65 /// and `before_read` (the rest, always present). The values sum to the
66 /// wait. Open set — keep unrecognized part names. Present only on
67 /// results that carry `turn_start_resume_kind` (CLI 2.1.300+).
68 #[serde(default, skip_serializing_if = "Option::is_none")]
69 pub handoff_intake_phases_ms: Option<std::collections::BTreeMap<String, u64>>,
70
71 /// Number of earlier turns of this CLI process that sent a
72 /// main-conversation model request: 0 is the process's first turn to
73 /// reach the model, not the conversation's first. Turns stopped or
74 /// failed after sending count but carry no value, so values can skip.
75 /// Where one process hosts several sessions, each has its own count.
76 /// Present where
77 /// [`time_to_request_phases_ms`](Self::time_to_request_phases_ms) is
78 /// (CLI 2.1.285+).
79 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub process_turn_index: Option<u64>,
81
82 /// CPU time (user plus system) the CLI process used from turn start
83 /// until it sent the turn's first main-conversation model request, in
84 /// milliseconds (CLI 2.1.285+). Near `time_to_request_ms`, the window
85 /// was mostly computing; near 0, mostly waiting. It adds up all threads,
86 /// so it can exceed the window, and leaves out child processes. Present
87 /// where `time_to_request_phases_ms` is, unless the runtime reports no
88 /// resource usage or the process hosts other sessions too.
89 #[serde(default, skip_serializing_if = "Option::is_none")]
90 pub time_to_request_cpu_ms: Option<u64>,
91
92 /// The longest single stall of the session's thread between turn start
93 /// and the turn's first main-conversation model request, in
94 /// milliseconds, measured as how late a 50 ms timer fired (CLI
95 /// 2.1.285+): the real stall can be up to 50 ms longer, and a few ms is
96 /// timer noise. Only the first two minutes are measured. Present where
97 /// `time_to_request_phases_ms` is.
98 #[serde(default, skip_serializing_if = "Option::is_none")]
99 pub time_to_request_loop_lag_ms: Option<u64>,
100
101 /// Major page faults (waits for memory to be read from disk) by the
102 /// process in the
103 /// [`time_to_request_cpu_ms`](Self::time_to_request_cpu_ms) window;
104 /// Windows also counts faults needing no disk read. Present where
105 /// `time_to_request_cpu_ms` is (CLI 2.1.285+).
106 #[serde(default, skip_serializing_if = "Option::is_none")]
107 pub time_to_request_major_faults: Option<u64>,
108
109 /// Resident memory of the CLI process at turn start, in whole MiB
110 /// (`VmRSS`), child processes left out. Sent only by a worker Anthropic
111 /// hosts, with telemetry on, on Linux (not WSL); there it is present,
112 /// always with [`process_rss_mib_result`](Self::process_rss_mib_result),
113 /// where `process_turn_index` is, unless the process hosts other
114 /// sessions too (CLI 2.1.300+).
115 #[serde(default, skip_serializing_if = "Option::is_none")]
116 pub process_rss_mib_turn_start: Option<u64>,
117
118 /// The anonymous part (`RssAnon`: heaps, stacks, JIT code) of
119 /// [`process_rss_mib_turn_start`](Self::process_rss_mib_turn_start), in
120 /// whole MiB (CLI 2.1.300+).
121 #[serde(default, skip_serializing_if = "Option::is_none")]
122 pub process_anon_mib_turn_start: Option<u64>,
123
124 /// As [`process_rss_mib_turn_start`](Self::process_rss_mib_turn_start),
125 /// read again just before this result is built: the level the turn
126 /// leaves behind (CLI 2.1.300+).
127 #[serde(default, skip_serializing_if = "Option::is_none")]
128 pub process_rss_mib_result: Option<u64>,
129
130 /// The anonymous part of
131 /// [`process_rss_mib_result`](Self::process_rss_mib_result), in whole
132 /// MiB (CLI 2.1.300+).
133 #[serde(default, skip_serializing_if = "Option::is_none")]
134 pub process_anon_mib_result: Option<u64>,
135
136 /// The most memory the process has had resident from its start until
137 /// this result (`VmHWM`), in whole MiB — not this turn's peak alone
138 /// (CLI 2.1.300+).
139 #[serde(default, skip_serializing_if = "Option::is_none")]
140 pub process_peak_rss_mib: Option<u64>,
141
142 /// CPU time (user plus system, all threads, no child processes) the CLI
143 /// process used from the end of its previous turn to this turn's start,
144 /// in ms. Divide sums of it by sums of
145 /// [`process_wall_ms_between_turns`](Self::process_wall_ms_between_turns),
146 /// which always comes with it, for CPU per second. Present where
147 /// [`process_cpu_ms_turn`](Self::process_cpu_ms_turn) is, from the
148 /// process's second turn on (CLI 2.1.300+).
149 #[serde(default, skip_serializing_if = "Option::is_none")]
150 pub process_cpu_ms_between_turns: Option<u64>,
151
152 /// Monotonic wall time of the
153 /// [`process_cpu_ms_between_turns`](Self::process_cpu_ms_between_turns)
154 /// stretch, in ms (CLI 2.1.300+).
155 #[serde(default, skip_serializing_if = "Option::is_none")]
156 pub process_wall_ms_between_turns: Option<u64>,
157
158 /// CPU time, counted as in
159 /// [`process_cpu_ms_between_turns`](Self::process_cpu_ms_between_turns),
160 /// from this turn's start until just before this result is built,
161 /// including the waits for the model and tools. Always comes with
162 /// [`process_wall_ms_turn`](Self::process_wall_ms_turn). Sent only by the
163 /// workers named under
164 /// [`process_rss_mib_turn_start`](Self::process_rss_mib_turn_start)
165 /// (CLI 2.1.300+).
166 #[serde(default, skip_serializing_if = "Option::is_none")]
167 pub process_cpu_ms_turn: Option<u64>,
168
169 /// Monotonic wall time of the
170 /// [`process_cpu_ms_turn`](Self::process_cpu_ms_turn) stretch, in ms
171 /// (CLI 2.1.300+).
172 #[serde(default, skip_serializing_if = "Option::is_none")]
173 pub process_wall_ms_turn: Option<u64>,
174
175 /// How long, within the
176 /// [`process_cpu_ms_turn`](Self::process_cpu_ms_turn) stretch and by its
177 /// clock, a response stream of a main-conversation model request was
178 /// open, in ms: from the stream's first event until the CLI stopped
179 /// reading it. Summed over the turn's requests; overlapping streams count
180 /// once. Subagent, side-request and compaction streams are not in it
181 /// (CLI 2.1.311+).
182 #[serde(default, skip_serializing_if = "Option::is_none")]
183 pub process_wall_ms_streaming: Option<u64>,
184
185 /// CPU time, counted as in
186 /// [`process_cpu_ms_between_turns`](Self::process_cpu_ms_between_turns),
187 /// used inside
188 /// [`process_wall_ms_streaming`](Self::process_wall_ms_streaming); part
189 /// of [`process_cpu_ms_turn`](Self::process_cpu_ms_turn). Always comes
190 /// with `process_wall_ms_streaming`, `main_stream_count` and
191 /// `main_stream_event_count` (CLI 2.1.311+).
192 #[serde(default, skip_serializing_if = "Option::is_none")]
193 pub process_cpu_ms_streaming: Option<u64>,
194
195 /// How many streams
196 /// [`process_wall_ms_streaming`](Self::process_wall_ms_streaming)
197 /// covers: one per attempt of a main-conversation model request that
198 /// brought a first event, so a retry counts again (CLI 2.1.311+).
199 #[serde(default, skip_serializing_if = "Option::is_none")]
200 pub main_stream_count: Option<u64>,
201
202 /// How many stream events the API sent on those streams, leaving out
203 /// keepalive pings the CLI makes up itself (CLI 2.1.311+).
204 #[serde(default, skip_serializing_if = "Option::is_none")]
205 pub main_stream_event_count: Option<u64>,
206
207 /// In how many chunks the runtime's fetch handed over the bodies of
208 /// those streams. Absent, never 0, when chunks were not counted (Bedrock,
209 /// Vertex, Foundry, Mantle, byte watchdog off, or a stream still open)
210 /// (CLI 2.1.311+).
211 #[serde(default, skip_serializing_if = "Option::is_none")]
212 pub main_stream_chunk_count: Option<u64>,
213
214 /// Bit set of the runtime tuning variables the CLI process was started
215 /// with (set and not empty): 1 `BUN_GC_TIMER_INTERVAL`, 2
216 /// `MIMALLOC_PURGE_HOLES_MIN_INTERVAL`, 4 `BUN_IDLE_GC_SECONDS`, 8
217 /// `MIMALLOC_PURGE_DELAY`, 16 `BUN_JSC_useFTLJIT`, 32
218 /// `BUN_JSC_percentCPUPerMBForEdenTimer`, 64
219 /// `BUN_JSC_percentCPUPerMBForFullTimer`. Names only, never values. Sent
220 /// only by the workers named under
221 /// [`process_rss_mib_turn_start`](Self::process_rss_mib_turn_start), on
222 /// results of any subtype (CLI 2.1.311+).
223 #[serde(default, skip_serializing_if = "Option::is_none")]
224 pub process_start_tuning: Option<u64>,
225
226 /// `MIMALLOC_PURGE_DELAY` in ms as the CLI process was started with it.
227 /// Sent only beside
228 /// [`process_start_tuning`](Self::process_start_tuning), and absent when
229 /// the variable was unset, empty or not one to seven digits
230 /// (CLI 2.1.311+).
231 #[serde(default, skip_serializing_if = "Option::is_none")]
232 pub process_start_purge_delay_ms: Option<u64>,
233
234 /// Garbage collections on the CLI process's main thread, counted from
235 /// early start-up. Only on the process's first numbered result within an
236 /// hour of its start, when started with
237 /// `CLAUDE_CODE_COUNT_GARBAGE_COLLECTIONS=1`, and only from
238 /// Anthropic-hosted cloud workers with telemetry on (CLI 2.1.311+).
239 #[serde(default, skip_serializing_if = "Option::is_none")]
240 pub process_garbage_collections: Option<ProcessGarbageCollections>,
241
242 /// What the `input_attachments` phase of `time_to_request_phases_ms` did
243 /// on the turn, to tell a wait inside one attachment producer from a
244 /// process that was busy. Present on turns where the phase started,
245 /// unless nothing of it is known (CLI 2.1.288+).
246 #[serde(default, skip_serializing_if = "Option::is_none")]
247 pub input_attachments_detail: Option<InputAttachmentsDetail>,
248
249 /// How the `resume_store_confirm` phase of `time_to_request_phases_ms`
250 /// was spent. Present where that phase is, in a session whose transcript
251 /// goes to a hosted store: on the result of a handed-off turn whose lines
252 /// were confirmed and that went on to a model request (CLI 2.1.290+).
253 #[serde(default, skip_serializing_if = "Option::is_none")]
254 pub resume_store_confirm_detail: Option<ResumeStoreConfirmDetail>,
255
256 /// Time from spawning a worker/spare until the first request was issued, in milliseconds.
257 #[serde(skip_serializing_if = "Option::is_none")]
258 pub time_to_request_from_spawn_ms: Option<u64>,
259
260 /// Whether a warm spare process was claimed for this request.
261 #[serde(skip_serializing_if = "Option::is_none")]
262 pub warm_spare_claimed: Option<bool>,
263
264 /// Whether this process started its start-up feature-flag fetch before
265 /// the wait for it, or why not: the same value as `system/init`'s
266 /// `startup_timing.flag_fetch_kick`. An open string set
267 /// (`started_in_init_*`, `started_after_init_*`, `not_asked_warm`,
268 /// `settings_pending_*`, `launch_excluded`, `not_eligible`; an `_empty`
269 /// or `_warm` ending is the flag cache at that moment). Present only
270 /// where `time_to_request_from_spawn_ms` is, and only when start-up
271 /// judged it (CLI 2.1.288+).
272 #[serde(default, skip_serializing_if = "Option::is_none")]
273 pub flag_fetch_kick: Option<String>,
274
275 /// Epoch-ish timestamp origin used by CLI timing instrumentation.
276 #[serde(skip_serializing_if = "Option::is_none")]
277 pub time_origin_ms: Option<u64>,
278
279 /// Wall-clock epoch milliseconds when the API request was sent
280 /// (fractional; from CLI timing instrumentation).
281 #[serde(skip_serializing_if = "Option::is_none")]
282 pub request_sent_wall_ms: Option<f64>,
283
284 /// Input tokens of the model call whose send time is
285 /// [`request_sent_wall_ms`](Self::request_sent_wall_ms): `input_tokens +
286 /// cache_read_input_tokens + cache_creation_input_tokens` from that call's
287 /// `message_start`, so a consumer can group turn latency by prompt size
288 /// (CLI 2.1.286+). Present only with `request_sent_wall_ms`, and only
289 /// when the sum is above zero.
290 #[serde(default, skip_serializing_if = "Option::is_none")]
291 pub first_request_input_tokens: Option<u64>,
292
293 /// Time until the first content frame of the stream arrived, in
294 /// milliseconds (CLI 2.1.260+ timing instrumentation).
295 #[serde(default, skip_serializing_if = "Option::is_none")]
296 pub first_content_frame_ms: Option<u64>,
297
298 /// Time until the first stream POST was issued, in milliseconds
299 /// (CLI 2.1.260+).
300 #[serde(default, skip_serializing_if = "Option::is_none")]
301 pub first_stream_post_ms: Option<u64>,
302
303 /// Time until the first stream POST was acknowledged, in milliseconds
304 /// (CLI 2.1.260+).
305 #[serde(default, skip_serializing_if = "Option::is_none")]
306 pub first_stream_post_ack_ms: Option<u64>,
307
308 /// Time the first stream POST spent waiting in the outbound queue, in
309 /// milliseconds (CLI 2.1.278+).
310 #[serde(default, skip_serializing_if = "Option::is_none")]
311 pub first_stream_post_queue_wait_ms: Option<u64>,
312
313 /// What the first stream POST was queued behind (CLI 2.1.278+).
314 #[serde(default, skip_serializing_if = "Option::is_none")]
315 pub first_stream_post_queued_behind: Option<StreamPostQueuedBehind>,
316
317 /// Wall-clock epoch milliseconds when the first stream POST was issued
318 /// (fractional; CLI 2.1.260+).
319 #[serde(default, skip_serializing_if = "Option::is_none")]
320 pub first_stream_post_wall_ms: Option<f64>,
321
322 /// Wall-clock epoch milliseconds when the triggering send's frame arrived
323 /// on a session reading its input from the session server's SSE stream
324 /// (`--sdk-url`), before the input loop read it (CLI 2.1.278+). With
325 /// [`frame_enqueued_wall_ms`](Self::frame_enqueued_wall_ms) and
326 /// [`turn_started_wall_ms`](Self::turn_started_wall_ms) it splits the
327 /// stretch between the server's persist and `request_sent_wall_ms` into
328 /// transit, the input loop's handling of the frame, its wait on the
329 /// command queue, and the turn's own work. Present only together with
330 /// `request_sent_wall_ms`, and only when the transport recorded the
331 /// receipt; absent on a local stdin host.
332 #[serde(default, skip_serializing_if = "Option::is_none")]
333 pub frame_received_wall_ms: Option<f64>,
334
335 /// Wall-clock epoch milliseconds when the input loop put the triggering
336 /// send's frame on the command queue (CLI 2.1.278+). Present exactly
337 /// when [`frame_received_wall_ms`](Self::frame_received_wall_ms) is.
338 #[serde(default, skip_serializing_if = "Option::is_none")]
339 pub frame_enqueued_wall_ms: Option<f64>,
340
341 /// How the triggering send's frame spent the time between
342 /// [`frame_received_wall_ms`](Self::frame_received_wall_ms) and
343 /// [`frame_enqueued_wall_ms`](Self::frame_enqueued_wall_ms), in integer
344 /// milliseconds per intake step (CLI 2.1.282+): `before_read` (until the
345 /// input loop read the frame, including any wait behind earlier frames
346 /// and a first message's wait for the worker to finish starting),
347 /// `dedup`, `flag_settle`, `receive_hook`, `attachments`,
348 /// `admission_wait` (held behind a pending model switch, a pending MCP
349 /// server-set change, start-up work the worker still owed its first
350 /// turn, or an earlier held frame), `admit_check` (the host's decision
351 /// whether to queue the frame, when it had to be awaited) and `other`.
352 /// Steps that did not run are absent; `before_read` and `other` are
353 /// always present. The values sum to the enqueued-minus-received gap
354 /// unless a step came out negative and was clamped to 0. Open set —
355 /// keep unrecognized step names. Present exactly when
356 /// `frame_received_wall_ms` is, except from older producers.
357 #[serde(default, skip_serializing_if = "Option::is_none")]
358 pub frame_intake_phases_ms: Option<std::collections::BTreeMap<String, u64>>,
359
360 /// Wall-clock epoch milliseconds when the turn's clock started: the
361 /// anchor `duration_ms`, `ttft_ms`, `ttft_stream_ms`,
362 /// `time_to_request_ms`, `first_content_frame_ms`, `first_stream_post_ms`
363 /// and `first_stream_post_ack_ms` are measured from (CLI 2.1.278+).
364 /// Present exactly when
365 /// [`frame_received_wall_ms`](Self::frame_received_wall_ms) is.
366 #[serde(default, skip_serializing_if = "Option::is_none")]
367 pub turn_started_wall_ms: Option<f64>,
368
369 /// How the time from
370 /// [`frame_enqueued_wall_ms`](Self::frame_enqueued_wall_ms) to
371 /// [`turn_started_wall_ms`](Self::turn_started_wall_ms) was spent, in
372 /// integer milliseconds per step of the host's work through its message
373 /// queue (CLI 2.1.285+): `idle`, `earlier_turn`, `after_turn`,
374 /// `background_wait`, `entry_joins`, `sdk_mcp_update`, `loop_top`,
375 /// `session_start_wait`, `first_command`, `mcp_prewait`, `repo_wait`,
376 /// `turn_joins`, `tool_pool`, `commit`, `after_arm`, `turn_gate`,
377 /// `turn_open`, `engine_setup`, `tool_reread`, `cwd` and `other`. Each
378 /// step is where the host was at the time, which for part of the stretch
379 /// may be an earlier message's turn. A step that rounds to 0 is absent;
380 /// `other` is always present. The values sum to the started-minus-enqueued
381 /// gap, except that they can exceed it (usually by 1 ms from rounding).
382 /// Open set — keep unrecognized step names. Present only when
383 /// `frame_received_wall_ms` is, and absent from older producers.
384 #[serde(default, skip_serializing_if = "Option::is_none")]
385 pub turn_start_phases_ms: Option<std::collections::BTreeMap<String, u64>>,
386
387 /// Of the time from `frame_enqueued_wall_ms` to `turn_started_wall_ms`,
388 /// the integer milliseconds in which the `claude -p` host's message
389 /// reader was held by control requests (such as `mcp_set_servers` or
390 /// `set_permission_mode`) instead of reading the next message (CLI
391 /// 2.1.285+). It overlaps
392 /// [`turn_start_phases_ms`](Self::turn_start_phases_ms) and is not part
393 /// of its sum. Absent when 0.
394 #[serde(default, skip_serializing_if = "Option::is_none")]
395 pub turn_start_control_requests_ms: Option<u64>,
396
397 /// Time until the first text POST was issued, in milliseconds
398 /// (CLI 2.1.278+).
399 #[serde(default, skip_serializing_if = "Option::is_none")]
400 pub first_text_post_ms: Option<u64>,
401
402 /// Time the first text POST spent waiting in the outbound queue, in
403 /// milliseconds (CLI 2.1.287+).
404 #[serde(default, skip_serializing_if = "Option::is_none")]
405 pub first_text_post_queue_wait_ms: Option<u64>,
406
407 /// What the first text POST was queued behind (CLI 2.1.287+); the same
408 /// value set as
409 /// [`first_stream_post_queued_behind`](Self::first_stream_post_queued_behind).
410 #[serde(default, skip_serializing_if = "Option::is_none")]
411 pub first_text_post_queued_behind: Option<StreamPostQueuedBehind>,
412
413 /// Wall-clock epoch milliseconds when the first text POST was issued
414 /// (fractional; CLI 2.1.278+).
415 #[serde(default, skip_serializing_if = "Option::is_none")]
416 pub first_text_post_wall_ms: Option<f64>,
417
418 /// Wire uuid of the user message this result answers.
419 #[serde(skip_serializing_if = "Option::is_none")]
420 pub user_message_uuid: Option<String>,
421
422 /// The [`server_received_wall_ms`](crate::io::UserMessage::server_received_wall_ms)
423 /// of the user message [`user_message_uuid`](Self::user_message_uuid)
424 /// names, copied unchanged, so the session server can measure from its
425 /// own receipt to `request_sent_wall_ms` (CLI 2.1.286+). Present only with
426 /// `request_sent_wall_ms`, and only when that message carried a positive
427 /// finite number there.
428 #[serde(default, skip_serializing_if = "Option::is_none")]
429 pub user_message_server_received_wall_ms: Option<f64>,
430
431 /// Client uuids of every user message whose prompt this turn consumed, in
432 /// consumption order — all members of a prompt batch the host merged into
433 /// this one turn, plus any queued user message folded into the running
434 /// turn between tool rounds. Always contains `user_message_uuid`; at most
435 /// 64 entries. Absent on delivery-failure/zeroed results and from CLIs
436 /// before 2.1.259 (fall back to `user_message_uuid`).
437 #[serde(default, skip_serializing_if = "Vec::is_empty")]
438 pub user_message_uuids: Vec<String>,
439
440 /// Why this turn was the automatic re-run of a turn a worker restart
441 /// interrupted (`CLAUDE_CODE_RESUME_INTERRUPTED_TURN`): the host's
442 /// `CLAUDE_CODE_RESUME_REASON` when it set one (`host_draining`,
443 /// `checkpoint_restore`, `container_recreated`, ...), else
444 /// `interrupted_turn`. Present on a headless re-run's result, success or
445 /// error; absent on every other turn, on the Remote Control bridge's
446 /// per-turn synthetic results, and from CLIs before 2.1.268.
447 #[serde(default, skip_serializing_if = "Option::is_none")]
448 pub resume_reason: Option<String>,
449
450 /// The local slash command that produced this result when the query loop
451 /// was bypassed (success results only). Absent when the turn went to the
452 /// model and from CLIs before 2.1.268.
453 #[serde(default, skip_serializing_if = "Option::is_none")]
454 pub local_command: Option<String>,
455
456 /// User-initiated sends still waiting in the command queue when this
457 /// result was produced. Greater than 0 means at least one more user turn
458 /// follows without further input, barring cancellation. Absent on fatal
459 /// startup results, on surfaces without a command queue, and from CLIs
460 /// before 2.1.259.
461 #[serde(default, skip_serializing_if = "Option::is_none")]
462 pub queued_turn_count: Option<u64>,
463
464 pub num_turns: i32,
465
466 #[serde(skip_serializing_if = "Option::is_none")]
467 pub result: Option<String>,
468
469 #[serde(alias = "sessionId")]
470 pub session_id: String,
471 pub total_cost_usd: f64,
472
473 #[serde(skip_serializing_if = "Option::is_none")]
474 pub usage: Option<UsageInfo>,
475
476 /// Tools that were blocked due to permission denials during the session
477 #[serde(default)]
478 pub permission_denials: Vec<PermissionDenial>,
479
480 /// Error messages when `is_error` is true.
481 ///
482 /// Contains human-readable error strings (e.g., "No conversation found with session ID: ...").
483 /// This allows typed access to error conditions without needing to serialize to JSON and search.
484 #[serde(default)]
485 pub errors: Vec<String>,
486
487 #[serde(skip_serializing_if = "Option::is_none")]
488 pub uuid: Option<String>,
489
490 /// HTTP status code when the result is an API error (e.g., 429, 500, 529)
491 #[serde(skip_serializing_if = "Option::is_none")]
492 pub api_error_status: Option<u16>,
493
494 /// The `api_error_code` of the API error that ended the turn (see
495 /// `AssistantMessage::api_error_code`): the server's
496 /// `error.details.error_code` when it is an identifier. Absent when the
497 /// turn did not end on an API error, when the response carried no code,
498 /// and from CLIs before 2.1.274.
499 #[serde(default, skip_serializing_if = "Option::is_none")]
500 pub api_error_code: Option<String>,
501
502 /// The `api_error_origin` of the API error that ended the turn (see
503 /// `AssistantMessage::api_error_origin`): `first_party` when Anthropic's
504 /// own API sent the response. Absent when the turn did not end on an API
505 /// error or the origin is anything else; treat an unknown value as
506 /// absent (CLI 2.1.300+).
507 #[serde(default, skip_serializing_if = "Option::is_none")]
508 pub api_error_origin: Option<String>,
509
510 /// The typed kind of the API error that ended the turn (see
511 /// `AssistantMessage::api_error`). Absent when the turn did not end on
512 /// an API error, when the error has no typed kind, and from CLIs before
513 /// 2.1.285; treat an unknown value as absent.
514 #[serde(default, skip_serializing_if = "Option::is_none")]
515 pub api_error: Option<String>,
516
517 /// Why generation stopped (e.g., end_turn, max_tokens)
518 #[serde(skip_serializing_if = "Option::is_none")]
519 pub stop_reason: Option<String>,
520
521 /// Why the session ended (e.g., "completed")
522 #[serde(skip_serializing_if = "Option::is_none")]
523 pub terminal_reason: Option<String>,
524
525 /// Present, and true, when the host of a multi-tenant worker shut the
526 /// worker down while this turn ran, the shutdown was the first thing to
527 /// abort the turn, and the turn is left for the session's next worker.
528 /// The other frames of the ending, and `terminal_reason`, look the same
529 /// as a client's Stop; this tells the two apart. A success result can
530 /// carry it (a shutdown during a Stop hook), and a result without it can
531 /// still be a shutdown's (CLI 2.1.300+).
532 #[serde(default, skip_serializing_if = "Option::is_none")]
533 pub interrupted_by_shutdown: Option<bool>,
534
535 /// Delivery sequence of this result within the run: how many results the
536 /// run numbered before this one, starting at 0, in the order the process
537 /// writes them. A result whose write fails still consumes its number, so
538 /// a gap means a result was lost. Distinct from `num_turns`. Numbered by
539 /// the process hosting the run (`claude -p`); a local client relaying a
540 /// cloud session passes the cloud numbering through and its own locally
541 /// built error results carry none. Absent from CLIs before 2.1.268.
542 #[serde(default, skip_serializing_if = "Option::is_none")]
543 pub result_index: Option<u64>,
544
545 /// Fast mode toggle state (e.g., "off")
546 #[serde(skip_serializing_if = "Option::is_none")]
547 pub fast_mode_state: Option<String>,
548
549 /// Why fast mode can't serve right now. Absent when nothing blocks it.
550 /// A paused-after-rate-limit run is not reported here; it rides
551 /// `fast_mode_state` as `"cooldown"`.
552 #[serde(skip_serializing_if = "Option::is_none")]
553 pub fast_mode_disabled_reason: Option<FastModeDisabledReason>,
554
555 /// Per-model cost breakdown, keyed by model name (e.g. `"claude-opus-4-8"`).
556 #[serde(skip_serializing_if = "Option::is_none", rename = "modelUsage")]
557 pub model_usage: Option<std::collections::BTreeMap<String, ModelUsageEntry>>,
558
559 /// Per-model usage and cost of the calls this process counted since it
560 /// wrote its previous result (since it started, for its first), keyed and
561 /// shaped like `modelUsage` and covering the same calls. Sum it over a
562 /// conversation's results instead of subtracting `modelUsage` totals: each
563 /// call is stated on at most one result, whatever a resume or a kill does
564 /// to `modelUsage`. Calls that finish after a result (a background
565 /// subagent, a late title call) are stated on the next result. Nothing is
566 /// carried across processes, so calls counted after a process's last
567 /// result (including a turn in flight when it is killed) are stated
568 /// nowhere. A model with nothing counted is left out; `{}` means nothing
569 /// was counted, and absent is not `{}`. Set by stream-json and `--sdk-url`
570 /// runs only; not set on hand-numbered error results (start-up failures,
571 /// errors that escape the run). Absent from CLIs before 2.1.309. Marked
572 /// `@internal` upstream.
573 #[serde(default, skip_serializing_if = "Option::is_none")]
574 pub model_usage_since_last_result: Option<std::collections::BTreeMap<String, ModelUsageEntry>>,
575
576 /// Subagents started through the Agent tool in this session, as running
577 /// totals. Cumulative like `modelUsage`: read the latest result rather
578 /// than summing across results. Absent from CLIs before 2.1.239.
579 #[serde(skip_serializing_if = "Option::is_none")]
580 pub subagent_stats: Option<SubagentStats>,
581
582 /// How many times a safety system has stopped one of this session's
583 /// model calls (main loop, subagents, forked skills, compaction and other
584 /// internal calls), as a running total since the session started in this
585 /// process: a `refusal` stop reason, a refusal answered on a fallback
586 /// model, output the API's content filter stopped, and (where the build
587 /// can tell) a server-side safety monitor block. Never sum across
588 /// results. Not saved, so a resumed session or a mid-session `/clear`
589 /// starts again at 0: over a stored log any result above 0 means a stop
590 /// happened, and a later 0 does not cancel it. Absent from CLIs before
591 /// 2.1.292. Marked `@internal` upstream.
592 #[serde(default, skip_serializing_if = "Option::is_none")]
593 pub safety_stops: Option<u64>,
594
595 /// Structured-output payload returned by the model, when enabled.
596 #[serde(skip_serializing_if = "Option::is_none")]
597 pub structured_output: Option<Value>,
598
599 /// Deferred tool-use termination payload.
600 #[serde(skip_serializing_if = "Option::is_none")]
601 pub deferred_tool_use: Option<DeferredToolUse>,
602
603 /// Provenance of the message/run.
604 #[serde(skip_serializing_if = "Option::is_none")]
605 pub origin: Option<super::message_types::MessageOrigin>,
606
607 /// Set by the self-hosted runner on the result it synthesizes when the
608 /// session process fails to start or exits abnormally. Absent on normal
609 /// results and on CLIs before 2.1.266.
610 #[serde(default, skip_serializing_if = "Option::is_none")]
611 pub runner_exit: Option<RunnerExit>,
612
613 /// Why Claude Code refused to start. Set on the zeroed
614 /// `error_during_execution` result a stream-json run writes before
615 /// exiting on a known startup failure; `errors` carries the same text as
616 /// stderr. Failures that used to end with stderr alone write that result
617 /// only when the host sets `CLAUDE_CODE_STARTUP_FAILURE_RESULTS`. Absent
618 /// on every other result, on startup failures without a known cause, and
619 /// from CLIs before 2.1.274.
620 #[serde(default, skip_serializing_if = "Option::is_none")]
621 pub startup_failure_reason: Option<StartupFailureReason>,
622}
623
624/// [`ResultMessage::input_attachments_detail`] — what the
625/// `input_attachments` phase did on the turn (CLI 2.1.288+).
626#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
627pub struct InputAttachmentsDetail {
628 /// Label of the attachment producer that took longest from its start to
629 /// its result, among those that began within the phase.
630 #[serde(default, skip_serializing_if = "Option::is_none")]
631 pub slowest_producer: Option<String>,
632 /// How long [`Self::slowest_producer`] took. Well above
633 /// [`Self::cpu_ms`], that producer most likely waited (on a file, the
634 /// network or a child process).
635 #[serde(default, skip_serializing_if = "Option::is_none")]
636 pub slowest_producer_ms: Option<u64>,
637 /// `time_to_request_cpu_ms`'s counter over this phase alone. Absent
638 /// wherever `time_to_request_cpu_ms` is absent, and when the turn's
639 /// first model request went out before the phase ended.
640 #[serde(default, skip_serializing_if = "Option::is_none")]
641 pub cpu_ms: Option<u64>,
642 /// `time_to_request_major_faults`'s counter over this phase alone.
643 /// Absent where [`Self::cpu_ms`] is.
644 #[serde(default, skip_serializing_if = "Option::is_none")]
645 pub major_faults: Option<u64>,
646 /// How many files the `changed_files` producer set out to read again in
647 /// full because their modification time was later than the one recorded
648 /// when the conversation last wrote or edited them. Absent when the
649 /// conversation's record of files was empty or the producer did not run.
650 #[serde(default, skip_serializing_if = "Option::is_none")]
651 pub changed_files_reread: Option<u64>,
652 /// How the `changed_files` producer's compares ended in the main
653 /// thread's pass (a subagent's are not counted). Absent when nothing was
654 /// counted (CLI 2.1.300+).
655 #[serde(default, skip_serializing_if = "Option::is_none")]
656 pub touch_compare: Option<TouchCompareCounts>,
657}
658
659/// [`InputAttachmentsDetail::touch_compare`] — how the `changed_files`
660/// producer's compares of touched files (size, then bytes, against what the
661/// conversation last saw) ended. Whole numbers; a zero count is left out
662/// (CLI 2.1.300+).
663#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
664pub struct TouchCompareCounts {
665 /// The text had not changed, so it was not read again.
666 #[serde(default, skip_serializing_if = "Option::is_none")]
667 pub same: Option<u64>,
668 /// The text had changed, so it was read again.
669 #[serde(default, skip_serializing_if = "Option::is_none")]
670 pub differs: Option<u64>,
671 /// Those of `same` and `differs` reached through the hosted container's
672 /// outputs link (`/mnt/user-data/outputs` → `/mnt/attach/outputs`).
673 #[serde(default, skip_serializing_if = "Option::is_none")]
674 pub via_outputs_link: Option<u64>,
675 /// Not compared, because the conversation has seen only part of the
676 /// file; read again.
677 #[serde(default, skip_serializing_if = "Option::is_none")]
678 pub partial_view: Option<u64>,
679 /// Not compared, because it was compared once already since the
680 /// conversation last read or wrote it; read again.
681 #[serde(default, skip_serializing_if = "Option::is_none")]
682 pub already_compared: Option<u64>,
683 /// The file could not be shown to be the one its path names (a symbolic
684 /// link on the way, an unjudged outputs-link landing, or the file swapped
685 /// or removed meanwhile); read again.
686 #[serde(default, skip_serializing_if = "Option::is_none")]
687 pub link_on_path: Option<u64>,
688 /// The open met a symbolic link; read again.
689 #[serde(default, skip_serializing_if = "Option::is_none")]
690 pub leaf_link: Option<u64>,
691 /// The file has a second hard link; read again.
692 #[serde(default, skip_serializing_if = "Option::is_none")]
693 pub nlink: Option<u64>,
694 /// Not a regular file; read again.
695 #[serde(default, skip_serializing_if = "Option::is_none")]
696 pub not_regular: Option<u64>,
697 /// Too large to compare; read again.
698 #[serde(default, skip_serializing_if = "Option::is_none")]
699 pub oversize: Option<u64>,
700 /// The file was gone.
701 #[serde(default, skip_serializing_if = "Option::is_none")]
702 pub enoent: Option<u64>,
703 /// Anything else, errors included; read again.
704 #[serde(default, skip_serializing_if = "Option::is_none")]
705 pub other: Option<u64>,
706}
707
708/// [`ResultMessage::resume_store_confirm_detail`] — how the
709/// `resume_store_confirm` phase was spent (CLI 2.1.290+). The four `_ms`
710/// values sum to that phase exactly.
711#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
712pub struct ResumeStoreConfirmDetail {
713 /// The transcript write, until the carried lines are in the queue of the
714 /// lane that uploads transcript rows.
715 pub write_ms: u64,
716 /// A POST was out that held only rows queued before the hand-off's write
717 /// began.
718 pub ahead_ms: u64,
719 /// Any other POST was out, each retry included.
720 pub post_ms: u64,
721 /// No POST was out (backoff, batching, a busy event loop), plus rounding
722 /// and any POST still out when the wait was cut short.
723 pub other_ms: u64,
724 /// POST attempts that ended between the start of the write and the end
725 /// of the wait.
726 pub posts: u64,
727 /// Those of [`Self::posts`] that did not go through.
728 pub failed_posts: u64,
729 /// Rows the lane had accepted and the store had not yet confirmed when
730 /// the write began.
731 pub rows_ahead: u64,
732 /// Rows queued since then that a POST delivered, the carried lines among
733 /// them.
734 pub rows: u64,
735}
736
737/// [`ResultMessage::process_garbage_collections`] — garbage collections on
738/// the CLI process's main thread (CLI 2.1.311+). A worker claimed from a
739/// warm spare counts from the spare's own start.
740#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
741pub struct ProcessGarbageCollections {
742 /// Up to the start of the process's first turn. Absent if no turn began
743 /// first or its count failed.
744 #[serde(default, skip_serializing_if = "Option::is_none")]
745 pub to_first_message: Option<GarbageCollectionCounts>,
746 /// Up to this result, including
747 /// [`to_first_message`](Self::to_first_message)'s.
748 pub to_first_result: GarbageCollectionCounts,
749}
750
751/// One window of [`ProcessGarbageCollections`] (CLI 2.1.311+). A collection
752/// still running at the window's end is not counted.
753#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
754pub struct GarbageCollectionCounts {
755 /// Collections of young objects only (under Bun the process's first also
756 /// marks the whole heap).
757 pub eden: u64,
758 /// Collections of the whole heap.
759 pub full: u64,
760 /// Their summed wall-clock time in ms, not CPU time.
761 pub wall_ms: u64,
762 /// Heap in use after the last one, in MiB. Absent if none ran.
763 #[serde(default, skip_serializing_if = "Option::is_none")]
764 pub heap_after_mib: Option<u64>,
765}
766
767/// Why Claude Code refused to start, carried as
768/// [`ResultMessage::startup_failure_reason`] so a host can offer the fix
769/// instead of a retry (CLI 2.1.274+).
770#[derive(Debug, Clone, PartialEq, Eq, Hash)]
771pub enum StartupFailureReason {
772 /// Managed settings pin a first-party or Cloud gateway sign-in, and an
773 /// Anthropic API key or auth token is configured instead.
774 OrgPinApiKeyConflict,
775 /// Managed settings list the API providers this machine may use
776 /// (`allowedProviders`), and the session is set up for one that is not
777 /// listed (CLI 2.1.285+).
778 ProviderNotAllowed,
779 /// The sign-in's organization could not be verified against the pin
780 /// (network, or a revoked token).
781 OrgVerifyFailed,
782 /// The sign-in belongs to an organization the pin does not allow.
783 OrgPinMismatch,
784 /// Managed policy settings could not be read, the pin names no
785 /// organization, or managed model settings (`deniedModels`, or an
786 /// `availableModels` list matched exactly) block the default model and
787 /// leave no allowed model to use instead.
788 ManagedSettingsInvalid,
789 /// Managed settings the organization requires could not be loaded.
790 RemoteSettingsRequiredUnavailable,
791 /// The Cloud gateway ended this sign-in.
792 GatewaySigninRequired,
793 /// The Cloud gateway refused managed settings for this account.
794 GatewayAccessDenied,
795 /// A proxy setting is not a complete URL.
796 ProxyInvalid,
797 /// The per-user temp directory is unsafe or could not be created.
798 TempDirUnusable,
799 /// The working directory was deleted, moved or cannot be read.
800 CwdUnavailable,
801 /// Windows has no shell tool: Git Bash is missing, and PowerShell is
802 /// missing or turned off by `CLAUDE_CODE_USE_POWERSHELL_TOOL`.
803 ShellToolMissing,
804 /// The conversation to resume or continue is running as a background
805 /// session.
806 SessionHeldByBackground,
807 /// The resume was refused because the session's worktree failed its
808 /// safety checks or the resume was launched from inside it; `errors`
809 /// says whether a re-run continues without the worktree.
810 WorktreeResumeRefused,
811 /// The session's worktree could not be verified right now; retrying may
812 /// succeed.
813 WorktreeUnverified,
814 /// This Claude Code version is below the minimum Anthropic requires.
815 CliVersionTooOld,
816 /// Bypass permissions mode was requested while running as root.
817 BypassRoot,
818 /// The organization requires its policy limits and managed settings
819 /// before a session starts, and they could not be loaded (network,
820 /// proxy, or an Anthropic error); retrying may succeed (CLI 2.1.293+).
821 OrgConfigRequiredUnavailable,
822 /// The organization requires its policy limits and managed settings, and
823 /// Anthropic refused them for this sign-in (expired or revoked session,
824 /// or the organization does not allow Claude Code for this account);
825 /// signing in again or an admin's change is the fix, not a retry
826 /// (CLI 2.1.293+).
827 OrgConfigRefused,
828 /// A cause not yet known to this version of the crate.
829 Unknown(String),
830}
831
832impl StartupFailureReason {
833 pub fn as_str(&self) -> &str {
834 match self {
835 Self::OrgPinApiKeyConflict => "org_pin_api_key_conflict",
836 Self::ProviderNotAllowed => "provider_not_allowed",
837 Self::OrgVerifyFailed => "org_verify_failed",
838 Self::OrgPinMismatch => "org_pin_mismatch",
839 Self::ManagedSettingsInvalid => "managed_settings_invalid",
840 Self::RemoteSettingsRequiredUnavailable => "remote_settings_required_unavailable",
841 Self::GatewaySigninRequired => "gateway_signin_required",
842 Self::GatewayAccessDenied => "gateway_access_denied",
843 Self::ProxyInvalid => "proxy_invalid",
844 Self::TempDirUnusable => "temp_dir_unusable",
845 Self::CwdUnavailable => "cwd_unavailable",
846 Self::ShellToolMissing => "shell_tool_missing",
847 Self::SessionHeldByBackground => "session_held_by_background",
848 Self::WorktreeResumeRefused => "worktree_resume_refused",
849 Self::WorktreeUnverified => "worktree_unverified",
850 Self::CliVersionTooOld => "cli_version_too_old",
851 Self::BypassRoot => "bypass_root",
852 Self::OrgConfigRequiredUnavailable => "org_config_required_unavailable",
853 Self::OrgConfigRefused => "org_config_refused",
854 Self::Unknown(s) => s.as_str(),
855 }
856 }
857}
858
859impl fmt::Display for StartupFailureReason {
860 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
861 f.write_str(self.as_str())
862 }
863}
864
865impl From<&str> for StartupFailureReason {
866 fn from(s: &str) -> Self {
867 match s {
868 "org_pin_api_key_conflict" => Self::OrgPinApiKeyConflict,
869 "provider_not_allowed" => Self::ProviderNotAllowed,
870 "org_verify_failed" => Self::OrgVerifyFailed,
871 "org_pin_mismatch" => Self::OrgPinMismatch,
872 "managed_settings_invalid" => Self::ManagedSettingsInvalid,
873 "remote_settings_required_unavailable" => Self::RemoteSettingsRequiredUnavailable,
874 "gateway_signin_required" => Self::GatewaySigninRequired,
875 "gateway_access_denied" => Self::GatewayAccessDenied,
876 "proxy_invalid" => Self::ProxyInvalid,
877 "temp_dir_unusable" => Self::TempDirUnusable,
878 "cwd_unavailable" => Self::CwdUnavailable,
879 "shell_tool_missing" => Self::ShellToolMissing,
880 "session_held_by_background" => Self::SessionHeldByBackground,
881 "worktree_resume_refused" => Self::WorktreeResumeRefused,
882 "worktree_unverified" => Self::WorktreeUnverified,
883 "cli_version_too_old" => Self::CliVersionTooOld,
884 "bypass_root" => Self::BypassRoot,
885 "org_config_required_unavailable" => Self::OrgConfigRequiredUnavailable,
886 "org_config_refused" => Self::OrgConfigRefused,
887 other => Self::Unknown(other.to_string()),
888 }
889 }
890}
891
892impl Serialize for StartupFailureReason {
893 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
894 serializer.serialize_str(self.as_str())
895 }
896}
897
898impl<'de> Deserialize<'de> for StartupFailureReason {
899 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
900 let s = String::deserialize(deserializer)?;
901 Ok(Self::from(s.as_str()))
902 }
903}
904
905/// How the self-hosted runner's session process terminated, carried on a
906/// synthesized failure [`ResultMessage`] as [`ResultMessage::runner_exit`]
907/// (CLI 2.1.266+).
908#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
909pub struct RunnerExit {
910 /// Which phase the process was in when it exited.
911 pub phase: RunnerExitPhase,
912 /// Process exit code. Absent (or wire `null`) when it exited on a signal
913 /// instead, or when the runner did not capture one.
914 #[serde(default, skip_serializing_if = "Option::is_none")]
915 pub exit_code: Option<i64>,
916 /// Terminating signal name. Absent (or wire `null`) when it exited with a
917 /// code instead, or when the runner did not capture one.
918 #[serde(default, skip_serializing_if = "Option::is_none")]
919 pub signal: Option<String>,
920}
921
922/// Which phase the runner's session process was in when it exited, in
923/// [`RunnerExit::phase`]. Open set — unrecognized values deserialize to
924/// [`RunnerExitPhase::Unknown`].
925#[derive(Debug, Clone, PartialEq, Eq, Hash)]
926pub enum RunnerExitPhase {
927 /// Failed while starting up.
928 Setup,
929 /// Failed once running.
930 Run,
931 /// A phase not yet known to this version of the crate.
932 Unknown(String),
933}
934
935impl RunnerExitPhase {
936 pub fn as_str(&self) -> &str {
937 match self {
938 Self::Setup => "setup",
939 Self::Run => "run",
940 Self::Unknown(s) => s.as_str(),
941 }
942 }
943}
944
945impl std::fmt::Display for RunnerExitPhase {
946 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
947 f.write_str(self.as_str())
948 }
949}
950
951impl From<&str> for RunnerExitPhase {
952 fn from(s: &str) -> Self {
953 match s {
954 "setup" => Self::Setup,
955 "run" => Self::Run,
956 other => Self::Unknown(other.to_string()),
957 }
958 }
959}
960
961impl Serialize for RunnerExitPhase {
962 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
963 serializer.serialize_str(self.as_str())
964 }
965}
966
967impl<'de> Deserialize<'de> for RunnerExitPhase {
968 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
969 let s = String::deserialize(deserializer)?;
970 Ok(Self::from(s.as_str()))
971 }
972}
973
974/// Usage and cost for a single model within a session, as found in
975/// [`ResultMessage::model_usage`] and
976/// [`ResultMessage::model_usage_since_last_result`].
977///
978/// The `extra` field captures any keys the CLI adds that aren't modeled here,
979/// so new wire fields deserialize without error.
980#[derive(Debug, Clone, Default, Serialize, Deserialize)]
981#[serde(rename_all = "camelCase")]
982pub struct ModelUsageEntry {
983 #[serde(default)]
984 pub input_tokens: u64,
985 #[serde(default)]
986 pub output_tokens: u64,
987 #[serde(default)]
988 pub cache_read_input_tokens: u64,
989 #[serde(default)]
990 pub cache_creation_input_tokens: u64,
991 #[serde(default, rename = "costUSD")]
992 pub cost_usd: f64,
993 #[serde(default)]
994 pub web_search_requests: u32,
995 #[serde(default)]
996 pub context_window: u64,
997 #[serde(default)]
998 pub max_output_tokens: u64,
999 #[serde(flatten)]
1000 pub extra: serde_json::Map<String, serde_json::Value>,
1001}
1002
1003/// Tool use deferred by a terminal result.
1004#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1005pub struct DeferredToolUse {
1006 pub id: String,
1007 pub name: String,
1008 pub input: Value,
1009}
1010
1011/// Running totals for subagents started through the Agent tool, carried on
1012/// `result` frames (CLI 2.1.239+) as [`ResultMessage::subagent_stats`].
1013///
1014/// Cumulative for the session: a resumed session starts fresh, and a
1015/// mid-session `/clear` zeroes it — though a background subagent that outlives
1016/// the `/clear` still records its outcome, so `completed`, `failed`, and
1017/// `killed` can then exceed `spawned`. Forked skills, workflows, teammates,
1018/// and other internal agents are not counted.
1019#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
1020pub struct SubagentStats {
1021 /// Subagents actually started; a refused or failed launch is not counted.
1022 pub spawned: u64,
1023 /// Spawns by the `run_in_background` value the model passed; all count as
1024 /// `unset` while the parameter is not offered (background tasks disabled,
1025 /// or subagents forced into the background: in a terminal, the desktop
1026 /// app or the VS Code extension, or with `CLAUDE_CODE_FORK_SUBAGENT=1`).
1027 pub requested: SubagentSpawnRequests,
1028 /// Spawns that started in the background after defaults and session
1029 /// settings; the rest blocked the spawning tool call.
1030 pub started_in_background: u64,
1031 /// Spawns by agent type.
1032 #[serde(default)]
1033 pub by_type: std::collections::BTreeMap<String, u64>,
1034 /// Deepest spawn: 1 = started by the main thread, 2 = by a depth-1
1035 /// subagent.
1036 pub max_depth: u64,
1037 /// Spawns made from inside another subagent (depth > 1).
1038 pub spawned_by_subagents: u64,
1039 pub completed: u64,
1040 pub failed: u64,
1041 /// Subagents stopped before finishing, by who stopped them.
1042 pub killed: SubagentKillCounts,
1043 /// Agent tool calls turned down because a limit was reached (other
1044 /// denials, such as an unknown agent type, are not counted).
1045 pub refused: SubagentRefusalCounts,
1046}
1047
1048/// Spawn counts by the `run_in_background` value the model passed, carried in
1049/// [`SubagentStats::requested`].
1050#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
1051pub struct SubagentSpawnRequests {
1052 pub background: u64,
1053 pub foreground: u64,
1054 pub unset: u64,
1055}
1056
1057/// Subagents stopped before finishing, carried in [`SubagentStats::killed`].
1058/// `parent` = by another agent through TaskStop; `system` = by Claude Code
1059/// itself; `user` = any other stop.
1060#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
1061pub struct SubagentKillCounts {
1062 pub parent: u64,
1063 pub user: u64,
1064 pub system: u64,
1065}
1066
1067/// Agent tool calls refused at a limit, carried in [`SubagentStats::refused`].
1068#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
1069pub struct SubagentRefusalCounts {
1070 pub depth_limit: u64,
1071 pub concurrency_limit: u64,
1072 pub budget: u64,
1073}
1074
1075/// A record of a tool permission that was denied during the session.
1076///
1077/// This is included in `ResultMessage.permission_denials` to provide a summary
1078/// of all permission denials that occurred.
1079#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1080pub struct PermissionDenial {
1081 /// The name of the tool that was blocked (e.g., "Bash", "Write")
1082 pub tool_name: String,
1083
1084 /// The input that was passed to the tool
1085 pub tool_input: Value,
1086
1087 /// The unique identifier for this tool use request
1088 pub tool_use_id: String,
1089}
1090
1091/// What the first stream POST of a turn was queued behind, carried as
1092/// [`ResultMessage::first_stream_post_queued_behind`] (CLI 2.1.278+).
1093/// Internal timing instrumentation; the CLI does not describe the values.
1094#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1095pub enum StreamPostQueuedBehind {
1096 /// `durable_post`
1097 DurablePost,
1098 /// `ephemeral_post`
1099 EphemeralPost,
1100 /// `retry_backoff`
1101 RetryBackoff,
1102 /// `hold`
1103 Hold,
1104 /// `none`
1105 None,
1106 /// A value not yet known to this version of the crate.
1107 Unknown(String),
1108}
1109
1110impl StreamPostQueuedBehind {
1111 pub fn as_str(&self) -> &str {
1112 match self {
1113 Self::DurablePost => "durable_post",
1114 Self::EphemeralPost => "ephemeral_post",
1115 Self::RetryBackoff => "retry_backoff",
1116 Self::Hold => "hold",
1117 Self::None => "none",
1118 Self::Unknown(s) => s.as_str(),
1119 }
1120 }
1121}
1122
1123impl fmt::Display for StreamPostQueuedBehind {
1124 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1125 f.write_str(self.as_str())
1126 }
1127}
1128
1129impl From<&str> for StreamPostQueuedBehind {
1130 fn from(s: &str) -> Self {
1131 match s {
1132 "durable_post" => Self::DurablePost,
1133 "ephemeral_post" => Self::EphemeralPost,
1134 "retry_backoff" => Self::RetryBackoff,
1135 "hold" => Self::Hold,
1136 "none" => Self::None,
1137 other => Self::Unknown(other.to_string()),
1138 }
1139 }
1140}
1141
1142impl Serialize for StreamPostQueuedBehind {
1143 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1144 serializer.serialize_str(self.as_str())
1145 }
1146}
1147
1148impl<'de> Deserialize<'de> for StreamPostQueuedBehind {
1149 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1150 let s = String::deserialize(deserializer)?;
1151 Ok(Self::from(s.as_str()))
1152 }
1153}
1154
1155/// What a turn was given to settle before its own prompt, carried as
1156/// [`ResultMessage::turn_start_resume_kind`] (CLI 2.1.287+). A turn given
1157/// more than one reports the first in this order.
1158#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1159pub enum TurnStartResumeKind {
1160 /// `orphaned_permission` — a permission answer whose pending request was
1161 /// lost (as when a worker restarts), so the tool call is settled with
1162 /// that answer.
1163 OrphanedPermission,
1164 /// `turn_handoff` — a turn in progress that the session's client handed
1165 /// over.
1166 TurnHandoff,
1167 /// `deferred_tool_use` — a call a `PreToolUse` hook deferred.
1168 DeferredToolUse,
1169 /// `none` — nothing to settle (`resume_other` is still reported, at
1170 /// about 0).
1171 None,
1172 /// A value not yet known to this version of the crate.
1173 Unknown(String),
1174}
1175
1176impl TurnStartResumeKind {
1177 pub fn as_str(&self) -> &str {
1178 match self {
1179 Self::OrphanedPermission => "orphaned_permission",
1180 Self::TurnHandoff => "turn_handoff",
1181 Self::DeferredToolUse => "deferred_tool_use",
1182 Self::None => "none",
1183 Self::Unknown(s) => s.as_str(),
1184 }
1185 }
1186}
1187
1188impl fmt::Display for TurnStartResumeKind {
1189 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1190 f.write_str(self.as_str())
1191 }
1192}
1193
1194impl From<&str> for TurnStartResumeKind {
1195 fn from(s: &str) -> Self {
1196 match s {
1197 "orphaned_permission" => Self::OrphanedPermission,
1198 "turn_handoff" => Self::TurnHandoff,
1199 "deferred_tool_use" => Self::DeferredToolUse,
1200 "none" => Self::None,
1201 other => Self::Unknown(other.to_string()),
1202 }
1203 }
1204}
1205
1206impl Serialize for TurnStartResumeKind {
1207 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1208 serializer.serialize_str(self.as_str())
1209 }
1210}
1211
1212impl<'de> Deserialize<'de> for TurnStartResumeKind {
1213 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1214 let s = String::deserialize(deserializer)?;
1215 Ok(Self::from(s.as_str()))
1216 }
1217}
1218
1219/// Why fast mode can't serve right now, carried on `result` frames and
1220/// `system/init` (CLI 2.1.219+). Absent when nothing blocks fast mode.
1221#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1222pub enum FastModeDisabledReason {
1223 /// Free-tier account.
1224 Free,
1225 /// Disabled by user preference.
1226 Preference,
1227 /// Extra-usage purchases are disabled for the account.
1228 ExtraUsageDisabled,
1229 /// A network error prevented fast-mode eligibility from resolving.
1230 NetworkError,
1231 /// The CLI could not determine the reason.
1232 UnknownReason,
1233 /// Not a first-party API session (e.g. Bedrock/Vertex).
1234 NotFirstParty,
1235 /// Disabled via environment variable.
1236 DisabledByEnv,
1237 /// The active model does not support fast mode.
1238 ModelNotAllowed,
1239 /// SDK sessions must opt in to fast mode.
1240 SdkOptInRequired,
1241 /// Eligibility is still being determined.
1242 Pending,
1243 /// A reason not yet known to this version of the crate.
1244 Unknown(String),
1245}
1246
1247impl FastModeDisabledReason {
1248 pub fn as_str(&self) -> &str {
1249 match self {
1250 Self::Free => "free",
1251 Self::Preference => "preference",
1252 Self::ExtraUsageDisabled => "extra_usage_disabled",
1253 Self::NetworkError => "network_error",
1254 Self::UnknownReason => "unknown",
1255 Self::NotFirstParty => "not_first_party",
1256 Self::DisabledByEnv => "disabled_by_env",
1257 Self::ModelNotAllowed => "model_not_allowed",
1258 Self::SdkOptInRequired => "sdk_opt_in_required",
1259 Self::Pending => "pending",
1260 Self::Unknown(s) => s.as_str(),
1261 }
1262 }
1263}
1264
1265impl fmt::Display for FastModeDisabledReason {
1266 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1267 f.write_str(self.as_str())
1268 }
1269}
1270
1271impl From<&str> for FastModeDisabledReason {
1272 fn from(s: &str) -> Self {
1273 match s {
1274 "free" => Self::Free,
1275 "preference" => Self::Preference,
1276 "extra_usage_disabled" => Self::ExtraUsageDisabled,
1277 "network_error" => Self::NetworkError,
1278 "unknown" => Self::UnknownReason,
1279 "not_first_party" => Self::NotFirstParty,
1280 "disabled_by_env" => Self::DisabledByEnv,
1281 "model_not_allowed" => Self::ModelNotAllowed,
1282 "sdk_opt_in_required" => Self::SdkOptInRequired,
1283 "pending" => Self::Pending,
1284 other => Self::Unknown(other.to_string()),
1285 }
1286 }
1287}
1288
1289impl Serialize for FastModeDisabledReason {
1290 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1291 serializer.serialize_str(self.as_str())
1292 }
1293}
1294
1295impl<'de> Deserialize<'de> for FastModeDisabledReason {
1296 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1297 let s = String::deserialize(deserializer)?;
1298 Ok(Self::from(s.as_str()))
1299 }
1300}
1301
1302/// Result subtypes
1303#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1304pub enum ResultSubtype {
1305 Success,
1306 ErrorMaxTurns,
1307 ErrorDuringExecution,
1308 ErrorMaxBudgetUsd,
1309 ErrorMaxStructuredOutputRetries,
1310 Unknown(String),
1311}
1312
1313impl ResultSubtype {
1314 pub fn as_str(&self) -> &str {
1315 match self {
1316 Self::Success => "success",
1317 Self::ErrorMaxTurns => "error_max_turns",
1318 Self::ErrorDuringExecution => "error_during_execution",
1319 Self::ErrorMaxBudgetUsd => "error_max_budget_usd",
1320 Self::ErrorMaxStructuredOutputRetries => "error_max_structured_output_retries",
1321 Self::Unknown(s) => s.as_str(),
1322 }
1323 }
1324}
1325
1326impl fmt::Display for ResultSubtype {
1327 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1328 f.write_str(self.as_str())
1329 }
1330}
1331
1332impl From<&str> for ResultSubtype {
1333 fn from(s: &str) -> Self {
1334 match s {
1335 "success" => Self::Success,
1336 "error_max_turns" => Self::ErrorMaxTurns,
1337 "error_during_execution" => Self::ErrorDuringExecution,
1338 "error_max_budget_usd" => Self::ErrorMaxBudgetUsd,
1339 "error_max_structured_output_retries" => Self::ErrorMaxStructuredOutputRetries,
1340 other => Self::Unknown(other.to_string()),
1341 }
1342 }
1343}
1344
1345impl Serialize for ResultSubtype {
1346 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1347 serializer.serialize_str(self.as_str())
1348 }
1349}
1350
1351impl<'de> Deserialize<'de> for ResultSubtype {
1352 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1353 let s = String::deserialize(deserializer)?;
1354 Ok(Self::from(s.as_str()))
1355 }
1356}
1357
1358/// Usage information for the request.
1359///
1360/// **These counters are accumulated roll-ups, not snapshots.** The CLI sums
1361/// usage field-by-field across every API call ("iteration") in the turn's
1362/// tool-use loop, so on a turn with N iterations each counter is the sum of
1363/// all N. This is the right number for **cost**, and the wrong number for
1364/// **context occupancy**: `cache_read_input_tokens` in particular re-counts
1365/// the cached context on every iteration and can exceed the model's context
1366/// window several times over on tool-heavy turns. To estimate context
1367/// occupancy, use the *last* entry of [`iterations`](Self::iterations)
1368/// instead (the CLI itself does exactly this).
1369///
1370/// Note: the `result` frame's usage covers the **main agent only** — the
1371/// subagent (`Task` / sidechain) token rollup the CLI renders as
1372/// `<subagent_tokens>` / `<agent_count>` is not carried here or anywhere
1373/// else on the wire. Accumulate it from `Task` tool results with
1374/// [`SubagentUsageRollup`](crate::SubagentUsageRollup).
1375#[derive(Debug, Clone, Serialize, Deserialize)]
1376pub struct UsageInfo {
1377 /// Sum of fresh (uncached) input tokens across all iterations of the turn.
1378 #[serde(default)]
1379 pub input_tokens: u32,
1380 /// Sum of cache-write input tokens across all iterations of the turn.
1381 #[serde(default)]
1382 pub cache_creation_input_tokens: u32,
1383 /// Sum of cache-read input tokens across all iterations of the turn.
1384 /// Re-counts the cached context every iteration — **not** a measure of
1385 /// context occupancy; see the type-level docs.
1386 #[serde(default)]
1387 pub cache_read_input_tokens: u32,
1388 /// Sum of output tokens across all iterations of the turn.
1389 #[serde(default)]
1390 pub output_tokens: u32,
1391 #[serde(default)]
1392 pub server_tool_use: ServerToolUse,
1393 #[serde(default)]
1394 pub service_tier: String,
1395
1396 /// Cache creation breakdown
1397 #[serde(skip_serializing_if = "Option::is_none")]
1398 pub cache_creation: Option<super::message_types::CacheCreationDetails>,
1399
1400 /// Inference geography (e.g., "not_available")
1401 #[serde(skip_serializing_if = "Option::is_none")]
1402 pub inference_geo: Option<String>,
1403
1404 /// Per-iteration usage breakdown **within** this turn — one entry per
1405 /// API call in the tool-use loop, in order. The last entry reflects the
1406 /// final API call and is what the CLI reads for context-size estimates.
1407 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1408 pub iterations: Vec<UsageIteration>,
1409
1410 /// Speed tier (e.g., "standard")
1411 #[serde(skip_serializing_if = "Option::is_none")]
1412 pub speed: Option<String>,
1413
1414 /// Output-token breakdown (CLI 2.1.232+): currently the thinking-token
1415 /// share of `output_tokens`.
1416 #[serde(skip_serializing_if = "Option::is_none")]
1417 pub output_tokens_details: Option<OutputTokensDetails>,
1418
1419 /// Outcome of a fallback-credit token the request presented; `null` on
1420 /// the wire when it presented none (CLI 2.1.285+).
1421 #[serde(default, skip_serializing_if = "Option::is_none")]
1422 pub fallback_credit: Option<Value>,
1423}
1424
1425/// Breakdown of a turn's output tokens, carried in
1426/// [`UsageInfo::output_tokens_details`].
1427#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1428pub struct OutputTokensDetails {
1429 /// Output tokens spent on extended thinking.
1430 #[serde(skip_serializing_if = "Option::is_none")]
1431 pub thinking_tokens: Option<u64>,
1432}
1433
1434/// Usage for a single API call ("iteration") within a turn's tool-use loop.
1435///
1436/// Carried in [`UsageInfo::iterations`]. The cache fields are optional on
1437/// the wire: some frames carry only `input_tokens` + `output_tokens`
1438/// (observed with `type: "turn"`), while others carry the full cache
1439/// breakdown (observed with `type: "message"` in captured subagent
1440/// sessions). The CLI computes its context estimate from
1441/// `input_tokens + output_tokens` of the **last** iteration.
1442#[derive(Debug, Clone, Serialize, Deserialize)]
1443pub struct UsageIteration {
1444 #[serde(default)]
1445 pub input_tokens: u32,
1446 #[serde(default)]
1447 pub output_tokens: u32,
1448 /// Cache-read input tokens for this iteration, when carried.
1449 #[serde(default, skip_serializing_if = "Option::is_none")]
1450 pub cache_read_input_tokens: Option<u32>,
1451 /// Cache-write input tokens for this iteration, when carried.
1452 #[serde(default, skip_serializing_if = "Option::is_none")]
1453 pub cache_creation_input_tokens: Option<u32>,
1454 /// Cache-write breakdown by TTL, when carried.
1455 #[serde(default, skip_serializing_if = "Option::is_none")]
1456 pub cache_creation: Option<super::message_types::CacheCreationDetails>,
1457 /// Iteration kind; `"turn"` and `"message"` observed on the wire.
1458 #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
1459 pub kind: Option<String>,
1460}
1461
1462/// Server tool usage information
1463#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1464pub struct ServerToolUse {
1465 #[serde(default)]
1466 pub web_search_requests: u32,
1467 /// Number of web fetch requests made
1468 #[serde(default)]
1469 pub web_fetch_requests: u32,
1470}
1471
1472#[cfg(test)]
1473mod tests {
1474 use super::*;
1475 use crate::io::ClaudeOutput;
1476
1477 #[test]
1478 fn test_deserialize_result_message() {
1479 let json = r#"{
1480 "type": "result",
1481 "subtype": "success",
1482 "is_error": false,
1483 "duration_ms": 100,
1484 "duration_api_ms": 200,
1485 "num_turns": 1,
1486 "result": "Done",
1487 "session_id": "123",
1488 "total_cost_usd": 0.01,
1489 "permission_denials": []
1490 }"#;
1491
1492 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1493 assert!(!output.is_error());
1494 }
1495
1496 #[test]
1497 fn test_result_subtype_new_and_unknown_values_do_not_fail() {
1498 let json = r#"{
1499 "type": "result",
1500 "subtype": "error_max_budget_usd",
1501 "is_error": true,
1502 "duration_ms": 100,
1503 "duration_api_ms": 200,
1504 "num_turns": 1,
1505 "session_id": "123",
1506 "total_cost_usd": 0.01
1507 }"#;
1508
1509 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1510 let ClaudeOutput::Result(result) = output else {
1511 panic!("Expected Result");
1512 };
1513 assert_eq!(result.subtype, ResultSubtype::ErrorMaxBudgetUsd);
1514
1515 let json = r#"{
1516 "type": "result",
1517 "subtype": "future_result_subtype",
1518 "is_error": true,
1519 "duration_ms": 100,
1520 "duration_api_ms": 200,
1521 "num_turns": 1,
1522 "session_id": "123",
1523 "total_cost_usd": 0.01
1524 }"#;
1525
1526 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1527 let ClaudeOutput::Result(result) = output else {
1528 panic!("Expected Result");
1529 };
1530 assert_eq!(
1531 result.subtype,
1532 ResultSubtype::Unknown("future_result_subtype".to_string())
1533 );
1534 }
1535
1536 #[test]
1537 fn test_deserialize_result_with_permission_denials() {
1538 let json = r#"{
1539 "type": "result",
1540 "subtype": "success",
1541 "is_error": false,
1542 "duration_ms": 100,
1543 "duration_api_ms": 200,
1544 "num_turns": 2,
1545 "result": "Done",
1546 "session_id": "123",
1547 "total_cost_usd": 0.01,
1548 "permission_denials": [
1549 {
1550 "tool_name": "Bash",
1551 "tool_input": {"command": "rm -rf /", "description": "Delete everything"},
1552 "tool_use_id": "toolu_123"
1553 }
1554 ]
1555 }"#;
1556
1557 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1558 if let ClaudeOutput::Result(result) = output {
1559 assert_eq!(result.permission_denials.len(), 1);
1560 assert_eq!(result.permission_denials[0].tool_name, "Bash");
1561 assert_eq!(result.permission_denials[0].tool_use_id, "toolu_123");
1562 assert_eq!(
1563 result.permission_denials[0]
1564 .tool_input
1565 .get("command")
1566 .unwrap(),
1567 "rm -rf /"
1568 );
1569 } else {
1570 panic!("Expected Result");
1571 }
1572 }
1573
1574 #[test]
1575 fn test_permission_denial_roundtrip() {
1576 let denial = PermissionDenial {
1577 tool_name: "Write".to_string(),
1578 tool_input: serde_json::json!({"file_path": "/etc/passwd", "content": "bad"}),
1579 tool_use_id: "toolu_456".to_string(),
1580 };
1581
1582 let json = serde_json::to_string(&denial).unwrap();
1583 assert!(json.contains("\"tool_name\":\"Write\""));
1584 assert!(json.contains("\"tool_use_id\":\"toolu_456\""));
1585 assert!(json.contains("/etc/passwd"));
1586
1587 let parsed: PermissionDenial = serde_json::from_str(&json).unwrap();
1588 assert_eq!(parsed, denial);
1589 }
1590
1591 #[test]
1592 fn test_deserialize_result_message_with_errors() {
1593 let json = r#"{
1594 "type": "result",
1595 "subtype": "error_during_execution",
1596 "duration_ms": 0,
1597 "duration_api_ms": 0,
1598 "is_error": true,
1599 "num_turns": 0,
1600 "session_id": "27934753-425a-4182-892c-6b1c15050c3f",
1601 "total_cost_usd": 0,
1602 "errors": ["No conversation found with session ID: d56965c9-c855-4042-a8f5-f12bbb14d6f6"],
1603 "permission_denials": []
1604 }"#;
1605
1606 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1607 assert!(output.is_error());
1608
1609 if let ClaudeOutput::Result(res) = output {
1610 assert!(res.is_error);
1611 assert_eq!(res.errors.len(), 1);
1612 assert!(res.errors[0].contains("No conversation found"));
1613 } else {
1614 panic!("Expected Result message");
1615 }
1616 }
1617
1618 #[test]
1619 fn test_deserialize_result_message_errors_defaults_empty() {
1620 let json = r#"{
1621 "type": "result",
1622 "subtype": "success",
1623 "is_error": false,
1624 "duration_ms": 100,
1625 "duration_api_ms": 200,
1626 "num_turns": 1,
1627 "session_id": "123",
1628 "total_cost_usd": 0.01
1629 }"#;
1630
1631 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1632 if let ClaudeOutput::Result(res) = output {
1633 assert!(res.errors.is_empty());
1634 } else {
1635 panic!("Expected Result message");
1636 }
1637 }
1638
1639 #[test]
1640 fn test_result_message_errors_roundtrip() {
1641 let json = r#"{
1642 "type": "result",
1643 "subtype": "error_during_execution",
1644 "is_error": true,
1645 "duration_ms": 0,
1646 "duration_api_ms": 0,
1647 "num_turns": 0,
1648 "session_id": "test-session",
1649 "total_cost_usd": 0.0,
1650 "errors": ["Error 1", "Error 2"]
1651 }"#;
1652
1653 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1654 let reserialized = serde_json::to_string(&output).unwrap();
1655
1656 assert!(reserialized.contains("Error 1"));
1657 assert!(reserialized.contains("Error 2"));
1658 }
1659
1660 #[test]
1661 fn test_result_with_new_fields() {
1662 let json = r#"{
1663 "type": "result",
1664 "subtype": "success",
1665 "is_error": false,
1666 "duration_ms": 5000,
1667 "duration_api_ms": 4500,
1668 "num_turns": 1,
1669 "result": "Done",
1670 "session_id": "abc",
1671 "total_cost_usd": 0.06,
1672 "api_error_status": null,
1673 "stop_reason": "end_turn",
1674 "terminal_reason": "completed",
1675 "fast_mode_state": "off",
1676 "modelUsage": {
1677 "claude-opus-4-7[1m]": {
1678 "inputTokens": 3817,
1679 "outputTokens": 14,
1680 "costUSD": 0.06
1681 }
1682 },
1683 "usage": {
1684 "input_tokens": 3817,
1685 "output_tokens": 14,
1686 "cache_creation_input_tokens": 3540,
1687 "cache_read_input_tokens": 0,
1688 "server_tool_use": {
1689 "web_search_requests": 0,
1690 "web_fetch_requests": 2
1691 },
1692 "service_tier": "standard",
1693 "inference_geo": "not_available",
1694 "speed": "standard",
1695 "iterations": [
1696 {"input_tokens": 3817, "output_tokens": 14, "type": "turn"}
1697 ]
1698 }
1699 }"#;
1700
1701 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1702 if let ClaudeOutput::Result(res) = output {
1703 assert_eq!(res.stop_reason.as_deref(), Some("end_turn"));
1704 assert_eq!(res.terminal_reason.as_deref(), Some("completed"));
1705 assert_eq!(res.fast_mode_state.as_deref(), Some("off"));
1706 let model_usage = res.model_usage.as_ref().unwrap();
1707 let entry = model_usage
1708 .get("claude-opus-4-7[1m]")
1709 .expect("per-model entry present");
1710 assert_eq!(entry.input_tokens, 3817);
1711 assert_eq!(entry.output_tokens, 14);
1712 assert_eq!(entry.cost_usd, 0.06);
1713 assert!(res.api_error_status.is_none());
1714
1715 let usage = res.usage.unwrap();
1716 assert_eq!(usage.server_tool_use.web_fetch_requests, 2);
1717 assert_eq!(usage.inference_geo.as_deref(), Some("not_available"));
1718 assert_eq!(usage.speed.as_deref(), Some("standard"));
1719 assert_eq!(usage.iterations.len(), 1);
1720 assert_eq!(usage.iterations[0].input_tokens, 3817);
1721 assert_eq!(usage.iterations[0].output_tokens, 14);
1722 assert_eq!(usage.iterations[0].kind.as_deref(), Some("turn"));
1723 } else {
1724 panic!("Expected Result");
1725 }
1726 }
1727
1728 #[test]
1729 fn test_result_backwards_compatible_without_new_fields() {
1730 // Verify old-format messages still parse fine
1731 let json = r#"{
1732 "type": "result",
1733 "subtype": "success",
1734 "is_error": false,
1735 "duration_ms": 100,
1736 "duration_api_ms": 200,
1737 "num_turns": 1,
1738 "session_id": "abc",
1739 "total_cost_usd": 0.01
1740 }"#;
1741
1742 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1743 if let ClaudeOutput::Result(res) = output {
1744 assert!(res.api_error_status.is_none());
1745 assert!(res.stop_reason.is_none());
1746 assert!(res.terminal_reason.is_none());
1747 assert!(res.fast_mode_state.is_none());
1748 assert!(res.model_usage.is_none());
1749 } else {
1750 panic!("Expected Result");
1751 }
1752 }
1753
1754 #[test]
1755 fn test_result_fast_mode_disabled_reason() {
1756 let json = r#"{
1757 "type":"result","subtype":"success","is_error":false,
1758 "duration_ms":100,"duration_api_ms":80,"num_turns":1,
1759 "session_id":"s1","total_cost_usd":0.01,
1760 "fast_mode_state":"off",
1761 "fast_mode_disabled_reason":"sdk_opt_in_required"
1762 }"#;
1763 let output: crate::ClaudeOutput = serde_json::from_str(json).unwrap();
1764 let crate::ClaudeOutput::Result(res) = &output else {
1765 panic!("expected Result");
1766 };
1767 assert_eq!(
1768 res.fast_mode_disabled_reason,
1769 Some(FastModeDisabledReason::SdkOptInRequired)
1770 );
1771 assert!(serde_json::to_string(&output)
1772 .unwrap()
1773 .contains("\"fast_mode_disabled_reason\":\"sdk_opt_in_required\""));
1774
1775 // Unknown reasons survive decode and round-trip verbatim; the wire
1776 // literal "unknown" maps to the typed UnknownReason, not the fallback.
1777 assert_eq!(
1778 FastModeDisabledReason::from("unknown"),
1779 FastModeDisabledReason::UnknownReason
1780 );
1781 let novel = FastModeDisabledReason::from("solar_flare");
1782 assert_eq!(novel, FastModeDisabledReason::Unknown("solar_flare".into()));
1783 assert_eq!(novel.as_str(), "solar_flare");
1784 }
1785
1786 #[test]
1787 fn test_result_timing_and_user_message_uuid_fields() {
1788 let json = r#"{
1789 "type":"result","subtype":"success","is_error":false,
1790 "duration_ms":100,"duration_api_ms":80,"num_turns":1,
1791 "session_id":"s1","total_cost_usd":0.01,
1792 "request_sent_wall_ms":1753212345678.25,
1793 "user_message_uuid":"um-1"
1794 }"#;
1795 let output: crate::ClaudeOutput = serde_json::from_str(json).unwrap();
1796 let crate::ClaudeOutput::Result(res) = &output else {
1797 panic!("expected Result");
1798 };
1799 assert_eq!(res.request_sent_wall_ms, Some(1753212345678.25));
1800 assert_eq!(res.user_message_uuid.as_deref(), Some("um-1"));
1801
1802 let reserialized = serde_json::to_string(&output).unwrap();
1803 assert!(reserialized.contains("\"user_message_uuid\":\"um-1\""));
1804 }
1805
1806 #[test]
1807 fn test_result_queued_turn_count_and_user_message_uuids() {
1808 // CLI 2.1.259 additive fields on the result frame.
1809 let json = r#"{
1810 "type":"result","subtype":"success","is_error":false,
1811 "duration_ms":100,"duration_api_ms":80,"num_turns":1,
1812 "session_id":"s1","total_cost_usd":0.01,
1813 "user_message_uuid":"um-2",
1814 "user_message_uuids":["um-1","um-2"],
1815 "queued_turn_count":3
1816 }"#;
1817 let output: crate::ClaudeOutput = serde_json::from_str(json).unwrap();
1818 let crate::ClaudeOutput::Result(res) = &output else {
1819 panic!("expected Result");
1820 };
1821 assert_eq!(res.user_message_uuids, vec!["um-1", "um-2"]);
1822 assert_eq!(res.queued_turn_count, Some(3));
1823
1824 let reserialized = serde_json::to_string(&output).unwrap();
1825 assert!(reserialized.contains("\"user_message_uuids\":[\"um-1\",\"um-2\"]"));
1826 assert!(reserialized.contains("\"queued_turn_count\":3"));
1827
1828 // Both fields are absent from older producers and must default cleanly.
1829 let old = r#"{
1830 "type":"result","subtype":"success","is_error":false,
1831 "duration_ms":100,"duration_api_ms":80,"num_turns":1,
1832 "session_id":"s1","total_cost_usd":0.01
1833 }"#;
1834 let output: crate::ClaudeOutput = serde_json::from_str(old).unwrap();
1835 let crate::ClaudeOutput::Result(res) = &output else {
1836 panic!("expected Result");
1837 };
1838 assert!(res.user_message_uuids.is_empty());
1839 assert_eq!(res.queued_turn_count, None);
1840 let reserialized = serde_json::to_string(&output).unwrap();
1841 assert!(!reserialized.contains("user_message_uuids"));
1842 assert!(!reserialized.contains("queued_turn_count"));
1843 }
1844}