claude-codes 2.1.164

Typed Rust SDK for the Claude Code agent CLI: serde models of its JSON-Lines (stream-json) protocol with streaming parsing, plus sync and async (Tokio) clients for driving Claude Code sessions, tools, and subagents.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::Value;
use std::fmt;

/// Result message for completed queries
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResultMessage {
    pub subtype: ResultSubtype,
    pub is_error: bool,
    pub duration_ms: u64,
    pub duration_api_ms: u64,

    /// Time to first token, in milliseconds.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ttft_ms: Option<u64>,

    /// Time to first streamed token, in milliseconds.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ttft_stream_ms: Option<u64>,

    /// Time from session start until the first request was issued, in milliseconds.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time_to_request_ms: Option<u64>,

    /// Time from spawning a worker/spare until the first request was issued, in milliseconds.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time_to_request_from_spawn_ms: Option<u64>,

    /// Whether a warm spare process was claimed for this request.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub warm_spare_claimed: Option<bool>,

    /// Epoch-ish timestamp origin used by CLI timing instrumentation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time_origin_ms: Option<u64>,

    /// Wall-clock epoch milliseconds when the API request was sent
    /// (fractional; from CLI timing instrumentation).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub request_sent_wall_ms: Option<f64>,

    /// Wire uuid of the user message this result answers.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_message_uuid: Option<String>,

    pub num_turns: i32,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<String>,

    #[serde(alias = "sessionId")]
    pub session_id: String,
    pub total_cost_usd: f64,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub usage: Option<UsageInfo>,

    /// Tools that were blocked due to permission denials during the session
    #[serde(default)]
    pub permission_denials: Vec<PermissionDenial>,

    /// Error messages when `is_error` is true.
    ///
    /// Contains human-readable error strings (e.g., "No conversation found with session ID: ...").
    /// This allows typed access to error conditions without needing to serialize to JSON and search.
    #[serde(default)]
    pub errors: Vec<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub uuid: Option<String>,

    /// HTTP status code when the result is an API error (e.g., 429, 500, 529)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub api_error_status: Option<u16>,

    /// Why generation stopped (e.g., end_turn, max_tokens)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_reason: Option<String>,

    /// Why the session ended (e.g., "completed")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub terminal_reason: Option<String>,

    /// Fast mode toggle state (e.g., "off")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fast_mode_state: Option<String>,

    /// Why fast mode can't serve right now. Absent when nothing blocks it.
    /// A paused-after-rate-limit run is not reported here; it rides
    /// `fast_mode_state` as `"cooldown"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fast_mode_disabled_reason: Option<FastModeDisabledReason>,

    /// Per-model cost breakdown, keyed by model name (e.g. `"claude-opus-4-8"`).
    #[serde(skip_serializing_if = "Option::is_none", rename = "modelUsage")]
    pub model_usage: Option<std::collections::BTreeMap<String, ModelUsageEntry>>,

    /// Structured-output payload returned by the model, when enabled.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub structured_output: Option<Value>,

    /// Deferred tool-use termination payload.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deferred_tool_use: Option<DeferredToolUse>,

    /// Provenance of the message/run.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub origin: Option<super::message_types::MessageOrigin>,
}

/// Usage and cost for a single model within a session, as found in
/// [`ResultMessage::model_usage`].
///
/// The `extra` field captures any keys the CLI adds that aren't modeled here,
/// so new wire fields deserialize without error.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelUsageEntry {
    #[serde(default)]
    pub input_tokens: u64,
    #[serde(default)]
    pub output_tokens: u64,
    #[serde(default)]
    pub cache_read_input_tokens: u64,
    #[serde(default)]
    pub cache_creation_input_tokens: u64,
    #[serde(default, rename = "costUSD")]
    pub cost_usd: f64,
    #[serde(default)]
    pub web_search_requests: u32,
    #[serde(default)]
    pub context_window: u64,
    #[serde(default)]
    pub max_output_tokens: u64,
    #[serde(flatten)]
    pub extra: serde_json::Map<String, serde_json::Value>,
}

