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