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