/// Tool use deferred by a terminal result.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DeferredToolUse {
    pub id: String,
    pub name: String,
    pub input: Value,
}

/// A record of a tool permission that was denied during the session.
///
/// This is included in `ResultMessage.permission_denials` to provide a summary
/// of all permission denials that occurred.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PermissionDenial {
    /// The name of the tool that was blocked (e.g., "Bash", "Write")
    pub tool_name: String,

    /// The input that was passed to the tool
    pub tool_input: Value,

    /// The unique identifier for this tool use request
    pub tool_use_id: String,
}

/// Why fast mode can't serve right now, carried on `result` frames and
/// `system/init` (CLI 2.1.219+). Absent when nothing blocks fast mode.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum FastModeDisabledReason {
    /// Free-tier account.
    Free,
    /// Disabled by user preference.
    Preference,
    /// Extra-usage purchases are disabled for the account.
    ExtraUsageDisabled,
    /// A network error prevented fast-mode eligibility from resolving.
    NetworkError,
    /// The CLI could not determine the reason.
    UnknownReason,
    /// Not a first-party API session (e.g. Bedrock/Vertex).
    NotFirstParty,
    /// Disabled via environment variable.
    DisabledByEnv,
    /// The active model does not support fast mode.
    ModelNotAllowed,
    /// SDK sessions must opt in to fast mode.
    SdkOptInRequired,
    /// Eligibility is still being determined.
    Pending,
    /// A reason not yet known to this version of the crate.
    Unknown(String),
}

impl FastModeDisabledReason {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Free => "free",
            Self::Preference => "preference",
            Self::ExtraUsageDisabled => "extra_usage_disabled",
            Self::NetworkError => "network_error",
            Self::UnknownReason => "unknown",
            Self::NotFirstParty => "not_first_party",
            Self::DisabledByEnv => "disabled_by_env",
            Self::ModelNotAllowed => "model_not_allowed",
            Self::SdkOptInRequired => "sdk_opt_in_required",
            Self::Pending => "pending",
            Self::Unknown(s) => s.as_str(),
        }
    }
}

impl fmt::Display for FastModeDisabledReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl From<&str> for FastModeDisabledReason {
    fn from(s: &str) -> Self {
        match s {
            "free" => Self::Free,
            "preference" => Self::Preference,
            "extra_usage_disabled" => Self::ExtraUsageDisabled,
            "network_error" => Self::NetworkError,
            "unknown" => Self::UnknownReason,
            "not_first_party" => Self::NotFirstParty,
            "disabled_by_env" => Self::DisabledByEnv,
            "model_not_allowed" => Self::ModelNotAllowed,
            "sdk_opt_in_required" => Self::SdkOptInRequired,
            "pending" => Self::Pending,
            other => Self::Unknown(other.to_string()),
        }
    }
}

impl Serialize for FastModeDisabledReason {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for FastModeDisabledReason {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        Ok(Self::from(s.as_str()))
    }
}

/// Result subtypes
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ResultSubtype {
    Success,
    ErrorMaxTurns,
    ErrorDuringExecution,
    ErrorMaxBudgetUsd,
    ErrorMaxStructuredOutputRetries,
    Unknown(String),
}

impl ResultSubtype {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Success => "success",
            Self::ErrorMaxTurns => "error_max_turns",
            Self::ErrorDuringExecution => "error_during_execution",
            Self::ErrorMaxBudgetUsd => "error_max_budget_usd",
            Self::ErrorMaxStructuredOutputRetries => "error_max_structured_output_retries",
            Self::Unknown(s) => s.as_str(),
        }
    }
}

