Skip to main content

claude_codes/io/
result.rs

1use serde::{Deserialize, Deserializer, Serialize, Serializer};
2use serde_json::Value;
3use std::fmt;
4
5/// Result message for completed queries
6#[derive(Debug, Clone, Serialize, Deserialize)]
7pub struct ResultMessage {
8    pub subtype: ResultSubtype,
9    pub is_error: bool,
10    pub duration_ms: u64,
11    pub duration_api_ms: u64,
12
13    /// Time to first token, in milliseconds.
14    #[serde(skip_serializing_if = "Option::is_none")]
15    pub ttft_ms: Option<u64>,
16
17    /// Time to first streamed token, in milliseconds.
18    #[serde(skip_serializing_if = "Option::is_none")]
19    pub ttft_stream_ms: Option<u64>,
20
21    /// Time from session start until the first request was issued, in milliseconds.
22    #[serde(skip_serializing_if = "Option::is_none")]
23    pub time_to_request_ms: Option<u64>,
24
25    /// Time from spawning a worker/spare until the first request was issued, in milliseconds.
26    #[serde(skip_serializing_if = "Option::is_none")]
27    pub time_to_request_from_spawn_ms: Option<u64>,
28
29    /// Whether a warm spare process was claimed for this request.
30    #[serde(skip_serializing_if = "Option::is_none")]
31    pub warm_spare_claimed: Option<bool>,
32
33    /// Epoch-ish timestamp origin used by CLI timing instrumentation.
34    #[serde(skip_serializing_if = "Option::is_none")]
35    pub time_origin_ms: Option<u64>,
36
37    /// Wall-clock epoch milliseconds when the API request was sent
38    /// (fractional; from CLI timing instrumentation).
39    #[serde(skip_serializing_if = "Option::is_none")]
40    pub request_sent_wall_ms: Option<f64>,
41
42    /// Wire uuid of the user message this result answers.
43    #[serde(skip_serializing_if = "Option::is_none")]
44    pub user_message_uuid: Option<String>,
45
46    pub num_turns: i32,
47
48    #[serde(skip_serializing_if = "Option::is_none")]
49    pub result: Option<String>,
50
51    #[serde(alias = "sessionId")]
52    pub session_id: String,
53    pub total_cost_usd: f64,
54
55    #[serde(skip_serializing_if = "Option::is_none")]
56    pub usage: Option<UsageInfo>,
57
58    /// Tools that were blocked due to permission denials during the session
59    #[serde(default)]
60    pub permission_denials: Vec<PermissionDenial>,
61
62    /// Error messages when `is_error` is true.
63    ///
64    /// Contains human-readable error strings (e.g., "No conversation found with session ID: ...").
65    /// This allows typed access to error conditions without needing to serialize to JSON and search.
66    #[serde(default)]
67    pub errors: Vec<String>,
68
69    #[serde(skip_serializing_if = "Option::is_none")]
70    pub uuid: Option<String>,
71
72    /// HTTP status code when the result is an API error (e.g., 429, 500, 529)
73    #[serde(skip_serializing_if = "Option::is_none")]
74    pub api_error_status: Option<u16>,
75
76    /// Why generation stopped (e.g., end_turn, max_tokens)
77    #[serde(skip_serializing_if = "Option::is_none")]
78    pub stop_reason: Option<String>,
79
80    /// Why the session ended (e.g., "completed")
81    #[serde(skip_serializing_if = "Option::is_none")]
82    pub terminal_reason: Option<String>,
83
84    /// Fast mode toggle state (e.g., "off")
85    #[serde(skip_serializing_if = "Option::is_none")]
86    pub fast_mode_state: Option<String>,
87
88    /// Why fast mode can't serve right now. Absent when nothing blocks it.
89    /// A paused-after-rate-limit run is not reported here; it rides
90    /// `fast_mode_state` as `"cooldown"`.
91    #[serde(skip_serializing_if = "Option::is_none")]
92    pub fast_mode_disabled_reason: Option<FastModeDisabledReason>,
93
94    /// Per-model cost breakdown, keyed by model name (e.g. `"claude-opus-4-8"`).
95    #[serde(skip_serializing_if = "Option::is_none", rename = "modelUsage")]
96    pub model_usage: Option<std::collections::BTreeMap<String, ModelUsageEntry>>,
97
98    /// Structured-output payload returned by the model, when enabled.
99    #[serde(skip_serializing_if = "Option::is_none")]
100    pub structured_output: Option<Value>,
101
102    /// Deferred tool-use termination payload.
103    #[serde(skip_serializing_if = "Option::is_none")]
104    pub deferred_tool_use: Option<DeferredToolUse>,
105
106    /// Provenance of the message/run.
107    #[serde(skip_serializing_if = "Option::is_none")]
108    pub origin: Option<super::message_types::MessageOrigin>,
109}
110
111/// Usage and cost for a single model within a session, as found in
112/// [`ResultMessage::model_usage`].
113///
114/// The `extra` field captures any keys the CLI adds that aren't modeled here,
115/// so new wire fields deserialize without error.
116#[derive(Debug, Clone, Default, Serialize, Deserialize)]
117#[serde(rename_all = "camelCase")]
118pub struct ModelUsageEntry {
119    #[serde(default)]
120    pub input_tokens: u64,
121    #[serde(default)]
122    pub output_tokens: u64,
123    #[serde(default)]
124    pub cache_read_input_tokens: u64,
125    #[serde(default)]
126    pub cache_creation_input_tokens: u64,
127    #[serde(default, rename = "costUSD")]
128    pub cost_usd: f64,
129    #[serde(default)]
130    pub web_search_requests: u32,
131    #[serde(default)]
132    pub context_window: u64,
133    #[serde(default)]
134    pub max_output_tokens: u64,
135    #[serde(flatten)]
136    pub extra: serde_json::Map<String, serde_json::Value>,
137}
138
139/// Tool use deferred by a terminal result.
140#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
141pub struct DeferredToolUse {
142    pub id: String,
143    pub name: String,
144    pub input: Value,
145}
146
147/// A record of a tool permission that was denied during the session.
148///
149/// This is included in `ResultMessage.permission_denials` to provide a summary
150/// of all permission denials that occurred.
151#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
152pub struct PermissionDenial {
153    /// The name of the tool that was blocked (e.g., "Bash", "Write")
154    pub tool_name: String,
155
156    /// The input that was passed to the tool
157    pub tool_input: Value,
158
159    /// The unique identifier for this tool use request
160    pub tool_use_id: String,
161}
162
163/// Why fast mode can't serve right now, carried on `result` frames and
164/// `system/init` (CLI 2.1.219+). Absent when nothing blocks fast mode.
165#[derive(Debug, Clone, PartialEq, Eq, Hash)]
166pub enum FastModeDisabledReason {
167    /// Free-tier account.
168    Free,
169    /// Disabled by user preference.
170    Preference,
171    /// Extra-usage purchases are disabled for the account.
172    ExtraUsageDisabled,
173    /// A network error prevented fast-mode eligibility from resolving.
174    NetworkError,
175    /// The CLI could not determine the reason.
176    UnknownReason,
177    /// Not a first-party API session (e.g. Bedrock/Vertex).
178    NotFirstParty,
179    /// Disabled via environment variable.
180    DisabledByEnv,
181    /// The active model does not support fast mode.
182    ModelNotAllowed,
183    /// SDK sessions must opt in to fast mode.
184    SdkOptInRequired,
185    /// Eligibility is still being determined.
186    Pending,
187    /// A reason not yet known to this version of the crate.
188    Unknown(String),
189}
190
191impl FastModeDisabledReason {
192    pub fn as_str(&self) -> &str {
193        match self {
194            Self::Free => "free",
195            Self::Preference => "preference",
196            Self::ExtraUsageDisabled => "extra_usage_disabled",
197            Self::NetworkError => "network_error",
198            Self::UnknownReason => "unknown",
199            Self::NotFirstParty => "not_first_party",
200            Self::DisabledByEnv => "disabled_by_env",
201            Self::ModelNotAllowed => "model_not_allowed",
202            Self::SdkOptInRequired => "sdk_opt_in_required",
203            Self::Pending => "pending",
204            Self::Unknown(s) => s.as_str(),
205        }
206    }
207}
208
209impl fmt::Display for FastModeDisabledReason {
210    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
211        f.write_str(self.as_str())
212    }
213}
214
215impl From<&str> for FastModeDisabledReason {
216    fn from(s: &str) -> Self {
217        match s {
218            "free" => Self::Free,
219            "preference" => Self::Preference,
220            "extra_usage_disabled" => Self::ExtraUsageDisabled,
221            "network_error" => Self::NetworkError,
222            "unknown" => Self::UnknownReason,
223            "not_first_party" => Self::NotFirstParty,
224            "disabled_by_env" => Self::DisabledByEnv,
225            "model_not_allowed" => Self::ModelNotAllowed,
226            "sdk_opt_in_required" => Self::SdkOptInRequired,
227            "pending" => Self::Pending,
228            other => Self::Unknown(other.to_string()),
229        }
230    }
231}
232
233impl Serialize for FastModeDisabledReason {
234    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
235        serializer.serialize_str(self.as_str())
236    }
237}
238
239impl<'de> Deserialize<'de> for FastModeDisabledReason {
240    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
241        let s = String::deserialize(deserializer)?;
242        Ok(Self::from(s.as_str()))
243    }
244}
245
246/// Result subtypes
247#[derive(Debug, Clone, PartialEq, Eq, Hash)]
248pub enum ResultSubtype {
249    Success,
250    ErrorMaxTurns,
251    ErrorDuringExecution,
252    ErrorMaxBudgetUsd,
253    ErrorMaxStructuredOutputRetries,
254    Unknown(String),
255}
256
257impl ResultSubtype {
258    pub fn as_str(&self) -> &str {
259        match self {
260            Self::Success => "success",
261            Self::ErrorMaxTurns => "error_max_turns",
262            Self::ErrorDuringExecution => "error_during_execution",
263            Self::ErrorMaxBudgetUsd => "error_max_budget_usd",
264            Self::ErrorMaxStructuredOutputRetries => "error_max_structured_output_retries",
265            Self::Unknown(s) => s.as_str(),
266        }
267    }
268}
269
270impl fmt::Display for ResultSubtype {
271    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
272        f.write_str(self.as_str())
273    }
274}
275
276impl From<&str> for ResultSubtype {
277    fn from(s: &str) -> Self {
278        match s {
279            "success" => Self::Success,
280            "error_max_turns" => Self::ErrorMaxTurns,
281            "error_during_execution" => Self::ErrorDuringExecution,
282            "error_max_budget_usd" => Self::ErrorMaxBudgetUsd,
283            "error_max_structured_output_retries" => Self::ErrorMaxStructuredOutputRetries,
284            other => Self::Unknown(other.to_string()),
285        }
286    }
287}
288
289impl Serialize for ResultSubtype {
290    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
291        serializer.serialize_str(self.as_str())
292    }
293}
294
295impl<'de> Deserialize<'de> for ResultSubtype {
296    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
297        let s = String::deserialize(deserializer)?;
298        Ok(Self::from(s.as_str()))
299    }
300}
301
302/// Usage information for the request.
303///
304/// **These counters are accumulated roll-ups, not snapshots.** The CLI sums
305/// usage field-by-field across every API call ("iteration") in the turn's
306/// tool-use loop, so on a turn with N iterations each counter is the sum of
307/// all N. This is the right number for **cost**, and the wrong number for
308/// **context occupancy**: `cache_read_input_tokens` in particular re-counts
309/// the cached context on every iteration and can exceed the model's context
310/// window several times over on tool-heavy turns. To estimate context
311/// occupancy, use the *last* entry of [`iterations`](Self::iterations)
312/// instead (the CLI itself does exactly this).
313///
314/// Note: the `result` frame's usage covers the **main agent only** — the
315/// subagent (`Task` / sidechain) token rollup the CLI renders as
316/// `<subagent_tokens>` / `<agent_count>` is not carried here or anywhere
317/// else on the wire. Accumulate it from `Task` tool results with
318/// [`SubagentUsageRollup`](crate::SubagentUsageRollup).
319#[derive(Debug, Clone, Serialize, Deserialize)]
320pub struct UsageInfo {
321    /// Sum of fresh (uncached) input tokens across all iterations of the turn.
322    #[serde(default)]
323    pub input_tokens: u32,
324    /// Sum of cache-write input tokens across all iterations of the turn.
325    #[serde(default)]
326    pub cache_creation_input_tokens: u32,
327    /// Sum of cache-read input tokens across all iterations of the turn.
328    /// Re-counts the cached context every iteration — **not** a measure of
329    /// context occupancy; see the type-level docs.
330    #[serde(default)]
331    pub cache_read_input_tokens: u32,
332    /// Sum of output tokens across all iterations of the turn.
333    #[serde(default)]
334    pub output_tokens: u32,
335    #[serde(default)]
336    pub server_tool_use: ServerToolUse,
337    #[serde(default)]
338    pub service_tier: String,
339
340    /// Cache creation breakdown
341    #[serde(skip_serializing_if = "Option::is_none")]
342    pub cache_creation: Option<super::message_types::CacheCreationDetails>,
343
344    /// Inference geography (e.g., "not_available")
345    #[serde(skip_serializing_if = "Option::is_none")]
346    pub inference_geo: Option<String>,
347
348    /// Per-iteration usage breakdown **within** this turn — one entry per
349    /// API call in the tool-use loop, in order. The last entry reflects the
350    /// final API call and is what the CLI reads for context-size estimates.
351    #[serde(default, skip_serializing_if = "Vec::is_empty")]
352    pub iterations: Vec<UsageIteration>,
353
354    /// Speed tier (e.g., "standard")
355    #[serde(skip_serializing_if = "Option::is_none")]
356    pub speed: Option<String>,
357}
358
359/// Usage for a single API call ("iteration") within a turn's tool-use loop.
360///
361/// Carried in [`UsageInfo::iterations`]. The cache fields are optional on
362/// the wire: some frames carry only `input_tokens` + `output_tokens`
363/// (observed with `type: "turn"`), while others carry the full cache
364/// breakdown (observed with `type: "message"` in captured subagent
365/// sessions). The CLI computes its context estimate from
366/// `input_tokens + output_tokens` of the **last** iteration.
367#[derive(Debug, Clone, Serialize, Deserialize)]
368pub struct UsageIteration {
369    #[serde(default)]
370    pub input_tokens: u32,
371    #[serde(default)]
372    pub output_tokens: u32,
373    /// Cache-read input tokens for this iteration, when carried.
374    #[serde(default, skip_serializing_if = "Option::is_none")]
375    pub cache_read_input_tokens: Option<u32>,
376    /// Cache-write input tokens for this iteration, when carried.
377    #[serde(default, skip_serializing_if = "Option::is_none")]
378    pub cache_creation_input_tokens: Option<u32>,
379    /// Cache-write breakdown by TTL, when carried.
380    #[serde(default, skip_serializing_if = "Option::is_none")]
381    pub cache_creation: Option<super::message_types::CacheCreationDetails>,
382    /// Iteration kind; `"turn"` and `"message"` observed on the wire.
383    #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
384    pub kind: Option<String>,
385}
386
387/// Server tool usage information
388#[derive(Debug, Clone, Default, Serialize, Deserialize)]
389pub struct ServerToolUse {
390    #[serde(default)]
391    pub web_search_requests: u32,
392    /// Number of web fetch requests made
393    #[serde(default)]
394    pub web_fetch_requests: u32,
395}
396
397#[cfg(test)]
398mod tests {
399    use super::*;
400    use crate::io::ClaudeOutput;
401
402    #[test]
403    fn test_deserialize_result_message() {
404        let json = r#"{
405            "type": "result",
406            "subtype": "success",
407            "is_error": false,
408            "duration_ms": 100,
409            "duration_api_ms": 200,
410            "num_turns": 1,
411            "result": "Done",
412            "session_id": "123",
413            "total_cost_usd": 0.01,
414            "permission_denials": []
415        }"#;
416
417        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
418        assert!(!output.is_error());
419    }
420
421    #[test]
422    fn test_result_subtype_new_and_unknown_values_do_not_fail() {
423        let json = r#"{
424            "type": "result",
425            "subtype": "error_max_budget_usd",
426            "is_error": true,
427            "duration_ms": 100,
428            "duration_api_ms": 200,
429            "num_turns": 1,
430            "session_id": "123",
431            "total_cost_usd": 0.01
432        }"#;
433
434        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
435        let ClaudeOutput::Result(result) = output else {
436            panic!("Expected Result");
437        };
438        assert_eq!(result.subtype, ResultSubtype::ErrorMaxBudgetUsd);
439
440        let json = r#"{
441            "type": "result",
442            "subtype": "future_result_subtype",
443            "is_error": true,
444            "duration_ms": 100,
445            "duration_api_ms": 200,
446            "num_turns": 1,
447            "session_id": "123",
448            "total_cost_usd": 0.01
449        }"#;
450
451        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
452        let ClaudeOutput::Result(result) = output else {
453            panic!("Expected Result");
454        };
455        assert_eq!(
456            result.subtype,
457            ResultSubtype::Unknown("future_result_subtype".to_string())
458        );
459    }
460
461    #[test]
462    fn test_deserialize_result_with_permission_denials() {
463        let json = r#"{
464            "type": "result",
465            "subtype": "success",
466            "is_error": false,
467            "duration_ms": 100,
468            "duration_api_ms": 200,
469            "num_turns": 2,
470            "result": "Done",
471            "session_id": "123",
472            "total_cost_usd": 0.01,
473            "permission_denials": [
474                {
475                    "tool_name": "Bash",
476                    "tool_input": {"command": "rm -rf /", "description": "Delete everything"},
477                    "tool_use_id": "toolu_123"
478                }
479            ]
480        }"#;
481
482        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
483        if let ClaudeOutput::Result(result) = output {
484            assert_eq!(result.permission_denials.len(), 1);
485            assert_eq!(result.permission_denials[0].tool_name, "Bash");
486            assert_eq!(result.permission_denials[0].tool_use_id, "toolu_123");
487            assert_eq!(
488                result.permission_denials[0]
489                    .tool_input
490                    .get("command")
491                    .unwrap(),
492                "rm -rf /"
493            );
494        } else {
495            panic!("Expected Result");
496        }
497    }
498
499    #[test]
500    fn test_permission_denial_roundtrip() {
501        let denial = PermissionDenial {
502            tool_name: "Write".to_string(),
503            tool_input: serde_json::json!({"file_path": "/etc/passwd", "content": "bad"}),
504            tool_use_id: "toolu_456".to_string(),
505        };
506
507        let json = serde_json::to_string(&denial).unwrap();
508        assert!(json.contains("\"tool_name\":\"Write\""));
509        assert!(json.contains("\"tool_use_id\":\"toolu_456\""));
510        assert!(json.contains("/etc/passwd"));
511
512        let parsed: PermissionDenial = serde_json::from_str(&json).unwrap();
513        assert_eq!(parsed, denial);
514    }
515
516    #[test]
517    fn test_deserialize_result_message_with_errors() {
518        let json = r#"{
519            "type": "result",
520            "subtype": "error_during_execution",
521            "duration_ms": 0,
522            "duration_api_ms": 0,
523            "is_error": true,
524            "num_turns": 0,
525            "session_id": "27934753-425a-4182-892c-6b1c15050c3f",
526            "total_cost_usd": 0,
527            "errors": ["No conversation found with session ID: d56965c9-c855-4042-a8f5-f12bbb14d6f6"],
528            "permission_denials": []
529        }"#;
530
531        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
532        assert!(output.is_error());
533
534        if let ClaudeOutput::Result(res) = output {
535            assert!(res.is_error);
536            assert_eq!(res.errors.len(), 1);
537            assert!(res.errors[0].contains("No conversation found"));
538        } else {
539            panic!("Expected Result message");
540        }
541    }
542
543    #[test]
544    fn test_deserialize_result_message_errors_defaults_empty() {
545        let json = r#"{
546            "type": "result",
547            "subtype": "success",
548            "is_error": false,
549            "duration_ms": 100,
550            "duration_api_ms": 200,
551            "num_turns": 1,
552            "session_id": "123",
553            "total_cost_usd": 0.01
554        }"#;
555
556        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
557        if let ClaudeOutput::Result(res) = output {
558            assert!(res.errors.is_empty());
559        } else {
560            panic!("Expected Result message");
561        }
562    }
563
564    #[test]
565    fn test_result_message_errors_roundtrip() {
566        let json = r#"{
567            "type": "result",
568            "subtype": "error_during_execution",
569            "is_error": true,
570            "duration_ms": 0,
571            "duration_api_ms": 0,
572            "num_turns": 0,
573            "session_id": "test-session",
574            "total_cost_usd": 0.0,
575            "errors": ["Error 1", "Error 2"]
576        }"#;
577
578        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
579        let reserialized = serde_json::to_string(&output).unwrap();
580
581        assert!(reserialized.contains("Error 1"));
582        assert!(reserialized.contains("Error 2"));
583    }
584
585    #[test]
586    fn test_result_with_new_fields() {
587        let json = r#"{
588            "type": "result",
589            "subtype": "success",
590            "is_error": false,
591            "duration_ms": 5000,
592            "duration_api_ms": 4500,
593            "num_turns": 1,
594            "result": "Done",
595            "session_id": "abc",
596            "total_cost_usd": 0.06,
597            "api_error_status": null,
598            "stop_reason": "end_turn",
599            "terminal_reason": "completed",
600            "fast_mode_state": "off",
601            "modelUsage": {
602                "claude-opus-4-7[1m]": {
603                    "inputTokens": 3817,
604                    "outputTokens": 14,
605                    "costUSD": 0.06
606                }
607            },
608            "usage": {
609                "input_tokens": 3817,
610                "output_tokens": 14,
611                "cache_creation_input_tokens": 3540,
612                "cache_read_input_tokens": 0,
613                "server_tool_use": {
614                    "web_search_requests": 0,
615                    "web_fetch_requests": 2
616                },
617                "service_tier": "standard",
618                "inference_geo": "not_available",
619                "speed": "standard",
620                "iterations": [
621                    {"input_tokens": 3817, "output_tokens": 14, "type": "turn"}
622                ]
623            }
624        }"#;
625
626        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
627        if let ClaudeOutput::Result(res) = output {
628            assert_eq!(res.stop_reason.as_deref(), Some("end_turn"));
629            assert_eq!(res.terminal_reason.as_deref(), Some("completed"));
630            assert_eq!(res.fast_mode_state.as_deref(), Some("off"));
631            let model_usage = res.model_usage.as_ref().unwrap();
632            let entry = model_usage
633                .get("claude-opus-4-7[1m]")
634                .expect("per-model entry present");
635            assert_eq!(entry.input_tokens, 3817);
636            assert_eq!(entry.output_tokens, 14);
637            assert_eq!(entry.cost_usd, 0.06);
638            assert!(res.api_error_status.is_none());
639
640            let usage = res.usage.unwrap();
641            assert_eq!(usage.server_tool_use.web_fetch_requests, 2);
642            assert_eq!(usage.inference_geo.as_deref(), Some("not_available"));
643            assert_eq!(usage.speed.as_deref(), Some("standard"));
644            assert_eq!(usage.iterations.len(), 1);
645            assert_eq!(usage.iterations[0].input_tokens, 3817);
646            assert_eq!(usage.iterations[0].output_tokens, 14);
647            assert_eq!(usage.iterations[0].kind.as_deref(), Some("turn"));
648        } else {
649            panic!("Expected Result");
650        }
651    }
652
653    #[test]
654    fn test_result_backwards_compatible_without_new_fields() {
655        // Verify old-format messages still parse fine
656        let json = r#"{
657            "type": "result",
658            "subtype": "success",
659            "is_error": false,
660            "duration_ms": 100,
661            "duration_api_ms": 200,
662            "num_turns": 1,
663            "session_id": "abc",
664            "total_cost_usd": 0.01
665        }"#;
666
667        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
668        if let ClaudeOutput::Result(res) = output {
669            assert!(res.api_error_status.is_none());
670            assert!(res.stop_reason.is_none());
671            assert!(res.terminal_reason.is_none());
672            assert!(res.fast_mode_state.is_none());
673            assert!(res.model_usage.is_none());
674        } else {
675            panic!("Expected Result");
676        }
677    }
678
679    #[test]
680    fn test_result_fast_mode_disabled_reason() {
681        let json = r#"{
682            "type":"result","subtype":"success","is_error":false,
683            "duration_ms":100,"duration_api_ms":80,"num_turns":1,
684            "session_id":"s1","total_cost_usd":0.01,
685            "fast_mode_state":"off",
686            "fast_mode_disabled_reason":"sdk_opt_in_required"
687        }"#;
688        let output: crate::ClaudeOutput = serde_json::from_str(json).unwrap();
689        let crate::ClaudeOutput::Result(res) = &output else {
690            panic!("expected Result");
691        };
692        assert_eq!(
693            res.fast_mode_disabled_reason,
694            Some(FastModeDisabledReason::SdkOptInRequired)
695        );
696        assert!(serde_json::to_string(&output)
697            .unwrap()
698            .contains("\"fast_mode_disabled_reason\":\"sdk_opt_in_required\""));
699
700        // Unknown reasons survive decode and round-trip verbatim; the wire
701        // literal "unknown" maps to the typed UnknownReason, not the fallback.
702        assert_eq!(
703            FastModeDisabledReason::from("unknown"),
704            FastModeDisabledReason::UnknownReason
705        );
706        let novel = FastModeDisabledReason::from("solar_flare");
707        assert_eq!(novel, FastModeDisabledReason::Unknown("solar_flare".into()));
708        assert_eq!(novel.as_str(), "solar_flare");
709    }
710
711    #[test]
712    fn test_result_timing_and_user_message_uuid_fields() {
713        let json = r#"{
714            "type":"result","subtype":"success","is_error":false,
715            "duration_ms":100,"duration_api_ms":80,"num_turns":1,
716            "session_id":"s1","total_cost_usd":0.01,
717            "request_sent_wall_ms":1753212345678.25,
718            "user_message_uuid":"um-1"
719        }"#;
720        let output: crate::ClaudeOutput = serde_json::from_str(json).unwrap();
721        let crate::ClaudeOutput::Result(res) = &output else {
722            panic!("expected Result");
723        };
724        assert_eq!(res.request_sent_wall_ms, Some(1753212345678.25));
725        assert_eq!(res.user_message_uuid.as_deref(), Some("um-1"));
726
727        let reserialized = serde_json::to_string(&output).unwrap();
728        assert!(reserialized.contains("\"user_message_uuid\":\"um-1\""));
729    }
730}