Skip to main content

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    /// On the result the `claude --cloud` client writes for a message it
838    /// took and could not deliver. Absent on every other result, on the
839    /// refusal of a frame with a bad uuid or content, and from CLIs before
840    /// 2.1.328. Marked `@internal` upstream.
841    #[serde(default, skip_serializing_if = "Option::is_none")]
842    pub message_undelivered: Option<MessageUndelivered>,
843
844    /// Set when [`Self::startup_failure_reason`] is `config_file_invalid`:
845    /// the config file that did not parse and its backup, as separate
846    /// fields. Read paths from here, never from the text of `errors`. Each
847    /// path is in the form the machine running Claude Code uses, which can
848    /// differ from the host's. Absent on every other result and from CLIs
849    /// before 2.1.325.
850    #[serde(default, skip_serializing_if = "Option::is_none")]
851    pub invalid_config_file: Option<InvalidConfigFile>,
852}
853
854/// [`ResultMessage::message_undelivered`]: why a `claude --cloud` client
855/// could not deliver a message (CLI 2.1.328+).
856#[derive(Debug, Clone, PartialEq, Eq, Hash)]
857pub enum MessageUndelivered {
858    /// The session was not opened, so nothing was sent.
859    SessionNotOpened,
860    /// The send failed; the session may have the message all the same.
861    SendFailed,
862    /// A value not yet known to this version of the crate. Read it like
863    /// [`SendFailed`](Self::SendFailed): the session may have the message.
864    Unknown(String),
865}
866
867impl MessageUndelivered {
868    pub fn as_str(&self) -> &str {
869        match self {
870            Self::SessionNotOpened => "session_not_opened",
871            Self::SendFailed => "send_failed",
872            Self::Unknown(s) => s.as_str(),
873        }
874    }
875}
876
877impl fmt::Display for MessageUndelivered {
878    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
879        f.write_str(self.as_str())
880    }
881}
882
883impl From<&str> for MessageUndelivered {
884    fn from(s: &str) -> Self {
885        match s {
886            "session_not_opened" => Self::SessionNotOpened,
887            "send_failed" => Self::SendFailed,
888            other => Self::Unknown(other.to_string()),
889        }
890    }
891}
892
893impl Serialize for MessageUndelivered {
894    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
895        serializer.serialize_str(self.as_str())
896    }
897}
898
899impl<'de> Deserialize<'de> for MessageUndelivered {
900    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
901        let s = String::deserialize(deserializer)?;
902        Ok(Self::from(s.as_str()))
903    }
904}
905
906/// [`ResultMessage::restored_rewind`]: the rewind a usage-limited turn
907/// restored (CLI 2.1.325+).
908#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
909pub struct RestoredRewind {
910    /// The `request_id` of the `rewind_conversation` request.
911    pub request_id: String,
912    /// The last user or assistant message of the restored conversation that
913    /// a load of the session keeps.
914    pub last_message_uuid: String,
915}
916
917/// [`ResultMessage::invalid_config_file`]: a config file that is not valid
918/// JSON, and its backup (CLI 2.1.325+).
919#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
920pub struct InvalidConfigFile {
921    /// The file that is not valid JSON.
922    pub path: String,
923    /// Whether this is Claude Code's global config file. Only that file has
924    /// backups, and only its message says how to repair it.
925    pub is_global: bool,
926    /// Whether Claude Code knows the result of its search for a backup.
927    /// `true` with no [`backup_path`](Self::backup_path): it found none.
928    /// `false`: the result is not known, or this is not the global config.
929    pub backup_searched: bool,
930    /// The backup that the message in `errors` names. Usually one that
931    /// parses; where none does, the newest with an account, then the newest
932    /// holding anything, or at last one that does not parse or could not be
933    /// read. Show it to a person, or check that it parses before copying it
934    /// over [`path`](Self::path).
935    #[serde(default, skip_serializing_if = "Option::is_none")]
936    pub backup_path: Option<String>,
937}
938
939/// [`ResultMessage::input_attachments_detail`] — what the
940/// `input_attachments` phase did on the turn (CLI 2.1.288+).
941#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
942pub struct InputAttachmentsDetail {
943    /// Label of the attachment producer that took longest from its start to
944    /// its result, among those that began within the phase.
945    #[serde(default, skip_serializing_if = "Option::is_none")]
946    pub slowest_producer: Option<String>,
947    /// How long [`Self::slowest_producer`] took. Well above
948    /// [`Self::cpu_ms`], that producer most likely waited (on a file, the
949    /// network or a child process).
950    #[serde(default, skip_serializing_if = "Option::is_none")]
951    pub slowest_producer_ms: Option<u64>,
952    /// `time_to_request_cpu_ms`'s counter over this phase alone. Absent
953    /// wherever `time_to_request_cpu_ms` is absent, and when the turn's
954    /// first model request went out before the phase ended.
955    #[serde(default, skip_serializing_if = "Option::is_none")]
956    pub cpu_ms: Option<u64>,
957    /// `time_to_request_major_faults`'s counter over this phase alone.
958    /// Absent where [`Self::cpu_ms`] is.
959    #[serde(default, skip_serializing_if = "Option::is_none")]
960    pub major_faults: Option<u64>,
961    /// How many files the `changed_files` producer set out to read again in
962    /// full because their modification time was later than the one recorded
963    /// when the conversation last wrote or edited them. Absent when the
964    /// conversation's record of files was empty or the producer did not run.
965    #[serde(default, skip_serializing_if = "Option::is_none")]
966    pub changed_files_reread: Option<u64>,
967    /// How the `changed_files` producer's compares ended in the main
968    /// thread's pass (a subagent's are not counted). Absent when nothing was
969    /// counted (CLI 2.1.300+).
970    #[serde(default, skip_serializing_if = "Option::is_none")]
971    pub touch_compare: Option<TouchCompareCounts>,
972
973    // The members below add up what the main thread's attachment passes
974    // measured of themselves (CLI 2.1.316+). Only a pass that began and
975    // ended within one run of the phase, before the turn's first model
976    // request, counts: not a subagent's or a background agent's, and not a
977    // pass with attachments switched off. The five `_ms` splits run in order,
978    // each rounded down, so their sum is at most the phase's time.
979    /// Work before any producer starts, such as working out which tools the
980    /// tool announcements list (CLI 2.1.316+).
981    #[serde(default, skip_serializing_if = "Option::is_none")]
982    pub setup_ms: Option<u64>,
983    /// Starting the producers that read the prompt's own text (at-mentioned
984    /// files, MCP resources, mentions of agents, skills and peers) and
985    /// waiting for them (CLI 2.1.316+).
986    #[serde(default, skip_serializing_if = "Option::is_none")]
987    pub prompt_producers_ms: Option<u64>,
988    /// Starting every other producer, each one's work up to its first wait
989    /// included, so the thread ran code throughout (CLI 2.1.316+).
990    #[serde(default, skip_serializing_if = "Option::is_none")]
991    pub ambient_start_ms: Option<u64>,
992    /// Waiting for the producers [`Self::ambient_start_ms`] started
993    /// (CLI 2.1.316+).
994    #[serde(default, skip_serializing_if = "Option::is_none")]
995    pub ambient_wait_ms: Option<u64>,
996    /// The rest: merging the producers' results, logging the attachments
997    /// with their token estimates and making each into a message
998    /// (CLI 2.1.316+).
999    #[serde(default, skip_serializing_if = "Option::is_none")]
1000    pub render_ms: Option<u64>,
1001    /// How many producers the passes started. Present, 0 included, whenever
1002    /// a pass was kept (CLI 2.1.316+).
1003    #[serde(default, skip_serializing_if = "Option::is_none")]
1004    pub producers: Option<u64>,
1005    /// How many times the passes asked the API to count a file's tokens
1006    /// (only for text estimated above a quarter of the Read tool's token
1007    /// limit). Present, 0 included, whenever a pass was kept
1008    /// (CLI 2.1.316+).
1009    #[serde(default, skip_serializing_if = "Option::is_none")]
1010    pub token_counts: Option<u64>,
1011    /// Time at least one token count was under way, overlaps counted once.
1012    /// Absent when [`Self::token_counts`] is 0 (CLI 2.1.316+).
1013    #[serde(default, skip_serializing_if = "Option::is_none")]
1014    pub token_count_ms: Option<u64>,
1015    /// Time at least one of the `changed_files` producer's Read calls was
1016    /// under way, their token counts included. Absent when it made none
1017    /// (CLI 2.1.316+).
1018    #[serde(default, skip_serializing_if = "Option::is_none")]
1019    pub changed_files_read_ms: Option<u64>,
1020    /// The files counted under [`TouchCompareCounts::differs`], sorted by
1021    /// size on disk, counting only the passes kept here (so the bands can
1022    /// add up to less than `differs`). Absent when no compare in a kept pass
1023    /// ended in `differs` (CLI 2.1.316+).
1024    #[serde(default, skip_serializing_if = "Option::is_none")]
1025    pub differs_files: Option<DiffersFilesCounts>,
1026}
1027
1028/// [`InputAttachmentsDetail::differs_files`] — the `changed_files`
1029/// compares that ended in `differs`, banded by file size on disk (1 KB is
1030/// 1,024 bytes; a size on a boundary is in the band above it, except exactly
1031/// 256 KB). A zero count is left out (CLI 2.1.316+).
1032#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
1033pub struct DiffersFilesCounts {
1034    /// Under 25 KB.
1035    #[serde(default, skip_serializing_if = "Option::is_none")]
1036    pub size_under_25_kb: Option<u64>,
1037    /// 25 KB up to 50 KB.
1038    #[serde(default, skip_serializing_if = "Option::is_none")]
1039    pub size_25_to_50_kb: Option<u64>,
1040    /// 50 KB up to and including 256 KB.
1041    #[serde(default, skip_serializing_if = "Option::is_none")]
1042    pub size_50_to_256_kb: Option<u64>,
1043    /// Over 256 KB (only where the Read size limit has been raised).
1044    #[serde(default, skip_serializing_if = "Option::is_none")]
1045    pub size_over_256_kb: Option<u64>,
1046    /// Those files for which the conversation kept only a hash of the
1047    /// earlier text, so the model, if told, gets the file's name without a
1048    /// diff.
1049    #[serde(default, skip_serializing_if = "Option::is_none")]
1050    pub hash_only: Option<u64>,
1051}
1052
1053/// [`InputAttachmentsDetail::touch_compare`] — how the `changed_files`
1054/// producer's compares of touched files (size, then bytes, against what the
1055/// conversation last saw) ended. Whole numbers; a zero count is left out
1056/// (CLI 2.1.300+).
1057#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
1058pub struct TouchCompareCounts {
1059    /// The text had not changed, so it was not read again.
1060    #[serde(default, skip_serializing_if = "Option::is_none")]
1061    pub same: Option<u64>,
1062    /// The text had changed, so it was read again.
1063    #[serde(default, skip_serializing_if = "Option::is_none")]
1064    pub differs: Option<u64>,
1065    /// Not compared, because the conversation has seen only part of the
1066    /// file; read again.
1067    #[serde(default, skip_serializing_if = "Option::is_none")]
1068    pub partial_view: Option<u64>,
1069    /// Not compared, because it was compared once already since the
1070    /// conversation last read or wrote it; read again.
1071    #[serde(default, skip_serializing_if = "Option::is_none")]
1072    pub already_compared: Option<u64>,
1073    /// The file could not be shown to be the one its path names (the file
1074    /// swapped or removed meanwhile, or on Linux a symbolic link on the way);
1075    /// read again.
1076    #[serde(default, skip_serializing_if = "Option::is_none")]
1077    pub link_on_path: Option<u64>,
1078    /// The open met a symbolic link; read again.
1079    #[serde(default, skip_serializing_if = "Option::is_none")]
1080    pub leaf_link: Option<u64>,
1081    /// The file has a second hard link; read again.
1082    #[serde(default, skip_serializing_if = "Option::is_none")]
1083    pub nlink: Option<u64>,
1084    /// Not a regular file; read again.
1085    #[serde(default, skip_serializing_if = "Option::is_none")]
1086    pub not_regular: Option<u64>,
1087    /// Too large to compare; read again.
1088    #[serde(default, skip_serializing_if = "Option::is_none")]
1089    pub oversize: Option<u64>,
1090    /// The file was gone.
1091    #[serde(default, skip_serializing_if = "Option::is_none")]
1092    pub enoent: Option<u64>,
1093    /// Anything else, errors included; read again.
1094    #[serde(default, skip_serializing_if = "Option::is_none")]
1095    pub other: Option<u64>,
1096}
1097
1098/// [`ResultMessage::resume_store_confirm_detail`] — how the
1099/// `resume_store_confirm` phase was spent (CLI 2.1.290+). The four `_ms`
1100/// values sum to that phase exactly.
1101#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
1102pub struct ResumeStoreConfirmDetail {
1103    /// The transcript write, until the carried lines are in the queue of the
1104    /// lane that uploads transcript rows.
1105    pub write_ms: u64,
1106    /// A POST was out that held only rows queued before the hand-off's write
1107    /// began.
1108    pub ahead_ms: u64,
1109    /// Any other POST was out, each retry included.
1110    pub post_ms: u64,
1111    /// No POST was out (backoff, batching, a busy event loop), plus rounding
1112    /// and any POST still out when the wait was cut short.
1113    pub other_ms: u64,
1114    /// POST attempts that ended between the start of the write and the end
1115    /// of the wait.
1116    pub posts: u64,
1117    /// Those of [`Self::posts`] that did not go through.
1118    pub failed_posts: u64,
1119    /// Rows the lane had accepted and the store had not yet confirmed when
1120    /// the write began.
1121    pub rows_ahead: u64,
1122    /// Rows queued since then that a POST delivered, the carried lines among
1123    /// them.
1124    pub rows: u64,
1125}
1126
1127/// [`ResultMessage::tool_schema_build_detail`] — how the `tool_schema_build`
1128/// phase was spent, in whole ms, in the order the code runs (CLI 2.1.317+).
1129/// The six `_ms` values add up to the phase exactly; each is rounded so a
1130/// fraction of a ms carries into the next.
1131#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
1132pub struct ToolSchemaBuildDetail {
1133    /// Choosing the beta headers, reading what the model supports and the
1134    /// thinking configuration.
1135    pub betas_ms: u64,
1136    /// Waiting for the account's Artifact capabilities, early schema builds
1137    /// for plugin-movable tools, and deciding whether tool search is on.
1138    pub waits_ms: u64,
1139    /// Deciding which tools the request declares in full, deferred or by
1140    /// reference, with the waits that takes.
1141    pub placement_ms: u64,
1142    /// Making the API schema of every declared tool.
1143    pub render_ms: u64,
1144    /// The rest of the phase, such as in-message tool schemas and applying
1145    /// the plan for deferred tools.
1146    pub after_ms: u64,
1147    /// Time no part covers plus what rounding leaves: 0 or 1 unless some
1148    /// stretch of the phase has no mark.
1149    pub other_ms: u64,
1150    /// How many tools the render made schemas for (the last build's).
1151    #[serde(default, skip_serializing_if = "Option::is_none")]
1152    pub tools: Option<u64>,
1153    /// How much the process's tool-schema cache grew over the phase: about
1154    /// how many schemas were built from scratch (the last build's).
1155    #[serde(default, skip_serializing_if = "Option::is_none")]
1156    pub new_schemas: Option<u64>,
1157}
1158
1159/// [`ResultMessage::message_normalization_detail`] — how the
1160/// `message_normalization` phase was spent (CLI 2.1.317+). Read it as
1161/// [`ToolSchemaBuildDetail`]: six `_ms` values in the order the code runs,
1162/// which add up to the phase exactly.
1163#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
1164pub struct MessageNormalizationDetail {
1165    /// The passes ahead of the main one and the main pass's options.
1166    pub before_ms: u64,
1167    /// The main pass alone (`normalizeMessagesForAPI`).
1168    pub normalize_ms: u64,
1169    /// Checking every image against the model's size limit.
1170    pub images_ms: u64,
1171    /// The passes over the normalized list.
1172    pub post_process_ms: u64,
1173    /// The rest: per-turn notes, retry message lists, account-memory notes.
1174    pub after_ms: u64,
1175    /// As in [`ToolSchemaBuildDetail::other_ms`].
1176    pub other_ms: u64,
1177    /// How many messages the request was built from (the conversation since
1178    /// its last compaction, after any trimming); the last build's.
1179    #[serde(default, skip_serializing_if = "Option::is_none")]
1180    pub messages: Option<u64>,
1181    /// How many API messages this build made of them; the last build's.
1182    #[serde(default, skip_serializing_if = "Option::is_none")]
1183    pub wire_messages: Option<u64>,
1184}
1185
1186/// [`ResultMessage::request_build_detail`] — how the `request_build` phase
1187/// was spent (CLI 2.1.317+). The nine values from `records_ms` to
1188/// `other_ms` add up to the phase exactly; the three `sent_build_*` members
1189/// lie within [`sent_build_ms`](Self::sent_build_ms) and are not part of
1190/// the sum.
1191#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
1192pub struct RequestBuildDetail {
1193    /// Recording what this request sends and setting up the shared retry
1194    /// handlers.
1195    pub records_ms: u64,
1196    /// The fallback-block check, attribution header, cache lifetime and the
1197    /// system prompt's blocks.
1198    pub system_ms: u64,
1199    /// Tool/system-prompt change detection, effort, fast mode, permission
1200    /// context waits and beta headers.
1201    pub headers_ms: u64,
1202    /// Recording the prompt's state so a later prompt-cache break can be
1203    /// explained. In a cloud runner's session the on-disk write is queued
1204    /// after the response instead, outside this phase, unless the model is
1205    /// one that cache-break detection skips (CLI 2.1.318+).
1206    pub cache_break_record_ms: u64,
1207    /// Defining the first retry handlers, planning tool-result clearing and
1208    /// opening the request's tracing span.
1209    pub plans_ms: u64,
1210    /// Defining the rest of the retry and fallback handlers.
1211    pub retry_setup_ms: u64,
1212    /// Building the parameters that are sent, for every attempt before the
1213    /// first dispatch.
1214    pub sent_build_ms: u64,
1215    /// From there to the moment the request is recorded as sent.
1216    pub record_attempt_ms: u64,
1217    /// As in [`ToolSchemaBuildDetail::other_ms`].
1218    pub other_ms: u64,
1219    /// Assembling the context for the server-side safety check.
1220    #[serde(default, skip_serializing_if = "Option::is_none")]
1221    pub sent_build_safety_context_ms: Option<u64>,
1222    /// The last clean-up of the messages before sending, placing the
1223    /// prompt-cache breakpoints.
1224    #[serde(default, skip_serializing_if = "Option::is_none")]
1225    pub sent_build_cache_breakpoints_ms: Option<u64>,
1226    /// Scanning the body for lone UTF-16 surrogates, and the scrub where one
1227    /// is found.
1228    #[serde(default, skip_serializing_if = "Option::is_none")]
1229    pub sent_build_surrogate_scan_ms: Option<u64>,
1230}
1231
1232/// [`ResultMessage::process_turn_states`] — the turn's process CPU and wall
1233/// time split among mutually exclusive states (CLI 2.1.317+). A state says
1234/// what was open, not what the time was spent on. Where several were open,
1235/// the first of `main_stream`, `side_stream`, `tool`, `agent_tool`,
1236/// `first_event_wait` names the state; with nothing open, the state is
1237/// named after the turn's main-conversation model calls.
1238#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
1239pub struct ProcessTurnStates {
1240    /// A response stream of a main-conversation request was open.
1241    #[serde(default, skip_serializing_if = "Option::is_none")]
1242    pub main_stream: Option<ProcessStateTime>,
1243    /// Any other model request's stream was open (a subagent's, a
1244    /// compaction's).
1245    #[serde(default, skip_serializing_if = "Option::is_none")]
1246    pub side_stream: Option<ProcessStateTime>,
1247    /// A call of any tool but Agent was open, permission prompt included.
1248    #[serde(default, skip_serializing_if = "Option::is_none")]
1249    pub tool: Option<ProcessStateTime>,
1250    /// A call of the Agent tool was open.
1251    #[serde(default, skip_serializing_if = "Option::is_none")]
1252    pub agent_tool: Option<ProcessStateTime>,
1253    /// A main-conversation request was sent and no stream of it was open
1254    /// yet.
1255    #[serde(default, skip_serializing_if = "Option::is_none")]
1256    pub first_event_wait: Option<ProcessStateTime>,
1257    /// Nothing open, and no main-conversation model call sent yet.
1258    #[serde(default, skip_serializing_if = "Option::is_none")]
1259    pub before_first_request: Option<ProcessStateTime>,
1260    /// Nothing open, between two main-conversation model calls.
1261    #[serde(default, skip_serializing_if = "Option::is_none")]
1262    pub between_requests: Option<ProcessStateTime>,
1263    /// Nothing open, after the last main-conversation model call.
1264    #[serde(default, skip_serializing_if = "Option::is_none")]
1265    pub after_last_request: Option<ProcessStateTime>,
1266}
1267
1268/// Time in one [`ProcessTurnStates`] state (CLI 2.1.317+).
1269#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
1270pub struct ProcessStateTime {
1271    /// Process CPU time, counted as in `process_cpu_ms_between_turns`
1272    /// (child processes left out).
1273    pub cpu_ms: u64,
1274    /// Wall-clock time.
1275    pub wall_ms: u64,
1276    /// How many times the state was entered.
1277    pub entries: u64,
1278}
1279
1280/// [`ResultMessage::process_garbage_collections`] — garbage collections on
1281/// the CLI process's main thread (CLI 2.1.311+). A worker claimed from a
1282/// warm spare counts from the spare's own start.
1283#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
1284pub struct ProcessGarbageCollections {
1285    /// Up to the start of the process's first turn. Absent if no turn began
1286    /// first or its count failed.
1287    #[serde(default, skip_serializing_if = "Option::is_none")]
1288    pub to_first_message: Option<GarbageCollectionCounts>,
1289    /// Up to this result, including
1290    /// [`to_first_message`](Self::to_first_message)'s.
1291    pub to_first_result: GarbageCollectionCounts,
1292}
1293
1294/// One window of [`ProcessGarbageCollections`] (CLI 2.1.311+). A collection
1295/// still running at the window's end is not counted.
1296#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
1297pub struct GarbageCollectionCounts {
1298    /// Collections of young objects only (under Bun the process's first also
1299    /// marks the whole heap).
1300    pub eden: u64,
1301    /// Collections of the whole heap.
1302    pub full: u64,
1303    /// Their summed wall-clock time in ms, not CPU time.
1304    pub wall_ms: u64,
1305    /// Heap in use after the last one, in MiB. Absent if none ran.
1306    #[serde(default, skip_serializing_if = "Option::is_none")]
1307    pub heap_after_mib: Option<u64>,
1308}
1309
1310/// Why Claude Code refused to start, carried as
1311/// [`ResultMessage::startup_failure_reason`] so a host can offer the fix
1312/// instead of a retry (CLI 2.1.274+).
1313#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1314pub enum StartupFailureReason {
1315    /// Managed settings pin a first-party or Cloud gateway sign-in, and an
1316    /// Anthropic API key or auth token is configured instead.
1317    OrgPinApiKeyConflict,
1318    /// Managed settings list the API providers this machine may use
1319    /// (`allowedProviders`), and the session is set up for one that is not
1320    /// listed (CLI 2.1.285+).
1321    ProviderNotAllowed,
1322    /// The sign-in's organization could not be verified against the pin
1323    /// (network, or a revoked token).
1324    OrgVerifyFailed,
1325    /// The sign-in belongs to an organization the pin does not allow.
1326    OrgPinMismatch,
1327    /// Managed policy settings could not be read, the pin names no
1328    /// organization, or managed model settings (`deniedModels`, or an
1329    /// `availableModels` list matched exactly) block the default model and
1330    /// leave no allowed model to use instead.
1331    ManagedSettingsInvalid,
1332    /// Managed settings the organization requires could not be loaded.
1333    RemoteSettingsRequiredUnavailable,
1334    /// The Cloud gateway ended this sign-in.
1335    GatewaySigninRequired,
1336    /// The Cloud gateway refused managed settings for this account.
1337    GatewayAccessDenied,
1338    /// A proxy setting is not a complete URL.
1339    ProxyInvalid,
1340    /// The per-user temp directory is unsafe or could not be created.
1341    TempDirUnusable,
1342    /// The working directory was deleted, moved or cannot be read, or (not
1343    /// on Windows, CLI 2.1.327+) a folder name in its path is not valid
1344    /// UTF-8 and a different entry stands at the name Claude Code reads it
1345    /// as.
1346    CwdUnavailable,
1347    /// Windows has no shell tool: Git Bash is missing, and PowerShell is
1348    /// missing or turned off by `CLAUDE_CODE_USE_POWERSHELL_TOOL`.
1349    ShellToolMissing,
1350    /// The conversation to resume or continue is running as a background
1351    /// session.
1352    SessionHeldByBackground,
1353    /// The resume was refused because the session's worktree failed its
1354    /// safety checks or the resume was launched from inside it; `errors`
1355    /// says whether a re-run continues without the worktree.
1356    WorktreeResumeRefused,
1357    /// The session's worktree could not be verified right now; retrying may
1358    /// succeed.
1359    WorktreeUnverified,
1360    /// This Claude Code version is below the minimum Anthropic requires.
1361    CliVersionTooOld,
1362    /// Bypass permissions mode was requested while running as root.
1363    BypassRoot,
1364    /// The organization requires its policy limits and managed settings
1365    /// before a session starts, and they could not be loaded (network,
1366    /// proxy, or an Anthropic error); retrying may succeed (CLI 2.1.293+).
1367    OrgConfigRequiredUnavailable,
1368    /// The organization requires its policy limits and managed settings, and
1369    /// Anthropic refused them for this sign-in (expired or revoked session,
1370    /// or the organization does not allow Claude Code for this account);
1371    /// signing in again or an admin's change is the fix, not a retry
1372    /// (CLI 2.1.293+).
1373    OrgConfigRefused,
1374    /// A working sandbox is required and it cannot run in this session, for
1375    /// example because bubblewrap is missing or the platform is not
1376    /// supported; make the sandbox available or have the requirement
1377    /// changed (CLI 2.1.314+).
1378    SandboxRequiredUnavailable,
1379    /// `initialize_not_first` — Claude Code was started with
1380    /// `--await-initialize`, and its first stdin line was not the
1381    /// `initialize` control request (another message, or not valid JSON).
1382    /// The fix is in the host or a wrapper script between the host and
1383    /// Claude Code, not a retry (CLI 2.1.317+).
1384    InitializeNotFirst,
1385    /// `config_file_invalid` — a configuration file read at start-up is not
1386    /// valid JSON; `errors` names the file and, for the global configuration
1387    /// file, how to restore or repair it. The file is left unchanged, and
1388    /// every start without a terminal is refused until it is repaired, so a
1389    /// retry alone does not help (CLI 2.1.318+).
1390    ConfigFileInvalid,
1391    /// `managed_settings_not_delivered` — Claude Code was started with
1392    /// `--managed-settings-in-initialize` and could not use the managed
1393    /// settings in the `initialize` control request: stdin ended or failed
1394    /// first or its first line was too long; the request has no usable
1395    /// `managedSettings` object or a malformed `plugins` field; or the launch
1396    /// does not read that request at start-up or also passes
1397    /// `--managed-settings`. `errors` says which. The fix is in the host or a
1398    /// wrapper script, not a retry (CLI 2.1.323+).
1399    ManagedSettingsNotDelivered,
1400    /// `initialize_fields_not_delivered` — as
1401    /// [`ManagedSettingsNotDelivered`](Self::ManagedSettingsNotDelivered),
1402    /// for `--initialize-fields` and the settings or `disallowedTools` it
1403    /// names; also when a named field's own flag (`--settings`,
1404    /// `--disallowedTools`) is passed too (CLI 2.1.327+).
1405    InitializeFieldsNotDelivered,
1406    /// A cause not yet known to this version of the crate.
1407    Unknown(String),
1408}
1409
1410impl StartupFailureReason {
1411    pub fn as_str(&self) -> &str {
1412        match self {
1413            Self::OrgPinApiKeyConflict => "org_pin_api_key_conflict",
1414            Self::ProviderNotAllowed => "provider_not_allowed",
1415            Self::OrgVerifyFailed => "org_verify_failed",
1416            Self::OrgPinMismatch => "org_pin_mismatch",
1417            Self::ManagedSettingsInvalid => "managed_settings_invalid",
1418            Self::RemoteSettingsRequiredUnavailable => "remote_settings_required_unavailable",
1419            Self::GatewaySigninRequired => "gateway_signin_required",
1420            Self::GatewayAccessDenied => "gateway_access_denied",
1421            Self::ProxyInvalid => "proxy_invalid",
1422            Self::TempDirUnusable => "temp_dir_unusable",
1423            Self::CwdUnavailable => "cwd_unavailable",
1424            Self::ShellToolMissing => "shell_tool_missing",
1425            Self::SessionHeldByBackground => "session_held_by_background",
1426            Self::WorktreeResumeRefused => "worktree_resume_refused",
1427            Self::WorktreeUnverified => "worktree_unverified",
1428            Self::CliVersionTooOld => "cli_version_too_old",
1429            Self::BypassRoot => "bypass_root",
1430            Self::OrgConfigRequiredUnavailable => "org_config_required_unavailable",
1431            Self::OrgConfigRefused => "org_config_refused",
1432            Self::SandboxRequiredUnavailable => "sandbox_required_unavailable",
1433            Self::InitializeNotFirst => "initialize_not_first",
1434            Self::ConfigFileInvalid => "config_file_invalid",
1435            Self::ManagedSettingsNotDelivered => "managed_settings_not_delivered",
1436            Self::InitializeFieldsNotDelivered => "initialize_fields_not_delivered",
1437            Self::Unknown(s) => s.as_str(),
1438        }
1439    }
1440}
1441
1442impl fmt::Display for StartupFailureReason {
1443    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1444        f.write_str(self.as_str())
1445    }
1446}
1447
1448impl From<&str> for StartupFailureReason {
1449    fn from(s: &str) -> Self {
1450        match s {
1451            "org_pin_api_key_conflict" => Self::OrgPinApiKeyConflict,
1452            "provider_not_allowed" => Self::ProviderNotAllowed,
1453            "org_verify_failed" => Self::OrgVerifyFailed,
1454            "org_pin_mismatch" => Self::OrgPinMismatch,
1455            "managed_settings_invalid" => Self::ManagedSettingsInvalid,
1456            "remote_settings_required_unavailable" => Self::RemoteSettingsRequiredUnavailable,
1457            "gateway_signin_required" => Self::GatewaySigninRequired,
1458            "gateway_access_denied" => Self::GatewayAccessDenied,
1459            "proxy_invalid" => Self::ProxyInvalid,
1460            "temp_dir_unusable" => Self::TempDirUnusable,
1461            "cwd_unavailable" => Self::CwdUnavailable,
1462            "shell_tool_missing" => Self::ShellToolMissing,
1463            "session_held_by_background" => Self::SessionHeldByBackground,
1464            "worktree_resume_refused" => Self::WorktreeResumeRefused,
1465            "worktree_unverified" => Self::WorktreeUnverified,
1466            "cli_version_too_old" => Self::CliVersionTooOld,
1467            "bypass_root" => Self::BypassRoot,
1468            "org_config_required_unavailable" => Self::OrgConfigRequiredUnavailable,
1469            "org_config_refused" => Self::OrgConfigRefused,
1470            "sandbox_required_unavailable" => Self::SandboxRequiredUnavailable,
1471            "initialize_not_first" => Self::InitializeNotFirst,
1472            "config_file_invalid" => Self::ConfigFileInvalid,
1473            "managed_settings_not_delivered" => Self::ManagedSettingsNotDelivered,
1474            "initialize_fields_not_delivered" => Self::InitializeFieldsNotDelivered,
1475            other => Self::Unknown(other.to_string()),
1476        }
1477    }
1478}
1479
1480impl Serialize for StartupFailureReason {
1481    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1482        serializer.serialize_str(self.as_str())
1483    }
1484}
1485
1486impl<'de> Deserialize<'de> for StartupFailureReason {
1487    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1488        let s = String::deserialize(deserializer)?;
1489        Ok(Self::from(s.as_str()))
1490    }
1491}
1492
1493/// How the self-hosted runner's session process terminated, carried on a
1494/// synthesized failure [`ResultMessage`] as [`ResultMessage::runner_exit`]
1495/// (CLI 2.1.266+).
1496#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1497pub struct RunnerExit {
1498    /// Which phase the process was in when it exited.
1499    pub phase: RunnerExitPhase,
1500    /// Process exit code. Absent (or wire `null`) when it exited on a signal
1501    /// instead, or when the runner did not capture one.
1502    #[serde(default, skip_serializing_if = "Option::is_none")]
1503    pub exit_code: Option<i64>,
1504    /// Terminating signal name. Absent (or wire `null`) when it exited with a
1505    /// code instead, or when the runner did not capture one.
1506    #[serde(default, skip_serializing_if = "Option::is_none")]
1507    pub signal: Option<String>,
1508}
1509
1510/// Which phase the runner's session process was in when it exited, in
1511/// [`RunnerExit::phase`]. Open set — unrecognized values deserialize to
1512/// [`RunnerExitPhase::Unknown`].
1513#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1514pub enum RunnerExitPhase {
1515    /// Failed while starting up.
1516    Setup,
1517    /// Failed once running.
1518    Run,
1519    /// A phase not yet known to this version of the crate.
1520    Unknown(String),
1521}
1522
1523impl RunnerExitPhase {
1524    pub fn as_str(&self) -> &str {
1525        match self {
1526            Self::Setup => "setup",
1527            Self::Run => "run",
1528            Self::Unknown(s) => s.as_str(),
1529        }
1530    }
1531}
1532
1533impl std::fmt::Display for RunnerExitPhase {
1534    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1535        f.write_str(self.as_str())
1536    }
1537}
1538
1539impl From<&str> for RunnerExitPhase {
1540    fn from(s: &str) -> Self {
1541        match s {
1542            "setup" => Self::Setup,
1543            "run" => Self::Run,
1544            other => Self::Unknown(other.to_string()),
1545        }
1546    }
1547}
1548
1549impl Serialize for RunnerExitPhase {
1550    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1551        serializer.serialize_str(self.as_str())
1552    }
1553}
1554
1555impl<'de> Deserialize<'de> for RunnerExitPhase {
1556    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1557        let s = String::deserialize(deserializer)?;
1558        Ok(Self::from(s.as_str()))
1559    }
1560}
1561
1562/// Usage and cost for a single model within a session, as found in
1563/// [`ResultMessage::model_usage`] and
1564/// [`ResultMessage::model_usage_since_last_result`].
1565///
1566/// The `extra` field captures any keys the CLI adds that aren't modeled here,
1567/// so new wire fields deserialize without error.
1568#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1569#[serde(rename_all = "camelCase")]
1570pub struct ModelUsageEntry {
1571    #[serde(default)]
1572    pub input_tokens: u64,
1573    #[serde(default)]
1574    pub output_tokens: u64,
1575    #[serde(default)]
1576    pub cache_read_input_tokens: u64,
1577    #[serde(default)]
1578    pub cache_creation_input_tokens: u64,
1579    #[serde(default, rename = "costUSD")]
1580    pub cost_usd: f64,
1581    #[serde(default)]
1582    pub web_search_requests: u32,
1583    #[serde(default)]
1584    pub context_window: u64,
1585    #[serde(default)]
1586    pub max_output_tokens: u64,
1587    #[serde(flatten)]
1588    pub extra: serde_json::Map<String, serde_json::Value>,
1589}
1590
1591/// Tool use deferred by a terminal result.
1592#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1593pub struct DeferredToolUse {
1594    pub id: String,
1595    pub name: String,
1596    pub input: Value,
1597}
1598
1599/// Running totals for subagents started through the Agent tool, carried on
1600/// `result` frames (CLI 2.1.239+) as [`ResultMessage::subagent_stats`].
1601///
1602/// Cumulative for the session: a resumed session starts fresh, and a
1603/// mid-session `/clear` zeroes it — though a background subagent that outlives
1604/// the `/clear` still records its outcome, so `completed`, `failed`, and
1605/// `killed` can then exceed `spawned`. Forked skills, workflows, teammates,
1606/// and other internal agents are not counted.
1607#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
1608pub struct SubagentStats {
1609    /// Subagents actually started; a refused or failed launch is not counted.
1610    pub spawned: u64,
1611    /// Spawns by the `run_in_background` value the model passed; all count as
1612    /// `unset` while the parameter is not offered (background tasks disabled,
1613    /// or subagents forced into the background: in a terminal, the desktop
1614    /// app or the VS Code extension, or with `CLAUDE_CODE_FORK_SUBAGENT=1`).
1615    pub requested: SubagentSpawnRequests,
1616    /// Spawns that started in the background after defaults and session
1617    /// settings; the rest blocked the spawning tool call.
1618    pub started_in_background: u64,
1619    /// Spawns by agent type.
1620    #[serde(default)]
1621    pub by_type: std::collections::BTreeMap<String, u64>,
1622    /// Deepest spawn: 1 = started by the main thread, 2 = by a depth-1
1623    /// subagent.
1624    pub max_depth: u64,
1625    /// Spawns made from inside another subagent (depth > 1).
1626    pub spawned_by_subagents: u64,
1627    pub completed: u64,
1628    pub failed: u64,
1629    /// Subagents stopped before finishing, by who stopped them.
1630    pub killed: SubagentKillCounts,
1631    /// Agent tool calls turned down because a limit was reached (other
1632    /// denials, such as an unknown agent type, are not counted).
1633    pub refused: SubagentRefusalCounts,
1634}
1635
1636/// Spawn counts by the `run_in_background` value the model passed, carried in
1637/// [`SubagentStats::requested`].
1638#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
1639pub struct SubagentSpawnRequests {
1640    pub background: u64,
1641    pub foreground: u64,
1642    pub unset: u64,
1643}
1644
1645/// Subagents stopped before finishing, carried in [`SubagentStats::killed`].
1646/// `parent` = by another agent through TaskStop; `system` = by Claude Code
1647/// itself; `user` = any other stop.
1648#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
1649pub struct SubagentKillCounts {
1650    pub parent: u64,
1651    pub user: u64,
1652    pub system: u64,
1653}
1654
1655/// Agent tool calls refused at a limit, carried in [`SubagentStats::refused`].
1656#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
1657pub struct SubagentRefusalCounts {
1658    pub depth_limit: u64,
1659    pub concurrency_limit: u64,
1660    pub budget: u64,
1661}
1662
1663/// A record of a tool permission that was denied during the session.
1664///
1665/// This is included in `ResultMessage.permission_denials` to provide a summary
1666/// of all permission denials that occurred.
1667#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1668pub struct PermissionDenial {
1669    /// The name of the tool that was blocked (e.g., "Bash", "Write")
1670    pub tool_name: String,
1671
1672    /// The input that was passed to the tool
1673    pub tool_input: Value,
1674
1675    /// The unique identifier for this tool use request
1676    pub tool_use_id: String,
1677}
1678
1679/// What the first stream POST of a turn was queued behind, carried as
1680/// [`ResultMessage::first_stream_post_queued_behind`] (CLI 2.1.278+).
1681/// Internal timing instrumentation; the CLI does not describe the values.
1682#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1683pub enum StreamPostQueuedBehind {
1684    /// `durable_post`
1685    DurablePost,
1686    /// `ephemeral_post`
1687    EphemeralPost,
1688    /// `retry_backoff`
1689    RetryBackoff,
1690    /// `hold`
1691    Hold,
1692    /// `none`
1693    None,
1694    /// A value not yet known to this version of the crate.
1695    Unknown(String),
1696}
1697
1698impl StreamPostQueuedBehind {
1699    pub fn as_str(&self) -> &str {
1700        match self {
1701            Self::DurablePost => "durable_post",
1702            Self::EphemeralPost => "ephemeral_post",
1703            Self::RetryBackoff => "retry_backoff",
1704            Self::Hold => "hold",
1705            Self::None => "none",
1706            Self::Unknown(s) => s.as_str(),
1707        }
1708    }
1709}
1710
1711impl fmt::Display for StreamPostQueuedBehind {
1712    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1713        f.write_str(self.as_str())
1714    }
1715}
1716
1717impl From<&str> for StreamPostQueuedBehind {
1718    fn from(s: &str) -> Self {
1719        match s {
1720            "durable_post" => Self::DurablePost,
1721            "ephemeral_post" => Self::EphemeralPost,
1722            "retry_backoff" => Self::RetryBackoff,
1723            "hold" => Self::Hold,
1724            "none" => Self::None,
1725            other => Self::Unknown(other.to_string()),
1726        }
1727    }
1728}
1729
1730impl Serialize for StreamPostQueuedBehind {
1731    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1732        serializer.serialize_str(self.as_str())
1733    }
1734}
1735
1736impl<'de> Deserialize<'de> for StreamPostQueuedBehind {
1737    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1738        let s = String::deserialize(deserializer)?;
1739        Ok(Self::from(s.as_str()))
1740    }
1741}
1742
1743/// [`ResultMessage::memory_check_detail`] — how the turn went about its
1744/// memory check (CLI 2.1.326+). A turn that will wait for the answer can
1745/// first be held until the request is sent; the `memory_send_wait` phase of
1746/// `time_to_request_phases_ms` times that hold.
1747#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1748pub struct MemoryCheckDetail {
1749    /// The hold's feature flag as the turn started: `1` on in
1750    /// claude-code-server, `2` on in every cloud worker, `0` otherwise.
1751    /// Absent where the process's flags were not fresh.
1752    #[serde(default, skip_serializing_if = "Option::is_none")]
1753    pub flag: Option<u64>,
1754    /// Whether the turn was held until the request was sent, and how the
1755    /// hold ended.
1756    pub hold: MemoryCheckHold,
1757    /// How the wait for the check's answer went. Absent where the turn was
1758    /// stopped first or never came to that wait. Decided the same way with
1759    /// the hold on and off.
1760    #[serde(default, skip_serializing_if = "Option::is_none")]
1761    pub wait: Option<MemoryCheckWait>,
1762    /// How many such checks the process has started since the last turn that
1763    /// reported this number (start-up, ahead of the message, after the
1764    /// previous turn or for this turn), counting one refused before it was
1765    /// sent; `9` means 9 or more. Present with `wait`.
1766    #[serde(default, skip_serializing_if = "Option::is_none")]
1767    pub requests: Option<u64>,
1768    /// How long, in ms, before the turn came to its memory check the last
1769    /// answered check was sent, while that check is still the worker's
1770    /// start-up read (normally on a worker's first turn only). The age the
1771    /// boot grace is compared with. Absent once a later check has answered,
1772    /// before any check has answered, and where the server had stopped the
1773    /// checks or says that no turn waits (CLI 2.1.327+).
1774    #[serde(default, skip_serializing_if = "Option::is_none")]
1775    pub boot_age_ms: Option<u64>,
1776}
1777
1778/// [`MemoryCheckDetail::hold`] — whether a turn was held until its memory
1779/// check request was sent, and how the hold ended (CLI 2.1.326+).
1780#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1781pub enum MemoryCheckHold {
1782    /// `off` — the hold is not on for this worker.
1783    Off,
1784    /// `not_due` — the turn was not expected to wait, or that could not be
1785    /// told.
1786    NotDue,
1787    /// `nothing_to_send` — the request had already been sent or answered,
1788    /// none was due, or it is one the server may hold (the wait replaces it,
1789    /// or, since CLI 2.1.327, joins it where only the boot grace holds the
1790    /// turn back while the server picks memory files for its message).
1791    NothingToSend,
1792    /// `sent` — the hold ended when the request was sent.
1793    Sent,
1794    /// `cap` — the hold's time limit came first.
1795    Cap,
1796    /// `abort` — the turn was stopped.
1797    Abort,
1798    /// `failed` — the request ended before it was sent.
1799    Failed,
1800    /// A value not yet known to this version of the crate.
1801    Unknown(String),
1802}
1803
1804impl MemoryCheckHold {
1805    pub fn as_str(&self) -> &str {
1806        match self {
1807            Self::Off => "off",
1808            Self::NotDue => "not_due",
1809            Self::NothingToSend => "nothing_to_send",
1810            Self::Sent => "sent",
1811            Self::Cap => "cap",
1812            Self::Abort => "abort",
1813            Self::Failed => "failed",
1814            Self::Unknown(s) => s.as_str(),
1815        }
1816    }
1817}
1818
1819impl fmt::Display for MemoryCheckHold {
1820    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1821        f.write_str(self.as_str())
1822    }
1823}
1824
1825impl From<&str> for MemoryCheckHold {
1826    fn from(s: &str) -> Self {
1827        match s {
1828            "off" => Self::Off,
1829            "not_due" => Self::NotDue,
1830            "nothing_to_send" => Self::NothingToSend,
1831            "sent" => Self::Sent,
1832            "cap" => Self::Cap,
1833            "abort" => Self::Abort,
1834            "failed" => Self::Failed,
1835            other => Self::Unknown(other.to_string()),
1836        }
1837    }
1838}
1839
1840impl Serialize for MemoryCheckHold {
1841    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1842        serializer.serialize_str(self.as_str())
1843    }
1844}
1845
1846impl<'de> Deserialize<'de> for MemoryCheckHold {
1847    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1848        let s = String::deserialize(deserializer)?;
1849        Ok(Self::from(s.as_str()))
1850    }
1851}
1852
1853/// [`MemoryCheckDetail::wait`] — how a turn's wait for its memory check
1854/// answer went (CLI 2.1.326+).
1855#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1856pub enum MemoryCheckWait {
1857    /// `went_on` — the turn did not need its own check's answer, took one
1858    /// asked for ahead of the message, or the server had stopped the checks.
1859    WentOn,
1860    /// `answered` — the answer came.
1861    Answered,
1862    /// `cut` — the wait for the answer ran out.
1863    Cut,
1864    /// `unanswered` — the request was refused or failed.
1865    Unanswered,
1866    /// `grace_answered` — as [`Answered`](Self::Answered), for a turn that
1867    /// waited only because the last answer was still the worker's start-up
1868    /// read and older than the boot grace (CLI 2.1.327+; behind a flag that
1869    /// is off by default).
1870    GraceAnswered,
1871    /// `grace_cut` — as [`Cut`](Self::Cut), for a boot-grace wait
1872    /// (CLI 2.1.327+).
1873    GraceCut,
1874    /// `grace_unanswered` — as [`Unanswered`](Self::Unanswered), for a
1875    /// boot-grace wait (CLI 2.1.327+).
1876    GraceUnanswered,
1877    /// A value not yet known to this version of the crate.
1878    Unknown(String),
1879}
1880
1881impl MemoryCheckWait {
1882    pub fn as_str(&self) -> &str {
1883        match self {
1884            Self::WentOn => "went_on",
1885            Self::Answered => "answered",
1886            Self::Cut => "cut",
1887            Self::Unanswered => "unanswered",
1888            Self::GraceAnswered => "grace_answered",
1889            Self::GraceCut => "grace_cut",
1890            Self::GraceUnanswered => "grace_unanswered",
1891            Self::Unknown(s) => s.as_str(),
1892        }
1893    }
1894}
1895
1896impl fmt::Display for MemoryCheckWait {
1897    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1898        f.write_str(self.as_str())
1899    }
1900}
1901
1902impl From<&str> for MemoryCheckWait {
1903    fn from(s: &str) -> Self {
1904        match s {
1905            "went_on" => Self::WentOn,
1906            "answered" => Self::Answered,
1907            "cut" => Self::Cut,
1908            "unanswered" => Self::Unanswered,
1909            "grace_answered" => Self::GraceAnswered,
1910            "grace_cut" => Self::GraceCut,
1911            "grace_unanswered" => Self::GraceUnanswered,
1912            other => Self::Unknown(other.to_string()),
1913        }
1914    }
1915}
1916
1917impl Serialize for MemoryCheckWait {
1918    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1919        serializer.serialize_str(self.as_str())
1920    }
1921}
1922
1923impl<'de> Deserialize<'de> for MemoryCheckWait {
1924    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1925        let s = String::deserialize(deserializer)?;
1926        Ok(Self::from(s.as_str()))
1927    }
1928}
1929
1930/// What a turn was given to settle before its own prompt, carried as
1931/// [`ResultMessage::turn_start_resume_kind`] (CLI 2.1.287+). A turn given
1932/// more than one reports the first in this order.
1933#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1934pub enum TurnStartResumeKind {
1935    /// `orphaned_permission` — a permission answer whose pending request was
1936    /// lost (as when a worker restarts), so the tool call is settled with
1937    /// that answer.
1938    OrphanedPermission,
1939    /// `turn_handoff` — a turn in progress that the session's client handed
1940    /// over.
1941    TurnHandoff,
1942    /// `deferred_tool_use` — a call a `PreToolUse` hook deferred.
1943    DeferredToolUse,
1944    /// `none` — nothing to settle (`resume_other` is still reported, at
1945    /// about 0).
1946    None,
1947    /// A value not yet known to this version of the crate.
1948    Unknown(String),
1949}
1950
1951impl TurnStartResumeKind {
1952    pub fn as_str(&self) -> &str {
1953        match self {
1954            Self::OrphanedPermission => "orphaned_permission",
1955            Self::TurnHandoff => "turn_handoff",
1956            Self::DeferredToolUse => "deferred_tool_use",
1957            Self::None => "none",
1958            Self::Unknown(s) => s.as_str(),
1959        }
1960    }
1961}
1962
1963impl fmt::Display for TurnStartResumeKind {
1964    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1965        f.write_str(self.as_str())
1966    }
1967}
1968
1969impl From<&str> for TurnStartResumeKind {
1970    fn from(s: &str) -> Self {
1971        match s {
1972            "orphaned_permission" => Self::OrphanedPermission,
1973            "turn_handoff" => Self::TurnHandoff,
1974            "deferred_tool_use" => Self::DeferredToolUse,
1975            "none" => Self::None,
1976            other => Self::Unknown(other.to_string()),
1977        }
1978    }
1979}
1980
1981impl Serialize for TurnStartResumeKind {
1982    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1983        serializer.serialize_str(self.as_str())
1984    }
1985}
1986
1987impl<'de> Deserialize<'de> for TurnStartResumeKind {
1988    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1989        let s = String::deserialize(deserializer)?;
1990        Ok(Self::from(s.as_str()))
1991    }
1992}
1993
1994/// Why fast mode can't serve right now, carried on `result` frames and
1995/// `system/init` (CLI 2.1.219+). Absent when nothing blocks fast mode.
1996#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1997pub enum FastModeDisabledReason {
1998    /// Free-tier account.
1999    Free,
2000    /// Disabled by user preference.
2001    Preference,
2002    /// Extra-usage purchases are disabled for the account.
2003    ExtraUsageDisabled,
2004    /// A network error prevented fast-mode eligibility from resolving.
2005    NetworkError,
2006    /// The CLI could not determine the reason.
2007    UnknownReason,
2008    /// Not a first-party API session (e.g. Bedrock/Vertex).
2009    NotFirstParty,
2010    /// Disabled via environment variable.
2011    DisabledByEnv,
2012    /// The active model does not support fast mode.
2013    ModelNotAllowed,
2014    /// SDK sessions must opt in to fast mode.
2015    SdkOptInRequired,
2016    /// Eligibility is still being determined.
2017    Pending,
2018    /// A reason not yet known to this version of the crate.
2019    Unknown(String),
2020}
2021
2022impl FastModeDisabledReason {
2023    pub fn as_str(&self) -> &str {
2024        match self {
2025            Self::Free => "free",
2026            Self::Preference => "preference",
2027            Self::ExtraUsageDisabled => "extra_usage_disabled",
2028            Self::NetworkError => "network_error",
2029            Self::UnknownReason => "unknown",
2030            Self::NotFirstParty => "not_first_party",
2031            Self::DisabledByEnv => "disabled_by_env",
2032            Self::ModelNotAllowed => "model_not_allowed",
2033            Self::SdkOptInRequired => "sdk_opt_in_required",
2034            Self::Pending => "pending",
2035            Self::Unknown(s) => s.as_str(),
2036        }
2037    }
2038}
2039
2040impl fmt::Display for FastModeDisabledReason {
2041    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2042        f.write_str(self.as_str())
2043    }
2044}
2045
2046impl From<&str> for FastModeDisabledReason {
2047    fn from(s: &str) -> Self {
2048        match s {
2049            "free" => Self::Free,
2050            "preference" => Self::Preference,
2051            "extra_usage_disabled" => Self::ExtraUsageDisabled,
2052            "network_error" => Self::NetworkError,
2053            "unknown" => Self::UnknownReason,
2054            "not_first_party" => Self::NotFirstParty,
2055            "disabled_by_env" => Self::DisabledByEnv,
2056            "model_not_allowed" => Self::ModelNotAllowed,
2057            "sdk_opt_in_required" => Self::SdkOptInRequired,
2058            "pending" => Self::Pending,
2059            other => Self::Unknown(other.to_string()),
2060        }
2061    }
2062}
2063
2064impl Serialize for FastModeDisabledReason {
2065    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2066        serializer.serialize_str(self.as_str())
2067    }
2068}
2069
2070impl<'de> Deserialize<'de> for FastModeDisabledReason {
2071    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
2072        let s = String::deserialize(deserializer)?;
2073        Ok(Self::from(s.as_str()))
2074    }
2075}
2076
2077/// Result subtypes
2078#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2079pub enum ResultSubtype {
2080    Success,
2081    ErrorMaxTurns,
2082    ErrorDuringExecution,
2083    ErrorMaxBudgetUsd,
2084    ErrorMaxStructuredOutputRetries,
2085    Unknown(String),
2086}
2087
2088impl ResultSubtype {
2089    pub fn as_str(&self) -> &str {
2090        match self {
2091            Self::Success => "success",
2092            Self::ErrorMaxTurns => "error_max_turns",
2093            Self::ErrorDuringExecution => "error_during_execution",
2094            Self::ErrorMaxBudgetUsd => "error_max_budget_usd",
2095            Self::ErrorMaxStructuredOutputRetries => "error_max_structured_output_retries",
2096            Self::Unknown(s) => s.as_str(),
2097        }
2098    }
2099}
2100
2101impl fmt::Display for ResultSubtype {
2102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2103        f.write_str(self.as_str())
2104    }
2105}
2106
2107impl From<&str> for ResultSubtype {
2108    fn from(s: &str) -> Self {
2109        match s {
2110            "success" => Self::Success,
2111            "error_max_turns" => Self::ErrorMaxTurns,
2112            "error_during_execution" => Self::ErrorDuringExecution,
2113            "error_max_budget_usd" => Self::ErrorMaxBudgetUsd,
2114            "error_max_structured_output_retries" => Self::ErrorMaxStructuredOutputRetries,
2115            other => Self::Unknown(other.to_string()),
2116        }
2117    }
2118}
2119
2120impl Serialize for ResultSubtype {
2121    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2122        serializer.serialize_str(self.as_str())
2123    }
2124}
2125
2126impl<'de> Deserialize<'de> for ResultSubtype {
2127    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
2128        let s = String::deserialize(deserializer)?;
2129        Ok(Self::from(s.as_str()))
2130    }
2131}
2132
2133/// Usage information for the request.
2134///
2135/// **These counters are accumulated roll-ups, not snapshots.** The CLI sums
2136/// usage field-by-field across every API call ("iteration") in the turn's
2137/// tool-use loop, so on a turn with N iterations each counter is the sum of
2138/// all N. This is the right number for **cost**, and the wrong number for
2139/// **context occupancy**: `cache_read_input_tokens` in particular re-counts
2140/// the cached context on every iteration and can exceed the model's context
2141/// window several times over on tool-heavy turns. To estimate context
2142/// occupancy, use the *last* entry of [`iterations`](Self::iterations)
2143/// instead (the CLI itself does exactly this).
2144///
2145/// Note: the `result` frame's usage covers the **main agent only** — the
2146/// subagent (`Task` / sidechain) token rollup the CLI renders as
2147/// `<subagent_tokens>` / `<agent_count>` is not carried here or anywhere
2148/// else on the wire. Accumulate it from `Task` tool results with
2149/// [`SubagentUsageRollup`](crate::SubagentUsageRollup).
2150#[derive(Debug, Clone, Serialize, Deserialize)]
2151pub struct UsageInfo {
2152    /// Sum of fresh (uncached) input tokens across all iterations of the turn.
2153    #[serde(default)]
2154    pub input_tokens: u32,
2155    /// Sum of cache-write input tokens across all iterations of the turn.
2156    #[serde(default)]
2157    pub cache_creation_input_tokens: u32,
2158    /// Sum of cache-read input tokens across all iterations of the turn.
2159    /// Re-counts the cached context every iteration — **not** a measure of
2160    /// context occupancy; see the type-level docs.
2161    #[serde(default)]
2162    pub cache_read_input_tokens: u32,
2163    /// Sum of output tokens across all iterations of the turn.
2164    #[serde(default)]
2165    pub output_tokens: u32,
2166    #[serde(default)]
2167    pub server_tool_use: ServerToolUse,
2168    #[serde(default)]
2169    pub service_tier: String,
2170
2171    /// Cache creation breakdown
2172    #[serde(skip_serializing_if = "Option::is_none")]
2173    pub cache_creation: Option<super::message_types::CacheCreationDetails>,
2174
2175    /// Inference geography (e.g., "not_available")
2176    #[serde(skip_serializing_if = "Option::is_none")]
2177    pub inference_geo: Option<String>,
2178
2179    /// Per-iteration usage breakdown **within** this turn — one entry per
2180    /// API call in the tool-use loop, in order. The last entry reflects the
2181    /// final API call and is what the CLI reads for context-size estimates.
2182    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2183    pub iterations: Vec<UsageIteration>,
2184
2185    /// Speed tier (e.g., "standard")
2186    #[serde(skip_serializing_if = "Option::is_none")]
2187    pub speed: Option<String>,
2188
2189    /// Output-token breakdown (CLI 2.1.232+): currently the thinking-token
2190    /// share of `output_tokens`.
2191    #[serde(skip_serializing_if = "Option::is_none")]
2192    pub output_tokens_details: Option<OutputTokensDetails>,
2193
2194    /// Outcome of a fallback-credit token the request presented; `null` on
2195    /// the wire when it presented none (CLI 2.1.285+).
2196    #[serde(default, skip_serializing_if = "Option::is_none")]
2197    pub fallback_credit: Option<Value>,
2198}
2199
2200/// Breakdown of a turn's output tokens, carried in
2201/// [`UsageInfo::output_tokens_details`].
2202#[derive(Debug, Clone, Serialize, Deserialize, Default)]
2203pub struct OutputTokensDetails {
2204    /// Output tokens spent on extended thinking.
2205    #[serde(skip_serializing_if = "Option::is_none")]
2206    pub thinking_tokens: Option<u64>,
2207}
2208
2209/// Usage for a single API call ("iteration") within a turn's tool-use loop.
2210///
2211/// Carried in [`UsageInfo::iterations`]. The cache fields are optional on
2212/// the wire: some frames carry only `input_tokens` + `output_tokens`
2213/// (observed with `type: "turn"`), while others carry the full cache
2214/// breakdown (observed with `type: "message"` in captured subagent
2215/// sessions). The CLI computes its context estimate from
2216/// `input_tokens + output_tokens` of the **last** iteration.
2217#[derive(Debug, Clone, Serialize, Deserialize)]
2218pub struct UsageIteration {
2219    #[serde(default)]
2220    pub input_tokens: u32,
2221    #[serde(default)]
2222    pub output_tokens: u32,
2223    /// Cache-read input tokens for this iteration, when carried.
2224    #[serde(default, skip_serializing_if = "Option::is_none")]
2225    pub cache_read_input_tokens: Option<u32>,
2226    /// Cache-write input tokens for this iteration, when carried.
2227    #[serde(default, skip_serializing_if = "Option::is_none")]
2228    pub cache_creation_input_tokens: Option<u32>,
2229    /// Cache-write breakdown by TTL, when carried.
2230    #[serde(default, skip_serializing_if = "Option::is_none")]
2231    pub cache_creation: Option<super::message_types::CacheCreationDetails>,
2232    /// Iteration kind; `"turn"` and `"message"` observed on the wire.
2233    #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
2234    pub kind: Option<String>,
2235}
2236
2237/// Server tool usage information
2238#[derive(Debug, Clone, Default, Serialize, Deserialize)]
2239pub struct ServerToolUse {
2240    #[serde(default)]
2241    pub web_search_requests: u32,
2242    /// Number of web fetch requests made
2243    #[serde(default)]
2244    pub web_fetch_requests: u32,
2245}
2246
2247#[cfg(test)]
2248mod tests {
2249    use super::*;
2250    use crate::io::ClaudeOutput;
2251
2252    #[test]
2253    fn test_deserialize_result_message() {
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": 1,
2261            "result": "Done",
2262            "session_id": "123",
2263            "total_cost_usd": 0.01,
2264            "permission_denials": []
2265        }"#;
2266
2267        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
2268        assert!(!output.is_error());
2269    }
2270
2271    #[test]
2272    fn test_result_subtype_new_and_unknown_values_do_not_fail() {
2273        let json = r#"{
2274            "type": "result",
2275            "subtype": "error_max_budget_usd",
2276            "is_error": true,
2277            "duration_ms": 100,
2278            "duration_api_ms": 200,
2279            "num_turns": 1,
2280            "session_id": "123",
2281            "total_cost_usd": 0.01
2282        }"#;
2283
2284        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
2285        let ClaudeOutput::Result(result) = output else {
2286            panic!("Expected Result");
2287        };
2288        assert_eq!(result.subtype, ResultSubtype::ErrorMaxBudgetUsd);
2289
2290        let json = r#"{
2291            "type": "result",
2292            "subtype": "future_result_subtype",
2293            "is_error": true,
2294            "duration_ms": 100,
2295            "duration_api_ms": 200,
2296            "num_turns": 1,
2297            "session_id": "123",
2298            "total_cost_usd": 0.01
2299        }"#;
2300
2301        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
2302        let ClaudeOutput::Result(result) = output else {
2303            panic!("Expected Result");
2304        };
2305        assert_eq!(
2306            result.subtype,
2307            ResultSubtype::Unknown("future_result_subtype".to_string())
2308        );
2309    }
2310
2311    #[test]
2312    fn test_deserialize_result_with_permission_denials() {
2313        let json = r#"{
2314            "type": "result",
2315            "subtype": "success",
2316            "is_error": false,
2317            "duration_ms": 100,
2318            "duration_api_ms": 200,
2319            "num_turns": 2,
2320            "result": "Done",
2321            "session_id": "123",
2322            "total_cost_usd": 0.01,
2323            "permission_denials": [
2324                {
2325                    "tool_name": "Bash",
2326                    "tool_input": {"command": "rm -rf /", "description": "Delete everything"},
2327                    "tool_use_id": "toolu_123"
2328                }
2329            ]
2330        }"#;
2331
2332        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
2333        if let ClaudeOutput::Result(result) = output {
2334            assert_eq!(result.permission_denials.len(), 1);
2335            assert_eq!(result.permission_denials[0].tool_name, "Bash");
2336            assert_eq!(result.permission_denials[0].tool_use_id, "toolu_123");
2337            assert_eq!(
2338                result.permission_denials[0]
2339                    .tool_input
2340                    .get("command")
2341                    .unwrap(),
2342                "rm -rf /"
2343            );
2344        } else {
2345            panic!("Expected Result");
2346        }
2347    }
2348
2349    #[test]
2350    fn test_permission_denial_roundtrip() {
2351        let denial = PermissionDenial {
2352            tool_name: "Write".to_string(),
2353            tool_input: serde_json::json!({"file_path": "/etc/passwd", "content": "bad"}),
2354            tool_use_id: "toolu_456".to_string(),
2355        };
2356
2357        let json = serde_json::to_string(&denial).unwrap();
2358        assert!(json.contains("\"tool_name\":\"Write\""));
2359        assert!(json.contains("\"tool_use_id\":\"toolu_456\""));
2360        assert!(json.contains("/etc/passwd"));
2361
2362        let parsed: PermissionDenial = serde_json::from_str(&json).unwrap();
2363        assert_eq!(parsed, denial);
2364    }
2365
2366    #[test]
2367    fn test_deserialize_result_message_with_errors() {
2368        let json = r#"{
2369            "type": "result",
2370            "subtype": "error_during_execution",
2371            "duration_ms": 0,
2372            "duration_api_ms": 0,
2373            "is_error": true,
2374            "num_turns": 0,
2375            "session_id": "27934753-425a-4182-892c-6b1c15050c3f",
2376            "total_cost_usd": 0,
2377            "errors": ["No conversation found with session ID: d56965c9-c855-4042-a8f5-f12bbb14d6f6"],
2378            "permission_denials": []
2379        }"#;
2380
2381        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
2382        assert!(output.is_error());
2383
2384        if let ClaudeOutput::Result(res) = output {
2385            assert!(res.is_error);
2386            assert_eq!(res.errors.len(), 1);
2387            assert!(res.errors[0].contains("No conversation found"));
2388        } else {
2389            panic!("Expected Result message");
2390        }
2391    }
2392
2393    #[test]
2394    fn test_deserialize_result_message_errors_defaults_empty() {
2395        let json = r#"{
2396            "type": "result",
2397            "subtype": "success",
2398            "is_error": false,
2399            "duration_ms": 100,
2400            "duration_api_ms": 200,
2401            "num_turns": 1,
2402            "session_id": "123",
2403            "total_cost_usd": 0.01
2404        }"#;
2405
2406        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
2407        if let ClaudeOutput::Result(res) = output {
2408            assert!(res.errors.is_empty());
2409        } else {
2410            panic!("Expected Result message");
2411        }
2412    }
2413
2414    #[test]
2415    fn test_result_message_errors_roundtrip() {
2416        let json = r#"{
2417            "type": "result",
2418            "subtype": "error_during_execution",
2419            "is_error": true,
2420            "duration_ms": 0,
2421            "duration_api_ms": 0,
2422            "num_turns": 0,
2423            "session_id": "test-session",
2424            "total_cost_usd": 0.0,
2425            "errors": ["Error 1", "Error 2"]
2426        }"#;
2427
2428        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
2429        let reserialized = serde_json::to_string(&output).unwrap();
2430
2431        assert!(reserialized.contains("Error 1"));
2432        assert!(reserialized.contains("Error 2"));
2433    }
2434
2435    #[test]
2436    fn test_result_with_new_fields() {
2437        let json = r#"{
2438            "type": "result",
2439            "subtype": "success",
2440            "is_error": false,
2441            "duration_ms": 5000,
2442            "duration_api_ms": 4500,
2443            "num_turns": 1,
2444            "result": "Done",
2445            "session_id": "abc",
2446            "total_cost_usd": 0.06,
2447            "api_error_status": null,
2448            "stop_reason": "end_turn",
2449            "terminal_reason": "completed",
2450            "fast_mode_state": "off",
2451            "modelUsage": {
2452                "claude-opus-4-7[1m]": {
2453                    "inputTokens": 3817,
2454                    "outputTokens": 14,
2455                    "costUSD": 0.06
2456                }
2457            },
2458            "usage": {
2459                "input_tokens": 3817,
2460                "output_tokens": 14,
2461                "cache_creation_input_tokens": 3540,
2462                "cache_read_input_tokens": 0,
2463                "server_tool_use": {
2464                    "web_search_requests": 0,
2465                    "web_fetch_requests": 2
2466                },
2467                "service_tier": "standard",
2468                "inference_geo": "not_available",
2469                "speed": "standard",
2470                "iterations": [
2471                    {"input_tokens": 3817, "output_tokens": 14, "type": "turn"}
2472                ]
2473            }
2474        }"#;
2475
2476        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
2477        if let ClaudeOutput::Result(res) = output {
2478            assert_eq!(res.stop_reason.as_deref(), Some("end_turn"));
2479            assert_eq!(res.terminal_reason.as_deref(), Some("completed"));
2480            assert_eq!(res.fast_mode_state.as_deref(), Some("off"));
2481            let model_usage = res.model_usage.as_ref().unwrap();
2482            let entry = model_usage
2483                .get("claude-opus-4-7[1m]")
2484                .expect("per-model entry present");
2485            assert_eq!(entry.input_tokens, 3817);
2486            assert_eq!(entry.output_tokens, 14);
2487            assert_eq!(entry.cost_usd, 0.06);
2488            assert!(res.api_error_status.is_none());
2489
2490            let usage = res.usage.unwrap();
2491            assert_eq!(usage.server_tool_use.web_fetch_requests, 2);
2492            assert_eq!(usage.inference_geo.as_deref(), Some("not_available"));
2493            assert_eq!(usage.speed.as_deref(), Some("standard"));
2494            assert_eq!(usage.iterations.len(), 1);
2495            assert_eq!(usage.iterations[0].input_tokens, 3817);
2496            assert_eq!(usage.iterations[0].output_tokens, 14);
2497            assert_eq!(usage.iterations[0].kind.as_deref(), Some("turn"));
2498        } else {
2499            panic!("Expected Result");
2500        }
2501    }
2502
2503    #[test]
2504    fn test_result_backwards_compatible_without_new_fields() {
2505        // Verify old-format messages still parse fine
2506        let json = r#"{
2507            "type": "result",
2508            "subtype": "success",
2509            "is_error": false,
2510            "duration_ms": 100,
2511            "duration_api_ms": 200,
2512            "num_turns": 1,
2513            "session_id": "abc",
2514            "total_cost_usd": 0.01
2515        }"#;
2516
2517        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
2518        if let ClaudeOutput::Result(res) = output {
2519            assert!(res.api_error_status.is_none());
2520            assert!(res.stop_reason.is_none());
2521            assert!(res.terminal_reason.is_none());
2522            assert!(res.fast_mode_state.is_none());
2523            assert!(res.model_usage.is_none());
2524        } else {
2525            panic!("Expected Result");
2526        }
2527    }
2528
2529    #[test]
2530    fn test_result_fast_mode_disabled_reason() {
2531        let json = r#"{
2532            "type":"result","subtype":"success","is_error":false,
2533            "duration_ms":100,"duration_api_ms":80,"num_turns":1,
2534            "session_id":"s1","total_cost_usd":0.01,
2535            "fast_mode_state":"off",
2536            "fast_mode_disabled_reason":"sdk_opt_in_required"
2537        }"#;
2538        let output: crate::ClaudeOutput = serde_json::from_str(json).unwrap();
2539        let crate::ClaudeOutput::Result(res) = &output else {
2540            panic!("expected Result");
2541        };
2542        assert_eq!(
2543            res.fast_mode_disabled_reason,
2544            Some(FastModeDisabledReason::SdkOptInRequired)
2545        );
2546        assert!(serde_json::to_string(&output)
2547            .unwrap()
2548            .contains("\"fast_mode_disabled_reason\":\"sdk_opt_in_required\""));
2549
2550        // Unknown reasons survive decode and round-trip verbatim; the wire
2551        // literal "unknown" maps to the typed UnknownReason, not the fallback.
2552        assert_eq!(
2553            FastModeDisabledReason::from("unknown"),
2554            FastModeDisabledReason::UnknownReason
2555        );
2556        let novel = FastModeDisabledReason::from("solar_flare");
2557        assert_eq!(novel, FastModeDisabledReason::Unknown("solar_flare".into()));
2558        assert_eq!(novel.as_str(), "solar_flare");
2559    }
2560
2561    #[test]
2562    fn test_result_timing_and_user_message_uuid_fields() {
2563        let json = r#"{
2564            "type":"result","subtype":"success","is_error":false,
2565            "duration_ms":100,"duration_api_ms":80,"num_turns":1,
2566            "session_id":"s1","total_cost_usd":0.01,
2567            "request_sent_wall_ms":1753212345678.25,
2568            "user_message_uuid":"um-1"
2569        }"#;
2570        let output: crate::ClaudeOutput = serde_json::from_str(json).unwrap();
2571        let crate::ClaudeOutput::Result(res) = &output else {
2572            panic!("expected Result");
2573        };
2574        assert_eq!(res.request_sent_wall_ms, Some(1753212345678.25));
2575        assert_eq!(res.user_message_uuid.as_deref(), Some("um-1"));
2576
2577        let reserialized = serde_json::to_string(&output).unwrap();
2578        assert!(reserialized.contains("\"user_message_uuid\":\"um-1\""));
2579    }
2580
2581    #[test]
2582    fn test_result_queued_turn_count_and_user_message_uuids() {
2583        // CLI 2.1.259 additive fields on the result frame.
2584        let json = r#"{
2585            "type":"result","subtype":"success","is_error":false,
2586            "duration_ms":100,"duration_api_ms":80,"num_turns":1,
2587            "session_id":"s1","total_cost_usd":0.01,
2588            "user_message_uuid":"um-2",
2589            "user_message_uuids":["um-1","um-2"],
2590            "queued_turn_count":3
2591        }"#;
2592        let output: crate::ClaudeOutput = serde_json::from_str(json).unwrap();
2593        let crate::ClaudeOutput::Result(res) = &output else {
2594            panic!("expected Result");
2595        };
2596        assert_eq!(res.user_message_uuids, vec!["um-1", "um-2"]);
2597        assert_eq!(res.queued_turn_count, Some(3));
2598
2599        let reserialized = serde_json::to_string(&output).unwrap();
2600        assert!(reserialized.contains("\"user_message_uuids\":[\"um-1\",\"um-2\"]"));
2601        assert!(reserialized.contains("\"queued_turn_count\":3"));
2602
2603        // Both fields are absent from older producers and must default cleanly.
2604        let old = r#"{
2605            "type":"result","subtype":"success","is_error":false,
2606            "duration_ms":100,"duration_api_ms":80,"num_turns":1,
2607            "session_id":"s1","total_cost_usd":0.01
2608        }"#;
2609        let output: crate::ClaudeOutput = serde_json::from_str(old).unwrap();
2610        let crate::ClaudeOutput::Result(res) = &output else {
2611            panic!("expected Result");
2612        };
2613        assert!(res.user_message_uuids.is_empty());
2614        assert_eq!(res.queued_turn_count, None);
2615        let reserialized = serde_json::to_string(&output).unwrap();
2616        assert!(!reserialized.contains("user_message_uuids"));
2617        assert!(!reserialized.contains("queued_turn_count"));
2618    }
2619}