impl fmt::Display for ResultSubtype {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl From<&str> for ResultSubtype {
    fn from(s: &str) -> Self {
        match s {
            "success" => Self::Success,
            "error_max_turns" => Self::ErrorMaxTurns,
            "error_during_execution" => Self::ErrorDuringExecution,
            "error_max_budget_usd" => Self::ErrorMaxBudgetUsd,
            "error_max_structured_output_retries" => Self::ErrorMaxStructuredOutputRetries,
            other => Self::Unknown(other.to_string()),
        }
    }
}

impl Serialize for ResultSubtype {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for ResultSubtype {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        Ok(Self::from(s.as_str()))
    }
}

/// Usage information for the request
///
/// Note: the `result` frame's usage covers the **main agent only** — the
/// subagent (`Task` / sidechain) token rollup the CLI renders as
/// `<subagent_tokens>` / `<agent_count>` is not carried here or anywhere
/// else on the wire. Accumulate it from `Task` tool results with
/// [`SubagentUsageRollup`](crate::SubagentUsageRollup).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UsageInfo {
    #[serde(default)]
    pub input_tokens: u32,
    #[serde(default)]
    pub cache_creation_input_tokens: u32,
    #[serde(default)]
    pub cache_read_input_tokens: u32,
    #[serde(default)]
    pub output_tokens: u32,
    #[serde(default)]
    pub server_tool_use: ServerToolUse,
    #[serde(default)]
    pub service_tier: String,

    /// Cache creation breakdown
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cache_creation: Option<super::message_types::CacheCreationDetails>,

    /// Inference geography (e.g., "not_available")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inference_geo: Option<String>,

    /// Per-turn usage breakdown
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub iterations: Vec<Value>,

    /// Speed tier (e.g., "standard")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub speed: Option<String>,
}

