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