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