/// Server tool usage information
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ServerToolUse {
    #[serde(default)]
    pub web_search_requests: u32,
    /// Number of web fetch requests made
    #[serde(default)]
    pub web_fetch_requests: u32,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::io::ClaudeOutput;

    #[test]
    fn test_deserialize_result_message() {
        let json = r#"{
            "type": "result",
            "subtype": "success",
            "is_error": false,
            "duration_ms": 100,
            "duration_api_ms": 200,
            "num_turns": 1,
            "result": "Done",
            "session_id": "123",
            "total_cost_usd": 0.01,
            "permission_denials": []
        }"#;

        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
        assert!(!output.is_error());
    }

    #[test]
    fn test_result_subtype_new_and_unknown_values_do_not_fail() {
        let json = r#"{
            "type": "result",
            "subtype": "error_max_budget_usd",
            "is_error": true,
            "duration_ms": 100,
            "duration_api_ms": 200,
            "num_turns": 1,
            "session_id": "123",
            "total_cost_usd": 0.01
        }"#;

        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
        let ClaudeOutput::Result(result) = output else {
            panic!("Expected Result");
        };
        assert_eq!(result.subtype, ResultSubtype::ErrorMaxBudgetUsd);

        let json = r#"{
            "type": "result",
            "subtype": "future_result_subtype",
            "is_error": true,
            "duration_ms": 100,
            "duration_api_ms": 200,
            "num_turns": 1,
            "session_id": "123",
            "total_cost_usd": 0.01
        }"#;

        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
        let ClaudeOutput::Result(result) = output else {
            panic!("Expected Result");
        };
        assert_eq!(
            result.subtype,
            ResultSubtype::Unknown("future_result_subtype".to_string())
        );
    }

    #[test]
    fn test_deserialize_result_with_permission_denials() {
        let json = r#"{
            "type": "result",
            "subtype": "success",
            "is_error": false,
            "duration_ms": 100,
            "duration_api_ms": 200,
            "num_turns": 2,
            "result": "Done",
            "session_id": "123",
            "total_cost_usd": 0.01,
            "permission_denials": [
                {
                    "tool_name": "Bash",
                    "tool_input": {"command": "rm -rf /", "description": "Delete everything"},
                    "tool_use_id": "toolu_123"
                }
            ]
        }"#;

        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
        if let ClaudeOutput::Result(result) = output {
            assert_eq!(result.permission_denials.len(), 1);
            assert_eq!(result.permission_denials[0].tool_name, "Bash");
            assert_eq!(result.permission_denials[0].tool_use_id, "toolu_123");
            assert_eq!(
                result.permission_denials[0]
                    .tool_input
                    .get("command")
                    .unwrap(),
                "rm -rf /"
            );
        } else {
            panic!("Expected Result");
        }
    }

    #[test]
    fn test_permission_denial_roundtrip() {
        let denial = PermissionDenial {
            tool_name: "Write".to_string(),
            tool_input: serde_json::json!({"file_path": "/etc/passwd", "content": "bad"}),
            tool_use_id: "toolu_456".to_string(),
        };

        let json = serde_json::to_string(&denial).unwrap();
        assert!(json.contains("\"tool_name\":\"Write\""));
        assert!(json.contains("\"tool_use_id\":\"toolu_456\""));
        assert!(json.contains("/etc/passwd"));

        let parsed: PermissionDenial = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, denial);
    }

    #[test]
    fn test_deserialize_result_message_with_errors() {
        let json = r#"{
            "type": "result",
            "subtype": "error_during_execution",
            "duration_ms": 0,
            "duration_api_ms": 0,
            "is_error": true,
            "num_turns": 0,
            "session_id": "27934753-425a-4182-892c-6b1c15050c3f",
            "total_cost_usd": 0,
            "errors": ["No conversation found with session ID: d56965c9-c855-4042-a8f5-f12bbb14d6f6"],
            "permission_denials": []
        }"#;

        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
        assert!(output.is_error());

        if let ClaudeOutput::Result(res) = output {
            assert!(res.is_error);
            assert_eq!(res.errors.len(), 1);
            assert!(res.errors[0].contains("No conversation found"));
        } else {
            panic!("Expected Result message");
        }
    }

    #[test]
    fn test_deserialize_result_message_errors_defaults_empty() {
        let json = r#"{
            "type": "result",
            "subtype": "success",
            "is_error": false,
            "duration_ms": 100,
            "duration_api_ms": 200,
            "num_turns": 1,
            "session_id": "123",
            "total_cost_usd": 0.01
        }"#;

        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
        if let ClaudeOutput::Result(res) = output {
            assert!(res.errors.is_empty());
        } else {
            panic!("Expected Result message");
        }
    }

    #[test]
    fn test_result_message_errors_roundtrip() {
        let json = r#"{
            "type": "result",
            "subtype": "error_during_execution",
            "is_error": true,
            "duration_ms": 0,
            "duration_api_ms": 0,
            "num_turns": 0,
            "session_id": "test-session",
            "total_cost_usd": 0.0,
            "errors": ["Error 1", "Error 2"]
        }"#;

        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
        let reserialized = serde_json::to_string(&output).unwrap();

        assert!(reserialized.contains("Error 1"));
        assert!(reserialized.contains("Error 2"));
    }

    #[test]
    fn test_result_with_new_fields() {
        let json = r#"{
            "type": "result",
            "subtype": "success",
            "is_error": false,
            "duration_ms": 5000,
            "duration_api_ms": 4500,
            "num_turns": 1,
            "result": "Done",
            "session_id": "abc",
            "total_cost_usd": 0.06,
            "api_error_status": null,
            "stop_reason": "end_turn",
            "terminal_reason": "completed",
            "fast_mode_state": "off",
            "modelUsage": {
                "claude-opus-4-7[1m]": {
                    "inputTokens": 3817,
                    "outputTokens": 14,
                    "costUSD": 0.06
                }
            },
            "usage": {
                "input_tokens": 3817,
                "output_tokens": 14,
                "cache_creation_input_tokens": 3540,
                "cache_read_input_tokens": 0,
                "server_tool_use": {
                    "web_search_requests": 0,
                    "web_fetch_requests": 2
                },
                "service_tier": "standard",
                "inference_geo": "not_available",
                "speed": "standard",
                "iterations": [
                    {"input_tokens": 3817, "output_tokens": 14, "type": "turn"}
                ]
            }
        }"#;

        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
        if let ClaudeOutput::Result(res) = output {
            assert_eq!(res.stop_reason.as_deref(), Some("end_turn"));
            assert_eq!(res.terminal_reason.as_deref(), Some("completed"));
            assert_eq!(res.fast_mode_state.as_deref(), Some("off"));
            let model_usage = res.model_usage.as_ref().unwrap();
            let entry = model_usage
                .get("claude-opus-4-7[1m]")
                .expect("per-model entry present");
            assert_eq!(entry.input_tokens, 3817);
            assert_eq!(entry.output_tokens, 14);
            assert_eq!(entry.cost_usd, 0.06);
            assert!(res.api_error_status.is_none());

            let usage = res.usage.unwrap();
            assert_eq!(usage.server_tool_use.web_fetch_requests, 2);
            assert_eq!(usage.inference_geo.as_deref(), Some("not_available"));
            assert_eq!(usage.speed.as_deref(), Some("standard"));
            assert_eq!(usage.iterations.len(), 1);
        } else {
            panic!("Expected Result");
        }
    }

    #[test]
    fn test_result_backwards_compatible_without_new_fields() {
        // Verify old-format messages still parse fine
        let json = r#"{
            "type": "result",
            "subtype": "success",
            "is_error": false,
            "duration_ms": 100,
            "duration_api_ms": 200,
            "num_turns": 1,
            "session_id": "abc",
            "total_cost_usd": 0.01
        }"#;

        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
        if let ClaudeOutput::Result(res) = output {
            assert!(res.api_error_status.is_none());
            assert!(res.stop_reason.is_none());
            assert!(res.terminal_reason.is_none());
            assert!(res.fast_mode_state.is_none());
            assert!(res.model_usage.is_none());
        } else {
            panic!("Expected Result");
        }
    }

    #[test]
    fn test_result_fast_mode_disabled_reason() {
        let json = r#"{
            "type":"result","subtype":"success","is_error":false,
            "duration_ms":100,"duration_api_ms":80,"num_turns":1,
            "session_id":"s1","total_cost_usd":0.01,
            "fast_mode_state":"off",
            "fast_mode_disabled_reason":"sdk_opt_in_required"
        }"#;
        let output: crate::ClaudeOutput = serde_json::from_str(json).unwrap();
        let crate::ClaudeOutput::Result(res) = &output else {
            panic!("expected Result");
        };
        assert_eq!(
            res.fast_mode_disabled_reason,
            Some(FastModeDisabledReason::SdkOptInRequired)
        );
        assert!(serde_json::to_string(&output)
            .unwrap()
            .contains("\"fast_mode_disabled_reason\":\"sdk_opt_in_required\""));

        // Unknown reasons survive decode and round-trip verbatim; the wire
        // literal "unknown" maps to the typed UnknownReason, not the fallback.
        assert_eq!(
            FastModeDisabledReason::from("unknown"),
            FastModeDisabledReason::UnknownReason
        );
        let novel = FastModeDisabledReason::from("solar_flare");
        assert_eq!(novel, FastModeDisabledReason::Unknown("solar_flare".into()));
        assert_eq!(novel.as_str(), "solar_flare");
    }

    #[test]
    fn test_result_timing_and_user_message_uuid_fields() {
        let json = r#"{
            "type":"result","subtype":"success","is_error":false,
            "duration_ms":100,"duration_api_ms":80,"num_turns":1,
            "session_id":"s1","total_cost_usd":0.01,
            "request_sent_wall_ms":1753212345678.25,
            "user_message_uuid":"um-1"
        }"#;
        let output: crate::ClaudeOutput = serde_json::from_str(json).unwrap();
        let crate::ClaudeOutput::Result(res) = &output else {
            panic!("expected Result");
        };
        assert_eq!(res.request_sent_wall_ms, Some(1753212345678.25));
        assert_eq!(res.user_message_uuid.as_deref(), Some("um-1"));

        let reserialized = serde_json::to_string(&output).unwrap();
        assert!(reserialized.contains("\"user_message_uuid\":\"um-1\""));
    }
}