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