Skip to main content

claude_codes/io/
message_types.rs

1use serde::{Deserialize, Deserializer, Serialize, Serializer};
2use serde_json::Value;
3use std::fmt;
4use uuid::Uuid;
5
6use super::claude_output::ClaudeOutput;
7use super::content_blocks::{deserialize_content_blocks, ContentBlock};
8
9/// Known system message subtypes.
10///
11/// The Claude CLI emits system messages with a `subtype` field indicating what
12/// kind of system event occurred. This enum captures the known subtypes while
13/// preserving unknown values via the `Unknown` variant for forward compatibility.
14#[derive(Debug, Clone, PartialEq, Eq, Hash)]
15pub enum SystemSubtype {
16    Init,
17    Status,
18    CompactBoundary,
19    ThinkingTokens,
20    TaskStarted,
21    TaskProgress,
22    TaskUpdated,
23    TaskNotification,
24    ApiRetry,
25    ControlRequestProgress,
26    ModelRefusalFallback,
27    ModelRefusalNoFallback,
28    LocalCommandOutput,
29    HookStarted,
30    HookProgress,
31    HookResponse,
32    PluginInstall,
33    BackgroundTasksChanged,
34    SessionStateChanged,
35    WorkerShuttingDown,
36    CommandsChanged,
37    Notification,
38    FilesPersisted,
39    MemoryRecall,
40    ElicitationComplete,
41    PermissionDenied,
42    MirrorError,
43    Informational,
44    CodeChangePublished,
45    VcsStateChanged,
46    /// A subtype not yet known to this version of the crate.
47    Unknown(String),
48}
49
50impl SystemSubtype {
51    pub fn as_str(&self) -> &str {
52        match self {
53            Self::Init => "init",
54            Self::Status => "status",
55            Self::CompactBoundary => "compact_boundary",
56            Self::ThinkingTokens => "thinking_tokens",
57            Self::TaskStarted => "task_started",
58            Self::TaskProgress => "task_progress",
59            Self::TaskUpdated => "task_updated",
60            Self::TaskNotification => "task_notification",
61            Self::ApiRetry => "api_retry",
62            Self::ControlRequestProgress => "control_request_progress",
63            Self::ModelRefusalFallback => "model_refusal_fallback",
64            Self::ModelRefusalNoFallback => "model_refusal_no_fallback",
65            Self::LocalCommandOutput => "local_command_output",
66            Self::HookStarted => "hook_started",
67            Self::HookProgress => "hook_progress",
68            Self::HookResponse => "hook_response",
69            Self::PluginInstall => "plugin_install",
70            Self::BackgroundTasksChanged => "background_tasks_changed",
71            Self::SessionStateChanged => "session_state_changed",
72            Self::WorkerShuttingDown => "worker_shutting_down",
73            Self::CommandsChanged => "commands_changed",
74            Self::Notification => "notification",
75            Self::FilesPersisted => "files_persisted",
76            Self::MemoryRecall => "memory_recall",
77            Self::ElicitationComplete => "elicitation_complete",
78            Self::PermissionDenied => "permission_denied",
79            Self::MirrorError => "mirror_error",
80            Self::Informational => "informational",
81            Self::CodeChangePublished => "code_change_published",
82            Self::VcsStateChanged => "vcs_state_changed",
83            Self::Unknown(s) => s.as_str(),
84        }
85    }
86}
87
88impl fmt::Display for SystemSubtype {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        f.write_str(self.as_str())
91    }
92}
93
94impl From<&str> for SystemSubtype {
95    fn from(s: &str) -> Self {
96        match s {
97            "init" => Self::Init,
98            "status" => Self::Status,
99            "compact_boundary" => Self::CompactBoundary,
100            "thinking_tokens" => Self::ThinkingTokens,
101            "task_started" => Self::TaskStarted,
102            "task_progress" => Self::TaskProgress,
103            "task_updated" => Self::TaskUpdated,
104            "task_notification" => Self::TaskNotification,
105            "api_retry" => Self::ApiRetry,
106            "control_request_progress" => Self::ControlRequestProgress,
107            "model_refusal_fallback" => Self::ModelRefusalFallback,
108            "model_refusal_no_fallback" => Self::ModelRefusalNoFallback,
109            "local_command_output" => Self::LocalCommandOutput,
110            "hook_started" => Self::HookStarted,
111            "hook_progress" => Self::HookProgress,
112            "hook_response" => Self::HookResponse,
113            "plugin_install" => Self::PluginInstall,
114            "background_tasks_changed" => Self::BackgroundTasksChanged,
115            "session_state_changed" => Self::SessionStateChanged,
116            "worker_shutting_down" => Self::WorkerShuttingDown,
117            "commands_changed" => Self::CommandsChanged,
118            "notification" => Self::Notification,
119            "files_persisted" => Self::FilesPersisted,
120            "memory_recall" => Self::MemoryRecall,
121            "elicitation_complete" => Self::ElicitationComplete,
122            "permission_denied" => Self::PermissionDenied,
123            "mirror_error" => Self::MirrorError,
124            "informational" => Self::Informational,
125            "code_change_published" => Self::CodeChangePublished,
126            "vcs_state_changed" => Self::VcsStateChanged,
127            other => Self::Unknown(other.to_string()),
128        }
129    }
130}
131
132impl Serialize for SystemSubtype {
133    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
134        serializer.serialize_str(self.as_str())
135    }
136}
137
138impl<'de> Deserialize<'de> for SystemSubtype {
139    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
140        let s = String::deserialize(deserializer)?;
141        Ok(Self::from(s.as_str()))
142    }
143}
144
145/// Known message roles.
146///
147/// Used in `MessageContent` and `AssistantMessageContent` to indicate the
148/// speaker of a message.
149#[derive(Debug, Clone, PartialEq, Eq, Hash)]
150pub enum MessageRole {
151    User,
152    Assistant,
153    /// A role not yet known to this version of the crate.
154    Unknown(String),
155}
156
157impl MessageRole {
158    pub fn as_str(&self) -> &str {
159        match self {
160            Self::User => "user",
161            Self::Assistant => "assistant",
162            Self::Unknown(s) => s.as_str(),
163        }
164    }
165}
166
167impl fmt::Display for MessageRole {
168    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169        f.write_str(self.as_str())
170    }
171}
172
173impl From<&str> for MessageRole {
174    fn from(s: &str) -> Self {
175        match s {
176            "user" => Self::User,
177            "assistant" => Self::Assistant,
178            other => Self::Unknown(other.to_string()),
179        }
180    }
181}
182
183impl Serialize for MessageRole {
184    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
185        serializer.serialize_str(self.as_str())
186    }
187}
188
189impl<'de> Deserialize<'de> for MessageRole {
190    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
191        let s = String::deserialize(deserializer)?;
192        Ok(Self::from(s.as_str()))
193    }
194}
195
196/// What triggered a context compaction.
197#[derive(Debug, Clone, PartialEq, Eq, Hash)]
198pub enum CompactionTrigger {
199    /// Automatic compaction triggered by token limit.
200    Auto,
201    /// User-initiated compaction (e.g., /compact command).
202    Manual,
203    /// A trigger not yet known to this version of the crate.
204    Unknown(String),
205}
206
207impl CompactionTrigger {
208    pub fn as_str(&self) -> &str {
209        match self {
210            Self::Auto => "auto",
211            Self::Manual => "manual",
212            Self::Unknown(s) => s.as_str(),
213        }
214    }
215}
216
217impl fmt::Display for CompactionTrigger {
218    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219        f.write_str(self.as_str())
220    }
221}
222
223impl From<&str> for CompactionTrigger {
224    fn from(s: &str) -> Self {
225        match s {
226            "auto" => Self::Auto,
227            "manual" => Self::Manual,
228            other => Self::Unknown(other.to_string()),
229        }
230    }
231}
232
233impl Serialize for CompactionTrigger {
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 CompactionTrigger {
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/// Reason why the assistant stopped generating.
247#[derive(Debug, Clone, PartialEq, Eq, Hash)]
248pub enum StopReason {
249    /// The assistant reached a natural end of its turn.
250    EndTurn,
251    /// The response hit the maximum token limit.
252    MaxTokens,
253    /// The assistant wants to use a tool.
254    ToolUse,
255    /// A stop reason not yet known to this version of the crate.
256    Unknown(String),
257}
258
259impl StopReason {
260    pub fn as_str(&self) -> &str {
261        match self {
262            Self::EndTurn => "end_turn",
263            Self::MaxTokens => "max_tokens",
264            Self::ToolUse => "tool_use",
265            Self::Unknown(s) => s.as_str(),
266        }
267    }
268}
269
270impl fmt::Display for StopReason {
271    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
272        f.write_str(self.as_str())
273    }
274}
275
276impl From<&str> for StopReason {
277    fn from(s: &str) -> Self {
278        match s {
279            "end_turn" => Self::EndTurn,
280            "max_tokens" => Self::MaxTokens,
281            "tool_use" => Self::ToolUse,
282            other => Self::Unknown(other.to_string()),
283        }
284    }
285}
286
287impl Serialize for StopReason {
288    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
289        serializer.serialize_str(self.as_str())
290    }
291}
292
293impl<'de> Deserialize<'de> for StopReason {
294    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
295        let s = String::deserialize(deserializer)?;
296        Ok(Self::from(s.as_str()))
297    }
298}
299
300/// How the API key was sourced for the session.
301#[derive(Debug, Clone, PartialEq, Eq, Hash)]
302pub enum ApiKeySource {
303    /// No API key provided.
304    None,
305    User,
306    Project,
307    Org,
308    Temporary,
309    Oauth,
310    /// A source not yet known to this version of the crate.
311    Unknown(String),
312}
313
314impl ApiKeySource {
315    pub fn as_str(&self) -> &str {
316        match self {
317            Self::None => "none",
318            Self::User => "user",
319            Self::Project => "project",
320            Self::Org => "org",
321            Self::Temporary => "temporary",
322            Self::Oauth => "oauth",
323            Self::Unknown(s) => s.as_str(),
324        }
325    }
326}
327
328impl fmt::Display for ApiKeySource {
329    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
330        f.write_str(self.as_str())
331    }
332}
333
334impl From<&str> for ApiKeySource {
335    fn from(s: &str) -> Self {
336        match s {
337            "none" => Self::None,
338            "user" => Self::User,
339            "project" => Self::Project,
340            "org" => Self::Org,
341            "temporary" => Self::Temporary,
342            "oauth" => Self::Oauth,
343            other => Self::Unknown(other.to_string()),
344        }
345    }
346}
347
348impl Serialize for ApiKeySource {
349    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
350        serializer.serialize_str(self.as_str())
351    }
352}
353
354impl<'de> Deserialize<'de> for ApiKeySource {
355    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
356        let s = String::deserialize(deserializer)?;
357        Ok(Self::from(s.as_str()))
358    }
359}
360
361/// Output formatting style for the session.
362#[derive(Debug, Clone, PartialEq, Eq, Hash)]
363pub enum OutputStyle {
364    /// Default output style.
365    Default,
366    /// A style not yet known to this version of the crate.
367    Unknown(String),
368}
369
370impl OutputStyle {
371    pub fn as_str(&self) -> &str {
372        match self {
373            Self::Default => "default",
374            Self::Unknown(s) => s.as_str(),
375        }
376    }
377}
378
379impl fmt::Display for OutputStyle {
380    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
381        f.write_str(self.as_str())
382    }
383}
384
385impl From<&str> for OutputStyle {
386    fn from(s: &str) -> Self {
387        match s {
388            "default" => Self::Default,
389            other => Self::Unknown(other.to_string()),
390        }
391    }
392}
393
394impl Serialize for OutputStyle {
395    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
396        serializer.serialize_str(self.as_str())
397    }
398}
399
400impl<'de> Deserialize<'de> for OutputStyle {
401    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
402        let s = String::deserialize(deserializer)?;
403        Ok(Self::from(s.as_str()))
404    }
405}
406
407/// Permission mode reported in init messages.
408#[derive(Debug, Clone, PartialEq, Eq, Hash)]
409pub enum InitPermissionMode {
410    /// Default permission mode.
411    Default,
412    AcceptEdits,
413    BypassPermissions,
414    Plan,
415    DontAsk,
416    Auto,
417    /// A mode not yet known to this version of the crate.
418    Unknown(String),
419}
420
421impl InitPermissionMode {
422    pub fn as_str(&self) -> &str {
423        match self {
424            Self::Default => "default",
425            Self::AcceptEdits => "acceptEdits",
426            Self::BypassPermissions => "bypassPermissions",
427            Self::Plan => "plan",
428            Self::DontAsk => "dontAsk",
429            Self::Auto => "auto",
430            Self::Unknown(s) => s.as_str(),
431        }
432    }
433}
434
435impl fmt::Display for InitPermissionMode {
436    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
437        f.write_str(self.as_str())
438    }
439}
440
441impl From<&str> for InitPermissionMode {
442    fn from(s: &str) -> Self {
443        match s {
444            "default" => Self::Default,
445            "acceptEdits" => Self::AcceptEdits,
446            "bypassPermissions" => Self::BypassPermissions,
447            "plan" => Self::Plan,
448            "dontAsk" => Self::DontAsk,
449            "auto" => Self::Auto,
450            other => Self::Unknown(other.to_string()),
451        }
452    }
453}
454
455impl Serialize for InitPermissionMode {
456    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
457        serializer.serialize_str(self.as_str())
458    }
459}
460
461impl<'de> Deserialize<'de> for InitPermissionMode {
462    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
463        let s = String::deserialize(deserializer)?;
464        Ok(Self::from(s.as_str()))
465    }
466}
467
468/// Status of an ongoing operation (e.g., context compaction).
469#[derive(Debug, Clone, PartialEq, Eq, Hash)]
470pub enum StatusMessageStatus {
471    /// Context compaction is in progress.
472    Compacting,
473    /// The CLI is issuing a request.
474    Requesting,
475    /// A status not yet known to this version of the crate.
476    Unknown(String),
477}
478
479impl StatusMessageStatus {
480    pub fn as_str(&self) -> &str {
481        match self {
482            Self::Compacting => "compacting",
483            Self::Requesting => "requesting",
484            Self::Unknown(s) => s.as_str(),
485        }
486    }
487}
488
489impl fmt::Display for StatusMessageStatus {
490    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
491        f.write_str(self.as_str())
492    }
493}
494
495impl From<&str> for StatusMessageStatus {
496    fn from(s: &str) -> Self {
497        match s {
498            "compacting" => Self::Compacting,
499            "requesting" => Self::Requesting,
500            other => Self::Unknown(other.to_string()),
501        }
502    }
503}
504
505impl Serialize for StatusMessageStatus {
506    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
507        serializer.serialize_str(self.as_str())
508    }
509}
510
511impl<'de> Deserialize<'de> for StatusMessageStatus {
512    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
513        let s = String::deserialize(deserializer)?;
514        Ok(Self::from(s.as_str()))
515    }
516}
517
518/// Serialize an optional UUID as a string
519pub(crate) fn serialize_optional_uuid<S>(
520    uuid: &Option<Uuid>,
521    serializer: S,
522) -> Result<S::Ok, S::Error>
523where
524    S: Serializer,
525{
526    match uuid {
527        Some(id) => serializer.serialize_str(&id.to_string()),
528        None => serializer.serialize_none(),
529    }
530}
531
532/// Deserialize an optional UUID from a string
533pub(crate) fn deserialize_optional_uuid<'de, D>(deserializer: D) -> Result<Option<Uuid>, D::Error>
534where
535    D: Deserializer<'de>,
536{
537    let opt_str: Option<String> = Option::deserialize(deserializer)?;
538    match opt_str {
539        Some(s) => Uuid::parse_str(&s)
540            .map(Some)
541            .map_err(serde::de::Error::custom),
542        None => Ok(None),
543    }
544}
545
546/// Message provenance. The `kind` field is the stable discriminator; variant
547/// specific fields are preserved in `extra` for forward-compatible access.
548#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
549pub struct MessageOrigin {
550    pub kind: String,
551    #[serde(flatten)]
552    pub extra: serde_json::Map<String, Value>,
553}
554
555/// Metadata attached when user-visible transcript content summarizes prior messages.
556#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
557pub struct SummarizeMetadata {
558    pub messages_summarized: u64,
559    #[serde(default, skip_serializing_if = "Option::is_none")]
560    pub user_context: Option<String>,
561    #[serde(default, skip_serializing_if = "Option::is_none")]
562    pub direction: Option<String>,
563}
564
565/// MCP metadata passed through on user-message wrappers.
566#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
567pub struct McpMeta {
568    #[serde(default, skip_serializing_if = "Option::is_none", rename = "_meta")]
569    pub meta: Option<Value>,
570    #[serde(default, skip_serializing_if = "Option::is_none")]
571    pub structured_content: Option<Value>,
572}
573
574/// Display metadata for a `tool_result` block carried on the user wrapper.
575#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
576pub struct ToolResultMeta {
577    /// The `tool_use_id` of the matching `tool_result` block.
578    pub id: String,
579    /// Harness-stamped reason an `is_error: true` result did not carry the
580    /// tool's own execution output (`user-rejected`, `permission-rule`,
581    /// `automode-*`, `interrupted`, `cancelled`). Open set — treat
582    /// unrecognized values as valid reasons; absent means the tool ran to
583    /// completion.
584    pub non_execution_kind: String,
585    /// The deny comment a human typed at a permission prompt, when present.
586    #[serde(default, skip_serializing_if = "Option::is_none")]
587    pub user_feedback: Option<String>,
588}
589
590/// User message
591#[derive(Debug, Clone, Serialize, Deserialize)]
592pub struct UserMessage {
593    pub message: MessageContent,
594    #[serde(skip_serializing_if = "Option::is_none", alias = "sessionId")]
595    #[serde(
596        serialize_with = "serialize_optional_uuid",
597        deserialize_with = "deserialize_optional_uuid"
598    )]
599    pub session_id: Option<Uuid>,
600    /// Parent tool use ID for nested agent messages
601    #[serde(skip_serializing_if = "Option::is_none")]
602    pub parent_tool_use_id: Option<String>,
603    /// Message-level unique identifier
604    #[serde(skip_serializing_if = "Option::is_none")]
605    pub uuid: Option<String>,
606    /// CLI-emitted ISO-8601 timestamp for the message (present on echoed tool results).
607    #[serde(skip_serializing_if = "Option::is_none")]
608    pub timestamp: Option<String>,
609    /// Structured tool result data echoed by the CLI alongside the `tool_result`
610    /// content block. The shape depends on which tool produced it (e.g. for
611    /// `AskUserQuestion` it is `{ questions, answers }`; for `Bash` it is
612    /// `{ stdout, stderr, exit_code, ... }`). Stored as raw JSON to preserve
613    /// wire fidelity; use [`UserMessage::tool_use_result_as`] to parse into a
614    /// typed shape when you know which tool was invoked.
615    #[serde(skip_serializing_if = "Option::is_none")]
616    pub tool_use_result: Option<serde_json::Value>,
617    /// Subagent type, when this user message is the prompt echoed into a
618    /// `local_agent` subagent (e.g. `general-purpose`).
619    #[serde(skip_serializing_if = "Option::is_none")]
620    pub subagent_type: Option<String>,
621    /// Short description of the subagent task, present alongside `subagent_type`.
622    #[serde(skip_serializing_if = "Option::is_none")]
623    pub task_description: Option<String>,
624    #[serde(skip_serializing_if = "Option::is_none")]
625    pub origin: Option<MessageOrigin>,
626    #[serde(skip_serializing_if = "Option::is_none")]
627    pub priority: Option<String>,
628    #[serde(skip_serializing_if = "Option::is_none", rename = "isSynthetic")]
629    pub is_synthetic: Option<bool>,
630    #[serde(skip_serializing_if = "Option::is_none", rename = "shouldQuery")]
631    pub should_query: Option<bool>,
632    #[serde(default, skip_serializing_if = "Option::is_none")]
633    pub is_meta: Option<bool>,
634    #[serde(default, skip_serializing_if = "Option::is_none")]
635    pub is_visible_in_transcript_only: Option<bool>,
636    #[serde(default, skip_serializing_if = "Option::is_none")]
637    pub is_virtual: Option<bool>,
638    #[serde(default, skip_serializing_if = "Option::is_none")]
639    pub is_compact_summary: Option<bool>,
640    #[serde(skip_serializing_if = "Option::is_none")]
641    pub summarize_metadata: Option<SummarizeMetadata>,
642    #[serde(skip_serializing_if = "Option::is_none")]
643    pub mcp_meta: Option<McpMeta>,
644    /// Display metadata for this message's `tool_result` blocks, keyed by
645    /// `tool_use_id`.
646    #[serde(skip_serializing_if = "Option::is_none")]
647    pub tool_result_meta: Option<Vec<ToolResultMeta>>,
648    #[serde(skip_serializing_if = "Option::is_none")]
649    pub source_tool_use_id: Option<String>,
650    #[serde(skip_serializing_if = "Option::is_none")]
651    pub source_tool_assistant_uuid: Option<String>,
652    #[serde(skip_serializing_if = "Option::is_none")]
653    pub image_paste_ids: Option<Vec<u64>>,
654    #[serde(skip_serializing_if = "Option::is_none")]
655    pub client_platform: Option<String>,
656    #[serde(skip_serializing_if = "Option::is_none")]
657    pub inbound_origin: Option<String>,
658    #[serde(skip_serializing_if = "Option::is_none", rename = "isReplay")]
659    pub is_replay: Option<bool>,
660    #[serde(skip_serializing_if = "Option::is_none")]
661    pub file_attachments: Option<Vec<Value>>,
662}
663
664impl UserMessage {
665    /// Parse the `tool_use_result` field into a caller-specified type.
666    ///
667    /// Returns `None` if `tool_use_result` is absent, otherwise returns the
668    /// deserialization result. The caller must know which tool produced the
669    /// result and supply a matching type — e.g. for `AskUserQuestion` use
670    /// [`AskUserQuestionInput`](crate::AskUserQuestionInput), whose
671    /// `questions` + `answers` fields match the wire result shape.
672    pub fn tool_use_result_as<T: serde::de::DeserializeOwned>(
673        &self,
674    ) -> Option<Result<T, serde_json::Error>> {
675        self.tool_use_result
676            .as_ref()
677            .map(|v| serde_json::from_value(v.clone()))
678    }
679
680    /// Parse the `tool_use_result` as a subagent (`Task`) run result.
681    ///
682    /// When this user message echoes the result of a `Task` tool call, the CLI
683    /// attaches a structured `tool_use_result` carrying the subagent's token,
684    /// timing, and tool-use accounting. Returns `None` when the field is absent
685    /// or does not parse as a [`SubagentResult`].
686    ///
687    /// Summing [`SubagentResult::total_tokens`] across every `Task` result in a
688    /// session yields the subagent token rollup the CLI renders as
689    /// `subagent_tokens` in its terminal `<usage>` block.
690    pub fn subagent_result(&self) -> Option<SubagentResult> {
691        self.tool_use_result
692            .as_ref()
693            .and_then(|v| serde_json::from_value(v.clone()).ok())
694    }
695}
696
697/// Token, timing, and tool-use accounting for a completed subagent (`Task`) run.
698///
699/// The Claude CLI echoes this object in the `tool_use_result` of a `Task` tool's
700/// result message. It is the typed source of truth for subagent token
701/// attribution: the per-run [`total_tokens`](Self::total_tokens),
702/// [`total_duration_ms`](Self::total_duration_ms), and
703/// [`total_tool_use_count`](Self::total_tool_use_count) correspond to the
704/// `subagent_tokens` / `duration_ms` / `tool_uses` line items the CLI renders in
705/// its human-readable `<usage>` block, and [`usage`](Self::usage) carries the
706/// full per-model token breakdown for the run.
707#[derive(Debug, Clone, Serialize, Deserialize)]
708pub struct SubagentResult {
709    /// Completion status of the subagent run (e.g. `"completed"`).
710    #[serde(skip_serializing_if = "Option::is_none")]
711    pub status: Option<String>,
712    /// The prompt the subagent was launched with.
713    #[serde(skip_serializing_if = "Option::is_none")]
714    pub prompt: Option<String>,
715    /// Stable identifier of the spawned subagent.
716    #[serde(rename = "agentId", skip_serializing_if = "Option::is_none")]
717    pub agent_id: Option<String>,
718    /// Subagent type that ran (e.g. `general-purpose`, `Explore`).
719    #[serde(rename = "agentType", skip_serializing_if = "Option::is_none")]
720    pub agent_type: Option<String>,
721    /// Final content blocks the subagent returned.
722    #[serde(
723        default,
724        deserialize_with = "deserialize_content_blocks",
725        skip_serializing_if = "Vec::is_empty"
726    )]
727    pub content: Vec<ContentBlock>,
728    /// Model the subagent actually resolved to (e.g. `claude-sonnet-4-6`).
729    #[serde(rename = "resolvedModel", skip_serializing_if = "Option::is_none")]
730    pub resolved_model: Option<String>,
731    /// Wall-clock duration of the subagent run, in milliseconds.
732    #[serde(rename = "totalDurationMs", skip_serializing_if = "Option::is_none")]
733    pub total_duration_ms: Option<u64>,
734    /// Total tokens consumed by the subagent — the `subagent_tokens` rollup line.
735    #[serde(rename = "totalTokens", skip_serializing_if = "Option::is_none")]
736    pub total_tokens: Option<u64>,
737    /// Number of tool invocations the subagent made.
738    #[serde(rename = "totalToolUseCount", skip_serializing_if = "Option::is_none")]
739    pub total_tool_use_count: Option<u64>,
740    /// Detailed token / cache usage for the subagent run.
741    #[serde(skip_serializing_if = "Option::is_none")]
742    pub usage: Option<super::result::UsageInfo>,
743    /// Per-category tool-use counts, present for some agent types (e.g. `Explore`).
744    #[serde(rename = "toolStats", skip_serializing_if = "Option::is_none")]
745    pub tool_stats: Option<SubagentToolStats>,
746}
747
748/// Per-category tool-use counts for a subagent run, from `tool_use_result.toolStats`.
749///
750/// The `extra` field captures any counters the CLI adds that aren't modeled here,
751/// so new wire fields deserialize without error.
752#[derive(Debug, Clone, Default, Serialize, Deserialize)]
753#[serde(rename_all = "camelCase")]
754pub struct SubagentToolStats {
755    #[serde(default)]
756    pub read_count: u64,
757    #[serde(default)]
758    pub search_count: u64,
759    #[serde(default)]
760    pub bash_count: u64,
761    #[serde(default)]
762    pub edit_file_count: u64,
763    #[serde(default)]
764    pub lines_added: u64,
765    #[serde(default)]
766    pub lines_removed: u64,
767    #[serde(default)]
768    pub other_tool_count: u64,
769    #[serde(flatten)]
770    pub extra: serde_json::Map<String, Value>,
771}
772
773/// Session-level subagent token rollup — the `<subagent_tokens>` /
774/// `<agent_count>` line items the Claude CLI renders in its terminal
775/// `<usage>` block.
776///
777/// The `stream-json` protocol does **not** carry this rollup on the `result`
778/// frame's `usage` (confirmed against the CLI binary — the terminal renderer
779/// computes it from `Task` tool results). Consumers that need it must
780/// accumulate it the same way: feed every session message through
781/// [`observe`](Self::observe) and read the totals at any point.
782///
783/// A `Task` result observed twice under the same `agentId` (e.g. a replayed
784/// frame on resume) is counted once. Results with no `agentId` are counted
785/// every time they are observed.
786///
787/// # Example
788///
789/// ```
790/// use claude_codes::{ClaudeOutput, SubagentUsageRollup};
791///
792/// let mut rollup = SubagentUsageRollup::default();
793/// let json = r#"{"type":"user","message":{"role":"user","content":[]},"session_id":"7fbc568e-2bd6-45aa-b217-a1cf80004ba1","tool_use_result":{"status":"completed","agentId":"ab52f22445470d454","totalDurationMs":1853,"totalTokens":10201,"totalToolUseCount":0}}"#;
794/// let output: ClaudeOutput = serde_json::from_str(json).unwrap();
795/// rollup.observe(&output);
796/// assert_eq!(rollup.subagent_tokens, 10201);
797/// assert_eq!(rollup.agent_count, 1);
798/// ```
799#[derive(Debug, Clone, Default, PartialEq, Eq)]
800pub struct SubagentUsageRollup {
801    /// Total tokens consumed by subagents — sum of
802    /// [`SubagentResult::total_tokens`] over every observed `Task` result.
803    pub subagent_tokens: u64,
804    /// Number of subagent runs observed (`<agent_count>`).
805    pub agent_count: u32,
806    /// Total subagent tool invocations — sum of `total_tool_use_count`.
807    pub tool_uses: u64,
808    /// Total subagent wall-clock milliseconds — sum of `total_duration_ms`.
809    pub duration_ms: u64,
810    seen_agent_ids: std::collections::BTreeSet<String>,
811}
812
813impl SubagentUsageRollup {
814    /// Accumulate `output` into the rollup if it is a `Task` tool result.
815    ///
816    /// Returns `true` when the message contributed to the totals. Non-user
817    /// messages, user messages without a `tool_use_result`, results from
818    /// other tools, and duplicate `agentId`s are all ignored.
819    pub fn observe(&mut self, output: &ClaudeOutput) -> bool {
820        match output {
821            ClaudeOutput::User(user) => self.observe_user(user),
822            _ => false,
823        }
824    }
825
826    /// Accumulate a user message's `Task` tool result, if it carries one.
827    ///
828    /// Every [`SubagentResult`] field is optional, so any JSON object in
829    /// `tool_use_result` parses as one (e.g. a `Bash` or `ToolSearch`
830    /// result). Only results carrying an `agentId` or a `totalTokens`
831    /// line item are treated as genuine `Task` results.
832    pub fn observe_user(&mut self, user: &UserMessage) -> bool {
833        let Some(result) = user.subagent_result() else {
834            return false;
835        };
836        if result.total_tokens.is_none() && result.agent_id.is_none() {
837            return false;
838        }
839        if let Some(agent_id) = &result.agent_id {
840            if !self.seen_agent_ids.insert(agent_id.clone()) {
841                return false;
842            }
843        }
844        self.agent_count += 1;
845        self.subagent_tokens += result.total_tokens.unwrap_or(0);
846        self.tool_uses += result.total_tool_use_count.unwrap_or(0);
847        self.duration_ms += result.total_duration_ms.unwrap_or(0);
848        true
849    }
850}
851
852/// Message content with role
853#[derive(Debug, Clone, Serialize, Deserialize)]
854pub struct MessageContent {
855    pub role: MessageRole,
856    #[serde(deserialize_with = "deserialize_content_blocks")]
857    pub content: Vec<ContentBlock>,
858}
859
860/// System message with metadata
861#[derive(Debug, Clone, Serialize, Deserialize)]
862pub struct SystemMessage {
863    pub subtype: SystemSubtype,
864    #[serde(flatten)]
865    pub data: Value, // Captures all other fields
866}
867
868impl SystemMessage {
869    /// Check if this is an init message
870    pub fn is_init(&self) -> bool {
871        self.subtype == SystemSubtype::Init
872    }
873
874    /// Check if this is a status message
875    pub fn is_status(&self) -> bool {
876        self.subtype == SystemSubtype::Status
877    }
878
879    /// Check if this is a compact_boundary message
880    pub fn is_compact_boundary(&self) -> bool {
881        self.subtype == SystemSubtype::CompactBoundary
882    }
883
884    /// Try to parse as an init message
885    pub fn as_init(&self) -> Option<InitMessage> {
886        if self.subtype != SystemSubtype::Init {
887            return None;
888        }
889        serde_json::from_value(self.data.clone()).ok()
890    }
891
892    /// Try to parse as a status message
893    pub fn as_status(&self) -> Option<StatusMessage> {
894        if self.subtype != SystemSubtype::Status {
895            return None;
896        }
897        serde_json::from_value(self.data.clone()).ok()
898    }
899
900    /// Try to parse as a compact_boundary message
901    pub fn as_compact_boundary(&self) -> Option<CompactBoundaryMessage> {
902        if self.subtype != SystemSubtype::CompactBoundary {
903            return None;
904        }
905        serde_json::from_value(self.data.clone()).ok()
906    }
907
908    /// Check if this is a task_started message
909    pub fn is_task_started(&self) -> bool {
910        self.subtype == SystemSubtype::TaskStarted
911    }
912
913    /// Check if this is a task_progress message
914    pub fn is_task_progress(&self) -> bool {
915        self.subtype == SystemSubtype::TaskProgress
916    }
917
918    /// Check if this is a task_notification message
919    pub fn is_task_notification(&self) -> bool {
920        self.subtype == SystemSubtype::TaskNotification
921    }
922
923    /// Try to parse as a task_started message
924    pub fn as_task_started(&self) -> Option<TaskStartedMessage> {
925        if self.subtype != SystemSubtype::TaskStarted {
926            return None;
927        }
928        serde_json::from_value(self.data.clone()).ok()
929    }
930
931    /// Try to parse as a task_progress message
932    pub fn as_task_progress(&self) -> Option<TaskProgressMessage> {
933        if self.subtype != SystemSubtype::TaskProgress {
934            return None;
935        }
936        serde_json::from_value(self.data.clone()).ok()
937    }
938
939    /// Try to parse as a task_notification message
940    pub fn as_task_notification(&self) -> Option<TaskNotificationMessage> {
941        if self.subtype != SystemSubtype::TaskNotification {
942            return None;
943        }
944        serde_json::from_value(self.data.clone()).ok()
945    }
946
947    /// Check if this is a task_updated message
948    pub fn is_task_updated(&self) -> bool {
949        self.subtype == SystemSubtype::TaskUpdated
950    }
951
952    /// Try to parse as a task_updated message
953    pub fn as_task_updated(&self) -> Option<TaskUpdatedMessage> {
954        if self.subtype != SystemSubtype::TaskUpdated {
955            return None;
956        }
957        serde_json::from_value(self.data.clone()).ok()
958    }
959
960    /// Check if this is a thinking_tokens message
961    pub fn is_thinking_tokens(&self) -> bool {
962        self.subtype == SystemSubtype::ThinkingTokens
963    }
964
965    /// Try to parse as a thinking_tokens message
966    pub fn as_thinking_tokens(&self) -> Option<ThinkingTokensMessage> {
967        if self.subtype != SystemSubtype::ThinkingTokens {
968            return None;
969        }
970        serde_json::from_value(self.data.clone()).ok()
971    }
972
973    /// Parse any typed system subtype known to this crate version.
974    pub fn as_known_system_event(&self) -> Option<KnownSystemEvent> {
975        macro_rules! parse {
976            ($variant:ident, $ty:ty) => {
977                serde_json::from_value::<$ty>(self.data.clone())
978                    .ok()
979                    .map(KnownSystemEvent::$variant)
980            };
981        }
982
983        match self.subtype {
984            SystemSubtype::Init => parse!(Init, InitMessage),
985            SystemSubtype::Status => parse!(Status, StatusMessage),
986            SystemSubtype::CompactBoundary => parse!(CompactBoundary, CompactBoundaryMessage),
987            SystemSubtype::ThinkingTokens => parse!(ThinkingTokens, ThinkingTokensMessage),
988            SystemSubtype::TaskStarted => parse!(TaskStarted, TaskStartedMessage),
989            SystemSubtype::TaskProgress => parse!(TaskProgress, TaskProgressMessage),
990            SystemSubtype::TaskUpdated => parse!(TaskUpdated, TaskUpdatedMessage),
991            SystemSubtype::TaskNotification => parse!(TaskNotification, TaskNotificationMessage),
992            SystemSubtype::ApiRetry => parse!(ApiRetry, ApiRetryMessage),
993            SystemSubtype::ControlRequestProgress => {
994                parse!(ControlRequestProgress, ControlRequestProgressMessage)
995            }
996            SystemSubtype::ModelRefusalFallback => {
997                parse!(ModelRefusalFallback, ModelRefusalFallbackMessage)
998            }
999            SystemSubtype::ModelRefusalNoFallback => {
1000                parse!(ModelRefusalNoFallback, ModelRefusalNoFallbackMessage)
1001            }
1002            SystemSubtype::LocalCommandOutput => {
1003                parse!(LocalCommandOutput, LocalCommandOutputMessage)
1004            }
1005            SystemSubtype::HookStarted => parse!(HookStarted, HookStartedMessage),
1006            SystemSubtype::HookProgress => parse!(HookProgress, HookProgressMessage),
1007            SystemSubtype::HookResponse => parse!(HookResponse, HookResponseMessage),
1008            SystemSubtype::PluginInstall => parse!(PluginInstall, PluginInstallMessage),
1009            SystemSubtype::BackgroundTasksChanged => {
1010                parse!(BackgroundTasksChanged, BackgroundTasksChangedMessage)
1011            }
1012            SystemSubtype::SessionStateChanged => {
1013                parse!(SessionStateChanged, SessionStateChangedMessage)
1014            }
1015            SystemSubtype::WorkerShuttingDown => {
1016                parse!(WorkerShuttingDown, WorkerShuttingDownMessage)
1017            }
1018            SystemSubtype::CommandsChanged => parse!(CommandsChanged, CommandsChangedMessage),
1019            SystemSubtype::Notification => parse!(Notification, NotificationMessage),
1020            SystemSubtype::FilesPersisted => parse!(FilesPersisted, FilesPersistedMessage),
1021            SystemSubtype::MemoryRecall => parse!(MemoryRecall, MemoryRecallMessage),
1022            SystemSubtype::ElicitationComplete => {
1023                parse!(ElicitationComplete, ElicitationCompleteMessage)
1024            }
1025            SystemSubtype::PermissionDenied => parse!(PermissionDenied, PermissionDeniedMessage),
1026            SystemSubtype::MirrorError => parse!(MirrorError, MirrorErrorMessage),
1027            SystemSubtype::Informational => parse!(Informational, InformationalMessage),
1028            SystemSubtype::CodeChangePublished => {
1029                parse!(CodeChangePublished, CodeChangePublishedMessage)
1030            }
1031            SystemSubtype::VcsStateChanged => parse!(VcsStateChanged, VcsStateChangedMessage),
1032            SystemSubtype::Unknown(_) => None,
1033        }
1034    }
1035
1036    /// Re-serialize this system message's payload through the typed view that
1037    /// matches its `subtype`, returning the result as JSON.
1038    ///
1039    /// Used by the wrapping audit ([`crate::io::audit_frame`]) to verify that a
1040    /// subtype's dedicated struct captures every wire field: the audit compares
1041    /// this against the raw [`SystemMessage::data`]. Returns `None` for subtypes
1042    /// this crate version has no dedicated struct for (including
1043    /// [`SystemSubtype::Unknown`]) — those are reported as not fully wrapped.
1044    pub fn typed_value(&self) -> Option<Value> {
1045        fn reserialize<T: Serialize>(parsed: Option<T>) -> Option<Value> {
1046            parsed.and_then(|v| serde_json::to_value(v).ok())
1047        }
1048        match self.subtype {
1049            SystemSubtype::Init => reserialize(self.as_init()),
1050            SystemSubtype::Status => reserialize(self.as_status()),
1051            SystemSubtype::CompactBoundary => reserialize(self.as_compact_boundary()),
1052            SystemSubtype::ThinkingTokens => reserialize(self.as_thinking_tokens()),
1053            SystemSubtype::TaskStarted => reserialize(self.as_task_started()),
1054            SystemSubtype::TaskProgress => reserialize(self.as_task_progress()),
1055            SystemSubtype::TaskUpdated => reserialize(self.as_task_updated()),
1056            SystemSubtype::TaskNotification => reserialize(self.as_task_notification()),
1057            SystemSubtype::ApiRetry => reserialize(parse_system::<ApiRetryMessage>(self)),
1058            SystemSubtype::ControlRequestProgress => {
1059                reserialize(parse_system::<ControlRequestProgressMessage>(self))
1060            }
1061            SystemSubtype::ModelRefusalFallback => {
1062                reserialize(parse_system::<ModelRefusalFallbackMessage>(self))
1063            }
1064            SystemSubtype::ModelRefusalNoFallback => {
1065                reserialize(parse_system::<ModelRefusalNoFallbackMessage>(self))
1066            }
1067            SystemSubtype::LocalCommandOutput => {
1068                reserialize(parse_system::<LocalCommandOutputMessage>(self))
1069            }
1070            SystemSubtype::HookStarted => reserialize(parse_system::<HookStartedMessage>(self)),
1071            SystemSubtype::HookProgress => reserialize(parse_system::<HookProgressMessage>(self)),
1072            SystemSubtype::HookResponse => reserialize(parse_system::<HookResponseMessage>(self)),
1073            SystemSubtype::PluginInstall => reserialize(parse_system::<PluginInstallMessage>(self)),
1074            SystemSubtype::BackgroundTasksChanged => {
1075                reserialize(parse_system::<BackgroundTasksChangedMessage>(self))
1076            }
1077            SystemSubtype::SessionStateChanged => {
1078                reserialize(parse_system::<SessionStateChangedMessage>(self))
1079            }
1080            SystemSubtype::WorkerShuttingDown => {
1081                reserialize(parse_system::<WorkerShuttingDownMessage>(self))
1082            }
1083            SystemSubtype::CommandsChanged => {
1084                reserialize(parse_system::<CommandsChangedMessage>(self))
1085            }
1086            SystemSubtype::Notification => reserialize(parse_system::<NotificationMessage>(self)),
1087            SystemSubtype::FilesPersisted => {
1088                reserialize(parse_system::<FilesPersistedMessage>(self))
1089            }
1090            SystemSubtype::MemoryRecall => reserialize(parse_system::<MemoryRecallMessage>(self)),
1091            SystemSubtype::ElicitationComplete => {
1092                reserialize(parse_system::<ElicitationCompleteMessage>(self))
1093            }
1094            SystemSubtype::PermissionDenied => {
1095                reserialize(parse_system::<PermissionDeniedMessage>(self))
1096            }
1097            SystemSubtype::MirrorError => reserialize(parse_system::<MirrorErrorMessage>(self)),
1098            SystemSubtype::Informational => reserialize(parse_system::<InformationalMessage>(self)),
1099            SystemSubtype::CodeChangePublished => {
1100                reserialize(parse_system::<CodeChangePublishedMessage>(self))
1101            }
1102            SystemSubtype::VcsStateChanged => {
1103                reserialize(parse_system::<VcsStateChangedMessage>(self))
1104            }
1105            SystemSubtype::Unknown(_) => None,
1106        }
1107    }
1108}
1109
1110fn parse_system<T: serde::de::DeserializeOwned>(message: &SystemMessage) -> Option<T> {
1111    serde_json::from_value(message.data.clone()).ok()
1112}
1113
1114/// Owned typed view over any known system message subtype.
1115#[derive(Debug, Clone, Serialize, Deserialize)]
1116pub enum KnownSystemEvent {
1117    Init(InitMessage),
1118    Status(StatusMessage),
1119    CompactBoundary(CompactBoundaryMessage),
1120    ThinkingTokens(ThinkingTokensMessage),
1121    TaskStarted(TaskStartedMessage),
1122    TaskProgress(TaskProgressMessage),
1123    TaskUpdated(TaskUpdatedMessage),
1124    TaskNotification(TaskNotificationMessage),
1125    ApiRetry(ApiRetryMessage),
1126    ControlRequestProgress(ControlRequestProgressMessage),
1127    ModelRefusalFallback(ModelRefusalFallbackMessage),
1128    ModelRefusalNoFallback(ModelRefusalNoFallbackMessage),
1129    LocalCommandOutput(LocalCommandOutputMessage),
1130    HookStarted(HookStartedMessage),
1131    HookProgress(HookProgressMessage),
1132    HookResponse(HookResponseMessage),
1133    PluginInstall(PluginInstallMessage),
1134    BackgroundTasksChanged(BackgroundTasksChangedMessage),
1135    SessionStateChanged(SessionStateChangedMessage),
1136    WorkerShuttingDown(WorkerShuttingDownMessage),
1137    CommandsChanged(CommandsChangedMessage),
1138    Notification(NotificationMessage),
1139    FilesPersisted(FilesPersistedMessage),
1140    MemoryRecall(MemoryRecallMessage),
1141    ElicitationComplete(ElicitationCompleteMessage),
1142    PermissionDenied(PermissionDeniedMessage),
1143    MirrorError(MirrorErrorMessage),
1144    Informational(InformationalMessage),
1145    CodeChangePublished(CodeChangePublishedMessage),
1146    VcsStateChanged(VcsStateChangedMessage),
1147}
1148
1149#[derive(Debug, Clone, Serialize, Deserialize)]
1150pub struct ApiRetryMessage {
1151    pub attempt: u64,
1152    pub max_retries: u64,
1153    pub retry_delay_ms: u64,
1154    pub error_status: Option<u16>,
1155    pub error: String,
1156    #[serde(default, skip_serializing_if = "Option::is_none")]
1157    pub uuid: Option<String>,
1158    #[serde(default, skip_serializing_if = "Option::is_none")]
1159    pub session_id: Option<String>,
1160}
1161
1162#[derive(Debug, Clone, Serialize, Deserialize)]
1163pub struct ControlRequestProgressMessage {
1164    pub request_id: String,
1165    pub status: String,
1166    #[serde(default, skip_serializing_if = "Option::is_none")]
1167    pub attempt: Option<u64>,
1168    #[serde(default, skip_serializing_if = "Option::is_none")]
1169    pub max_retries: Option<u64>,
1170    #[serde(default, skip_serializing_if = "Option::is_none")]
1171    pub retry_delay_ms: Option<u64>,
1172    #[serde(default, skip_serializing_if = "Option::is_none")]
1173    pub error_status: Option<u16>,
1174    #[serde(default, skip_serializing_if = "Option::is_none")]
1175    pub error: Option<String>,
1176    #[serde(default, skip_serializing_if = "Option::is_none")]
1177    pub uuid: Option<String>,
1178    #[serde(default, skip_serializing_if = "Option::is_none")]
1179    pub session_id: Option<String>,
1180}
1181
1182#[derive(Debug, Clone, Serialize, Deserialize)]
1183pub struct ModelRefusalFallbackMessage {
1184    pub trigger: String,
1185    pub direction: String,
1186    pub original_model: String,
1187    pub fallback_model: String,
1188    pub request_id: Option<String>,
1189    #[serde(default, skip_serializing_if = "Option::is_none")]
1190    pub api_refusal_category: Option<String>,
1191    #[serde(default, skip_serializing_if = "Option::is_none")]
1192    pub api_refusal_explanation: Option<String>,
1193    #[serde(default, skip_serializing_if = "Option::is_none")]
1194    pub retracted_message_uuids: Option<Vec<String>>,
1195    #[serde(default, skip_serializing_if = "Option::is_none")]
1196    pub refused_user_message_uuid: Option<String>,
1197    pub content: Value,
1198    #[serde(default, skip_serializing_if = "Option::is_none")]
1199    pub uuid: Option<String>,
1200    #[serde(default, skip_serializing_if = "Option::is_none")]
1201    pub session_id: Option<String>,
1202}
1203
1204#[derive(Debug, Clone, Serialize, Deserialize)]
1205pub struct ModelRefusalNoFallbackMessage {
1206    pub original_model: String,
1207    pub request_id: Option<String>,
1208    #[serde(default, skip_serializing_if = "Option::is_none")]
1209    pub api_refusal_category: Option<String>,
1210    #[serde(default, skip_serializing_if = "Option::is_none")]
1211    pub api_refusal_explanation: Option<String>,
1212    pub content: Value,
1213    #[serde(default, skip_serializing_if = "Option::is_none")]
1214    pub uuid: Option<String>,
1215    #[serde(default, skip_serializing_if = "Option::is_none")]
1216    pub session_id: Option<String>,
1217}
1218
1219#[derive(Debug, Clone, Serialize, Deserialize)]
1220pub struct LocalCommandOutputMessage {
1221    pub content: String,
1222    #[serde(default, skip_serializing_if = "Option::is_none")]
1223    pub uuid: Option<String>,
1224    #[serde(default, skip_serializing_if = "Option::is_none")]
1225    pub session_id: Option<String>,
1226}
1227
1228#[derive(Debug, Clone, Serialize, Deserialize)]
1229pub struct HookStartedMessage {
1230    pub hook_id: String,
1231    pub hook_name: String,
1232    pub hook_event: String,
1233    #[serde(default, skip_serializing_if = "Option::is_none")]
1234    pub uuid: Option<String>,
1235    #[serde(default, skip_serializing_if = "Option::is_none")]
1236    pub session_id: Option<String>,
1237}
1238
1239#[derive(Debug, Clone, Serialize, Deserialize)]
1240pub struct HookProgressMessage {
1241    pub hook_id: String,
1242    pub hook_name: String,
1243    pub hook_event: String,
1244    #[serde(default, skip_serializing_if = "Option::is_none")]
1245    pub stdout: Option<String>,
1246    #[serde(default, skip_serializing_if = "Option::is_none")]
1247    pub stderr: Option<String>,
1248    #[serde(default, skip_serializing_if = "Option::is_none")]
1249    pub output: Option<String>,
1250    #[serde(default, skip_serializing_if = "Option::is_none")]
1251    pub uuid: Option<String>,
1252    #[serde(default, skip_serializing_if = "Option::is_none")]
1253    pub session_id: Option<String>,
1254}
1255
1256#[derive(Debug, Clone, Serialize, Deserialize)]
1257pub struct HookResponseMessage {
1258    pub hook_id: String,
1259    pub hook_name: String,
1260    pub hook_event: String,
1261    #[serde(default, skip_serializing_if = "Option::is_none")]
1262    pub stdout: Option<String>,
1263    #[serde(default, skip_serializing_if = "Option::is_none")]
1264    pub stderr: Option<String>,
1265    #[serde(default, skip_serializing_if = "Option::is_none")]
1266    pub output: Option<String>,
1267    #[serde(default, skip_serializing_if = "Option::is_none")]
1268    pub exit_code: Option<i32>,
1269    pub outcome: String,
1270    #[serde(default, skip_serializing_if = "Option::is_none")]
1271    pub uuid: Option<String>,
1272    #[serde(default, skip_serializing_if = "Option::is_none")]
1273    pub session_id: Option<String>,
1274}
1275
1276#[derive(Debug, Clone, Serialize, Deserialize)]
1277pub struct PluginInstallMessage {
1278    pub status: String,
1279    #[serde(default, skip_serializing_if = "Option::is_none")]
1280    pub name: Option<String>,
1281    #[serde(default, skip_serializing_if = "Option::is_none")]
1282    pub error: Option<String>,
1283    #[serde(default, skip_serializing_if = "Option::is_none")]
1284    pub uuid: Option<String>,
1285    #[serde(default, skip_serializing_if = "Option::is_none")]
1286    pub session_id: Option<String>,
1287}
1288
1289#[derive(Debug, Clone, Serialize, Deserialize)]
1290pub struct BackgroundTasksChangedMessage {
1291    pub tasks: Vec<BackgroundTaskInfo>,
1292    #[serde(default, skip_serializing_if = "Option::is_none")]
1293    pub uuid: Option<String>,
1294    #[serde(default, skip_serializing_if = "Option::is_none")]
1295    pub session_id: Option<String>,
1296}
1297
1298#[derive(Debug, Clone, Serialize, Deserialize)]
1299pub struct BackgroundTaskInfo {
1300    pub task_id: String,
1301    pub task_type: String,
1302    pub description: String,
1303}
1304
1305#[derive(Debug, Clone, Serialize, Deserialize)]
1306pub struct SessionStateChangedMessage {
1307    pub state: String,
1308    #[serde(default, skip_serializing_if = "Option::is_none")]
1309    pub uuid: Option<String>,
1310    #[serde(default, skip_serializing_if = "Option::is_none")]
1311    pub session_id: Option<String>,
1312}
1313
1314#[derive(Debug, Clone, Serialize, Deserialize)]
1315pub struct WorkerShuttingDownMessage {
1316    pub reason: String,
1317    #[serde(default, skip_serializing_if = "Option::is_none")]
1318    pub uuid: Option<String>,
1319    #[serde(default, skip_serializing_if = "Option::is_none")]
1320    pub session_id: Option<String>,
1321}
1322
1323#[derive(Debug, Clone, Serialize, Deserialize)]
1324pub struct CommandsChangedMessage {
1325    pub commands: Vec<CommandInfo>,
1326    #[serde(default, skip_serializing_if = "Option::is_none")]
1327    pub uuid: Option<String>,
1328    #[serde(default, skip_serializing_if = "Option::is_none")]
1329    pub session_id: Option<String>,
1330}
1331
1332#[derive(Debug, Clone, Serialize, Deserialize)]
1333pub struct CommandInfo {
1334    pub name: String,
1335    pub description: String,
1336    #[serde(rename = "argumentHint")]
1337    pub argument_hint: String,
1338    #[serde(default, skip_serializing_if = "Option::is_none")]
1339    pub aliases: Option<Vec<String>>,
1340}
1341
1342#[derive(Debug, Clone, Serialize, Deserialize)]
1343pub struct NotificationMessage {
1344    pub key: String,
1345    pub text: String,
1346    pub priority: String,
1347    #[serde(default, skip_serializing_if = "Option::is_none")]
1348    pub color: Option<String>,
1349    #[serde(default, skip_serializing_if = "Option::is_none")]
1350    pub timeout_ms: Option<u64>,
1351    #[serde(default, skip_serializing_if = "Option::is_none")]
1352    pub uuid: Option<String>,
1353    #[serde(default, skip_serializing_if = "Option::is_none")]
1354    pub session_id: Option<String>,
1355}
1356
1357#[derive(Debug, Clone, Serialize, Deserialize)]
1358pub struct FilesPersistedMessage {
1359    pub files: Vec<PersistedFile>,
1360    pub failed: Vec<FailedPersistedFile>,
1361    pub processed_at: String,
1362    #[serde(default, skip_serializing_if = "Option::is_none")]
1363    pub uuid: Option<String>,
1364    #[serde(default, skip_serializing_if = "Option::is_none")]
1365    pub session_id: Option<String>,
1366}
1367
1368#[derive(Debug, Clone, Serialize, Deserialize)]
1369pub struct PersistedFile {
1370    pub filename: String,
1371    pub file_id: String,
1372}
1373
1374#[derive(Debug, Clone, Serialize, Deserialize)]
1375pub struct FailedPersistedFile {
1376    pub filename: String,
1377    pub error: String,
1378}
1379
1380#[derive(Debug, Clone, Serialize, Deserialize)]
1381pub struct MemoryRecallMessage {
1382    pub mode: String,
1383    pub memories: Vec<MemoryRecallItem>,
1384    #[serde(default, skip_serializing_if = "Option::is_none")]
1385    pub uuid: Option<String>,
1386    #[serde(default, skip_serializing_if = "Option::is_none")]
1387    pub session_id: Option<String>,
1388}
1389
1390#[derive(Debug, Clone, Serialize, Deserialize)]
1391pub struct MemoryRecallItem {
1392    pub path: String,
1393    pub scope: String,
1394    #[serde(default, skip_serializing_if = "Option::is_none")]
1395    pub content: Option<String>,
1396}
1397
1398#[derive(Debug, Clone, Serialize, Deserialize)]
1399pub struct ElicitationCompleteMessage {
1400    pub mcp_server_name: String,
1401    pub elicitation_id: String,
1402    #[serde(default, skip_serializing_if = "Option::is_none")]
1403    pub uuid: Option<String>,
1404    #[serde(default, skip_serializing_if = "Option::is_none")]
1405    pub session_id: Option<String>,
1406}
1407
1408#[derive(Debug, Clone, Serialize, Deserialize)]
1409pub struct PermissionDeniedMessage {
1410    pub tool_name: String,
1411    pub tool_use_id: String,
1412    #[serde(default, skip_serializing_if = "Option::is_none")]
1413    pub agent_id: Option<String>,
1414    #[serde(default, skip_serializing_if = "Option::is_none")]
1415    pub decision_reason_type: Option<String>,
1416    #[serde(default, skip_serializing_if = "Option::is_none")]
1417    pub decision_reason: Option<String>,
1418    pub message: String,
1419    #[serde(default, skip_serializing_if = "Option::is_none")]
1420    pub uuid: Option<String>,
1421    #[serde(default, skip_serializing_if = "Option::is_none")]
1422    pub session_id: Option<String>,
1423}
1424
1425#[derive(Debug, Clone, Serialize, Deserialize)]
1426pub struct MirrorErrorMessage {
1427    pub error: String,
1428    pub key: MirrorErrorKey,
1429    #[serde(default, skip_serializing_if = "Option::is_none")]
1430    pub uuid: Option<String>,
1431    #[serde(default, skip_serializing_if = "Option::is_none")]
1432    pub session_id: Option<String>,
1433}
1434
1435#[derive(Debug, Clone, Serialize, Deserialize)]
1436pub struct MirrorErrorKey {
1437    #[serde(rename = "projectKey")]
1438    pub project_key: String,
1439    #[serde(rename = "sessionId")]
1440    pub session_id: String,
1441    #[serde(default, skip_serializing_if = "Option::is_none")]
1442    pub subpath: Option<String>,
1443}
1444
1445#[derive(Debug, Clone, Serialize, Deserialize)]
1446pub struct InformationalMessage {
1447    pub content: String,
1448    pub level: String,
1449    #[serde(default, skip_serializing_if = "Option::is_none")]
1450    pub tool_use_id: Option<String>,
1451    #[serde(default, skip_serializing_if = "Option::is_none")]
1452    pub prevent_continuation: Option<bool>,
1453    #[serde(default, skip_serializing_if = "Option::is_none")]
1454    pub uuid: Option<String>,
1455    #[serde(default, skip_serializing_if = "Option::is_none")]
1456    pub session_id: Option<String>,
1457}
1458
1459/// Plugin info from the init message
1460#[derive(Debug, Clone, Serialize, Deserialize)]
1461pub struct PluginInfo {
1462    /// Plugin name
1463    pub name: String,
1464    /// Path to the plugin on disk
1465    pub path: String,
1466    /// Plugin registry source (e.g., "rust-analyzer-lsp@claude-plugins-official")
1467    #[serde(skip_serializing_if = "Option::is_none")]
1468    pub source: Option<String>,
1469    /// Installed plugin version (e.g., "1.0.0"). Added in CLI 2.1.219.
1470    #[serde(default, skip_serializing_if = "Option::is_none")]
1471    pub version: Option<String>,
1472}
1473
1474/// Plugin load diagnostic reported by system init.
1475#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1476pub struct PluginDiagnostic {
1477    pub plugin: String,
1478    #[serde(rename = "type")]
1479    pub diagnostic_type: String,
1480    pub message: String,
1481}
1482
1483/// Memory paths reported by system init.
1484#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1485pub struct MemoryPaths {
1486    #[serde(default, skip_serializing_if = "Option::is_none")]
1487    pub auto: Option<String>,
1488    #[serde(default, skip_serializing_if = "Option::is_none")]
1489    pub team: Option<String>,
1490    #[serde(flatten)]
1491    pub extra: serde_json::Map<String, Value>,
1492}
1493
1494/// An MCP server config entry that failed validation, reported by system
1495/// init (e.g. a `url` entry with no `type`). The affected server is skipped
1496/// and absent from `InitMessage::mcp_servers`.
1497#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1498pub struct McpServerError {
1499    pub name: String,
1500    /// Stable error category.
1501    #[serde(rename = "type")]
1502    pub error_type: String,
1503    pub message: String,
1504}
1505
1506/// Init system message data - sent at session start
1507#[derive(Debug, Clone, Serialize, Deserialize)]
1508pub struct InitMessage {
1509    /// Session identifier
1510    pub session_id: String,
1511    /// Current working directory
1512    #[serde(skip_serializing_if = "Option::is_none")]
1513    pub cwd: Option<String>,
1514    /// Model being used
1515    #[serde(skip_serializing_if = "Option::is_none")]
1516    pub model: Option<String>,
1517    /// List of available tools
1518    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1519    pub tools: Vec<String>,
1520    /// MCP servers configured
1521    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1522    pub mcp_servers: Vec<Value>,
1523    /// Available slash commands (e.g., "compact", "cost", "review")
1524    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1525    pub slash_commands: Vec<String>,
1526    /// Available agent types (e.g., "Bash", "Explore", "Plan")
1527    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1528    pub agents: Vec<String>,
1529    /// Installed plugins
1530    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1531    pub plugins: Vec<PluginInfo>,
1532    /// Installed skills
1533    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1534    pub skills: Vec<Value>,
1535    /// Claude Code CLI version
1536    #[serde(skip_serializing_if = "Option::is_none")]
1537    pub claude_code_version: Option<String>,
1538    /// How the API key was sourced
1539    #[serde(skip_serializing_if = "Option::is_none", rename = "apiKeySource")]
1540    pub api_key_source: Option<ApiKeySource>,
1541    /// Output style
1542    #[serde(skip_serializing_if = "Option::is_none")]
1543    pub output_style: Option<OutputStyle>,
1544    /// Permission mode
1545    #[serde(skip_serializing_if = "Option::is_none", rename = "permissionMode")]
1546    pub permission_mode: Option<InitPermissionMode>,
1547
1548    /// Message-level unique identifier
1549    #[serde(skip_serializing_if = "Option::is_none")]
1550    pub uuid: Option<String>,
1551
1552    /// Memory storage paths (e.g., {"auto": "/path/to/memory/"})
1553    #[serde(skip_serializing_if = "Option::is_none")]
1554    pub memory_paths: Option<MemoryPaths>,
1555
1556    /// Fast mode toggle state (e.g., "off")
1557    #[serde(skip_serializing_if = "Option::is_none")]
1558    pub fast_mode_state: Option<String>,
1559
1560    /// Why fast mode can't serve right now. Absent when nothing blocks it.
1561    #[serde(default, skip_serializing_if = "Option::is_none")]
1562    pub fast_mode_disabled_reason: Option<super::result::FastModeDisabledReason>,
1563
1564    /// MCP server config entries (from `--mcp-config`) that failed validation
1565    /// and were skipped. Affected servers are absent from `mcp_servers`.
1566    #[serde(default, skip_serializing_if = "Option::is_none")]
1567    pub mcp_server_errors: Option<Vec<McpServerError>>,
1568
1569    /// Whether analytics collection is disabled for this session.
1570    #[serde(default, skip_serializing_if = "Option::is_none")]
1571    pub analytics_disabled: Option<bool>,
1572
1573    /// Whether product-feedback prompts are disabled for this session.
1574    #[serde(default, skip_serializing_if = "Option::is_none")]
1575    pub product_feedback_disabled: Option<bool>,
1576
1577    /// API beta flags active for the session.
1578    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1579    pub betas: Vec<String>,
1580
1581    /// Open-set protocol capability names supported by this CLI.
1582    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1583    pub capabilities: Vec<String>,
1584
1585    /// Plugin load errors.
1586    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1587    pub plugin_errors: Vec<PluginDiagnostic>,
1588
1589    /// Plugin load warnings.
1590    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1591    pub plugin_warnings: Vec<PluginDiagnostic>,
1592}
1593
1594/// Status system message - sent during operations like context compaction
1595#[derive(Debug, Clone, Serialize, Deserialize)]
1596pub struct StatusMessage {
1597    /// Session identifier
1598    pub session_id: String,
1599    /// Current status (e.g., compacting) or null when complete
1600    pub status: Option<StatusMessageStatus>,
1601    /// Unique identifier for this message
1602    #[serde(skip_serializing_if = "Option::is_none")]
1603    pub uuid: Option<String>,
1604    /// Current permission mode when changed mid-session.
1605    #[serde(skip_serializing_if = "Option::is_none", rename = "permissionMode")]
1606    pub permission_mode: Option<InitPermissionMode>,
1607    #[serde(skip_serializing_if = "Option::is_none")]
1608    pub compact_result: Option<String>,
1609    #[serde(skip_serializing_if = "Option::is_none")]
1610    pub compact_error: Option<String>,
1611}
1612
1613/// Compact boundary message - marks where context compaction occurred
1614#[derive(Debug, Clone, Serialize, Deserialize)]
1615pub struct CompactBoundaryMessage {
1616    /// Session identifier
1617    pub session_id: String,
1618    /// Metadata about the compaction
1619    pub compact_metadata: CompactMetadata,
1620    /// Human-readable summary of what was compacted, when the CLI emits one.
1621    ///
1622    /// Also accepted under the `content` / `text` wire keys.
1623    #[serde(
1624        default,
1625        skip_serializing_if = "Option::is_none",
1626        alias = "content",
1627        alias = "text"
1628    )]
1629    pub summary: Option<String>,
1630    /// Number of messages summarized in this compaction pass, when present.
1631    ///
1632    /// Also accepted under the `message_count` wire key.
1633    #[serde(
1634        default,
1635        skip_serializing_if = "Option::is_none",
1636        alias = "message_count"
1637    )]
1638    pub leaf_message_count: Option<u32>,
1639    /// Wall-clock duration of the compaction pass in milliseconds, when present.
1640    #[serde(default, skip_serializing_if = "Option::is_none")]
1641    pub duration_ms: Option<u64>,
1642    /// Unique identifier for this message
1643    #[serde(skip_serializing_if = "Option::is_none")]
1644    pub uuid: Option<String>,
1645    /// Logical parent across the compaction boundary.
1646    #[serde(skip_serializing_if = "Option::is_none")]
1647    pub logical_parent_uuid: Option<Option<String>>,
1648}
1649
1650/// Metadata about context compaction
1651#[derive(Debug, Clone, Serialize, Deserialize)]
1652pub struct CompactMetadata {
1653    /// Number of tokens before compaction
1654    pub pre_tokens: u64,
1655    /// What triggered the compaction
1656    pub trigger: CompactionTrigger,
1657    #[serde(default, skip_serializing_if = "Option::is_none")]
1658    pub post_tokens: Option<u64>,
1659    #[serde(default, skip_serializing_if = "Option::is_none")]
1660    pub cumulative_dropped_tokens: Option<u64>,
1661    #[serde(default, skip_serializing_if = "Option::is_none")]
1662    pub duration_ms: Option<u64>,
1663    #[serde(default, skip_serializing_if = "Option::is_none")]
1664    pub user_context: Option<String>,
1665    #[serde(default, skip_serializing_if = "Option::is_none")]
1666    pub messages_summarized: Option<u64>,
1667    #[serde(default, skip_serializing_if = "Option::is_none")]
1668    pub precomputed: Option<bool>,
1669    #[serde(default, skip_serializing_if = "Option::is_none")]
1670    pub pre_compact_discovered_tools: Option<Vec<String>>,
1671    #[serde(default, skip_serializing_if = "Option::is_none")]
1672    pub preserved_segment: Option<PreservedSegment>,
1673    #[serde(default, skip_serializing_if = "Option::is_none")]
1674    pub preserved_messages: Option<PreservedMessages>,
1675}
1676
1677#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1678pub struct PreservedSegment {
1679    pub head_uuid: String,
1680    pub anchor_uuid: String,
1681    pub tail_uuid: String,
1682}
1683
1684#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1685pub struct PreservedMessages {
1686    pub anchor_uuid: String,
1687    pub uuids: Vec<String>,
1688    #[serde(default, skip_serializing_if = "Option::is_none")]
1689    pub all_uuids: Option<Vec<String>>,
1690}
1691
1692// ---------------------------------------------------------------------------
1693// Task system message types (task_started, task_progress, task_notification)
1694// ---------------------------------------------------------------------------
1695
1696/// Cumulative usage statistics for a background task.
1697#[derive(Debug, Clone, Serialize, Deserialize)]
1698pub struct TaskUsage {
1699    /// Wall-clock milliseconds since the task started.
1700    pub duration_ms: u64,
1701    /// Total number of tool calls made so far.
1702    pub tool_uses: u64,
1703    /// Total tokens consumed so far.
1704    pub total_tokens: u64,
1705}
1706
1707/// The kind of background task.
1708#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1709pub enum TaskType {
1710    /// A sub-agent task (e.g., Explore, Plan).
1711    LocalAgent,
1712    /// A background bash command.
1713    LocalBash,
1714    /// A local workflow task.
1715    LocalWorkflow,
1716    /// A task type not yet known to this version of the crate.
1717    Unknown(String),
1718}
1719
1720impl TaskType {
1721    pub fn as_str(&self) -> &str {
1722        match self {
1723            Self::LocalAgent => "local_agent",
1724            Self::LocalBash => "local_bash",
1725            Self::LocalWorkflow => "local_workflow",
1726            Self::Unknown(s) => s.as_str(),
1727        }
1728    }
1729}
1730
1731impl fmt::Display for TaskType {
1732    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1733        f.write_str(self.as_str())
1734    }
1735}
1736
1737impl From<&str> for TaskType {
1738    fn from(s: &str) -> Self {
1739        match s {
1740            "local_agent" => Self::LocalAgent,
1741            "local_bash" => Self::LocalBash,
1742            "local_workflow" => Self::LocalWorkflow,
1743            other => Self::Unknown(other.to_string()),
1744        }
1745    }
1746}
1747
1748impl Serialize for TaskType {
1749    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1750        serializer.serialize_str(self.as_str())
1751    }
1752}
1753
1754impl<'de> Deserialize<'de> for TaskType {
1755    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1756        let s = String::deserialize(deserializer)?;
1757        Ok(Self::from(s.as_str()))
1758    }
1759}
1760
1761/// Completion status of a background task.
1762#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1763pub enum TaskStatus {
1764    Pending,
1765    Running,
1766    Completed,
1767    Failed,
1768    Killed,
1769    Paused,
1770    Stopped,
1771    Unknown(String),
1772}
1773
1774impl TaskStatus {
1775    pub fn as_str(&self) -> &str {
1776        match self {
1777            Self::Pending => "pending",
1778            Self::Running => "running",
1779            Self::Completed => "completed",
1780            Self::Failed => "failed",
1781            Self::Killed => "killed",
1782            Self::Paused => "paused",
1783            Self::Stopped => "stopped",
1784            Self::Unknown(s) => s.as_str(),
1785        }
1786    }
1787}
1788
1789impl fmt::Display for TaskStatus {
1790    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1791        f.write_str(self.as_str())
1792    }
1793}
1794
1795impl From<&str> for TaskStatus {
1796    fn from(s: &str) -> Self {
1797        match s {
1798            "pending" => Self::Pending,
1799            "running" => Self::Running,
1800            "completed" => Self::Completed,
1801            "failed" => Self::Failed,
1802            "killed" => Self::Killed,
1803            "paused" => Self::Paused,
1804            "stopped" => Self::Stopped,
1805            other => Self::Unknown(other.to_string()),
1806        }
1807    }
1808}
1809
1810impl Serialize for TaskStatus {
1811    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1812        serializer.serialize_str(self.as_str())
1813    }
1814}
1815
1816impl<'de> Deserialize<'de> for TaskStatus {
1817    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1818        let s = String::deserialize(deserializer)?;
1819        Ok(Self::from(s.as_str()))
1820    }
1821}
1822
1823/// `task_started` system message — emitted once when a background task begins.
1824#[derive(Debug, Clone, Serialize, Deserialize)]
1825pub struct TaskStartedMessage {
1826    pub session_id: String,
1827    pub task_id: String,
1828    #[serde(default, skip_serializing_if = "Option::is_none")]
1829    pub task_type: Option<TaskType>,
1830    #[serde(default, skip_serializing_if = "Option::is_none")]
1831    pub tool_use_id: Option<String>,
1832    pub description: String,
1833    /// The subagent type for `local_agent` tasks (e.g. `general-purpose`,
1834    /// `Explore`). Absent for `local_bash` tasks.
1835    #[serde(default, skip_serializing_if = "Option::is_none")]
1836    pub subagent_type: Option<String>,
1837    /// The prompt handed to the subagent. Present for `local_agent` tasks.
1838    #[serde(default, skip_serializing_if = "Option::is_none")]
1839    pub prompt: Option<String>,
1840    #[serde(default, skip_serializing_if = "Option::is_none")]
1841    pub workflow_name: Option<String>,
1842    #[serde(default, skip_serializing_if = "Option::is_none")]
1843    pub skip_transcript: Option<bool>,
1844    pub uuid: String,
1845}
1846
1847/// `task_updated` system message — emitted when a background task's state
1848/// changes (e.g. transitions to `completed`). Carries a partial `patch` of the
1849/// fields that changed rather than the full task record.
1850#[derive(Debug, Clone, Serialize, Deserialize)]
1851pub struct TaskUpdatedMessage {
1852    pub session_id: String,
1853    pub task_id: String,
1854    pub patch: TaskPatch,
1855    pub uuid: String,
1856}
1857
1858/// The partial update carried by a [`TaskUpdatedMessage`]. Every field is
1859/// optional because the CLI only sends the keys that changed.
1860#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1861pub struct TaskPatch {
1862    #[serde(default, skip_serializing_if = "Option::is_none")]
1863    pub status: Option<TaskStatus>,
1864    /// Wall-clock epoch milliseconds when the task finished, when the patch
1865    /// reports completion.
1866    #[serde(default, skip_serializing_if = "Option::is_none")]
1867    pub end_time: Option<u64>,
1868    #[serde(default, skip_serializing_if = "Option::is_none")]
1869    pub description: Option<String>,
1870    #[serde(default, skip_serializing_if = "Option::is_none")]
1871    pub total_paused_ms: Option<u64>,
1872    #[serde(default, skip_serializing_if = "Option::is_none")]
1873    pub error: Option<String>,
1874    #[serde(default, skip_serializing_if = "Option::is_none")]
1875    pub is_backgrounded: Option<bool>,
1876}
1877
1878/// `thinking_tokens` system message — emitted as the model streams extended
1879/// thinking, reporting the running estimate of thinking tokens consumed.
1880#[derive(Debug, Clone, Serialize, Deserialize)]
1881pub struct ThinkingTokensMessage {
1882    pub session_id: String,
1883    /// Running estimate of total thinking tokens for the current turn.
1884    pub estimated_tokens: u64,
1885    /// Increase in the estimate since the previous `thinking_tokens` event.
1886    pub estimated_tokens_delta: u64,
1887    pub uuid: String,
1888}
1889
1890/// `task_progress` system message — emitted periodically as a background
1891/// agent task executes tools. Not emitted for `local_bash` tasks.
1892#[derive(Debug, Clone, Serialize, Deserialize)]
1893pub struct TaskProgressMessage {
1894    pub session_id: String,
1895    pub task_id: String,
1896    #[serde(default, skip_serializing_if = "Option::is_none")]
1897    pub tool_use_id: Option<String>,
1898    pub description: String,
1899    #[serde(default, skip_serializing_if = "Option::is_none")]
1900    pub last_tool_name: Option<String>,
1901    pub usage: TaskUsage,
1902    /// Subagent type for `local_agent` tasks (e.g. `Explore`).
1903    #[serde(default, skip_serializing_if = "Option::is_none")]
1904    pub subagent_type: Option<String>,
1905    #[serde(default, skip_serializing_if = "Option::is_none")]
1906    pub summary: Option<String>,
1907    pub uuid: String,
1908}
1909
1910/// `task_notification` system message — emitted once when a background
1911/// task completes or fails.
1912#[derive(Debug, Clone, Serialize, Deserialize)]
1913pub struct TaskNotificationMessage {
1914    pub session_id: String,
1915    pub task_id: String,
1916    pub status: TaskStatus,
1917    pub summary: String,
1918    pub output_file: Option<String>,
1919    #[serde(skip_serializing_if = "Option::is_none")]
1920    pub tool_use_id: Option<String>,
1921    #[serde(skip_serializing_if = "Option::is_none")]
1922    pub usage: Option<TaskUsage>,
1923    #[serde(default, skip_serializing_if = "Option::is_none")]
1924    pub skip_transcript: Option<bool>,
1925    #[serde(skip_serializing_if = "Option::is_none")]
1926    pub uuid: Option<String>,
1927}
1928
1929/// API error category attached to assistant wrapper frames.
1930#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1931pub enum AssistantErrorKind {
1932    AuthenticationFailed,
1933    OauthOrgNotAllowed,
1934    BillingError,
1935    RateLimit,
1936    Overloaded,
1937    InvalidRequest,
1938    ModelNotFound,
1939    ServerError,
1940    UnknownError,
1941    MaxOutputTokens,
1942    Unknown(String),
1943}
1944
1945impl AssistantErrorKind {
1946    pub fn as_str(&self) -> &str {
1947        match self {
1948            Self::AuthenticationFailed => "authentication_failed",
1949            Self::OauthOrgNotAllowed => "oauth_org_not_allowed",
1950            Self::BillingError => "billing_error",
1951            Self::RateLimit => "rate_limit",
1952            Self::Overloaded => "overloaded",
1953            Self::InvalidRequest => "invalid_request",
1954            Self::ModelNotFound => "model_not_found",
1955            Self::ServerError => "server_error",
1956            Self::UnknownError => "unknown",
1957            Self::MaxOutputTokens => "max_output_tokens",
1958            Self::Unknown(s) => s.as_str(),
1959        }
1960    }
1961}
1962
1963impl fmt::Display for AssistantErrorKind {
1964    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1965        f.write_str(self.as_str())
1966    }
1967}
1968
1969impl From<&str> for AssistantErrorKind {
1970    fn from(s: &str) -> Self {
1971        match s {
1972            "authentication_failed" => Self::AuthenticationFailed,
1973            "oauth_org_not_allowed" => Self::OauthOrgNotAllowed,
1974            "billing_error" => Self::BillingError,
1975            "rate_limit" => Self::RateLimit,
1976            "overloaded" => Self::Overloaded,
1977            "invalid_request" => Self::InvalidRequest,
1978            "model_not_found" => Self::ModelNotFound,
1979            "server_error" => Self::ServerError,
1980            "unknown" => Self::UnknownError,
1981            "max_output_tokens" => Self::MaxOutputTokens,
1982            other => Self::Unknown(other.to_string()),
1983        }
1984    }
1985}
1986
1987impl Serialize for AssistantErrorKind {
1988    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1989        serializer.serialize_str(self.as_str())
1990    }
1991}
1992
1993impl<'de> Deserialize<'de> for AssistantErrorKind {
1994    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1995        let s = String::deserialize(deserializer)?;
1996        Ok(Self::from(s.as_str()))
1997    }
1998}
1999
2000/// `code_change_published` system message — the session is now associated
2001/// with a published code change (a pull/merge request). Fires on creation and
2002/// whenever the session contributes to an existing one, so bind on every
2003/// event; re-emission for the same URL is possible and idempotent. Values are
2004/// scraped from captured command output — treat them as a binding hint and
2005/// verify against the forge before routing authenticated requests.
2006#[derive(Debug, Clone, Serialize, Deserialize)]
2007pub struct CodeChangePublishedMessage {
2008    /// Forge classification derived from the URL's shape (`github`,
2009    /// `github-enterprise`, `gitlab`, `bitbucket` today). Open set — treat an
2010    /// unknown value as a valid provider, never as an error.
2011    pub provider: String,
2012    /// Web URL of the pull/merge request. Unverified.
2013    pub url: String,
2014    /// Repository path from the URL (`owner/name` on GitHub; may carry more
2015    /// segments on GitLab).
2016    pub repo: String,
2017    /// Provider-native change identifier — the PR/MR number as a string.
2018    pub identifier: String,
2019    pub uuid: String,
2020    pub session_id: String,
2021}
2022
2023/// `vcs_state_changed` system message — a harness-observed shell command
2024/// mutated repository state. A cache-invalidation signal, deliberately
2025/// payload-free beyond classification: consumers re-read state (branch, head,
2026/// PR status) instead of decoding the event.
2027#[derive(Debug, Clone, Serialize, Deserialize)]
2028pub struct VcsStateChangedMessage {
2029    /// What class of mutation was observed. New kinds may be added — treat an
2030    /// unrecognized kind exactly like a recognized one (something changed).
2031    pub kind: VcsMutationKind,
2032    /// The session's working directory — a hint, not necessarily the mutated
2033    /// repo's path (`git -C` or an inner `cd` mutates elsewhere).
2034    pub cwd: String,
2035    pub uuid: String,
2036    pub session_id: String,
2037}
2038
2039/// Mutation class carried by a [`VcsStateChangedMessage`].
2040#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2041pub enum VcsMutationKind {
2042    Commit,
2043    Push,
2044    Merge,
2045    Rebase,
2046    /// A kind not yet known to this version of the crate.
2047    Unknown(String),
2048}
2049
2050impl VcsMutationKind {
2051    pub fn as_str(&self) -> &str {
2052        match self {
2053            Self::Commit => "commit",
2054            Self::Push => "push",
2055            Self::Merge => "merge",
2056            Self::Rebase => "rebase",
2057            Self::Unknown(s) => s.as_str(),
2058        }
2059    }
2060}
2061
2062impl fmt::Display for VcsMutationKind {
2063    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2064        f.write_str(self.as_str())
2065    }
2066}
2067
2068impl From<&str> for VcsMutationKind {
2069    fn from(s: &str) -> Self {
2070        match s {
2071            "commit" => Self::Commit,
2072            "push" => Self::Push,
2073            "merge" => Self::Merge,
2074            "rebase" => Self::Rebase,
2075            other => Self::Unknown(other.to_string()),
2076        }
2077    }
2078}
2079
2080impl Serialize for VcsMutationKind {
2081    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2082        serializer.serialize_str(self.as_str())
2083    }
2084}
2085
2086impl<'de> Deserialize<'de> for VcsMutationKind {
2087    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
2088        let s = String::deserialize(deserializer)?;
2089        Ok(Self::from(s.as_str()))
2090    }
2091}
2092
2093/// Display metadata for a tool-use block carried on the assistant wrapper.
2094#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2095pub struct ToolUseMeta {
2096    pub id: String,
2097    pub display_name: String,
2098    #[serde(default, skip_serializing_if = "Option::is_none")]
2099    pub server_display_name: Option<String>,
2100    #[serde(default, skip_serializing_if = "Option::is_none")]
2101    pub icon_url: Option<String>,
2102}
2103
2104/// Assistant message
2105#[derive(Debug, Clone, Serialize, Deserialize)]
2106pub struct AssistantMessage {
2107    pub message: AssistantMessageContent,
2108    #[serde(alias = "sessionId")]
2109    pub session_id: String,
2110    #[serde(skip_serializing_if = "Option::is_none")]
2111    pub uuid: Option<String>,
2112    #[serde(skip_serializing_if = "Option::is_none")]
2113    pub parent_tool_use_id: Option<String>,
2114    /// Anthropic API request id that produced this message (e.g. `req_...`).
2115    #[serde(skip_serializing_if = "Option::is_none")]
2116    pub request_id: Option<String>,
2117    /// Subagent type, when this assistant message was produced inside a
2118    /// `local_agent` subagent (e.g. `general-purpose`, `Explore`).
2119    #[serde(skip_serializing_if = "Option::is_none")]
2120    pub subagent_type: Option<String>,
2121    /// Short description of the subagent task, present alongside `subagent_type`.
2122    #[serde(skip_serializing_if = "Option::is_none")]
2123    pub task_description: Option<String>,
2124    #[serde(skip_serializing_if = "Option::is_none")]
2125    pub error: Option<AssistantErrorKind>,
2126    /// True when this message was truncated by an interrupt/abort before the
2127    /// stream completed — `stop_reason` was never received and the content
2128    /// may end mid-word. Absent on normally completed messages.
2129    #[serde(default, skip_serializing_if = "Option::is_none")]
2130    pub aborted: Option<bool>,
2131    /// True when this turn continued the preceding truncated assistant turn
2132    /// inside its trailing signed thinking block (max-output-tokens
2133    /// recovery). Histories replayed through the bridge must carry the flag
2134    /// back so the normalizer keeps the run's prefix on the wire.
2135    #[serde(default, skip_serializing_if = "Option::is_none")]
2136    pub resumed_from_incomplete_thinking: Option<bool>,
2137    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2138    pub supersedes: Vec<String>,
2139    #[serde(skip_serializing_if = "Option::is_none")]
2140    pub timestamp: Option<String>,
2141    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2142    pub tool_use_meta: Vec<ToolUseMeta>,
2143    #[serde(default, skip_serializing_if = "Option::is_none")]
2144    pub is_meta: Option<bool>,
2145    #[serde(default, skip_serializing_if = "Option::is_none")]
2146    pub is_virtual: Option<bool>,
2147    #[serde(default, skip_serializing_if = "Option::is_none")]
2148    pub is_api_error_message: Option<bool>,
2149    #[serde(skip_serializing_if = "Option::is_none")]
2150    pub api_error_status: Option<u16>,
2151    #[serde(skip_serializing_if = "Option::is_none")]
2152    pub api_error: Option<String>,
2153    #[serde(skip_serializing_if = "Option::is_none")]
2154    pub error_details: Option<String>,
2155    #[serde(skip_serializing_if = "Option::is_none")]
2156    pub advisor_model: Option<String>,
2157    #[serde(skip_serializing_if = "Option::is_none")]
2158    pub attribution_agent: Option<String>,
2159    #[serde(skip_serializing_if = "Option::is_none")]
2160    pub attribution_skill: Option<String>,
2161    #[serde(skip_serializing_if = "Option::is_none")]
2162    pub attribution_plugin: Option<String>,
2163    #[serde(skip_serializing_if = "Option::is_none")]
2164    pub attribution_mcp_server: Option<String>,
2165    #[serde(skip_serializing_if = "Option::is_none")]
2166    pub attribution_mcp_tool: Option<String>,
2167}
2168
2169/// Nested message content for assistant messages
2170#[derive(Debug, Clone, Serialize, Deserialize)]
2171pub struct AssistantMessageContent {
2172    pub id: String,
2173    /// The Anthropic API message type — always `"message"`.
2174    #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
2175    pub message_type: Option<String>,
2176    pub role: MessageRole,
2177    pub model: String,
2178    pub content: Vec<ContentBlock>,
2179    #[serde(skip_serializing_if = "Option::is_none")]
2180    pub stop_reason: Option<StopReason>,
2181    #[serde(skip_serializing_if = "Option::is_none")]
2182    pub stop_sequence: Option<String>,
2183    #[serde(skip_serializing_if = "Option::is_none")]
2184    pub usage: Option<AssistantUsage>,
2185    /// Details about why generation stopped
2186    #[serde(skip_serializing_if = "Option::is_none")]
2187    pub stop_details: Option<Value>,
2188    /// Context management metadata
2189    #[serde(skip_serializing_if = "Option::is_none")]
2190    pub context_management: Option<Value>,
2191}
2192
2193/// Usage information for assistant messages
2194#[derive(Debug, Clone, Serialize, Deserialize)]
2195pub struct AssistantUsage {
2196    /// Number of input tokens
2197    #[serde(default)]
2198    pub input_tokens: u32,
2199
2200    /// Number of output tokens
2201    #[serde(default)]
2202    pub output_tokens: u32,
2203
2204    /// Tokens used to create cache
2205    #[serde(default)]
2206    pub cache_creation_input_tokens: u32,
2207
2208    /// Tokens read from cache
2209    #[serde(default)]
2210    pub cache_read_input_tokens: u32,
2211
2212    /// Service tier used (e.g., "standard")
2213    #[serde(skip_serializing_if = "Option::is_none")]
2214    pub service_tier: Option<String>,
2215
2216    /// Detailed cache creation breakdown
2217    #[serde(skip_serializing_if = "Option::is_none")]
2218    pub cache_creation: Option<CacheCreationDetails>,
2219
2220    /// Inference geography (e.g., "not_available")
2221    #[serde(skip_serializing_if = "Option::is_none")]
2222    pub inference_geo: Option<String>,
2223}
2224
2225/// Detailed cache creation information
2226#[derive(Debug, Clone, Serialize, Deserialize)]
2227pub struct CacheCreationDetails {
2228    /// Ephemeral 1-hour input tokens
2229    #[serde(default)]
2230    pub ephemeral_1h_input_tokens: u32,
2231
2232    /// Ephemeral 5-minute input tokens
2233    #[serde(default)]
2234    pub ephemeral_5m_input_tokens: u32,
2235}
2236
2237#[cfg(test)]
2238mod tests {
2239    use crate::io::ClaudeOutput;
2240
2241    #[test]
2242    fn test_subagent_usage_rollup_accumulates_task_results() {
2243        use super::SubagentUsageRollup;
2244
2245        let mut rollup = SubagentUsageRollup::default();
2246
2247        let task_result = r#"{"type":"user","message":{"role":"user","content":[]},"session_id":"7fbc568e-2bd6-45aa-b217-a1cf80004ba1","tool_use_result":{"status":"completed","prompt":"Compute 6 times 7.","agentId":"ab52f22445470d454","agentType":"general-purpose","resolvedModel":"claude-sonnet-4-6","totalDurationMs":1853,"totalTokens":10201,"totalToolUseCount":3}}"#;
2248        let output: ClaudeOutput = serde_json::from_str(task_result).unwrap();
2249        assert!(rollup.observe(&output));
2250        assert_eq!(rollup.subagent_tokens, 10201);
2251        assert_eq!(rollup.agent_count, 1);
2252        assert_eq!(rollup.tool_uses, 3);
2253        assert_eq!(rollup.duration_ms, 1853);
2254
2255        // Replayed frame with the same agentId is counted once.
2256        assert!(!rollup.observe(&output));
2257        assert_eq!(rollup.agent_count, 1);
2258        assert_eq!(rollup.subagent_tokens, 10201);
2259
2260        // A second agent accumulates.
2261        let second = r#"{"type":"user","message":{"role":"user","content":[]},"session_id":"7fbc568e-2bd6-45aa-b217-a1cf80004ba1","tool_use_result":{"status":"completed","agentId":"ffff00001111","totalDurationMs":100,"totalTokens":500,"totalToolUseCount":1}}"#;
2262        let output: ClaudeOutput = serde_json::from_str(second).unwrap();
2263        assert!(rollup.observe(&output));
2264        assert_eq!(rollup.agent_count, 2);
2265        assert_eq!(rollup.subagent_tokens, 10701);
2266    }
2267
2268    #[test]
2269    fn test_subagent_usage_rollup_ignores_non_task_results() {
2270        use super::SubagentUsageRollup;
2271
2272        let mut rollup = SubagentUsageRollup::default();
2273
2274        // A ToolSearch tool_use_result parses as an all-None SubagentResult;
2275        // it must not count as a subagent.
2276        let tool_search = r#"{"type":"user","message":{"role":"user","content":[]},"session_id":"7fbc568e-2bd6-45aa-b217-a1cf80004ba1","tool_use_result":{"matches":["TaskCreate"],"query":"select:TaskCreate","total_deferred_tools":27}}"#;
2277        let output: ClaudeOutput = serde_json::from_str(tool_search).unwrap();
2278        assert!(!rollup.observe(&output));
2279
2280        // Plain user message without tool_use_result.
2281        let plain = r#"{"type":"user","message":{"role":"user","content":[]},"session_id":"7fbc568e-2bd6-45aa-b217-a1cf80004ba1"}"#;
2282        let output: ClaudeOutput = serde_json::from_str(plain).unwrap();
2283        assert!(!rollup.observe(&output));
2284
2285        // Non-user frames are ignored.
2286        let system = r#"{"type":"system","subtype":"status","status":null,"session_id":"7fbc568e-2bd6-45aa-b217-a1cf80004ba1"}"#;
2287        let output: ClaudeOutput = serde_json::from_str(system).unwrap();
2288        assert!(!rollup.observe(&output));
2289
2290        assert_eq!(rollup, SubagentUsageRollup::default());
2291    }
2292
2293    #[test]
2294    fn test_subagent_usage_rollup_over_captured_session() {
2295        use super::SubagentUsageRollup;
2296
2297        let mut rollup = SubagentUsageRollup::default();
2298        let fixture =
2299            include_str!("../../test_cases/subagent_sessions/general_purpose_compute.jsonl");
2300        for line in fixture.lines().filter(|l| !l.trim().is_empty()) {
2301            if let Ok(output) = serde_json::from_str::<ClaudeOutput>(line) {
2302                rollup.observe(&output);
2303            }
2304        }
2305        assert_eq!(rollup.agent_count, 1);
2306        assert_eq!(rollup.subagent_tokens, 10201);
2307    }
2308
2309    #[test]
2310    fn test_system_message_init() {
2311        let json = r#"{
2312            "type": "system",
2313            "subtype": "init",
2314            "session_id": "test-session-123",
2315            "cwd": "/home/user/project",
2316            "model": "claude-sonnet-4",
2317            "tools": ["Bash", "Read", "Write"],
2318            "mcp_servers": [],
2319            "slash_commands": ["compact", "cost", "review"],
2320            "agents": ["Bash", "Explore", "Plan"],
2321            "plugins": [{"name": "rust-analyzer-lsp", "path": "/home/user/.claude/plugins/rust-analyzer-lsp/1.0.0"}],
2322            "skills": [],
2323            "claude_code_version": "2.1.15",
2324            "apiKeySource": "none",
2325            "output_style": "default",
2326            "permissionMode": "default"
2327        }"#;
2328
2329        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
2330        if let ClaudeOutput::System(sys) = output {
2331            assert!(sys.is_init());
2332            assert!(!sys.is_status());
2333            assert!(!sys.is_compact_boundary());
2334
2335            let init = sys.as_init().expect("Should parse as init");
2336            assert_eq!(init.session_id, "test-session-123");
2337            assert_eq!(init.cwd, Some("/home/user/project".to_string()));
2338            assert_eq!(init.model, Some("claude-sonnet-4".to_string()));
2339            assert_eq!(init.tools, vec!["Bash", "Read", "Write"]);
2340            assert_eq!(init.slash_commands, vec!["compact", "cost", "review"]);
2341            assert_eq!(init.agents, vec!["Bash", "Explore", "Plan"]);
2342            assert_eq!(init.plugins.len(), 1);
2343            assert_eq!(init.plugins[0].name, "rust-analyzer-lsp");
2344            assert_eq!(init.claude_code_version, Some("2.1.15".to_string()));
2345            assert_eq!(init.api_key_source, Some(super::ApiKeySource::None));
2346            assert_eq!(init.output_style, Some(super::OutputStyle::Default));
2347            assert_eq!(
2348                init.permission_mode,
2349                Some(super::InitPermissionMode::Default)
2350            );
2351        } else {
2352            panic!("Expected System message");
2353        }
2354    }
2355
2356    #[test]
2357    fn test_system_message_init_from_real_capture() {
2358        let json = include_str!("../../test_cases/tool_use_captures/tool_msg_0.json");
2359        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
2360        if let ClaudeOutput::System(sys) = output {
2361            let init = sys.as_init().expect("Should parse real init capture");
2362            assert_eq!(init.slash_commands.len(), 8);
2363            assert!(init.slash_commands.contains(&"compact".to_string()));
2364            assert!(init.slash_commands.contains(&"review".to_string()));
2365            assert_eq!(init.agents.len(), 5);
2366            assert!(init.agents.contains(&"Bash".to_string()));
2367            assert!(init.agents.contains(&"Explore".to_string()));
2368            assert_eq!(init.plugins.len(), 1);
2369            assert_eq!(init.plugins[0].name, "rust-analyzer-lsp");
2370            assert_eq!(init.claude_code_version, Some("2.1.15".to_string()));
2371        } else {
2372            panic!("Expected System message");
2373        }
2374    }
2375
2376    #[test]
2377    fn test_system_message_status() {
2378        let json = r#"{
2379            "type": "system",
2380            "subtype": "status",
2381            "session_id": "879c1a88-3756-4092-aa95-0020c4ed9692",
2382            "status": "compacting",
2383            "uuid": "32eb9f9d-5ef7-47ff-8fce-bbe22fe7ed93"
2384        }"#;
2385
2386        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
2387        if let ClaudeOutput::System(sys) = output {
2388            assert!(sys.is_status());
2389            assert!(!sys.is_init());
2390
2391            let status = sys.as_status().expect("Should parse as status");
2392            assert_eq!(status.session_id, "879c1a88-3756-4092-aa95-0020c4ed9692");
2393            assert_eq!(status.status, Some(super::StatusMessageStatus::Compacting));
2394            assert_eq!(
2395                status.uuid,
2396                Some("32eb9f9d-5ef7-47ff-8fce-bbe22fe7ed93".to_string())
2397            );
2398        } else {
2399            panic!("Expected System message");
2400        }
2401    }
2402
2403    #[test]
2404    fn test_system_message_status_null() {
2405        let json = r#"{
2406            "type": "system",
2407            "subtype": "status",
2408            "session_id": "879c1a88-3756-4092-aa95-0020c4ed9692",
2409            "status": null,
2410            "uuid": "92d9637e-d00e-418e-acd2-a504e3861c6a"
2411        }"#;
2412
2413        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
2414        if let ClaudeOutput::System(sys) = output {
2415            let status = sys.as_status().expect("Should parse as status");
2416            assert_eq!(status.status, None);
2417        } else {
2418            panic!("Expected System message");
2419        }
2420    }
2421
2422    #[test]
2423    fn test_system_message_task_started() {
2424        let json = r#"{
2425            "type": "system",
2426            "subtype": "task_started",
2427            "session_id": "9abbc466-dad0-4b8e-b6b0-cad5eb7a16b9",
2428            "task_id": "b6daf3f",
2429            "task_type": "local_bash",
2430            "tool_use_id": "toolu_011rfSTFumpJZdCCfzeD7jaS",
2431            "description": "Wait for CI on PR #12",
2432            "uuid": "c4243261-c128-4747-b8c3-5e1c7c10eeb8"
2433        }"#;
2434
2435        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
2436        if let ClaudeOutput::System(sys) = output {
2437            assert!(sys.is_task_started());
2438            assert!(!sys.is_task_progress());
2439            assert!(!sys.is_task_notification());
2440
2441            let task = sys.as_task_started().expect("Should parse as task_started");
2442            assert_eq!(task.session_id, "9abbc466-dad0-4b8e-b6b0-cad5eb7a16b9");
2443            assert_eq!(task.task_id, "b6daf3f");
2444            assert_eq!(task.task_type, Some(super::TaskType::LocalBash));
2445            assert_eq!(
2446                task.tool_use_id.as_deref(),
2447                Some("toolu_011rfSTFumpJZdCCfzeD7jaS")
2448            );
2449            assert_eq!(task.description, "Wait for CI on PR #12");
2450        } else {
2451            panic!("Expected System message");
2452        }
2453    }
2454
2455    #[test]
2456    fn test_system_message_task_started_agent() {
2457        let json = r#"{
2458            "type": "system",
2459            "subtype": "task_started",
2460            "session_id": "bff4f716-17c1-4255-ab7b-eea9d33824e3",
2461            "task_id": "a4a7e0906e5fc64cc",
2462            "task_type": "local_agent",
2463            "tool_use_id": "toolu_01SFz9FwZ1cYgCSy8vRM7wep",
2464            "description": "Explore Scene/ArrayScene duplication",
2465            "uuid": "85a39f5a-e4d4-47f7-9a6d-1125f1a8035f"
2466        }"#;
2467
2468        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
2469        if let ClaudeOutput::System(sys) = output {
2470            let task = sys.as_task_started().expect("Should parse as task_started");
2471            assert_eq!(task.task_type, Some(super::TaskType::LocalAgent));
2472            assert_eq!(task.task_id, "a4a7e0906e5fc64cc");
2473        } else {
2474            panic!("Expected System message");
2475        }
2476    }
2477
2478    #[test]
2479    fn test_system_message_task_progress() {
2480        let json = r#"{
2481            "type": "system",
2482            "subtype": "task_progress",
2483            "session_id": "bff4f716-17c1-4255-ab7b-eea9d33824e3",
2484            "task_id": "a4a7e0906e5fc64cc",
2485            "tool_use_id": "toolu_01SFz9FwZ1cYgCSy8vRM7wep",
2486            "description": "Reading src/jplephem/chebyshev.rs",
2487            "last_tool_name": "Read",
2488            "usage": {
2489                "duration_ms": 13996,
2490                "tool_uses": 9,
2491                "total_tokens": 38779
2492            },
2493            "uuid": "85a39f5a-e4d4-47f7-9a6d-1125f1a8035f"
2494        }"#;
2495
2496        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
2497        if let ClaudeOutput::System(sys) = output {
2498            assert!(sys.is_task_progress());
2499            assert!(!sys.is_task_started());
2500
2501            let progress = sys
2502                .as_task_progress()
2503                .expect("Should parse as task_progress");
2504            assert_eq!(progress.task_id, "a4a7e0906e5fc64cc");
2505            assert_eq!(progress.description, "Reading src/jplephem/chebyshev.rs");
2506            assert_eq!(progress.last_tool_name.as_deref(), Some("Read"));
2507            assert_eq!(progress.usage.duration_ms, 13996);
2508            assert_eq!(progress.usage.tool_uses, 9);
2509            assert_eq!(progress.usage.total_tokens, 38779);
2510        } else {
2511            panic!("Expected System message");
2512        }
2513    }
2514
2515    #[test]
2516    fn test_system_message_task_notification_completed() {
2517        let json = r#"{
2518            "type": "system",
2519            "subtype": "task_notification",
2520            "session_id": "bff4f716-17c1-4255-ab7b-eea9d33824e3",
2521            "task_id": "a0ba761e9dc9c316f",
2522            "tool_use_id": "toolu_01Ho6XVXFLVNjTQ9YqowdBXW",
2523            "status": "completed",
2524            "summary": "Agent \"Write Hipparcos data source doc\" completed",
2525            "output_file": "",
2526            "usage": {
2527                "duration_ms": 172300,
2528                "tool_uses": 11,
2529                "total_tokens": 42005
2530            },
2531            "uuid": "269f49b9-218d-4c8d-9f7e-3a5383a0c5b2"
2532        }"#;
2533
2534        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
2535        if let ClaudeOutput::System(sys) = output {
2536            assert!(sys.is_task_notification());
2537
2538            let notif = sys
2539                .as_task_notification()
2540                .expect("Should parse as task_notification");
2541            assert_eq!(notif.status, super::TaskStatus::Completed);
2542            assert_eq!(
2543                notif.summary,
2544                "Agent \"Write Hipparcos data source doc\" completed"
2545            );
2546            assert_eq!(notif.output_file, Some("".to_string()));
2547            assert_eq!(
2548                notif.tool_use_id,
2549                Some("toolu_01Ho6XVXFLVNjTQ9YqowdBXW".to_string())
2550            );
2551            let usage = notif.usage.expect("Should have usage");
2552            assert_eq!(usage.duration_ms, 172300);
2553            assert_eq!(usage.tool_uses, 11);
2554            assert_eq!(usage.total_tokens, 42005);
2555        } else {
2556            panic!("Expected System message");
2557        }
2558    }
2559
2560    #[test]
2561    fn test_system_message_task_notification_failed_no_usage() {
2562        let json = r#"{
2563            "type": "system",
2564            "subtype": "task_notification",
2565            "session_id": "ea629737-3c36-48a8-a1c4-ad761ad35784",
2566            "task_id": "b98f6a3",
2567            "status": "failed",
2568            "summary": "Background command \"Run FSM calibration\" failed with exit code 1",
2569            "output_file": "/tmp/claude-1000/tasks/b98f6a3.output"
2570        }"#;
2571
2572        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
2573        if let ClaudeOutput::System(sys) = output {
2574            let notif = sys
2575                .as_task_notification()
2576                .expect("Should parse as task_notification");
2577            assert_eq!(notif.status, super::TaskStatus::Failed);
2578            assert!(notif.tool_use_id.is_none());
2579            assert!(notif.usage.is_none());
2580            assert_eq!(
2581                notif.output_file,
2582                Some("/tmp/claude-1000/tasks/b98f6a3.output".to_string())
2583            );
2584        } else {
2585            panic!("Expected System message");
2586        }
2587    }
2588
2589    /// Task system messages survive a `to_value` → `from_value` round-trip
2590    /// with their typed accessors still resolving. Mirrors the proxy/relay
2591    /// path where output is reparsed from a `serde_json::Value` rather than
2592    /// straight from the CLI's stdout, so a silently dropped or renamed field
2593    /// surfaces here instead of as a `None` downstream.
2594    #[test]
2595    fn test_task_messages_roundtrip_through_value() {
2596        let cases = [
2597            r#"{"type":"system","subtype":"task_started","session_id":"s1",
2598                "task_id":"t1","task_type":"local_bash","tool_use_id":"tu1",
2599                "description":"Sleep 3s","uuid":"u1"}"#,
2600            r#"{"type":"system","subtype":"task_progress","session_id":"s1",
2601                "task_id":"t1","tool_use_id":"tu1","description":"Running ls",
2602                "last_tool_name":"Bash",
2603                "usage":{"duration_ms":100,"tool_uses":1,"total_tokens":500},
2604                "uuid":"u2"}"#,
2605            r#"{"type":"system","subtype":"task_notification","session_id":"s1",
2606                "task_id":"t1","tool_use_id":"tu1","status":"completed",
2607                "summary":"done","output_file":"",
2608                "usage":{"duration_ms":100,"tool_uses":1,"total_tokens":500},
2609                "uuid":"u3"}"#,
2610        ];
2611
2612        for json in cases {
2613            let output: ClaudeOutput = serde_json::from_str(json).unwrap();
2614            let value = serde_json::to_value(&output).unwrap();
2615            let reparsed: ClaudeOutput = serde_json::from_value(value).unwrap();
2616
2617            let ClaudeOutput::System(sys) = reparsed else {
2618                panic!("Expected System variant after round-trip");
2619            };
2620
2621            match sys.subtype {
2622                super::SystemSubtype::TaskStarted => {
2623                    assert!(
2624                        sys.as_task_started().is_some(),
2625                        "as_task_started failed after round-trip"
2626                    );
2627                }
2628                super::SystemSubtype::TaskProgress => {
2629                    assert!(
2630                        sys.as_task_progress().is_some(),
2631                        "as_task_progress failed after round-trip"
2632                    );
2633                }
2634                super::SystemSubtype::TaskNotification => {
2635                    assert!(
2636                        sys.as_task_notification().is_some(),
2637                        "as_task_notification failed after round-trip"
2638                    );
2639                }
2640                other => panic!("unexpected subtype after round-trip: {other:?}"),
2641            }
2642        }
2643    }
2644
2645    #[test]
2646    fn test_system_message_compact_boundary() {
2647        let json = r#"{
2648            "type": "system",
2649            "subtype": "compact_boundary",
2650            "session_id": "879c1a88-3756-4092-aa95-0020c4ed9692",
2651            "compact_metadata": {
2652                "pre_tokens": 155285,
2653                "trigger": "auto"
2654            },
2655            "uuid": "a67780d5-74cb-48b1-9137-7a6e7cee45d7"
2656        }"#;
2657
2658        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
2659        if let ClaudeOutput::System(sys) = output {
2660            assert!(sys.is_compact_boundary());
2661            assert!(!sys.is_init());
2662            assert!(!sys.is_status());
2663
2664            let compact = sys
2665                .as_compact_boundary()
2666                .expect("Should parse as compact_boundary");
2667            assert_eq!(compact.session_id, "879c1a88-3756-4092-aa95-0020c4ed9692");
2668            assert_eq!(compact.compact_metadata.pre_tokens, 155285);
2669            assert_eq!(
2670                compact.compact_metadata.trigger,
2671                super::CompactionTrigger::Auto
2672            );
2673            // Per-compaction stats are optional and absent here.
2674            assert!(compact.summary.is_none());
2675            assert!(compact.leaf_message_count.is_none());
2676            assert!(compact.duration_ms.is_none());
2677        } else {
2678            panic!("Expected System message");
2679        }
2680    }
2681
2682    #[test]
2683    fn test_compact_boundary_with_summary_stats() {
2684        // Canonical keys.
2685        let json = r#"{
2686            "type": "system",
2687            "subtype": "compact_boundary",
2688            "session_id": "s1",
2689            "compact_metadata": { "pre_tokens": 1000, "trigger": "manual" },
2690            "summary": "Summarized the earlier exploration.",
2691            "leaf_message_count": 42,
2692            "duration_ms": 1234,
2693            "uuid": "u1"
2694        }"#;
2695        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
2696        let ClaudeOutput::System(sys) = output else {
2697            panic!("Expected System message");
2698        };
2699        let compact = sys.as_compact_boundary().expect("compact_boundary");
2700        assert_eq!(
2701            compact.summary.as_deref(),
2702            Some("Summarized the earlier exploration.")
2703        );
2704        assert_eq!(compact.leaf_message_count, Some(42));
2705        assert_eq!(compact.duration_ms, Some(1234));
2706
2707        // Alternate wire keys (`content` for summary, `message_count` for count)
2708        // deserialize into the same fields.
2709        let json_alt = r#"{
2710            "type": "system",
2711            "subtype": "compact_boundary",
2712            "session_id": "s2",
2713            "compact_metadata": { "pre_tokens": 2000, "trigger": "auto" },
2714            "content": "alt-key summary",
2715            "message_count": 7
2716        }"#;
2717        let output: ClaudeOutput = serde_json::from_str(json_alt).unwrap();
2718        let ClaudeOutput::System(sys) = output else {
2719            panic!("Expected System message");
2720        };
2721        let compact = sys.as_compact_boundary().expect("compact_boundary");
2722        assert_eq!(compact.summary.as_deref(), Some("alt-key summary"));
2723        assert_eq!(compact.leaf_message_count, Some(7));
2724    }
2725
2726    #[test]
2727    fn test_init_message_with_new_fields() {
2728        let json = r#"{
2729            "type": "system",
2730            "subtype": "init",
2731            "session_id": "test-session",
2732            "cwd": "/home/user",
2733            "model": "claude-opus-4-7",
2734            "tools": ["Bash"],
2735            "mcp_servers": [],
2736            "permissionMode": "default",
2737            "apiKeySource": "none",
2738            "uuid": "44841a0d-182d-493a-86b5-79800d3d9665",
2739            "memory_paths": {"auto": "/home/user/.claude/projects/memory/"},
2740            "fast_mode_state": "off",
2741            "plugins": [{"name": "lsp", "path": "/plugins/lsp", "source": "lsp@official"}],
2742            "claude_code_version": "2.1.117"
2743        }"#;
2744
2745        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
2746        if let ClaudeOutput::System(sys) = output {
2747            let init = sys.as_init().expect("Should parse as init");
2748            assert_eq!(
2749                init.uuid.as_deref(),
2750                Some("44841a0d-182d-493a-86b5-79800d3d9665")
2751            );
2752            assert!(init.memory_paths.is_some());
2753            assert_eq!(init.fast_mode_state.as_deref(), Some("off"));
2754            assert_eq!(init.plugins[0].source.as_deref(), Some("lsp@official"));
2755            assert_eq!(init.claude_code_version.as_deref(), Some("2.1.117"));
2756        } else {
2757            panic!("Expected System message");
2758        }
2759    }
2760
2761    #[test]
2762    fn test_assistant_message_with_new_fields() {
2763        let json = r#"{
2764            "type": "assistant",
2765            "message": {
2766                "id": "msg_1",
2767                "type": "message",
2768                "role": "assistant",
2769                "model": "claude-opus-4-7",
2770                "content": [{"type": "text", "text": "Hello"}],
2771                "stop_reason": "end_turn",
2772                "stop_details": null,
2773                "context_management": null,
2774                "usage": {
2775                    "input_tokens": 100,
2776                    "output_tokens": 10,
2777                    "cache_creation_input_tokens": 50,
2778                    "cache_read_input_tokens": 0,
2779                    "service_tier": "standard",
2780                    "inference_geo": "not_available"
2781                }
2782            },
2783            "session_id": "abc",
2784            "uuid": "msg-uuid-123"
2785        }"#;
2786
2787        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
2788        if let ClaudeOutput::Assistant(asst) = output {
2789            assert_eq!(asst.message.stop_details, None);
2790            assert_eq!(asst.message.context_management, None);
2791            let usage = asst.message.usage.unwrap();
2792            assert_eq!(usage.inference_geo.as_deref(), Some("not_available"));
2793        } else {
2794            panic!("Expected Assistant message");
2795        }
2796    }
2797
2798    #[test]
2799    fn test_user_message_with_new_fields() {
2800        let json = r#"{
2801            "type": "user",
2802            "message": {
2803                "role": "user",
2804                "content": [{"type": "text", "text": "Hello"}]
2805            },
2806            "session_id": "9abbc466-dad0-4b8e-b6b0-cad5eb7a16b9",
2807            "parent_tool_use_id": "toolu_123",
2808            "uuid": "user-msg-456"
2809        }"#;
2810
2811        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
2812        if let ClaudeOutput::User(user) = output {
2813            assert_eq!(user.parent_tool_use_id.as_deref(), Some("toolu_123"));
2814            assert_eq!(user.uuid.as_deref(), Some("user-msg-456"));
2815        } else {
2816            panic!("Expected User message");
2817        }
2818    }
2819
2820    /// Real wire payload captured from the CLI after answering an
2821    /// AskUserQuestion via the permission control protocol. The top-level
2822    /// `tool_use_result` and `timestamp` fields must round-trip without loss —
2823    /// proxies using this crate to relay messages to a viewer rely on those
2824    /// fields being preserved (the viewer reads `tool_use_result.answers`).
2825    #[test]
2826    fn test_user_message_preserves_tool_use_result_and_timestamp() {
2827        let json = r#"{
2828            "type":"user",
2829            "message":{"role":"user","content":[{"type":"tool_result","content":"User has answered your questions: . You can now continue with the user's answers in mind.","tool_use_id":"toolu_01331duMqP2PrRaqR2yWa8e4"}]},
2830            "parent_tool_use_id":null,
2831            "session_id":"622ae0c3-3d50-4fa7-9ee0-69d691238c6d",
2832            "uuid":"8ef6e997-a849-4d15-bed3-2837c3d3f4cd",
2833            "timestamp":"2026-05-12T23:12:04.121Z",
2834            "tool_use_result":{"questions":[{"question":"Which color do you prefer?","header":"Color","options":[{"label":"Red","description":"A warm color"},{"label":"Blue","description":"A cool color"}],"multiSelect":false}],"answers":{"Color":"Blue"}}
2835        }"#;
2836
2837        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
2838        let user = match output {
2839            ClaudeOutput::User(u) => u,
2840            other => panic!("Expected User message, got {:?}", other.message_type()),
2841        };
2842
2843        assert_eq!(user.timestamp.as_deref(), Some("2026-05-12T23:12:04.121Z"));
2844        let raw = user
2845            .tool_use_result
2846            .as_ref()
2847            .expect("tool_use_result must be captured");
2848        assert_eq!(raw["answers"]["Color"], "Blue");
2849        assert_eq!(raw["questions"][0]["header"], "Color");
2850
2851        // Round-trip: re-serialize and confirm tool_use_result + timestamp
2852        // survive — the bug we're guarding against is that the proxy silently
2853        // drops these fields when relaying user messages.
2854        let reser: serde_json::Value = serde_json::to_value(&user).unwrap();
2855        assert_eq!(reser["timestamp"], "2026-05-12T23:12:04.121Z");
2856        assert_eq!(reser["tool_use_result"]["answers"]["Color"], "Blue");
2857        assert_eq!(
2858            reser["tool_use_result"]["questions"][0]["question"],
2859            "Which color do you prefer?"
2860        );
2861
2862        // Typed accessor: AskUserQuestionInput has the same shape as the
2863        // AskUserQuestion tool_use_result.
2864        let typed: crate::AskUserQuestionInput = user
2865            .tool_use_result_as::<crate::AskUserQuestionInput>()
2866            .expect("tool_use_result present")
2867            .expect("AskUserQuestionInput parses");
2868        assert_eq!(typed.questions.len(), 1);
2869        assert_eq!(typed.questions[0].header, "Color");
2870        let answers = typed.answers.expect("answers populated");
2871        assert_eq!(answers.get("Color").map(String::as_str), Some("Blue"));
2872    }
2873
2874    /// User messages without `tool_use_result` / `timestamp` must still
2875    /// deserialize fine and serialize back without spuriously emitting nulls.
2876    #[test]
2877    fn test_user_message_without_tool_use_result_omits_field() {
2878        let json = r#"{
2879            "type":"user",
2880            "message":{"role":"user","content":[{"type":"text","text":"hello"}]},
2881            "session_id":"622ae0c3-3d50-4fa7-9ee0-69d691238c6d"
2882        }"#;
2883
2884        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
2885        let user = match output {
2886            ClaudeOutput::User(u) => u,
2887            _ => panic!("Expected User message"),
2888        };
2889        assert!(user.tool_use_result.is_none());
2890        assert!(user.timestamp.is_none());
2891
2892        let reser = serde_json::to_value(&user).unwrap();
2893        assert!(reser.get("tool_use_result").is_none());
2894        assert!(reser.get("timestamp").is_none());
2895    }
2896
2897    /// A `Task` tool result must expose subagent token / timing / tool-use
2898    /// accounting through the typed [`UserMessage::subagent_result`] accessor,
2899    /// including the nested per-model `usage` breakdown and `toolStats`.
2900    #[test]
2901    fn test_subagent_result_exposes_token_accounting() {
2902        let json = r#"{
2903            "type":"user",
2904            "message":{"role":"user","content":[{"tool_use_id":"toolu_01","type":"tool_result","content":[{"type":"text","text":"21"}]}]},
2905            "session_id":"d3fc5942-75e5-4aa1-a87d-b9484a176541",
2906            "tool_use_result":{
2907                "status":"completed",
2908                "prompt":"Count the .rs files.",
2909                "agentId":"ac4f0276e9d4b6232",
2910                "agentType":"Explore",
2911                "content":[{"type":"text","text":"21"}],
2912                "resolvedModel":"claude-haiku-4-5-20251001",
2913                "totalDurationMs":6869,
2914                "totalTokens":7834,
2915                "totalToolUseCount":1,
2916                "usage":{"input_tokens":6,"cache_creation_input_tokens":125,"cache_read_input_tokens":7699,"output_tokens":4,"service_tier":"standard"},
2917                "toolStats":{"readCount":0,"searchCount":0,"bashCount":1,"editFileCount":0,"linesAdded":0,"linesRemoved":0,"otherToolCount":0}
2918            }
2919        }"#;
2920
2921        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
2922        let user = match output {
2923            ClaudeOutput::User(u) => u,
2924            _ => panic!("Expected User message"),
2925        };
2926
2927        let result = user.subagent_result().expect("subagent result parses");
2928        assert_eq!(result.agent_type.as_deref(), Some("Explore"));
2929        assert_eq!(
2930            result.resolved_model.as_deref(),
2931            Some("claude-haiku-4-5-20251001")
2932        );
2933        assert_eq!(result.total_tokens, Some(7834));
2934        assert_eq!(result.total_duration_ms, Some(6869));
2935        assert_eq!(result.total_tool_use_count, Some(1));
2936
2937        let usage = result.usage.expect("nested usage present");
2938        assert_eq!(usage.input_tokens, 6);
2939        assert_eq!(usage.cache_read_input_tokens, 7699);
2940
2941        let stats = result.tool_stats.expect("toolStats present");
2942        assert_eq!(stats.bash_count, 1);
2943    }
2944
2945    /// `tool_use_result` shapes that aren't subagent runs (e.g. AskUserQuestion)
2946    /// parse leniently into the all-`Option` [`SubagentResult`] with empty
2947    /// accounting rather than failing, so callers can probe without panicking.
2948    #[test]
2949    fn test_subagent_result_absent_for_non_task_result() {
2950        let json = r#"{
2951            "type":"user",
2952            "message":{"role":"user","content":[{"type":"text","text":"hi"}]},
2953            "session_id":"622ae0c3-3d50-4fa7-9ee0-69d691238c6d",
2954            "tool_use_result":{"questions":[],"answers":{"Color":"Blue"}}
2955        }"#;
2956
2957        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
2958        let user = match output {
2959            ClaudeOutput::User(u) => u,
2960            _ => panic!("Expected User message"),
2961        };
2962
2963        let result = user.subagent_result().expect("lenient parse");
2964        assert_eq!(result.total_tokens, None);
2965        assert_eq!(result.agent_type, None);
2966    }
2967
2968    #[test]
2969    fn test_init_fast_mode_reason_and_mcp_server_errors_fully_wrapped() {
2970        use serde_json::Value;
2971
2972        let raw: Value = serde_json::from_str(
2973            r#"{
2974            "type":"system","subtype":"init","session_id":"s1","uuid":"u1",
2975            "fast_mode_state":"off",
2976            "fast_mode_disabled_reason":"not_first_party",
2977            "mcp_server_errors":[{"name":"broken","type":"invalid_config","message":"url entry with no type"}]
2978        }"#,
2979        )
2980        .unwrap();
2981        crate::io::assert_fully_wrapped(&raw);
2982
2983        let output: ClaudeOutput = serde_json::from_value(raw).unwrap();
2984        let ClaudeOutput::System(sys) = output else {
2985            panic!("expected System");
2986        };
2987        let init = sys.as_init().expect("parses as init");
2988        assert_eq!(
2989            init.fast_mode_disabled_reason,
2990            Some(crate::FastModeDisabledReason::NotFirstParty)
2991        );
2992        let errs = init.mcp_server_errors.unwrap();
2993        assert_eq!(errs.len(), 1);
2994        assert_eq!(errs[0].name, "broken");
2995        assert_eq!(errs[0].error_type, "invalid_config");
2996    }
2997
2998    #[test]
2999    fn test_code_change_published_fully_wrapped() {
3000        use super::{KnownSystemEvent, SystemSubtype};
3001        use serde_json::Value;
3002
3003        let raw: Value = serde_json::from_str(
3004            r#"{
3005            "type":"system","subtype":"code_change_published",
3006            "provider":"github","url":"https://github.com/owner/repo/pull/42",
3007            "repo":"owner/repo","identifier":"42",
3008            "uuid":"u1","session_id":"s1"
3009        }"#,
3010        )
3011        .unwrap();
3012        crate::io::assert_fully_wrapped(&raw);
3013
3014        let output: ClaudeOutput = serde_json::from_value(raw).unwrap();
3015        let ClaudeOutput::System(sys) = output else {
3016            panic!("expected System");
3017        };
3018        assert_eq!(sys.subtype, SystemSubtype::CodeChangePublished);
3019        let Some(KnownSystemEvent::CodeChangePublished(msg)) = sys.as_known_system_event() else {
3020            panic!("expected CodeChangePublished event");
3021        };
3022        assert_eq!(msg.provider, "github");
3023        assert_eq!(msg.repo, "owner/repo");
3024        assert_eq!(msg.identifier, "42");
3025    }
3026
3027    #[test]
3028    fn test_vcs_state_changed_fully_wrapped() {
3029        use super::{KnownSystemEvent, VcsMutationKind};
3030        use serde_json::Value;
3031
3032        for kind in ["commit", "push", "merge", "rebase"] {
3033            let raw: Value = serde_json::from_str(&format!(
3034                r#"{{"type":"system","subtype":"vcs_state_changed","kind":"{}","cwd":"/repo","uuid":"u1","session_id":"s1"}}"#,
3035                kind
3036            ))
3037            .unwrap();
3038            crate::io::assert_fully_wrapped(&raw);
3039
3040            let output: ClaudeOutput = serde_json::from_value(raw).unwrap();
3041            let ClaudeOutput::System(sys) = output else {
3042                panic!("expected System");
3043            };
3044            let Some(KnownSystemEvent::VcsStateChanged(msg)) = sys.as_known_system_event() else {
3045                panic!("expected VcsStateChanged event");
3046            };
3047            assert_eq!(msg.kind.as_str(), kind);
3048            assert!(!matches!(msg.kind, VcsMutationKind::Unknown(_)));
3049        }
3050
3051        // Unknown kinds are valid per the wire contract.
3052        let raw: Value = serde_json::from_str(
3053            r#"{"type":"system","subtype":"vcs_state_changed","kind":"tag","cwd":"/repo","uuid":"u2","session_id":"s2"}"#,
3054        )
3055        .unwrap();
3056        crate::io::assert_fully_wrapped(&raw);
3057        let output: ClaudeOutput = serde_json::from_value(raw).unwrap();
3058        let ClaudeOutput::System(sys) = output else {
3059            panic!("expected System");
3060        };
3061        let Some(KnownSystemEvent::VcsStateChanged(msg)) = sys.as_known_system_event() else {
3062            panic!("expected VcsStateChanged event");
3063        };
3064        assert_eq!(msg.kind, VcsMutationKind::Unknown("tag".to_string()));
3065    }
3066
3067    #[test]
3068    fn test_assistant_aborted_and_resume_flags_roundtrip() {
3069        let json = r#"{
3070            "type":"assistant",
3071            "message":{"id":"msg_1","role":"assistant","model":"claude-3","content":[{"type":"text","text":"partial"}]},
3072            "session_id":"s1",
3073            "aborted":true,
3074            "resumed_from_incomplete_thinking":true
3075        }"#;
3076        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
3077        let ClaudeOutput::Assistant(msg) = &output else {
3078            panic!("expected Assistant");
3079        };
3080        assert_eq!(msg.aborted, Some(true));
3081        assert_eq!(msg.resumed_from_incomplete_thinking, Some(true));
3082        let reserialized = serde_json::to_string(&output).unwrap();
3083        assert!(reserialized.contains("\"aborted\":true"));
3084        assert!(reserialized.contains("\"resumed_from_incomplete_thinking\":true"));
3085
3086        // Absent flags stay absent on the wire.
3087        let json = r#"{
3088            "type":"assistant",
3089            "message":{"id":"msg_2","role":"assistant","model":"claude-3","content":[]},
3090            "session_id":"s2"
3091        }"#;
3092        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
3093        let reserialized = serde_json::to_string(&output).unwrap();
3094        assert!(!reserialized.contains("aborted"));
3095        assert!(!reserialized.contains("resumed_from_incomplete_thinking"));
3096    }
3097
3098    #[test]
3099    fn test_user_tool_result_meta_roundtrip() {
3100        let json = r#"{
3101            "type":"user",
3102            "message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_1","content":"denied"}]},
3103            "session_id":"622ae0c3-3d50-4fa7-9ee0-69d691238c6d",
3104            "tool_result_meta":[
3105                {"id":"toolu_1","non_execution_kind":"user-rejected","user_feedback":"use the staging db"},
3106                {"id":"toolu_2","non_execution_kind":"permission-rule"}
3107            ]
3108        }"#;
3109        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
3110        let ClaudeOutput::User(user) = &output else {
3111            panic!("expected User");
3112        };
3113        let meta = user.tool_result_meta.as_ref().unwrap();
3114        assert_eq!(meta.len(), 2);
3115        assert_eq!(meta[0].non_execution_kind, "user-rejected");
3116        assert_eq!(meta[0].user_feedback.as_deref(), Some("use the staging db"));
3117        assert_eq!(meta[1].user_feedback, None);
3118
3119        let reserialized = serde_json::to_string(&output).unwrap();
3120        assert!(reserialized.contains("\"non_execution_kind\":\"user-rejected\""));
3121        assert!(!reserialized.contains("\"user_feedback\":null"));
3122    }
3123}