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};
8use super::rate_limit::RateLimitInfo;
9use crate::tool_inputs::TodoStatus;
10
11/// Known system message subtypes.
12///
13/// The Claude CLI emits system messages with a `subtype` field indicating what
14/// kind of system event occurred. This enum captures the known subtypes while
15/// preserving unknown values via the `Unknown` variant for forward compatibility.
16#[derive(Debug, Clone, PartialEq, Eq, Hash)]
17pub enum SystemSubtype {
18    Init,
19    Status,
20    CompactBoundary,
21    ThinkingTokens,
22    TaskStarted,
23    TaskProgress,
24    TaskUpdated,
25    TaskNotification,
26    ApiRetry,
27    ControlRequestProgress,
28    ModelRefusalFallback,
29    ModelRefusalNoFallback,
30    LocalCommandOutput,
31    HookStarted,
32    HookProgress,
33    HookResponse,
34    PluginInstall,
35    BackgroundTasksChanged,
36    SessionStateChanged,
37    WorkerShuttingDown,
38    CommandsChanged,
39    Notification,
40    FilesPersisted,
41    MemoryRecall,
42    ElicitationComplete,
43    PermissionDenied,
44    MirrorError,
45    Informational,
46    CodeChangePublished,
47    VcsStateChanged,
48    FeedbackDraftQueued,
49    CloudSessionDelta,
50    DevIntent,
51    TurnHandoffAvailable,
52    TurnPreempted,
53    PeerMessageHold,
54    PerTurnEffortChanged,
55    SessionTitleChanged,
56    SessionWritesLost,
57    InstructionSizeWarning,
58    FileAttachmentsMissing,
59    PermissionCheckStatus,
60    InheritedAsksSettled,
61    LateAllowNotRun,
62    ShellCwd,
63    TaskListStatuses,
64    UiFocus,
65    UiInvalidate,
66    UiLog,
67    UiNotify,
68    UiNotifyCancel,
69    UiPanes,
70    UiPlaced,
71    UiScroll,
72    UiStatus,
73    UiToast,
74    /// A subtype not yet known to this version of the crate.
75    Unknown(String),
76}
77
78impl SystemSubtype {
79    pub fn as_str(&self) -> &str {
80        match self {
81            Self::Init => "init",
82            Self::Status => "status",
83            Self::CompactBoundary => "compact_boundary",
84            Self::ThinkingTokens => "thinking_tokens",
85            Self::TaskStarted => "task_started",
86            Self::TaskProgress => "task_progress",
87            Self::TaskUpdated => "task_updated",
88            Self::TaskNotification => "task_notification",
89            Self::ApiRetry => "api_retry",
90            Self::ControlRequestProgress => "control_request_progress",
91            Self::ModelRefusalFallback => "model_refusal_fallback",
92            Self::ModelRefusalNoFallback => "model_refusal_no_fallback",
93            Self::LocalCommandOutput => "local_command_output",
94            Self::HookStarted => "hook_started",
95            Self::HookProgress => "hook_progress",
96            Self::HookResponse => "hook_response",
97            Self::PluginInstall => "plugin_install",
98            Self::BackgroundTasksChanged => "background_tasks_changed",
99            Self::SessionStateChanged => "session_state_changed",
100            Self::WorkerShuttingDown => "worker_shutting_down",
101            Self::CommandsChanged => "commands_changed",
102            Self::Notification => "notification",
103            Self::FilesPersisted => "files_persisted",
104            Self::MemoryRecall => "memory_recall",
105            Self::ElicitationComplete => "elicitation_complete",
106            Self::PermissionDenied => "permission_denied",
107            Self::MirrorError => "mirror_error",
108            Self::Informational => "informational",
109            Self::CodeChangePublished => "code_change_published",
110            Self::VcsStateChanged => "vcs_state_changed",
111            Self::FeedbackDraftQueued => "feedback_draft_queued",
112            Self::CloudSessionDelta => "cloud_session_delta",
113            Self::DevIntent => "dev_intent",
114            Self::TurnHandoffAvailable => "turn_handoff_available",
115            Self::TurnPreempted => "turn_preempted",
116            Self::PeerMessageHold => "peer_message_hold",
117            Self::PerTurnEffortChanged => "per_turn_effort_changed",
118            Self::SessionTitleChanged => "session_title_changed",
119            Self::SessionWritesLost => "session_writes_lost",
120            Self::InstructionSizeWarning => "instruction_size_warning",
121            Self::FileAttachmentsMissing => "file_attachments_missing",
122            Self::PermissionCheckStatus => "permission_check_status",
123            Self::InheritedAsksSettled => "inherited_asks_settled",
124            Self::LateAllowNotRun => "late_allow_not_run",
125            Self::ShellCwd => "shell_cwd",
126            Self::TaskListStatuses => "task_list_statuses",
127            Self::UiFocus => "ui_focus",
128            Self::UiInvalidate => "ui_invalidate",
129            Self::UiLog => "ui_log",
130            Self::UiNotify => "ui_notify",
131            Self::UiNotifyCancel => "ui_notify_cancel",
132            Self::UiPanes => "ui_panes",
133            Self::UiPlaced => "ui_placed",
134            Self::UiScroll => "ui_scroll",
135            Self::UiStatus => "ui_status",
136            Self::UiToast => "ui_toast",
137            Self::Unknown(s) => s.as_str(),
138        }
139    }
140}
141
142impl fmt::Display for SystemSubtype {
143    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
144        f.write_str(self.as_str())
145    }
146}
147
148impl From<&str> for SystemSubtype {
149    fn from(s: &str) -> Self {
150        match s {
151            "init" => Self::Init,
152            "status" => Self::Status,
153            "compact_boundary" => Self::CompactBoundary,
154            "thinking_tokens" => Self::ThinkingTokens,
155            "task_started" => Self::TaskStarted,
156            "task_progress" => Self::TaskProgress,
157            "task_updated" => Self::TaskUpdated,
158            "task_notification" => Self::TaskNotification,
159            "api_retry" => Self::ApiRetry,
160            "control_request_progress" => Self::ControlRequestProgress,
161            "model_refusal_fallback" => Self::ModelRefusalFallback,
162            "model_refusal_no_fallback" => Self::ModelRefusalNoFallback,
163            "local_command_output" => Self::LocalCommandOutput,
164            "hook_started" => Self::HookStarted,
165            "hook_progress" => Self::HookProgress,
166            "hook_response" => Self::HookResponse,
167            "plugin_install" => Self::PluginInstall,
168            "background_tasks_changed" => Self::BackgroundTasksChanged,
169            "session_state_changed" => Self::SessionStateChanged,
170            "worker_shutting_down" => Self::WorkerShuttingDown,
171            "commands_changed" => Self::CommandsChanged,
172            "notification" => Self::Notification,
173            "files_persisted" => Self::FilesPersisted,
174            "memory_recall" => Self::MemoryRecall,
175            "elicitation_complete" => Self::ElicitationComplete,
176            "permission_denied" => Self::PermissionDenied,
177            "mirror_error" => Self::MirrorError,
178            "informational" => Self::Informational,
179            "code_change_published" => Self::CodeChangePublished,
180            "vcs_state_changed" => Self::VcsStateChanged,
181            "feedback_draft_queued" => Self::FeedbackDraftQueued,
182            "cloud_session_delta" => Self::CloudSessionDelta,
183            "dev_intent" => Self::DevIntent,
184            "turn_handoff_available" => Self::TurnHandoffAvailable,
185            "turn_preempted" => Self::TurnPreempted,
186            "peer_message_hold" => Self::PeerMessageHold,
187            "per_turn_effort_changed" => Self::PerTurnEffortChanged,
188            "session_title_changed" => Self::SessionTitleChanged,
189            "session_writes_lost" => Self::SessionWritesLost,
190            "instruction_size_warning" => Self::InstructionSizeWarning,
191            "file_attachments_missing" => Self::FileAttachmentsMissing,
192            "permission_check_status" => Self::PermissionCheckStatus,
193            "inherited_asks_settled" => Self::InheritedAsksSettled,
194            "late_allow_not_run" => Self::LateAllowNotRun,
195            "shell_cwd" => Self::ShellCwd,
196            "task_list_statuses" => Self::TaskListStatuses,
197            "ui_focus" => Self::UiFocus,
198            "ui_invalidate" => Self::UiInvalidate,
199            "ui_log" => Self::UiLog,
200            "ui_notify" => Self::UiNotify,
201            "ui_notify_cancel" => Self::UiNotifyCancel,
202            "ui_panes" => Self::UiPanes,
203            "ui_placed" => Self::UiPlaced,
204            "ui_scroll" => Self::UiScroll,
205            "ui_status" => Self::UiStatus,
206            "ui_toast" => Self::UiToast,
207            other => Self::Unknown(other.to_string()),
208        }
209    }
210}
211
212impl Serialize for SystemSubtype {
213    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
214        serializer.serialize_str(self.as_str())
215    }
216}
217
218impl<'de> Deserialize<'de> for SystemSubtype {
219    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
220        let s = String::deserialize(deserializer)?;
221        Ok(Self::from(s.as_str()))
222    }
223}
224
225/// Known message roles.
226///
227/// Used in `MessageContent` and `AssistantMessageContent` to indicate the
228/// speaker of a message.
229#[derive(Debug, Clone, PartialEq, Eq, Hash)]
230pub enum MessageRole {
231    User,
232    Assistant,
233    /// A role not yet known to this version of the crate.
234    Unknown(String),
235}
236
237impl MessageRole {
238    pub fn as_str(&self) -> &str {
239        match self {
240            Self::User => "user",
241            Self::Assistant => "assistant",
242            Self::Unknown(s) => s.as_str(),
243        }
244    }
245}
246
247impl fmt::Display for MessageRole {
248    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
249        f.write_str(self.as_str())
250    }
251}
252
253impl From<&str> for MessageRole {
254    fn from(s: &str) -> Self {
255        match s {
256            "user" => Self::User,
257            "assistant" => Self::Assistant,
258            other => Self::Unknown(other.to_string()),
259        }
260    }
261}
262
263impl Serialize for MessageRole {
264    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
265        serializer.serialize_str(self.as_str())
266    }
267}
268
269impl<'de> Deserialize<'de> for MessageRole {
270    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
271        let s = String::deserialize(deserializer)?;
272        Ok(Self::from(s.as_str()))
273    }
274}
275
276/// What triggered a context compaction.
277#[derive(Debug, Clone, PartialEq, Eq, Hash)]
278pub enum CompactionTrigger {
279    /// Automatic compaction triggered by token limit.
280    Auto,
281    /// User-initiated compaction (e.g., /compact command).
282    Manual,
283    /// A trigger not yet known to this version of the crate.
284    Unknown(String),
285}
286
287impl CompactionTrigger {
288    pub fn as_str(&self) -> &str {
289        match self {
290            Self::Auto => "auto",
291            Self::Manual => "manual",
292            Self::Unknown(s) => s.as_str(),
293        }
294    }
295}
296
297impl fmt::Display for CompactionTrigger {
298    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
299        f.write_str(self.as_str())
300    }
301}
302
303impl From<&str> for CompactionTrigger {
304    fn from(s: &str) -> Self {
305        match s {
306            "auto" => Self::Auto,
307            "manual" => Self::Manual,
308            other => Self::Unknown(other.to_string()),
309        }
310    }
311}
312
313impl Serialize for CompactionTrigger {
314    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
315        serializer.serialize_str(self.as_str())
316    }
317}
318
319impl<'de> Deserialize<'de> for CompactionTrigger {
320    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
321        let s = String::deserialize(deserializer)?;
322        Ok(Self::from(s.as_str()))
323    }
324}
325
326/// Reason why the assistant stopped generating.
327#[derive(Debug, Clone, PartialEq, Eq, Hash)]
328pub enum StopReason {
329    /// The assistant reached a natural end of its turn.
330    EndTurn,
331    /// The response hit the maximum token limit.
332    MaxTokens,
333    /// The assistant wants to use a tool.
334    ToolUse,
335    /// A stop reason not yet known to this version of the crate.
336    Unknown(String),
337}
338
339impl StopReason {
340    pub fn as_str(&self) -> &str {
341        match self {
342            Self::EndTurn => "end_turn",
343            Self::MaxTokens => "max_tokens",
344            Self::ToolUse => "tool_use",
345            Self::Unknown(s) => s.as_str(),
346        }
347    }
348}
349
350impl fmt::Display for StopReason {
351    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
352        f.write_str(self.as_str())
353    }
354}
355
356impl From<&str> for StopReason {
357    fn from(s: &str) -> Self {
358        match s {
359            "end_turn" => Self::EndTurn,
360            "max_tokens" => Self::MaxTokens,
361            "tool_use" => Self::ToolUse,
362            other => Self::Unknown(other.to_string()),
363        }
364    }
365}
366
367impl Serialize for StopReason {
368    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
369        serializer.serialize_str(self.as_str())
370    }
371}
372
373impl<'de> Deserialize<'de> for StopReason {
374    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
375        let s = String::deserialize(deserializer)?;
376        Ok(Self::from(s.as_str()))
377    }
378}
379
380/// How the API key was sourced for the session.
381#[derive(Debug, Clone, PartialEq, Eq, Hash)]
382pub enum ApiKeySource {
383    /// No API key provided.
384    None,
385    User,
386    Project,
387    Org,
388    Temporary,
389    Oauth,
390    /// A source not yet known to this version of the crate.
391    Unknown(String),
392}
393
394impl ApiKeySource {
395    pub fn as_str(&self) -> &str {
396        match self {
397            Self::None => "none",
398            Self::User => "user",
399            Self::Project => "project",
400            Self::Org => "org",
401            Self::Temporary => "temporary",
402            Self::Oauth => "oauth",
403            Self::Unknown(s) => s.as_str(),
404        }
405    }
406}
407
408impl fmt::Display for ApiKeySource {
409    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
410        f.write_str(self.as_str())
411    }
412}
413
414impl From<&str> for ApiKeySource {
415    fn from(s: &str) -> Self {
416        match s {
417            "none" => Self::None,
418            "user" => Self::User,
419            "project" => Self::Project,
420            "org" => Self::Org,
421            "temporary" => Self::Temporary,
422            "oauth" => Self::Oauth,
423            other => Self::Unknown(other.to_string()),
424        }
425    }
426}
427
428impl Serialize for ApiKeySource {
429    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
430        serializer.serialize_str(self.as_str())
431    }
432}
433
434impl<'de> Deserialize<'de> for ApiKeySource {
435    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
436        let s = String::deserialize(deserializer)?;
437        Ok(Self::from(s.as_str()))
438    }
439}
440
441/// Output formatting style for the session.
442#[derive(Debug, Clone, PartialEq, Eq, Hash)]
443pub enum OutputStyle {
444    /// Default output style.
445    Default,
446    /// A style not yet known to this version of the crate.
447    Unknown(String),
448}
449
450impl OutputStyle {
451    pub fn as_str(&self) -> &str {
452        match self {
453            Self::Default => "default",
454            Self::Unknown(s) => s.as_str(),
455        }
456    }
457}
458
459impl fmt::Display for OutputStyle {
460    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
461        f.write_str(self.as_str())
462    }
463}
464
465impl From<&str> for OutputStyle {
466    fn from(s: &str) -> Self {
467        match s {
468            "default" => Self::Default,
469            other => Self::Unknown(other.to_string()),
470        }
471    }
472}
473
474impl Serialize for OutputStyle {
475    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
476        serializer.serialize_str(self.as_str())
477    }
478}
479
480impl<'de> Deserialize<'de> for OutputStyle {
481    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
482        let s = String::deserialize(deserializer)?;
483        Ok(Self::from(s.as_str()))
484    }
485}
486
487/// Permission mode reported in init messages.
488#[derive(Debug, Clone, PartialEq, Eq, Hash)]
489pub enum InitPermissionMode {
490    /// Default permission mode.
491    Default,
492    AcceptEdits,
493    BypassPermissions,
494    Plan,
495    DontAsk,
496    Auto,
497    /// A mode not yet known to this version of the crate.
498    Unknown(String),
499}
500
501impl InitPermissionMode {
502    pub fn as_str(&self) -> &str {
503        match self {
504            Self::Default => "default",
505            Self::AcceptEdits => "acceptEdits",
506            Self::BypassPermissions => "bypassPermissions",
507            Self::Plan => "plan",
508            Self::DontAsk => "dontAsk",
509            Self::Auto => "auto",
510            Self::Unknown(s) => s.as_str(),
511        }
512    }
513}
514
515impl fmt::Display for InitPermissionMode {
516    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
517        f.write_str(self.as_str())
518    }
519}
520
521impl From<&str> for InitPermissionMode {
522    fn from(s: &str) -> Self {
523        match s {
524            "default" => Self::Default,
525            "acceptEdits" => Self::AcceptEdits,
526            "bypassPermissions" => Self::BypassPermissions,
527            "plan" => Self::Plan,
528            "dontAsk" => Self::DontAsk,
529            "auto" => Self::Auto,
530            other => Self::Unknown(other.to_string()),
531        }
532    }
533}
534
535impl Serialize for InitPermissionMode {
536    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
537        serializer.serialize_str(self.as_str())
538    }
539}
540
541impl<'de> Deserialize<'de> for InitPermissionMode {
542    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
543        let s = String::deserialize(deserializer)?;
544        Ok(Self::from(s.as_str()))
545    }
546}
547
548/// Status of an ongoing operation (e.g., context compaction).
549#[derive(Debug, Clone, PartialEq, Eq, Hash)]
550pub enum StatusMessageStatus {
551    /// Context compaction is in progress.
552    Compacting,
553    /// The CLI is issuing a request.
554    Requesting,
555    /// A status not yet known to this version of the crate.
556    Unknown(String),
557}
558
559impl StatusMessageStatus {
560    pub fn as_str(&self) -> &str {
561        match self {
562            Self::Compacting => "compacting",
563            Self::Requesting => "requesting",
564            Self::Unknown(s) => s.as_str(),
565        }
566    }
567}
568
569impl fmt::Display for StatusMessageStatus {
570    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
571        f.write_str(self.as_str())
572    }
573}
574
575impl From<&str> for StatusMessageStatus {
576    fn from(s: &str) -> Self {
577        match s {
578            "compacting" => Self::Compacting,
579            "requesting" => Self::Requesting,
580            other => Self::Unknown(other.to_string()),
581        }
582    }
583}
584
585impl Serialize for StatusMessageStatus {
586    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
587        serializer.serialize_str(self.as_str())
588    }
589}
590
591impl<'de> Deserialize<'de> for StatusMessageStatus {
592    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
593        let s = String::deserialize(deserializer)?;
594        Ok(Self::from(s.as_str()))
595    }
596}
597
598/// Serialize an optional UUID as a string
599pub(crate) fn serialize_optional_uuid<S>(
600    uuid: &Option<Uuid>,
601    serializer: S,
602) -> Result<S::Ok, S::Error>
603where
604    S: Serializer,
605{
606    match uuid {
607        Some(id) => serializer.serialize_str(&id.to_string()),
608        None => serializer.serialize_none(),
609    }
610}
611
612/// Deserialize an optional UUID from a string
613pub(crate) fn deserialize_optional_uuid<'de, D>(deserializer: D) -> Result<Option<Uuid>, D::Error>
614where
615    D: Deserializer<'de>,
616{
617    let opt_str: Option<String> = Option::deserialize(deserializer)?;
618    match opt_str {
619        Some(s) => Uuid::parse_str(&s)
620            .map(Some)
621            .map_err(serde::de::Error::custom),
622        None => Ok(None),
623    }
624}
625
626/// Message provenance. The `kind` field is the stable discriminator; variant
627/// specific fields are preserved in `extra` for forward-compatible access.
628#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
629pub struct MessageOrigin {
630    pub kind: String,
631    #[serde(flatten)]
632    pub extra: serde_json::Map<String, Value>,
633}
634
635/// Metadata attached when user-visible transcript content summarizes prior messages.
636#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
637pub struct SummarizeMetadata {
638    pub messages_summarized: u64,
639    #[serde(default, skip_serializing_if = "Option::is_none")]
640    pub user_context: Option<String>,
641    #[serde(default, skip_serializing_if = "Option::is_none")]
642    pub direction: Option<String>,
643}
644
645/// MCP metadata passed through on user-message wrappers.
646#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
647pub struct McpMeta {
648    #[serde(default, skip_serializing_if = "Option::is_none", rename = "_meta")]
649    pub meta: Option<Value>,
650    #[serde(default, skip_serializing_if = "Option::is_none")]
651    pub structured_content: Option<Value>,
652    /// The `resource_link` content blocks the MCP tool returned, collected
653    /// from the raw result before the CLI rewrites each into the
654    /// `[Resource link: NAME] URI` text line the model reads. At most 50
655    /// links and 64 KiB serialized; absent when the result had none.
656    #[serde(default, skip_serializing_if = "Vec::is_empty")]
657    pub resource_links: Vec<ResourceLink>,
658}
659
660/// A file an MCP tool returned by reference — a `resource_link` content block
661/// as carried on [`McpMeta::resource_links`] and
662/// [`TaskNotificationMessage::resource_links`] (CLI 2.1.259+).
663#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
664pub struct ResourceLink {
665    pub uri: String,
666    pub name: String,
667    #[serde(default, skip_serializing_if = "Option::is_none")]
668    pub title: Option<String>,
669    #[serde(default, skip_serializing_if = "Option::is_none")]
670    pub description: Option<String>,
671    #[serde(default, skip_serializing_if = "Option::is_none", rename = "mimeType")]
672    pub mime_type: Option<String>,
673    #[serde(default, skip_serializing_if = "Option::is_none")]
674    pub size: Option<u64>,
675    #[serde(default, skip_serializing_if = "Option::is_none")]
676    pub annotations: Option<Value>,
677}
678
679/// Display metadata for a `tool_result` block carried on the user wrapper.
680#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
681pub struct ToolResultMeta {
682    /// The `tool_use_id` of the matching `tool_result` block.
683    pub id: String,
684    /// Harness-stamped reason an `is_error: true` result did not carry the
685    /// tool's own execution output (`user-rejected`, `permission-rule`,
686    /// `automode-*`, `interrupted`, `cancelled`). Open set — treat
687    /// unrecognized values as valid reasons; absent means the tool ran to
688    /// completion. Optional since CLI 2.1.276, when an entry may carry a
689    /// [`remedy`](Self::remedy) alone.
690    #[serde(default, skip_serializing_if = "Option::is_none")]
691    pub non_execution_kind: Option<String>,
692    /// The deny comment a human typed at a permission prompt, when present.
693    #[serde(default, skip_serializing_if = "Option::is_none")]
694    pub user_feedback: Option<String>,
695    /// The fix a host can offer for what the result reports (CLI 2.1.276+).
696    /// May be present on a result that did run (a staged settings write, a
697    /// sandbox violation on exit 0), so read whether the call ran from
698    /// [`non_execution_kind`](Self::non_execution_kind), not from this.
699    #[serde(default, skip_serializing_if = "Option::is_none")]
700    pub remedy: Option<ToolResultRemedy>,
701    /// How the call's permission check ended (CLI 2.1.293+). On a
702    /// subagent's messages (`parent_tool_use_id` set) entries carry only
703    /// this, so those messages do not say whether a call ran. Absent when
704    /// the call ended before its permission check, and on some results
705    /// built apart from the call's own run (a plugin hook's refusal, a
706    /// hook's rewrite of a denied result, a queued call a stop cancelled).
707    #[serde(default, skip_serializing_if = "Option::is_none")]
708    pub permission_decision: Option<ToolPermissionDecision>,
709    /// The name of the Claude Code built-in tool whose own completed run, in
710    /// the process that wrote this message, made the result. Stamped for
711    /// the few built-ins a host acts on; absent once a hook rewrote the
712    /// result, on a message read from a session file or taken from another
713    /// frame (a resumed session), on a result a client wrote (a handed-over
714    /// turn), and on a subagent's messages (CLI 2.1.317+).
715    #[serde(default, skip_serializing_if = "Option::is_none")]
716    pub built_in_tool: Option<String>,
717    /// Stands only beside [`built_in_tool`](Self::built_in_tool), and only
718    /// from a worker that takes its messages over Claude Code Remote. Its one
719    /// value today, `person_typed`, says a person typed (in the iOS, Android,
720    /// claude.ai or desktop app) every message that opened or joined the run
721    /// up to this call, as far as the messages show. Absent on any doubt;
722    /// read absence, and any value you do not know, as no (CLI 2.1.325+).
723    #[serde(default, skip_serializing_if = "Option::is_none")]
724    pub run_input: Option<String>,
725}
726
727/// [`ToolResultMeta::permission_decision`] — how a tool call's permission
728/// check ended, as Claude Code's `claude_code.tool.blocked_on_user` trace
729/// span reports it (CLI 2.1.293+).
730#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
731pub struct ToolPermissionDecision {
732    /// The outcome.
733    pub decision: PermissionDecisionOutcome,
734    /// What decided: `config`, `classifier`, `hook`, `user_temporary`,
735    /// `user_permanent`, `user_reject`, `user_abort`, or `invalid_input`,
736    /// `permission_updated_input_invalid` or `server_fallback_tombstone`
737    /// when bad input or the server ended the wait. In SDK sessions a rule
738    /// for this session or in the user's own settings reports
739    /// `user_temporary`, `user_permanent` or `user_reject` and other rules
740    /// report `config`; interactive sessions report every rule as `config`.
741    pub source: String,
742    /// The kind of reason the check gave when it decided by itself, such as
743    /// `rule` whenever a rule decided, or `classifier` for an auto-mode
744    /// allow (which reports source `config`). Absent when a person or the
745    /// SDK host answered, when the outcome was still a question, and for
746    /// `user_abort` and the last three sources above.
747    #[serde(default, skip_serializing_if = "Option::is_none")]
748    pub reason_type: Option<PermissionDecisionReasonType>,
749    /// Set only in a `claude plugin eval` run: `applied` when the call was
750    /// allowed because a plugin's permission hook allowed it where the
751    /// eval's own check did not, `refused` when a deny rule blocked the call
752    /// (or it could not be checked against the deny rules) even though a
753    /// plugin's hook allowed it (CLI 2.1.327+).
754    #[serde(default, skip_serializing_if = "Option::is_none")]
755    pub plugin_approval: Option<PluginApproval>,
756    /// Beside a `classifier` [`reason_type`](Self::reason_type): the
757    /// server-side auto-mode classifier named an entry in the session's
758    /// auto-mode settings — an `allow` exception for an accept, a
759    /// `soft_deny` entry for a reject — and this is that entry
760    /// (CLI 2.1.319+).
761    #[serde(default, skip_serializing_if = "Option::is_none")]
762    pub auto_mode_rule: Option<AutoModeRule>,
763}
764
765/// [`ToolPermissionDecision::plugin_approval`] — how a plugin's permission
766/// hook figured in a `claude plugin eval` call (CLI 2.1.327+).
767#[derive(Debug, Clone, PartialEq, Eq, Hash)]
768pub enum PluginApproval {
769    /// The call ran because a plugin's hook allowed it.
770    Applied,
771    /// A deny rule blocked the call despite a plugin's hook allowing it.
772    Refused,
773    /// A value not yet known to this version of the crate.
774    Unknown(String),
775}
776
777impl PluginApproval {
778    pub fn as_str(&self) -> &str {
779        match self {
780            Self::Applied => "applied",
781            Self::Refused => "refused",
782            Self::Unknown(s) => s.as_str(),
783        }
784    }
785}
786
787impl fmt::Display for PluginApproval {
788    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
789        f.write_str(self.as_str())
790    }
791}
792
793impl From<&str> for PluginApproval {
794    fn from(s: &str) -> Self {
795        match s {
796            "applied" => Self::Applied,
797            "refused" => Self::Refused,
798            other => Self::Unknown(other.to_string()),
799        }
800    }
801}
802
803impl Serialize for PluginApproval {
804    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
805        serializer.serialize_str(self.as_str())
806    }
807}
808
809impl<'de> Deserialize<'de> for PluginApproval {
810    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
811        let s = String::deserialize(deserializer)?;
812        Ok(Self::from(s.as_str()))
813    }
814}
815
816/// [`ToolPermissionDecision::auto_mode_rule`] — the auto-mode settings entry
817/// the classifier named (CLI 2.1.319+).
818#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
819pub struct AutoModeRule {
820    /// Which list the entry is on.
821    pub list: AutoModeRuleList,
822    /// The entry's name.
823    pub name: String,
824}
825
826/// [`AutoModeRule::list`].
827#[derive(Debug, Clone, PartialEq, Eq, Hash)]
828pub enum AutoModeRuleList {
829    /// An `allow` exception.
830    Allow,
831    /// A `soft_deny` entry.
832    SoftDeny,
833    /// A list not yet known to this version of the crate.
834    Unknown(String),
835}
836
837impl AutoModeRuleList {
838    pub fn as_str(&self) -> &str {
839        match self {
840            Self::Allow => "allow",
841            Self::SoftDeny => "soft_deny",
842            Self::Unknown(s) => s.as_str(),
843        }
844    }
845}
846
847impl fmt::Display for AutoModeRuleList {
848    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
849        f.write_str(self.as_str())
850    }
851}
852
853impl From<&str> for AutoModeRuleList {
854    fn from(s: &str) -> Self {
855        match s {
856            "allow" => Self::Allow,
857            "soft_deny" => Self::SoftDeny,
858            other => Self::Unknown(other.to_string()),
859        }
860    }
861}
862
863impl Serialize for AutoModeRuleList {
864    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
865        serializer.serialize_str(self.as_str())
866    }
867}
868
869impl<'de> Deserialize<'de> for AutoModeRuleList {
870    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
871        let s = String::deserialize(deserializer)?;
872        Ok(Self::from(s.as_str()))
873    }
874}
875
876/// [`ToolPermissionDecision::decision`].
877#[derive(Debug, Clone, PartialEq, Eq, Hash)]
878pub enum PermissionDecisionOutcome {
879    /// The call was allowed.
880    Accept,
881    /// The call was denied.
882    Reject,
883    /// The permission wait was cancelled.
884    Cancelled,
885    /// An outcome not yet known to this version of the crate.
886    Unknown(String),
887}
888
889impl PermissionDecisionOutcome {
890    pub fn as_str(&self) -> &str {
891        match self {
892            Self::Accept => "accept",
893            Self::Reject => "reject",
894            Self::Cancelled => "cancelled",
895            Self::Unknown(s) => s.as_str(),
896        }
897    }
898}
899
900impl fmt::Display for PermissionDecisionOutcome {
901    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
902        f.write_str(self.as_str())
903    }
904}
905
906impl From<&str> for PermissionDecisionOutcome {
907    fn from(s: &str) -> Self {
908        match s {
909            "accept" => Self::Accept,
910            "reject" => Self::Reject,
911            "cancelled" => Self::Cancelled,
912            other => Self::Unknown(other.to_string()),
913        }
914    }
915}
916
917impl Serialize for PermissionDecisionOutcome {
918    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
919        serializer.serialize_str(self.as_str())
920    }
921}
922
923impl<'de> Deserialize<'de> for PermissionDecisionOutcome {
924    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
925        let s = String::deserialize(deserializer)?;
926        Ok(Self::from(s.as_str()))
927    }
928}
929
930/// [`ToolPermissionDecision::reason_type`] — the kind of reason a
931/// self-decided permission check gave.
932#[derive(Debug, Clone, PartialEq, Eq, Hash)]
933pub enum PermissionDecisionReasonType {
934    /// A permission rule decided.
935    Rule,
936    /// The permission mode decided.
937    Mode,
938    /// The results of a compound command's subcommands decided.
939    SubcommandResults,
940    /// The `--permission-prompt-tool` decided.
941    PermissionPromptTool,
942    /// A hook decided.
943    Hook,
944    /// An async agent's permission handling decided.
945    AsyncAgent,
946    /// A sandbox override decided.
947    SandboxOverride,
948    /// The working-directory check decided.
949    WorkingDir,
950    /// A safety check decided.
951    SafetyCheck,
952    /// The auto-mode classifier decided.
953    Classifier,
954    /// Some other reason.
955    Other,
956    /// A reason type not yet known to this version of the crate.
957    Unknown(String),
958}
959
960impl PermissionDecisionReasonType {
961    pub fn as_str(&self) -> &str {
962        match self {
963            Self::Rule => "rule",
964            Self::Mode => "mode",
965            Self::SubcommandResults => "subcommandResults",
966            Self::PermissionPromptTool => "permissionPromptTool",
967            Self::Hook => "hook",
968            Self::AsyncAgent => "asyncAgent",
969            Self::SandboxOverride => "sandboxOverride",
970            Self::WorkingDir => "workingDir",
971            Self::SafetyCheck => "safetyCheck",
972            Self::Classifier => "classifier",
973            Self::Other => "other",
974            Self::Unknown(s) => s.as_str(),
975        }
976    }
977}
978
979impl fmt::Display for PermissionDecisionReasonType {
980    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
981        f.write_str(self.as_str())
982    }
983}
984
985impl From<&str> for PermissionDecisionReasonType {
986    fn from(s: &str) -> Self {
987        match s {
988            "rule" => Self::Rule,
989            "mode" => Self::Mode,
990            "subcommandResults" => Self::SubcommandResults,
991            "permissionPromptTool" => Self::PermissionPromptTool,
992            "hook" => Self::Hook,
993            "asyncAgent" => Self::AsyncAgent,
994            "sandboxOverride" => Self::SandboxOverride,
995            "workingDir" => Self::WorkingDir,
996            "safetyCheck" => Self::SafetyCheck,
997            "classifier" => Self::Classifier,
998            "other" => Self::Other,
999            other => Self::Unknown(other.to_string()),
1000        }
1001    }
1002}
1003
1004impl Serialize for PermissionDecisionReasonType {
1005    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1006        serializer.serialize_str(self.as_str())
1007    }
1008}
1009
1010impl<'de> Deserialize<'de> for PermissionDecisionReasonType {
1011    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1012        let s = String::deserialize(deserializer)?;
1013        Ok(Self::from(s.as_str()))
1014    }
1015}
1016
1017/// The fix a host can offer for what a `tool_result` reports, stamped from
1018/// structured producer state (never parsed from the result text), carried
1019/// as [`ToolResultMeta::remedy`] (CLI 2.1.276+). Only the parameters the
1020/// [`kind`](Self::kind) needs are present.
1021#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1022pub struct ToolResultRemedy {
1023    /// What the host can fix. New kinds are additive — treat
1024    /// [`ToolResultRemedyKind::Unknown`] as no remedy.
1025    pub kind: ToolResultRemedyKind,
1026    /// `mcp_needs_auth` / `mcp_disabled`: the server names as configured.
1027    /// `mcp_required_missing`: the name patterns the agent definition
1028    /// requires that no connected server matches.
1029    #[serde(default, skip_serializing_if = "Option::is_none")]
1030    pub servers: Option<Vec<String>>,
1031    /// `auth_expired` / `auth_overridden` / `auth_missing_scope` /
1032    /// `design_needs_authorization`: whose login the fix names.
1033    #[serde(default, skip_serializing_if = "Option::is_none")]
1034    pub provider: Option<RemedyLoginProvider>,
1035    /// `outside_reads_blocked`: the path the read block refused, when the
1036    /// refusal names one. `staged_for_review`: the settings file the write
1037    /// was held for.
1038    #[serde(default, skip_serializing_if = "Option::is_none")]
1039    pub path: Option<String>,
1040    /// `outside_reads_blocked`: an organization policy sets the block, so
1041    /// the user cannot remove it. `auth_overridden`: the overriding
1042    /// credential was injected by the host environment, so nothing in this
1043    /// session can unset it.
1044    #[serde(default, skip_serializing_if = "Option::is_none")]
1045    pub managed: Option<bool>,
1046    /// `feature_disabled` / `policy_denied`: the feature that is off.
1047    #[serde(default, skip_serializing_if = "Option::is_none")]
1048    pub feature: Option<RemedyFeature>,
1049    /// `feature_disabled`: why the feature is off.
1050    #[serde(default, skip_serializing_if = "Option::is_none")]
1051    pub cause: Option<RemedyFeatureCause>,
1052    /// `policy_denied`: the verdict.
1053    #[serde(default, skip_serializing_if = "Option::is_none")]
1054    pub policy_kind: Option<RemedyPolicyKind>,
1055}
1056
1057/// What a host can fix for a tool result ([`ToolResultRemedy::kind`]).
1058#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1059pub enum ToolResultRemedyKind {
1060    /// An MCP server needs its login completed.
1061    McpNeedsAuth,
1062    /// An MCP server is disabled in settings.
1063    McpDisabled,
1064    /// The agent definition requires MCP servers that are not connected.
1065    McpRequiredMissing,
1066    /// The named login has expired.
1067    AuthExpired,
1068    /// A host-injected credential overrides the named login.
1069    AuthOverridden,
1070    /// The named login lacks a scope the call needed.
1071    AuthMissingScope,
1072    /// Claude Design needs its own authorization.
1073    DesignNeedsAuthorization,
1074    /// The command violated the sandbox policy.
1075    SandboxViolation,
1076    /// A read outside the working directories was refused.
1077    OutsideReadsBlocked,
1078    /// Memory is paused by `/pause-memory`.
1079    MemoryPaused,
1080    /// A feature is switched off; see [`ToolResultRemedy::cause`].
1081    FeatureDisabled,
1082    /// An organization policy denies a feature; see
1083    /// [`ToolResultRemedy::policy_kind`].
1084    PolicyDenied,
1085    /// The command's exec image exceeded the OS argument limit.
1086    SpawnArgLimit,
1087    /// A settings-file write was held for the machine owner's review.
1088    StagedForReview,
1089    /// The call did not run: a `claude-code-server` session's cloud
1090    /// environment was refused at the limit on containers running at once
1091    /// (CLI 2.1.328+).
1092    ContainerLimit,
1093    /// A remedy kind not yet known to this version of the crate.
1094    Unknown(String),
1095}
1096
1097impl ToolResultRemedyKind {
1098    pub fn as_str(&self) -> &str {
1099        match self {
1100            Self::McpNeedsAuth => "mcp_needs_auth",
1101            Self::McpDisabled => "mcp_disabled",
1102            Self::McpRequiredMissing => "mcp_required_missing",
1103            Self::AuthExpired => "auth_expired",
1104            Self::AuthOverridden => "auth_overridden",
1105            Self::AuthMissingScope => "auth_missing_scope",
1106            Self::DesignNeedsAuthorization => "design_needs_authorization",
1107            Self::SandboxViolation => "sandbox_violation",
1108            Self::OutsideReadsBlocked => "outside_reads_blocked",
1109            Self::MemoryPaused => "memory_paused",
1110            Self::FeatureDisabled => "feature_disabled",
1111            Self::PolicyDenied => "policy_denied",
1112            Self::SpawnArgLimit => "spawn_arg_limit",
1113            Self::StagedForReview => "staged_for_review",
1114            Self::ContainerLimit => "container_limit",
1115            Self::Unknown(s) => s.as_str(),
1116        }
1117    }
1118}
1119
1120impl fmt::Display for ToolResultRemedyKind {
1121    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1122        f.write_str(self.as_str())
1123    }
1124}
1125
1126impl From<&str> for ToolResultRemedyKind {
1127    fn from(s: &str) -> Self {
1128        match s {
1129            "mcp_needs_auth" => Self::McpNeedsAuth,
1130            "mcp_disabled" => Self::McpDisabled,
1131            "mcp_required_missing" => Self::McpRequiredMissing,
1132            "auth_expired" => Self::AuthExpired,
1133            "auth_overridden" => Self::AuthOverridden,
1134            "auth_missing_scope" => Self::AuthMissingScope,
1135            "design_needs_authorization" => Self::DesignNeedsAuthorization,
1136            "sandbox_violation" => Self::SandboxViolation,
1137            "outside_reads_blocked" => Self::OutsideReadsBlocked,
1138            "memory_paused" => Self::MemoryPaused,
1139            "feature_disabled" => Self::FeatureDisabled,
1140            "policy_denied" => Self::PolicyDenied,
1141            "spawn_arg_limit" => Self::SpawnArgLimit,
1142            "staged_for_review" => Self::StagedForReview,
1143            "container_limit" => Self::ContainerLimit,
1144            other => Self::Unknown(other.to_string()),
1145        }
1146    }
1147}
1148
1149impl Serialize for ToolResultRemedyKind {
1150    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1151        serializer.serialize_str(self.as_str())
1152    }
1153}
1154
1155impl<'de> Deserialize<'de> for ToolResultRemedyKind {
1156    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1157        let s = String::deserialize(deserializer)?;
1158        Ok(Self::from(s.as_str()))
1159    }
1160}
1161
1162/// Whose login a remedy names ([`ToolResultRemedy::provider`]).
1163#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1164pub enum RemedyLoginProvider {
1165    /// The claude.ai account (`/login`).
1166    ClaudeAi,
1167    /// Claude Design's own authorization (`/design login`).
1168    ClaudeDesign,
1169    /// A provider not yet known to this version of the crate.
1170    Unknown(String),
1171}
1172
1173impl RemedyLoginProvider {
1174    pub fn as_str(&self) -> &str {
1175        match self {
1176            Self::ClaudeAi => "claude_ai",
1177            Self::ClaudeDesign => "claude_design",
1178            Self::Unknown(s) => s.as_str(),
1179        }
1180    }
1181}
1182
1183impl fmt::Display for RemedyLoginProvider {
1184    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1185        f.write_str(self.as_str())
1186    }
1187}
1188
1189impl From<&str> for RemedyLoginProvider {
1190    fn from(s: &str) -> Self {
1191        match s {
1192            "claude_ai" => Self::ClaudeAi,
1193            "claude_design" => Self::ClaudeDesign,
1194            other => Self::Unknown(other.to_string()),
1195        }
1196    }
1197}
1198
1199impl Serialize for RemedyLoginProvider {
1200    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1201        serializer.serialize_str(self.as_str())
1202    }
1203}
1204
1205impl<'de> Deserialize<'de> for RemedyLoginProvider {
1206    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1207        let s = String::deserialize(deserializer)?;
1208        Ok(Self::from(s.as_str()))
1209    }
1210}
1211
1212/// The feature a `feature_disabled` / `policy_denied` remedy names
1213/// ([`ToolResultRemedy::feature`]).
1214#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1215pub enum RemedyFeature {
1216    Workflows,
1217    Artifacts,
1218    /// A feature not yet known to this version of the crate.
1219    Unknown(String),
1220}
1221
1222impl RemedyFeature {
1223    pub fn as_str(&self) -> &str {
1224        match self {
1225            Self::Workflows => "workflows",
1226            Self::Artifacts => "artifacts",
1227            Self::Unknown(s) => s.as_str(),
1228        }
1229    }
1230}
1231
1232impl fmt::Display for RemedyFeature {
1233    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1234        f.write_str(self.as_str())
1235    }
1236}
1237
1238impl From<&str> for RemedyFeature {
1239    fn from(s: &str) -> Self {
1240        match s {
1241            "workflows" => Self::Workflows,
1242            "artifacts" => Self::Artifacts,
1243            other => Self::Unknown(other.to_string()),
1244        }
1245    }
1246}
1247
1248impl Serialize for RemedyFeature {
1249    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1250        serializer.serialize_str(self.as_str())
1251    }
1252}
1253
1254impl<'de> Deserialize<'de> for RemedyFeature {
1255    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1256        let s = String::deserialize(deserializer)?;
1257        Ok(Self::from(s.as_str()))
1258    }
1259}
1260
1261/// Why a feature is off for a `feature_disabled` remedy
1262/// ([`ToolResultRemedy::cause`]).
1263#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1264pub enum RemedyFeatureCause {
1265    /// `CLAUDE_CODE_DISABLE_WORKFLOWS`, or `disableWorkflows` set by a
1266    /// settings layer above the user's own.
1267    ManagedSettings,
1268    /// An organization policy.
1269    OrgPolicy,
1270    /// Not launched for this account.
1271    Unavailable,
1272    /// The user's own `/config` setting is off (including a
1273    /// `disableWorkflows` in their own settings).
1274    UserSetting,
1275    /// This Claude Code process is not running on Bun, the runtime its
1276    /// binary is built with, and workflow scripts run only there
1277    /// (CLI 2.1.307+).
1278    UnsupportedRuntime,
1279    /// A cause not yet known to this version of the crate.
1280    Unknown(String),
1281}
1282
1283impl RemedyFeatureCause {
1284    pub fn as_str(&self) -> &str {
1285        match self {
1286            Self::ManagedSettings => "managed_settings",
1287            Self::OrgPolicy => "org_policy",
1288            Self::Unavailable => "unavailable",
1289            Self::UserSetting => "user_setting",
1290            Self::UnsupportedRuntime => "unsupported_runtime",
1291            Self::Unknown(s) => s.as_str(),
1292        }
1293    }
1294}
1295
1296impl fmt::Display for RemedyFeatureCause {
1297    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1298        f.write_str(self.as_str())
1299    }
1300}
1301
1302impl From<&str> for RemedyFeatureCause {
1303    fn from(s: &str) -> Self {
1304        match s {
1305            "managed_settings" => Self::ManagedSettings,
1306            "org_policy" => Self::OrgPolicy,
1307            "unavailable" => Self::Unavailable,
1308            "user_setting" => Self::UserSetting,
1309            "unsupported_runtime" => Self::UnsupportedRuntime,
1310            other => Self::Unknown(other.to_string()),
1311        }
1312    }
1313}
1314
1315impl Serialize for RemedyFeatureCause {
1316    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1317        serializer.serialize_str(self.as_str())
1318    }
1319}
1320
1321impl<'de> Deserialize<'de> for RemedyFeatureCause {
1322    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1323        let s = String::deserialize(deserializer)?;
1324        Ok(Self::from(s.as_str()))
1325    }
1326}
1327
1328/// The verdict behind a `policy_denied` remedy
1329/// ([`ToolResultRemedy::policy_kind`]).
1330#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1331pub enum RemedyPolicyKind {
1332    /// The organization's policy turns the feature off.
1333    OrgDenied,
1334    /// A HIPAA-regulated organization signed in earlier in this process;
1335    /// restarting clears it.
1336    Latched,
1337    /// A verdict not yet known to this version of the crate.
1338    Unknown(String),
1339}
1340
1341impl RemedyPolicyKind {
1342    pub fn as_str(&self) -> &str {
1343        match self {
1344            Self::OrgDenied => "org_denied",
1345            Self::Latched => "latched",
1346            Self::Unknown(s) => s.as_str(),
1347        }
1348    }
1349}
1350
1351impl fmt::Display for RemedyPolicyKind {
1352    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1353        f.write_str(self.as_str())
1354    }
1355}
1356
1357impl From<&str> for RemedyPolicyKind {
1358    fn from(s: &str) -> Self {
1359        match s {
1360            "org_denied" => Self::OrgDenied,
1361            "latched" => Self::Latched,
1362            other => Self::Unknown(other.to_string()),
1363        }
1364    }
1365}
1366
1367impl Serialize for RemedyPolicyKind {
1368    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1369        serializer.serialize_str(self.as_str())
1370    }
1371}
1372
1373impl<'de> Deserialize<'de> for RemedyPolicyKind {
1374    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1375        let s = String::deserialize(deserializer)?;
1376        Ok(Self::from(s.as_str()))
1377    }
1378}
1379
1380/// User message
1381#[derive(Debug, Clone, Serialize, Deserialize)]
1382pub struct UserMessage {
1383    pub message: MessageContent,
1384    #[serde(skip_serializing_if = "Option::is_none", alias = "sessionId")]
1385    #[serde(
1386        serialize_with = "serialize_optional_uuid",
1387        deserialize_with = "deserialize_optional_uuid"
1388    )]
1389    pub session_id: Option<Uuid>,
1390    /// Parent tool use ID for nested agent messages
1391    #[serde(skip_serializing_if = "Option::is_none")]
1392    pub parent_tool_use_id: Option<String>,
1393    /// Message-level unique identifier
1394    #[serde(skip_serializing_if = "Option::is_none")]
1395    pub uuid: Option<String>,
1396    /// CLI-emitted ISO-8601 timestamp for the message (present on echoed tool results).
1397    #[serde(skip_serializing_if = "Option::is_none")]
1398    pub timestamp: Option<String>,
1399    /// Structured tool result data echoed by the CLI alongside the `tool_result`
1400    /// content block. The shape depends on which tool produced it (e.g. for
1401    /// `AskUserQuestion` it is `{ questions, answers }`; for `Bash` it is
1402    /// `{ stdout, stderr, exit_code, ... }`). Stored as raw JSON to preserve
1403    /// wire fidelity; use [`UserMessage::tool_use_result_as`] to parse into a
1404    /// typed shape when you know which tool was invoked.
1405    #[serde(skip_serializing_if = "Option::is_none")]
1406    pub tool_use_result: Option<serde_json::Value>,
1407    /// ID of the subagent this user message belongs to (the `task_id` of its
1408    /// task events), on the prompt echoed into a `local_agent` subagent.
1409    /// Seen on the wire from CLI 2.1.292, where it is not part of the
1410    /// published user-message schema. Not settable by clients.
1411    #[serde(default, skip_serializing_if = "Option::is_none")]
1412    pub agent_id: Option<String>,
1413    /// Subagent type, when this user message is the prompt echoed into a
1414    /// `local_agent` subagent (e.g. `general-purpose`).
1415    #[serde(skip_serializing_if = "Option::is_none")]
1416    pub subagent_type: Option<String>,
1417    /// Short description of the subagent task, present alongside `subagent_type`.
1418    #[serde(skip_serializing_if = "Option::is_none")]
1419    pub task_description: Option<String>,
1420    #[serde(skip_serializing_if = "Option::is_none")]
1421    pub origin: Option<MessageOrigin>,
1422    #[serde(skip_serializing_if = "Option::is_none")]
1423    pub priority: Option<String>,
1424    #[serde(skip_serializing_if = "Option::is_none", rename = "isSynthetic")]
1425    pub is_synthetic: Option<bool>,
1426    #[serde(skip_serializing_if = "Option::is_none", rename = "shouldQuery")]
1427    pub should_query: Option<bool>,
1428    #[serde(default, skip_serializing_if = "Option::is_none")]
1429    pub is_meta: Option<bool>,
1430    #[serde(default, skip_serializing_if = "Option::is_none")]
1431    pub is_visible_in_transcript_only: Option<bool>,
1432    #[serde(default, skip_serializing_if = "Option::is_none")]
1433    pub is_virtual: Option<bool>,
1434    #[serde(default, skip_serializing_if = "Option::is_none")]
1435    pub is_compact_summary: Option<bool>,
1436    #[serde(skip_serializing_if = "Option::is_none")]
1437    pub summarize_metadata: Option<SummarizeMetadata>,
1438    #[serde(skip_serializing_if = "Option::is_none")]
1439    pub mcp_meta: Option<McpMeta>,
1440    /// Display metadata for this message's `tool_result` blocks, keyed by
1441    /// `tool_use_id`.
1442    #[serde(skip_serializing_if = "Option::is_none")]
1443    pub tool_result_meta: Option<Vec<ToolResultMeta>>,
1444    #[serde(skip_serializing_if = "Option::is_none")]
1445    pub source_tool_use_id: Option<String>,
1446    #[serde(skip_serializing_if = "Option::is_none")]
1447    pub source_tool_assistant_uuid: Option<String>,
1448    #[serde(skip_serializing_if = "Option::is_none")]
1449    pub image_paste_ids: Option<Vec<u64>>,
1450    #[serde(skip_serializing_if = "Option::is_none")]
1451    pub client_platform: Option<String>,
1452    /// The width, in CSS pixels, of the chat column of the client that sent
1453    /// this message. Marked `@internal` upstream (CLI 2.1.329+).
1454    #[serde(default, skip_serializing_if = "Option::is_none")]
1455    pub client_content_width: Option<f64>,
1456    #[serde(skip_serializing_if = "Option::is_none")]
1457    pub inbound_origin: Option<String>,
1458    /// Input only: the `request_id` of an unanswered permission card that the
1459    /// sender keeps up behind this message. A worker that took the card over
1460    /// then sends no cancel for it when this message ends it, so a later
1461    /// Allow can still run its call (CLI 2.1.326+).
1462    #[serde(default, skip_serializing_if = "Option::is_none")]
1463    pub keeps_request_id: Option<String>,
1464    #[serde(skip_serializing_if = "Option::is_none", rename = "isReplay")]
1465    pub is_replay: Option<bool>,
1466    #[serde(skip_serializing_if = "Option::is_none")]
1467    pub file_attachments: Option<Vec<Value>>,
1468    /// Desktop host only: the host's own seeded summon (CLI 2.1.239+).
1469    #[serde(default, skip_serializing_if = "Option::is_none")]
1470    pub seeded_summon: Option<bool>,
1471    /// True when the client composed this turn from content the user did not
1472    /// type; its text is delivered as written (CLI 2.1.259+).
1473    #[serde(default, skip_serializing_if = "Option::is_none")]
1474    pub client_composed: Option<bool>,
1475    /// True when no person typed this message's text in this session (a
1476    /// server or an app composed it). The text is delivered as written: no
1477    /// slash-command dispatch, no at-mention expansion beyond the message's
1478    /// own uploaded files, no keyword reminders or commands, and a skill it
1479    /// names does not count as typed by the user. Unlike
1480    /// [`client_composed`](Self::client_composed), the turn-start attachment
1481    /// pass still runs. Who sent it stays with [`origin`](Self::origin)
1482    /// (CLI 2.1.300+).
1483    #[serde(default, skip_serializing_if = "Option::is_none")]
1484    pub text_not_typed: Option<bool>,
1485    /// The host's own label for what started this turn (e.g. the desktop
1486    /// app's `scheduled-task`, `sleep-auto-resume`); `user`, an empty string
1487    /// or absent means a person sent it. For usage attribution; on CLI
1488    /// 2.1.317+ any other label also keeps a message with no origin, sent
1489    /// while a turn is running, from going out as the user's words
1490    /// (CLI 2.1.278+).
1491    #[serde(default, skip_serializing_if = "Option::is_none")]
1492    pub initiator: Option<String>,
1493    /// Content the user pasted into the prompt rather than typed: each entry
1494    /// a string or an array of content blocks. The CLI appends the text of
1495    /// each entry after the typed text, in order, and may wrap it in
1496    /// `<pasted_content>` tags. Blocks other than text are ignored; send
1497    /// images and documents in `message.content` (CLI 2.1.278+).
1498    #[serde(default, skip_serializing_if = "Option::is_none")]
1499    pub pasted_content: Option<Vec<Value>>,
1500    /// Replayed history rather than a live message: the Remote Control
1501    /// bridge stamps it on the messages it flushes to the session server,
1502    /// which also stamps it on deliveries it replays (CLI 2.1.266+).
1503    #[serde(default, skip_serializing_if = "Option::is_none")]
1504    pub historical: Option<bool>,
1505    /// Epoch milliseconds on the session server's clock when it received the
1506    /// HTTP request that delivered this message. Written by the session
1507    /// server; the CLI copies it to the turn's result as
1508    /// [`user_message_server_received_wall_ms`](crate::io::ResultMessage::user_message_server_received_wall_ms)
1509    /// (CLI 2.1.286+). Not settable by clients.
1510    #[serde(default, skip_serializing_if = "Option::is_none")]
1511    pub server_received_wall_ms: Option<f64>,
1512    /// Only on the synthetic message that re-asks the same model after a
1513    /// refusal: the API `msg_*` id of the refused response. Absent when the
1514    /// CLI has no well-formed id for it (CLI 2.1.290+).
1515    #[serde(default, skip_serializing_if = "Option::is_none")]
1516    pub refused_message_id: Option<String>,
1517    /// Input only: asks the CLI to put this prompt back at the front of its
1518    /// queue, under the same uuid, when an interrupt without `cancel_queued`
1519    /// stops the turn taking it in within this many milliseconds (counted
1520    /// from the turn's `system/status` `requesting` frame) and before the
1521    /// model's reply begins. Values above 10000 count as 10000
1522    /// (CLI 2.1.307+).
1523    #[serde(default, skip_serializing_if = "Option::is_none")]
1524    pub requeue_if_interrupted_within_ms: Option<u64>,
1525    /// Input only: the sender's statement that the person typed `ultrathink`
1526    /// in this prompt and was shown the word colored before sending, and
1527    /// that nothing in the prompt arrived whole (no paste, no share, no
1528    /// prompt the sender suggested). Send it only as `Some(true)`, and only
1529    /// while the session's newest `system/init` carried
1530    /// [`ultrathink_typed_raises`](crate::io::InitMessage::ultrathink_typed_raises)
1531    /// `true`. The turn then runs at `xhigh` effort if the CLI's own checks
1532    /// agree; it is the sender's claim, not proof (CLI 2.1.317+).
1533    #[serde(default, skip_serializing_if = "Option::is_none")]
1534    pub ultrathink_typed: Option<bool>,
1535    /// Input only: the MCP App views' states a remote client sent with this
1536    /// prompt, replacing the set the worker holds (`[]` clears it). Entries
1537    /// are opaque (CLI 2.1.317+).
1538    #[serde(default, skip_serializing_if = "Option::is_none")]
1539    pub tool_states: Option<Vec<Value>>,
1540    /// Output only, and to be read only on a message the CLI wrote (on a
1541    /// session event, only where its `source` is `worker`). On a message a
1542    /// plugin sent, what a host can show under the plugin's name in place
1543    /// of `message`. Absent on any other message, and on a prompt sent as
1544    /// the person's own words; there, show `message` (CLI 2.1.317+).
1545    #[serde(default, skip_serializing_if = "Option::is_none")]
1546    pub plugin_prompt: Option<PluginPrompt>,
1547    /// Output only, and to be read only on a message the CLI wrote (on a
1548    /// session event, only where its `source` is `worker`). Only on the
1549    /// synthetic message that asks the model again after a response whose
1550    /// tool call could not be parsed: the uuids of that response's
1551    /// messages, which the CLI has dropped from the conversation. Remove them
1552    /// on receipt; an unknown uuid is a no-op. If another assistant message
1553    /// follows in the turn, it names them again in
1554    /// [`AssistantMessage::supersedes`]. Absent if none of the response's
1555    /// messages was sent, on a subagent's messages, over Remote Control, and
1556    /// from older CLIs. Marked `@internal` upstream (CLI 2.1.323+).
1557    #[serde(default, skip_serializing_if = "Option::is_none")]
1558    pub retracted_message_uuids: Option<Vec<String>>,
1559}
1560
1561/// [`UserMessage::plugin_prompt`]: what a host can show for a message a
1562/// plugin sent (CLI 2.1.317+).
1563#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1564pub struct PluginPrompt {
1565    /// The plugin's name as the wrapper the model reads prints it, on one
1566    /// line and scrubbed; `origin.name` holds it raw.
1567    pub name: String,
1568    /// The prompt as hooks left it (prompts merged into one turn joined by
1569    /// newlines) when `message` is exactly the wrapper the model reads
1570    /// around that prompt; or the command the plugin ran as a person would
1571    /// type it, such as `/review 12`, when `message` is only that command's
1572    /// tags. Can be more than one line; show all of it.
1573    pub text: String,
1574}
1575
1576impl UserMessage {
1577    /// Parse the `tool_use_result` field into a caller-specified type.
1578    ///
1579    /// Returns `None` if `tool_use_result` is absent, otherwise returns the
1580    /// deserialization result. The caller must know which tool produced the
1581    /// result and supply a matching type — e.g. for `AskUserQuestion` use
1582    /// [`AskUserQuestionInput`](crate::AskUserQuestionInput), whose
1583    /// `questions` + `answers` fields match the wire result shape.
1584    pub fn tool_use_result_as<T: serde::de::DeserializeOwned>(
1585        &self,
1586    ) -> Option<Result<T, serde_json::Error>> {
1587        self.tool_use_result
1588            .as_ref()
1589            .map(|v| serde_json::from_value(v.clone()))
1590    }
1591
1592    /// Parse the `tool_use_result` as a subagent (`Task`) run result.
1593    ///
1594    /// When this user message echoes the result of a `Task` tool call, the CLI
1595    /// attaches a structured `tool_use_result` carrying the subagent's token,
1596    /// timing, and tool-use accounting. Returns `None` when the field is absent
1597    /// or does not parse as a [`SubagentResult`].
1598    ///
1599    /// Summing [`SubagentResult::total_tokens`] across every `Task` result in a
1600    /// session yields the subagent token rollup the CLI renders as
1601    /// `subagent_tokens` in its terminal `<usage>` block.
1602    pub fn subagent_result(&self) -> Option<SubagentResult> {
1603        self.tool_use_result
1604            .as_ref()
1605            .and_then(|v| serde_json::from_value(v.clone()).ok())
1606    }
1607}
1608
1609/// Token, timing, and tool-use accounting for a completed subagent (`Task`) run.
1610///
1611/// The Claude CLI echoes this object in the `tool_use_result` of a `Task` tool's
1612/// result message. It is the typed source of truth for subagent token
1613/// attribution: the per-run [`total_tokens`](Self::total_tokens),
1614/// [`total_duration_ms`](Self::total_duration_ms), and
1615/// [`total_tool_use_count`](Self::total_tool_use_count) correspond to the
1616/// `subagent_tokens` / `duration_ms` / `tool_uses` line items the CLI renders in
1617/// its human-readable `<usage>` block, and [`usage`](Self::usage) carries the
1618/// full per-model token breakdown for the run.
1619#[derive(Debug, Clone, Serialize, Deserialize)]
1620pub struct SubagentResult {
1621    /// Completion status of the subagent run (e.g. `"completed"`).
1622    #[serde(skip_serializing_if = "Option::is_none")]
1623    pub status: Option<String>,
1624    /// The prompt the subagent was launched with.
1625    #[serde(skip_serializing_if = "Option::is_none")]
1626    pub prompt: Option<String>,
1627    /// Stable identifier of the spawned subagent.
1628    #[serde(rename = "agentId", skip_serializing_if = "Option::is_none")]
1629    pub agent_id: Option<String>,
1630    /// Subagent type that ran (e.g. `general-purpose`, `Explore`).
1631    #[serde(rename = "agentType", skip_serializing_if = "Option::is_none")]
1632    pub agent_type: Option<String>,
1633    /// Final content blocks the subagent returned.
1634    #[serde(
1635        default,
1636        deserialize_with = "deserialize_content_blocks",
1637        skip_serializing_if = "Vec::is_empty"
1638    )]
1639    pub content: Vec<ContentBlock>,
1640    /// Model the subagent actually resolved to (e.g. `claude-sonnet-4-6`).
1641    #[serde(rename = "resolvedModel", skip_serializing_if = "Option::is_none")]
1642    pub resolved_model: Option<String>,
1643    /// Wall-clock duration of the subagent run, in milliseconds.
1644    #[serde(rename = "totalDurationMs", skip_serializing_if = "Option::is_none")]
1645    pub total_duration_ms: Option<u64>,
1646    /// Total tokens consumed by the subagent — the `subagent_tokens` rollup line.
1647    #[serde(rename = "totalTokens", skip_serializing_if = "Option::is_none")]
1648    pub total_tokens: Option<u64>,
1649    /// Number of tool invocations the subagent made.
1650    #[serde(rename = "totalToolUseCount", skip_serializing_if = "Option::is_none")]
1651    pub total_tool_use_count: Option<u64>,
1652    /// Detailed token / cache usage for the subagent run.
1653    #[serde(skip_serializing_if = "Option::is_none")]
1654    pub usage: Option<super::result::UsageInfo>,
1655    /// Per-category tool-use counts, present for some agent types (e.g. `Explore`).
1656    #[serde(rename = "toolStats", skip_serializing_if = "Option::is_none")]
1657    pub tool_stats: Option<SubagentToolStats>,
1658}
1659
1660/// Per-category tool-use counts for a subagent run, from `tool_use_result.toolStats`.
1661///
1662/// The `extra` field captures any counters the CLI adds that aren't modeled here,
1663/// so new wire fields deserialize without error.
1664#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1665#[serde(rename_all = "camelCase")]
1666pub struct SubagentToolStats {
1667    #[serde(default)]
1668    pub read_count: u64,
1669    #[serde(default)]
1670    pub search_count: u64,
1671    #[serde(default)]
1672    pub bash_count: u64,
1673    #[serde(default)]
1674    pub edit_file_count: u64,
1675    #[serde(default)]
1676    pub lines_added: u64,
1677    #[serde(default)]
1678    pub lines_removed: u64,
1679    #[serde(default)]
1680    pub other_tool_count: u64,
1681    #[serde(flatten)]
1682    pub extra: serde_json::Map<String, Value>,
1683}
1684
1685/// Session-level subagent token rollup — the `<subagent_tokens>` /
1686/// `<agent_count>` line items the Claude CLI renders in its terminal
1687/// `<usage>` block.
1688///
1689/// The `stream-json` protocol does **not** carry this rollup on the `result`
1690/// frame's `usage` (confirmed against the CLI binary — the terminal renderer
1691/// computes it from `Task` tool results). Consumers that need it must
1692/// accumulate it the same way: feed every session message through
1693/// [`observe`](Self::observe) and read the totals at any point.
1694///
1695/// A `Task` result observed twice under the same `agentId` (e.g. a replayed
1696/// frame on resume) is counted once. Results with no `agentId` are counted
1697/// every time they are observed.
1698///
1699/// # Example
1700///
1701/// ```
1702/// use claude_codes::{ClaudeOutput, SubagentUsageRollup};
1703///
1704/// let mut rollup = SubagentUsageRollup::default();
1705/// 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}}"#;
1706/// let output: ClaudeOutput = serde_json::from_str(json).unwrap();
1707/// rollup.observe(&output);
1708/// assert_eq!(rollup.subagent_tokens, 10201);
1709/// assert_eq!(rollup.agent_count, 1);
1710/// ```
1711#[derive(Debug, Clone, Default, PartialEq, Eq)]
1712pub struct SubagentUsageRollup {
1713    /// Total tokens consumed by subagents — sum of
1714    /// [`SubagentResult::total_tokens`] over every observed `Task` result.
1715    pub subagent_tokens: u64,
1716    /// Number of subagent runs observed (`<agent_count>`).
1717    pub agent_count: u32,
1718    /// Total subagent tool invocations — sum of `total_tool_use_count`.
1719    pub tool_uses: u64,
1720    /// Total subagent wall-clock milliseconds — sum of `total_duration_ms`.
1721    pub duration_ms: u64,
1722    seen_agent_ids: std::collections::BTreeSet<String>,
1723}
1724
1725impl SubagentUsageRollup {
1726    /// Accumulate `output` into the rollup if it is a `Task` tool result.
1727    ///
1728    /// Returns `true` when the message contributed to the totals. Non-user
1729    /// messages, user messages without a `tool_use_result`, results from
1730    /// other tools, and duplicate `agentId`s are all ignored.
1731    pub fn observe(&mut self, output: &ClaudeOutput) -> bool {
1732        match output {
1733            ClaudeOutput::User(user) => self.observe_user(user),
1734            _ => false,
1735        }
1736    }
1737
1738    /// Accumulate a user message's `Task` tool result, if it carries one.
1739    ///
1740    /// Every [`SubagentResult`] field is optional, so any JSON object in
1741    /// `tool_use_result` parses as one (e.g. a `Bash` or `ToolSearch`
1742    /// result). Only results carrying an `agentId` or a `totalTokens`
1743    /// line item are treated as genuine `Task` results.
1744    pub fn observe_user(&mut self, user: &UserMessage) -> bool {
1745        let Some(result) = user.subagent_result() else {
1746            return false;
1747        };
1748        if result.total_tokens.is_none() && result.agent_id.is_none() {
1749            return false;
1750        }
1751        if let Some(agent_id) = &result.agent_id {
1752            if !self.seen_agent_ids.insert(agent_id.clone()) {
1753                return false;
1754            }
1755        }
1756        self.agent_count += 1;
1757        self.subagent_tokens += result.total_tokens.unwrap_or(0);
1758        self.tool_uses += result.total_tool_use_count.unwrap_or(0);
1759        self.duration_ms += result.total_duration_ms.unwrap_or(0);
1760        true
1761    }
1762}
1763
1764/// Message content with role
1765#[derive(Debug, Clone, Serialize, Deserialize)]
1766pub struct MessageContent {
1767    pub role: MessageRole,
1768    #[serde(deserialize_with = "deserialize_content_blocks")]
1769    pub content: Vec<ContentBlock>,
1770}
1771
1772/// System message with metadata
1773#[derive(Debug, Clone, Serialize, Deserialize)]
1774pub struct SystemMessage {
1775    pub subtype: SystemSubtype,
1776    #[serde(flatten)]
1777    pub data: Value, // Captures all other fields
1778}
1779
1780impl SystemMessage {
1781    /// Check if this is an init message
1782    pub fn is_init(&self) -> bool {
1783        self.subtype == SystemSubtype::Init
1784    }
1785
1786    /// Check if this is a status message
1787    pub fn is_status(&self) -> bool {
1788        self.subtype == SystemSubtype::Status
1789    }
1790
1791    /// Check if this is a compact_boundary message
1792    pub fn is_compact_boundary(&self) -> bool {
1793        self.subtype == SystemSubtype::CompactBoundary
1794    }
1795
1796    /// Try to parse as an init message
1797    pub fn as_init(&self) -> Option<InitMessage> {
1798        if self.subtype != SystemSubtype::Init {
1799            return None;
1800        }
1801        serde_json::from_value(self.data.clone()).ok()
1802    }
1803
1804    /// Try to parse as a status message
1805    pub fn as_status(&self) -> Option<StatusMessage> {
1806        if self.subtype != SystemSubtype::Status {
1807            return None;
1808        }
1809        serde_json::from_value(self.data.clone()).ok()
1810    }
1811
1812    /// Try to parse as a compact_boundary message
1813    pub fn as_compact_boundary(&self) -> Option<CompactBoundaryMessage> {
1814        if self.subtype != SystemSubtype::CompactBoundary {
1815            return None;
1816        }
1817        serde_json::from_value(self.data.clone()).ok()
1818    }
1819
1820    /// Check if this is a task_started message
1821    pub fn is_task_started(&self) -> bool {
1822        self.subtype == SystemSubtype::TaskStarted
1823    }
1824
1825    /// Check if this is a task_progress message
1826    pub fn is_task_progress(&self) -> bool {
1827        self.subtype == SystemSubtype::TaskProgress
1828    }
1829
1830    /// Check if this is a task_notification message
1831    pub fn is_task_notification(&self) -> bool {
1832        self.subtype == SystemSubtype::TaskNotification
1833    }
1834
1835    /// Try to parse as a task_started message
1836    pub fn as_task_started(&self) -> Option<TaskStartedMessage> {
1837        if self.subtype != SystemSubtype::TaskStarted {
1838            return None;
1839        }
1840        serde_json::from_value(self.data.clone()).ok()
1841    }
1842
1843    /// Try to parse as a task_progress message
1844    pub fn as_task_progress(&self) -> Option<TaskProgressMessage> {
1845        if self.subtype != SystemSubtype::TaskProgress {
1846            return None;
1847        }
1848        serde_json::from_value(self.data.clone()).ok()
1849    }
1850
1851    /// Try to parse as a task_notification message
1852    pub fn as_task_notification(&self) -> Option<TaskNotificationMessage> {
1853        if self.subtype != SystemSubtype::TaskNotification {
1854            return None;
1855        }
1856        serde_json::from_value(self.data.clone()).ok()
1857    }
1858
1859    /// Check if this is a task_updated message
1860    pub fn is_task_updated(&self) -> bool {
1861        self.subtype == SystemSubtype::TaskUpdated
1862    }
1863
1864    /// Try to parse as a task_updated message
1865    pub fn as_task_updated(&self) -> Option<TaskUpdatedMessage> {
1866        if self.subtype != SystemSubtype::TaskUpdated {
1867            return None;
1868        }
1869        serde_json::from_value(self.data.clone()).ok()
1870    }
1871
1872    /// Check if this is a thinking_tokens message
1873    pub fn is_thinking_tokens(&self) -> bool {
1874        self.subtype == SystemSubtype::ThinkingTokens
1875    }
1876
1877    /// Try to parse as a thinking_tokens message
1878    pub fn as_thinking_tokens(&self) -> Option<ThinkingTokensMessage> {
1879        if self.subtype != SystemSubtype::ThinkingTokens {
1880            return None;
1881        }
1882        serde_json::from_value(self.data.clone()).ok()
1883    }
1884
1885    /// Check if this is a code_change_published message
1886    pub fn is_code_change_published(&self) -> bool {
1887        self.subtype == SystemSubtype::CodeChangePublished
1888    }
1889
1890    /// Try to parse as a code_change_published message
1891    pub fn as_code_change_published(&self) -> Option<CodeChangePublishedMessage> {
1892        if self.subtype != SystemSubtype::CodeChangePublished {
1893            return None;
1894        }
1895        serde_json::from_value(self.data.clone()).ok()
1896    }
1897
1898    /// Check if this is a vcs_state_changed message
1899    pub fn is_vcs_state_changed(&self) -> bool {
1900        self.subtype == SystemSubtype::VcsStateChanged
1901    }
1902
1903    /// Try to parse as a vcs_state_changed message
1904    pub fn as_vcs_state_changed(&self) -> Option<VcsStateChangedMessage> {
1905        if self.subtype != SystemSubtype::VcsStateChanged {
1906            return None;
1907        }
1908        serde_json::from_value(self.data.clone()).ok()
1909    }
1910
1911    /// Check if this is a feedback_draft_queued message.
1912    pub fn is_feedback_draft_queued(&self) -> bool {
1913        self.subtype == SystemSubtype::FeedbackDraftQueued
1914    }
1915
1916    /// Try to parse as a feedback_draft_queued message.
1917    pub fn as_feedback_draft_queued(&self) -> Option<FeedbackDraftQueuedMessage> {
1918        if self.subtype != SystemSubtype::FeedbackDraftQueued {
1919            return None;
1920        }
1921        serde_json::from_value(self.data.clone()).ok()
1922    }
1923
1924    /// Check if this is a cloud_session_delta message.
1925    pub fn is_cloud_session_delta(&self) -> bool {
1926        self.subtype == SystemSubtype::CloudSessionDelta
1927    }
1928
1929    /// Try to parse as a cloud_session_delta message.
1930    pub fn as_cloud_session_delta(&self) -> Option<CloudSessionDeltaMessage> {
1931        if self.subtype != SystemSubtype::CloudSessionDelta {
1932            return None;
1933        }
1934        serde_json::from_value(self.data.clone()).ok()
1935    }
1936
1937    /// Check if this is a dev_intent message.
1938    pub fn is_dev_intent(&self) -> bool {
1939        self.subtype == SystemSubtype::DevIntent
1940    }
1941
1942    /// Try to parse as a dev_intent message.
1943    pub fn as_dev_intent(&self) -> Option<DevIntentMessage> {
1944        if self.subtype != SystemSubtype::DevIntent {
1945            return None;
1946        }
1947        serde_json::from_value(self.data.clone()).ok()
1948    }
1949
1950    /// Check if this is a turn_handoff_available message.
1951    pub fn is_turn_handoff_available(&self) -> bool {
1952        self.subtype == SystemSubtype::TurnHandoffAvailable
1953    }
1954
1955    /// Try to parse as a turn_handoff_available message.
1956    pub fn as_turn_handoff_available(&self) -> Option<TurnHandoffAvailableMessage> {
1957        if self.subtype != SystemSubtype::TurnHandoffAvailable {
1958            return None;
1959        }
1960        serde_json::from_value(self.data.clone()).ok()
1961    }
1962
1963    /// Check if this is a turn_preempted message.
1964    pub fn is_turn_preempted(&self) -> bool {
1965        self.subtype == SystemSubtype::TurnPreempted
1966    }
1967
1968    /// Try to parse as a turn_preempted message.
1969    pub fn as_turn_preempted(&self) -> Option<TurnPreemptedMessage> {
1970        if self.subtype != SystemSubtype::TurnPreempted {
1971            return None;
1972        }
1973        serde_json::from_value(self.data.clone()).ok()
1974    }
1975
1976    /// Check if this is a peer_message_hold message.
1977    pub fn is_peer_message_hold(&self) -> bool {
1978        self.subtype == SystemSubtype::PeerMessageHold
1979    }
1980
1981    /// Try to parse as a peer_message_hold message.
1982    pub fn as_peer_message_hold(&self) -> Option<PeerMessageHoldMessage> {
1983        if self.subtype != SystemSubtype::PeerMessageHold {
1984            return None;
1985        }
1986        serde_json::from_value(self.data.clone()).ok()
1987    }
1988
1989    /// Check if this is a per_turn_effort_changed message.
1990    pub fn is_per_turn_effort_changed(&self) -> bool {
1991        self.subtype == SystemSubtype::PerTurnEffortChanged
1992    }
1993
1994    /// Try to parse as a per_turn_effort_changed message.
1995    pub fn as_per_turn_effort_changed(&self) -> Option<PerTurnEffortChangedMessage> {
1996        if self.subtype != SystemSubtype::PerTurnEffortChanged {
1997            return None;
1998        }
1999        serde_json::from_value(self.data.clone()).ok()
2000    }
2001
2002    /// Check if this is a session_title_changed message.
2003    pub fn is_session_title_changed(&self) -> bool {
2004        self.subtype == SystemSubtype::SessionTitleChanged
2005    }
2006
2007    /// Try to parse as a session_title_changed message.
2008    pub fn as_session_title_changed(&self) -> Option<SessionTitleChangedMessage> {
2009        if self.subtype != SystemSubtype::SessionTitleChanged {
2010            return None;
2011        }
2012        serde_json::from_value(self.data.clone()).ok()
2013    }
2014
2015    /// Check if this is a session_writes_lost message.
2016    pub fn is_session_writes_lost(&self) -> bool {
2017        self.subtype == SystemSubtype::SessionWritesLost
2018    }
2019
2020    /// Try to parse as a session_writes_lost message.
2021    pub fn as_session_writes_lost(&self) -> Option<SessionWritesLostMessage> {
2022        if self.subtype != SystemSubtype::SessionWritesLost {
2023            return None;
2024        }
2025        serde_json::from_value(self.data.clone()).ok()
2026    }
2027
2028    /// Check if this is an instruction_size_warning message.
2029    pub fn is_instruction_size_warning(&self) -> bool {
2030        self.subtype == SystemSubtype::InstructionSizeWarning
2031    }
2032
2033    /// Try to parse as an instruction_size_warning message.
2034    pub fn as_instruction_size_warning(&self) -> Option<InstructionSizeWarningMessage> {
2035        if self.subtype != SystemSubtype::InstructionSizeWarning {
2036            return None;
2037        }
2038        serde_json::from_value(self.data.clone()).ok()
2039    }
2040
2041    /// Check if this is a permission_check_status message.
2042    pub fn is_permission_check_status(&self) -> bool {
2043        self.subtype == SystemSubtype::PermissionCheckStatus
2044    }
2045
2046    /// Try to parse as a permission_check_status message.
2047    pub fn as_permission_check_status(&self) -> Option<PermissionCheckStatusMessage> {
2048        if self.subtype != SystemSubtype::PermissionCheckStatus {
2049            return None;
2050        }
2051        serde_json::from_value(self.data.clone()).ok()
2052    }
2053
2054    /// Check if this is an inherited_asks_settled message.
2055    pub fn is_inherited_asks_settled(&self) -> bool {
2056        self.subtype == SystemSubtype::InheritedAsksSettled
2057    }
2058
2059    /// Try to parse as an inherited_asks_settled message.
2060    pub fn as_inherited_asks_settled(&self) -> Option<InheritedAsksSettledMessage> {
2061        if self.subtype != SystemSubtype::InheritedAsksSettled {
2062            return None;
2063        }
2064        serde_json::from_value(self.data.clone()).ok()
2065    }
2066
2067    /// Check if this is a late_allow_not_run message.
2068    pub fn is_late_allow_not_run(&self) -> bool {
2069        self.subtype == SystemSubtype::LateAllowNotRun
2070    }
2071
2072    /// Try to parse as a late_allow_not_run message.
2073    pub fn as_late_allow_not_run(&self) -> Option<LateAllowNotRunMessage> {
2074        if self.subtype != SystemSubtype::LateAllowNotRun {
2075            return None;
2076        }
2077        serde_json::from_value(self.data.clone()).ok()
2078    }
2079
2080    /// Check if this is a shell_cwd message.
2081    pub fn is_shell_cwd(&self) -> bool {
2082        self.subtype == SystemSubtype::ShellCwd
2083    }
2084
2085    /// Try to parse as a shell_cwd message.
2086    pub fn as_shell_cwd(&self) -> Option<ShellCwdMessage> {
2087        if self.subtype != SystemSubtype::ShellCwd {
2088            return None;
2089        }
2090        serde_json::from_value(self.data.clone()).ok()
2091    }
2092
2093    /// Check if this is a task_list_statuses message.
2094    pub fn is_task_list_statuses(&self) -> bool {
2095        self.subtype == SystemSubtype::TaskListStatuses
2096    }
2097
2098    /// Try to parse as a task_list_statuses message.
2099    pub fn as_task_list_statuses(&self) -> Option<TaskListStatusesMessage> {
2100        if self.subtype != SystemSubtype::TaskListStatuses {
2101            return None;
2102        }
2103        serde_json::from_value(self.data.clone()).ok()
2104    }
2105
2106    /// Check if this is a file_attachments_missing message.
2107    pub fn is_file_attachments_missing(&self) -> bool {
2108        self.subtype == SystemSubtype::FileAttachmentsMissing
2109    }
2110
2111    /// Try to parse as a file_attachments_missing message.
2112    pub fn as_file_attachments_missing(&self) -> Option<FileAttachmentsMissingMessage> {
2113        if self.subtype != SystemSubtype::FileAttachmentsMissing {
2114            return None;
2115        }
2116        serde_json::from_value(self.data.clone()).ok()
2117    }
2118
2119    /// Check if this is a ui_focus message.
2120    pub fn is_ui_focus(&self) -> bool {
2121        self.subtype == SystemSubtype::UiFocus
2122    }
2123
2124    /// Try to parse as a ui_focus message.
2125    pub fn as_ui_focus(&self) -> Option<UiFocusMessage> {
2126        if self.subtype != SystemSubtype::UiFocus {
2127            return None;
2128        }
2129        serde_json::from_value(self.data.clone()).ok()
2130    }
2131
2132    /// Check if this is a ui_invalidate message.
2133    pub fn is_ui_invalidate(&self) -> bool {
2134        self.subtype == SystemSubtype::UiInvalidate
2135    }
2136
2137    /// Try to parse as a ui_invalidate message.
2138    pub fn as_ui_invalidate(&self) -> Option<UiInvalidateMessage> {
2139        if self.subtype != SystemSubtype::UiInvalidate {
2140            return None;
2141        }
2142        serde_json::from_value(self.data.clone()).ok()
2143    }
2144
2145    /// Check if this is a ui_log message.
2146    pub fn is_ui_log(&self) -> bool {
2147        self.subtype == SystemSubtype::UiLog
2148    }
2149
2150    /// Try to parse as a ui_log message.
2151    pub fn as_ui_log(&self) -> Option<UiLogMessage> {
2152        if self.subtype != SystemSubtype::UiLog {
2153            return None;
2154        }
2155        serde_json::from_value(self.data.clone()).ok()
2156    }
2157
2158    /// Check if this is a ui_notify message.
2159    pub fn is_ui_notify(&self) -> bool {
2160        self.subtype == SystemSubtype::UiNotify
2161    }
2162
2163    /// Try to parse as a ui_notify message.
2164    pub fn as_ui_notify(&self) -> Option<UiNotifyMessage> {
2165        if self.subtype != SystemSubtype::UiNotify {
2166            return None;
2167        }
2168        serde_json::from_value(self.data.clone()).ok()
2169    }
2170
2171    /// Check if this is a ui_notify_cancel message.
2172    pub fn is_ui_notify_cancel(&self) -> bool {
2173        self.subtype == SystemSubtype::UiNotifyCancel
2174    }
2175
2176    /// Try to parse as a ui_notify_cancel message.
2177    pub fn as_ui_notify_cancel(&self) -> Option<UiNotifyCancelMessage> {
2178        if self.subtype != SystemSubtype::UiNotifyCancel {
2179            return None;
2180        }
2181        serde_json::from_value(self.data.clone()).ok()
2182    }
2183
2184    /// Check if this is a ui_panes message.
2185    pub fn is_ui_panes(&self) -> bool {
2186        self.subtype == SystemSubtype::UiPanes
2187    }
2188
2189    /// Try to parse as a ui_panes message.
2190    pub fn as_ui_panes(&self) -> Option<UiPanesMessage> {
2191        if self.subtype != SystemSubtype::UiPanes {
2192            return None;
2193        }
2194        serde_json::from_value(self.data.clone()).ok()
2195    }
2196
2197    /// Check if this is a ui_placed message.
2198    pub fn is_ui_placed(&self) -> bool {
2199        self.subtype == SystemSubtype::UiPlaced
2200    }
2201
2202    /// Try to parse as a ui_placed message.
2203    pub fn as_ui_placed(&self) -> Option<UiPlacedMessage> {
2204        if self.subtype != SystemSubtype::UiPlaced {
2205            return None;
2206        }
2207        serde_json::from_value(self.data.clone()).ok()
2208    }
2209
2210    /// Check if this is a ui_scroll message.
2211    pub fn is_ui_scroll(&self) -> bool {
2212        self.subtype == SystemSubtype::UiScroll
2213    }
2214
2215    /// Try to parse as a ui_scroll message.
2216    pub fn as_ui_scroll(&self) -> Option<UiScrollMessage> {
2217        if self.subtype != SystemSubtype::UiScroll {
2218            return None;
2219        }
2220        serde_json::from_value(self.data.clone()).ok()
2221    }
2222
2223    /// Check if this is a ui_status message.
2224    pub fn is_ui_status(&self) -> bool {
2225        self.subtype == SystemSubtype::UiStatus
2226    }
2227
2228    /// Try to parse as a ui_status message.
2229    pub fn as_ui_status(&self) -> Option<UiStatusMessage> {
2230        if self.subtype != SystemSubtype::UiStatus {
2231            return None;
2232        }
2233        serde_json::from_value(self.data.clone()).ok()
2234    }
2235
2236    /// Check if this is a ui_toast message.
2237    pub fn is_ui_toast(&self) -> bool {
2238        self.subtype == SystemSubtype::UiToast
2239    }
2240
2241    /// Try to parse as a ui_toast message.
2242    pub fn as_ui_toast(&self) -> Option<UiToastMessage> {
2243        if self.subtype != SystemSubtype::UiToast {
2244            return None;
2245        }
2246        serde_json::from_value(self.data.clone()).ok()
2247    }
2248
2249    /// Parse any typed system subtype known to this crate version.
2250    pub fn as_known_system_event(&self) -> Option<KnownSystemEvent> {
2251        macro_rules! parse {
2252            ($variant:ident, $ty:ty) => {
2253                serde_json::from_value::<$ty>(self.data.clone())
2254                    .ok()
2255                    .map(KnownSystemEvent::$variant)
2256            };
2257        }
2258
2259        match self.subtype {
2260            SystemSubtype::Init => parse!(Init, InitMessage),
2261            SystemSubtype::Status => parse!(Status, StatusMessage),
2262            SystemSubtype::CompactBoundary => parse!(CompactBoundary, CompactBoundaryMessage),
2263            SystemSubtype::ThinkingTokens => parse!(ThinkingTokens, ThinkingTokensMessage),
2264            SystemSubtype::TaskStarted => parse!(TaskStarted, TaskStartedMessage),
2265            SystemSubtype::TaskProgress => parse!(TaskProgress, TaskProgressMessage),
2266            SystemSubtype::TaskUpdated => parse!(TaskUpdated, TaskUpdatedMessage),
2267            SystemSubtype::TaskNotification => parse!(TaskNotification, TaskNotificationMessage),
2268            SystemSubtype::ApiRetry => parse!(ApiRetry, ApiRetryMessage),
2269            SystemSubtype::ControlRequestProgress => {
2270                parse!(ControlRequestProgress, ControlRequestProgressMessage)
2271            }
2272            SystemSubtype::ModelRefusalFallback => {
2273                parse!(ModelRefusalFallback, ModelRefusalFallbackMessage)
2274            }
2275            SystemSubtype::ModelRefusalNoFallback => {
2276                parse!(ModelRefusalNoFallback, ModelRefusalNoFallbackMessage)
2277            }
2278            SystemSubtype::LocalCommandOutput => {
2279                parse!(LocalCommandOutput, LocalCommandOutputMessage)
2280            }
2281            SystemSubtype::HookStarted => parse!(HookStarted, HookStartedMessage),
2282            SystemSubtype::HookProgress => parse!(HookProgress, HookProgressMessage),
2283            SystemSubtype::HookResponse => parse!(HookResponse, HookResponseMessage),
2284            SystemSubtype::PluginInstall => parse!(PluginInstall, PluginInstallMessage),
2285            SystemSubtype::BackgroundTasksChanged => {
2286                parse!(BackgroundTasksChanged, BackgroundTasksChangedMessage)
2287            }
2288            SystemSubtype::SessionStateChanged => {
2289                parse!(SessionStateChanged, SessionStateChangedMessage)
2290            }
2291            SystemSubtype::WorkerShuttingDown => {
2292                parse!(WorkerShuttingDown, WorkerShuttingDownMessage)
2293            }
2294            SystemSubtype::CommandsChanged => parse!(CommandsChanged, CommandsChangedMessage),
2295            SystemSubtype::Notification => parse!(Notification, NotificationMessage),
2296            SystemSubtype::FilesPersisted => parse!(FilesPersisted, FilesPersistedMessage),
2297            SystemSubtype::MemoryRecall => parse!(MemoryRecall, MemoryRecallMessage),
2298            SystemSubtype::ElicitationComplete => {
2299                parse!(ElicitationComplete, ElicitationCompleteMessage)
2300            }
2301            SystemSubtype::PermissionDenied => parse!(PermissionDenied, PermissionDeniedMessage),
2302            SystemSubtype::MirrorError => parse!(MirrorError, MirrorErrorMessage),
2303            SystemSubtype::Informational => parse!(Informational, InformationalMessage),
2304            SystemSubtype::CodeChangePublished => {
2305                parse!(CodeChangePublished, CodeChangePublishedMessage)
2306            }
2307            SystemSubtype::VcsStateChanged => parse!(VcsStateChanged, VcsStateChangedMessage),
2308            SystemSubtype::FeedbackDraftQueued => {
2309                parse!(FeedbackDraftQueued, FeedbackDraftQueuedMessage)
2310            }
2311            SystemSubtype::CloudSessionDelta => {
2312                parse!(CloudSessionDelta, CloudSessionDeltaMessage)
2313            }
2314            SystemSubtype::DevIntent => parse!(DevIntent, DevIntentMessage),
2315            SystemSubtype::TurnHandoffAvailable => {
2316                parse!(TurnHandoffAvailable, TurnHandoffAvailableMessage)
2317            }
2318            SystemSubtype::TurnPreempted => parse!(TurnPreempted, TurnPreemptedMessage),
2319            SystemSubtype::PeerMessageHold => parse!(PeerMessageHold, PeerMessageHoldMessage),
2320            SystemSubtype::PerTurnEffortChanged => {
2321                parse!(PerTurnEffortChanged, PerTurnEffortChangedMessage)
2322            }
2323            SystemSubtype::SessionTitleChanged => {
2324                parse!(SessionTitleChanged, SessionTitleChangedMessage)
2325            }
2326            SystemSubtype::SessionWritesLost => {
2327                parse!(SessionWritesLost, SessionWritesLostMessage)
2328            }
2329            SystemSubtype::InstructionSizeWarning => {
2330                parse!(InstructionSizeWarning, InstructionSizeWarningMessage)
2331            }
2332            SystemSubtype::FileAttachmentsMissing => {
2333                parse!(FileAttachmentsMissing, FileAttachmentsMissingMessage)
2334            }
2335            SystemSubtype::PermissionCheckStatus => {
2336                parse!(PermissionCheckStatus, PermissionCheckStatusMessage)
2337            }
2338            SystemSubtype::InheritedAsksSettled => {
2339                parse!(InheritedAsksSettled, InheritedAsksSettledMessage)
2340            }
2341            SystemSubtype::LateAllowNotRun => parse!(LateAllowNotRun, LateAllowNotRunMessage),
2342            SystemSubtype::ShellCwd => parse!(ShellCwd, ShellCwdMessage),
2343            SystemSubtype::TaskListStatuses => {
2344                parse!(TaskListStatuses, TaskListStatusesMessage)
2345            }
2346            SystemSubtype::UiFocus => parse!(UiFocus, UiFocusMessage),
2347            SystemSubtype::UiInvalidate => parse!(UiInvalidate, UiInvalidateMessage),
2348            SystemSubtype::UiLog => parse!(UiLog, UiLogMessage),
2349            SystemSubtype::UiNotify => parse!(UiNotify, UiNotifyMessage),
2350            SystemSubtype::UiNotifyCancel => parse!(UiNotifyCancel, UiNotifyCancelMessage),
2351            SystemSubtype::UiPanes => parse!(UiPanes, UiPanesMessage),
2352            SystemSubtype::UiPlaced => parse!(UiPlaced, UiPlacedMessage),
2353            SystemSubtype::UiScroll => parse!(UiScroll, UiScrollMessage),
2354            SystemSubtype::UiStatus => parse!(UiStatus, UiStatusMessage),
2355            SystemSubtype::UiToast => parse!(UiToast, UiToastMessage),
2356            SystemSubtype::Unknown(_) => None,
2357        }
2358    }
2359
2360    /// Re-serialize this system message's payload through the typed view that
2361    /// matches its `subtype`, returning the result as JSON.
2362    ///
2363    /// Used by the wrapping audit ([`crate::io::audit_frame`]) to verify that a
2364    /// subtype's dedicated struct captures every wire field: the audit compares
2365    /// this against the raw [`SystemMessage::data`]. Returns `None` for subtypes
2366    /// this crate version has no dedicated struct for (including
2367    /// [`SystemSubtype::Unknown`]) — those are reported as not fully wrapped.
2368    pub fn typed_value(&self) -> Option<Value> {
2369        fn reserialize<T: Serialize>(parsed: Option<T>) -> Option<Value> {
2370            parsed.and_then(|v| serde_json::to_value(v).ok())
2371        }
2372        match self.subtype {
2373            SystemSubtype::Init => reserialize(self.as_init()),
2374            SystemSubtype::Status => reserialize(self.as_status()),
2375            SystemSubtype::CompactBoundary => reserialize(self.as_compact_boundary()),
2376            SystemSubtype::ThinkingTokens => reserialize(self.as_thinking_tokens()),
2377            SystemSubtype::TaskStarted => reserialize(self.as_task_started()),
2378            SystemSubtype::TaskProgress => reserialize(self.as_task_progress()),
2379            SystemSubtype::TaskUpdated => reserialize(self.as_task_updated()),
2380            SystemSubtype::TaskNotification => reserialize(self.as_task_notification()),
2381            SystemSubtype::ApiRetry => reserialize(parse_system::<ApiRetryMessage>(self)),
2382            SystemSubtype::ControlRequestProgress => {
2383                reserialize(parse_system::<ControlRequestProgressMessage>(self))
2384            }
2385            SystemSubtype::ModelRefusalFallback => {
2386                reserialize(parse_system::<ModelRefusalFallbackMessage>(self))
2387            }
2388            SystemSubtype::ModelRefusalNoFallback => {
2389                reserialize(parse_system::<ModelRefusalNoFallbackMessage>(self))
2390            }
2391            SystemSubtype::LocalCommandOutput => {
2392                reserialize(parse_system::<LocalCommandOutputMessage>(self))
2393            }
2394            SystemSubtype::HookStarted => reserialize(parse_system::<HookStartedMessage>(self)),
2395            SystemSubtype::HookProgress => reserialize(parse_system::<HookProgressMessage>(self)),
2396            SystemSubtype::HookResponse => reserialize(parse_system::<HookResponseMessage>(self)),
2397            SystemSubtype::PluginInstall => reserialize(parse_system::<PluginInstallMessage>(self)),
2398            SystemSubtype::BackgroundTasksChanged => {
2399                reserialize(parse_system::<BackgroundTasksChangedMessage>(self))
2400            }
2401            SystemSubtype::SessionStateChanged => {
2402                reserialize(parse_system::<SessionStateChangedMessage>(self))
2403            }
2404            SystemSubtype::WorkerShuttingDown => {
2405                reserialize(parse_system::<WorkerShuttingDownMessage>(self))
2406            }
2407            SystemSubtype::CommandsChanged => {
2408                reserialize(parse_system::<CommandsChangedMessage>(self))
2409            }
2410            SystemSubtype::Notification => reserialize(parse_system::<NotificationMessage>(self)),
2411            SystemSubtype::FilesPersisted => {
2412                reserialize(parse_system::<FilesPersistedMessage>(self))
2413            }
2414            SystemSubtype::MemoryRecall => reserialize(parse_system::<MemoryRecallMessage>(self)),
2415            SystemSubtype::ElicitationComplete => {
2416                reserialize(parse_system::<ElicitationCompleteMessage>(self))
2417            }
2418            SystemSubtype::PermissionDenied => {
2419                reserialize(parse_system::<PermissionDeniedMessage>(self))
2420            }
2421            SystemSubtype::MirrorError => reserialize(parse_system::<MirrorErrorMessage>(self)),
2422            SystemSubtype::Informational => reserialize(parse_system::<InformationalMessage>(self)),
2423            SystemSubtype::CodeChangePublished => {
2424                reserialize(parse_system::<CodeChangePublishedMessage>(self))
2425            }
2426            SystemSubtype::VcsStateChanged => {
2427                reserialize(parse_system::<VcsStateChangedMessage>(self))
2428            }
2429            SystemSubtype::FeedbackDraftQueued => {
2430                reserialize(parse_system::<FeedbackDraftQueuedMessage>(self))
2431            }
2432            SystemSubtype::CloudSessionDelta => {
2433                reserialize(parse_system::<CloudSessionDeltaMessage>(self))
2434            }
2435            SystemSubtype::DevIntent => reserialize(parse_system::<DevIntentMessage>(self)),
2436            SystemSubtype::TurnHandoffAvailable => {
2437                reserialize(parse_system::<TurnHandoffAvailableMessage>(self))
2438            }
2439            SystemSubtype::TurnPreempted => reserialize(parse_system::<TurnPreemptedMessage>(self)),
2440            SystemSubtype::PeerMessageHold => {
2441                reserialize(parse_system::<PeerMessageHoldMessage>(self))
2442            }
2443            SystemSubtype::PerTurnEffortChanged => {
2444                reserialize(parse_system::<PerTurnEffortChangedMessage>(self))
2445            }
2446            SystemSubtype::SessionTitleChanged => {
2447                reserialize(parse_system::<SessionTitleChangedMessage>(self))
2448            }
2449            SystemSubtype::SessionWritesLost => {
2450                reserialize(parse_system::<SessionWritesLostMessage>(self))
2451            }
2452            SystemSubtype::InstructionSizeWarning => {
2453                reserialize(parse_system::<InstructionSizeWarningMessage>(self))
2454            }
2455            SystemSubtype::FileAttachmentsMissing => {
2456                reserialize(parse_system::<FileAttachmentsMissingMessage>(self))
2457            }
2458            SystemSubtype::PermissionCheckStatus => {
2459                reserialize(parse_system::<PermissionCheckStatusMessage>(self))
2460            }
2461            SystemSubtype::InheritedAsksSettled => {
2462                reserialize(parse_system::<InheritedAsksSettledMessage>(self))
2463            }
2464            SystemSubtype::LateAllowNotRun => {
2465                reserialize(parse_system::<LateAllowNotRunMessage>(self))
2466            }
2467            SystemSubtype::ShellCwd => reserialize(parse_system::<ShellCwdMessage>(self)),
2468            SystemSubtype::TaskListStatuses => {
2469                reserialize(parse_system::<TaskListStatusesMessage>(self))
2470            }
2471            SystemSubtype::UiFocus => reserialize(parse_system::<UiFocusMessage>(self)),
2472            SystemSubtype::UiInvalidate => reserialize(parse_system::<UiInvalidateMessage>(self)),
2473            SystemSubtype::UiLog => reserialize(parse_system::<UiLogMessage>(self)),
2474            SystemSubtype::UiNotify => reserialize(parse_system::<UiNotifyMessage>(self)),
2475            SystemSubtype::UiNotifyCancel => {
2476                reserialize(parse_system::<UiNotifyCancelMessage>(self))
2477            }
2478            SystemSubtype::UiPanes => reserialize(parse_system::<UiPanesMessage>(self)),
2479            SystemSubtype::UiPlaced => reserialize(parse_system::<UiPlacedMessage>(self)),
2480            SystemSubtype::UiScroll => reserialize(parse_system::<UiScrollMessage>(self)),
2481            SystemSubtype::UiStatus => reserialize(parse_system::<UiStatusMessage>(self)),
2482            SystemSubtype::UiToast => reserialize(parse_system::<UiToastMessage>(self)),
2483            SystemSubtype::Unknown(_) => None,
2484        }
2485    }
2486}
2487
2488fn parse_system<T: serde::de::DeserializeOwned>(message: &SystemMessage) -> Option<T> {
2489    serde_json::from_value(message.data.clone()).ok()
2490}
2491
2492/// Owned typed view over any known system message subtype.
2493// `InitMessage` outgrew clippy's variant-size threshold when CLI 2.1.232
2494// added fields. This enum is a transient per-parse classification (never
2495// stored in bulk), so boxing would break every match site for no retained-
2496// memory win.
2497#[allow(clippy::large_enum_variant)]
2498#[derive(Debug, Clone, Serialize, Deserialize)]
2499pub enum KnownSystemEvent {
2500    Init(InitMessage),
2501    Status(StatusMessage),
2502    CompactBoundary(CompactBoundaryMessage),
2503    ThinkingTokens(ThinkingTokensMessage),
2504    TaskStarted(TaskStartedMessage),
2505    TaskProgress(TaskProgressMessage),
2506    TaskUpdated(TaskUpdatedMessage),
2507    TaskNotification(TaskNotificationMessage),
2508    ApiRetry(ApiRetryMessage),
2509    ControlRequestProgress(ControlRequestProgressMessage),
2510    ModelRefusalFallback(ModelRefusalFallbackMessage),
2511    ModelRefusalNoFallback(ModelRefusalNoFallbackMessage),
2512    LocalCommandOutput(LocalCommandOutputMessage),
2513    HookStarted(HookStartedMessage),
2514    HookProgress(HookProgressMessage),
2515    HookResponse(HookResponseMessage),
2516    PluginInstall(PluginInstallMessage),
2517    BackgroundTasksChanged(BackgroundTasksChangedMessage),
2518    SessionStateChanged(SessionStateChangedMessage),
2519    WorkerShuttingDown(WorkerShuttingDownMessage),
2520    CommandsChanged(CommandsChangedMessage),
2521    Notification(NotificationMessage),
2522    FilesPersisted(FilesPersistedMessage),
2523    MemoryRecall(MemoryRecallMessage),
2524    ElicitationComplete(ElicitationCompleteMessage),
2525    PermissionDenied(PermissionDeniedMessage),
2526    MirrorError(MirrorErrorMessage),
2527    Informational(InformationalMessage),
2528    CodeChangePublished(CodeChangePublishedMessage),
2529    VcsStateChanged(VcsStateChangedMessage),
2530    FeedbackDraftQueued(FeedbackDraftQueuedMessage),
2531    CloudSessionDelta(CloudSessionDeltaMessage),
2532    DevIntent(DevIntentMessage),
2533    TurnHandoffAvailable(TurnHandoffAvailableMessage),
2534    TurnPreempted(TurnPreemptedMessage),
2535    PeerMessageHold(PeerMessageHoldMessage),
2536    PerTurnEffortChanged(PerTurnEffortChangedMessage),
2537    SessionTitleChanged(SessionTitleChangedMessage),
2538    SessionWritesLost(SessionWritesLostMessage),
2539    InstructionSizeWarning(InstructionSizeWarningMessage),
2540    FileAttachmentsMissing(FileAttachmentsMissingMessage),
2541    PermissionCheckStatus(PermissionCheckStatusMessage),
2542    InheritedAsksSettled(InheritedAsksSettledMessage),
2543    LateAllowNotRun(LateAllowNotRunMessage),
2544    ShellCwd(ShellCwdMessage),
2545    TaskListStatuses(TaskListStatusesMessage),
2546    UiFocus(UiFocusMessage),
2547    UiInvalidate(UiInvalidateMessage),
2548    UiLog(UiLogMessage),
2549    UiNotify(UiNotifyMessage),
2550    UiNotifyCancel(UiNotifyCancelMessage),
2551    UiPanes(UiPanesMessage),
2552    UiPlaced(UiPlacedMessage),
2553    UiScroll(UiScrollMessage),
2554    UiStatus(UiStatusMessage),
2555    UiToast(UiToastMessage),
2556}
2557
2558#[derive(Debug, Clone, Serialize, Deserialize)]
2559pub struct ApiRetryMessage {
2560    pub attempt: u64,
2561    pub max_retries: u64,
2562    pub retry_delay_ms: u64,
2563    pub error_status: Option<u16>,
2564    pub error: String,
2565    /// Present only when the API sent no response headers within the
2566    /// first-byte window (`CLAUDE_STREAM_FIRST_BYTE_TIMEOUT_MS`). For this
2567    /// cause `max_retries` is its own cap (normally one retry), not the
2568    /// session budget (CLI 2.1.261+).
2569    #[serde(default, skip_serializing_if = "Option::is_none")]
2570    pub no_response: Option<ApiRetryNoResponse>,
2571    #[serde(default, skip_serializing_if = "Option::is_none")]
2572    pub uuid: Option<String>,
2573    #[serde(default, skip_serializing_if = "Option::is_none")]
2574    pub session_id: Option<String>,
2575}
2576
2577/// Timing of a first-byte-timeout retry, carried as
2578/// [`ApiRetryMessage::no_response`].
2579#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2580pub struct ApiRetryNoResponse {
2581    /// How long the failed attempt waited for response headers.
2582    pub waited_ms: u64,
2583    /// How long the retry will wait for them.
2584    pub retry_wait_ms: u64,
2585}
2586
2587#[derive(Debug, Clone, Serialize, Deserialize)]
2588pub struct ControlRequestProgressMessage {
2589    pub request_id: String,
2590    pub status: String,
2591    #[serde(default, skip_serializing_if = "Option::is_none")]
2592    pub attempt: Option<u64>,
2593    #[serde(default, skip_serializing_if = "Option::is_none")]
2594    pub max_retries: Option<u64>,
2595    #[serde(default, skip_serializing_if = "Option::is_none")]
2596    pub retry_delay_ms: Option<u64>,
2597    #[serde(default, skip_serializing_if = "Option::is_none")]
2598    pub error_status: Option<u16>,
2599    #[serde(default, skip_serializing_if = "Option::is_none")]
2600    pub error: Option<String>,
2601    #[serde(default, skip_serializing_if = "Option::is_none")]
2602    pub uuid: Option<String>,
2603    #[serde(default, skip_serializing_if = "Option::is_none")]
2604    pub session_id: Option<String>,
2605}
2606
2607#[derive(Debug, Clone, Serialize, Deserialize)]
2608pub struct ModelRefusalFallbackMessage {
2609    pub trigger: String,
2610    pub direction: String,
2611    /// `"session"`: the main thread fell back and the session model is
2612    /// swapped. `"local"`: a subagent / side-question (`/btw`) / background
2613    /// fork fell back — only that response came from the fallback model and
2614    /// the session model is unchanged. Absent from CLIs before 2.1.222
2615    /// (treat as `"session"`).
2616    #[serde(default, skip_serializing_if = "Option::is_none")]
2617    pub scope: Option<RefusalFallbackScope>,
2618    pub original_model: String,
2619    pub fallback_model: String,
2620    pub request_id: Option<String>,
2621    #[serde(default, skip_serializing_if = "Option::is_none")]
2622    pub api_refusal_category: Option<String>,
2623    /// Present when any hop of this banner's multi-hop episode was a cyber
2624    /// refusal — not only the origin hop `api_refusal_category` describes.
2625    /// Re-arm evidence for the CLI's cyber-exclusion header on session
2626    /// restore; absent on cyber-free episodes and older CLIs (2.1.239+).
2627    #[serde(default, skip_serializing_if = "Option::is_none")]
2628    pub saw_cyber_refusal: Option<bool>,
2629    #[serde(default, skip_serializing_if = "Option::is_none")]
2630    pub api_refusal_explanation: Option<String>,
2631    /// Cyber Verification Program status of the account that made the
2632    /// request, as the API gave it for `original_model` (`stop_details.
2633    /// cyber_verification`). Only on session-scope notices whose
2634    /// `api_refusal_category` is `cyber`; it may not belong to `request_id`
2635    /// when the switch went through several hops. Absent, or `{type:
2636    /// "inactive"}` with no reason, means unknown, not "no access". Map
2637    /// known values to your own text; never display them (CLI 2.1.317+).
2638    #[serde(default, skip_serializing_if = "Option::is_none")]
2639    pub api_refusal_cyber_verification: Option<CyberVerificationStatus>,
2640    #[serde(default, skip_serializing_if = "Option::is_none")]
2641    pub retracted_message_uuids: Option<Vec<String>>,
2642    #[serde(default, skip_serializing_if = "Option::is_none")]
2643    pub refused_user_message_uuid: Option<String>,
2644    pub content: Value,
2645    #[serde(default, skip_serializing_if = "Option::is_none")]
2646    pub uuid: Option<String>,
2647    #[serde(default, skip_serializing_if = "Option::is_none")]
2648    pub session_id: Option<String>,
2649}
2650
2651/// [`ModelRefusalFallbackMessage::api_refusal_cyber_verification`]: the
2652/// account's Cyber Verification Program status as the API reported it
2653/// (CLI 2.1.317+). All three values are opaque API strings.
2654#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2655pub struct CyberVerificationStatus {
2656    #[serde(rename = "type")]
2657    pub verification_type: String,
2658    #[serde(default, skip_serializing_if = "Option::is_none")]
2659    pub tier: Option<String>,
2660    #[serde(default, skip_serializing_if = "Option::is_none")]
2661    pub reason: Option<String>,
2662}
2663
2664/// Scope of a refusal-fallback model swap, carried by
2665/// [`ModelRefusalFallbackMessage::scope`]. Open — new scopes may ship on the
2666/// wire ahead of schema updates.
2667#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2668pub enum RefusalFallbackScope {
2669    /// The main thread fell back; the session model is swapped.
2670    Session,
2671    /// A subagent / side-question / background fork fell back; only that
2672    /// response used the fallback model, the session model is unchanged.
2673    Local,
2674    /// A scope not yet known to this version of the crate.
2675    Unknown(String),
2676}
2677
2678impl RefusalFallbackScope {
2679    pub fn as_str(&self) -> &str {
2680        match self {
2681            Self::Session => "session",
2682            Self::Local => "local",
2683            Self::Unknown(s) => s.as_str(),
2684        }
2685    }
2686}
2687
2688impl fmt::Display for RefusalFallbackScope {
2689    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2690        f.write_str(self.as_str())
2691    }
2692}
2693
2694impl From<&str> for RefusalFallbackScope {
2695    fn from(s: &str) -> Self {
2696        match s {
2697            "session" => Self::Session,
2698            "local" => Self::Local,
2699            other => Self::Unknown(other.to_string()),
2700        }
2701    }
2702}
2703
2704impl Serialize for RefusalFallbackScope {
2705    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2706        serializer.serialize_str(self.as_str())
2707    }
2708}
2709
2710impl<'de> Deserialize<'de> for RefusalFallbackScope {
2711    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
2712        let s = String::deserialize(deserializer)?;
2713        Ok(Self::from(s.as_str()))
2714    }
2715}
2716
2717#[derive(Debug, Clone, Serialize, Deserialize)]
2718pub struct ModelRefusalNoFallbackMessage {
2719    pub original_model: String,
2720    pub request_id: Option<String>,
2721    #[serde(default, skip_serializing_if = "Option::is_none")]
2722    pub api_refusal_category: Option<String>,
2723    #[serde(default, skip_serializing_if = "Option::is_none")]
2724    pub api_refusal_explanation: Option<String>,
2725    pub content: Value,
2726    #[serde(default, skip_serializing_if = "Option::is_none")]
2727    pub uuid: Option<String>,
2728    #[serde(default, skip_serializing_if = "Option::is_none")]
2729    pub session_id: Option<String>,
2730}
2731
2732#[derive(Debug, Clone, Serialize, Deserialize)]
2733pub struct LocalCommandOutputMessage {
2734    pub content: String,
2735    #[serde(default, skip_serializing_if = "Option::is_none")]
2736    pub uuid: Option<String>,
2737    #[serde(default, skip_serializing_if = "Option::is_none")]
2738    pub session_id: Option<String>,
2739}
2740
2741#[derive(Debug, Clone, Serialize, Deserialize)]
2742pub struct HookStartedMessage {
2743    pub hook_id: String,
2744    pub hook_name: String,
2745    pub hook_event: String,
2746    /// Who configured the hook (`user_settings`, `project_settings`,
2747    /// `policy_settings`, `official_plugin`, …); treat an unfamiliar value as
2748    /// unknown. Set only on `SessionStart` hooks in the Claude desktop app's
2749    /// Code tab while the session's records stay local (CLI 2.1.326+).
2750    #[serde(default, skip_serializing_if = "Option::is_none")]
2751    pub origin: Option<String>,
2752    /// With `origin`: a short display name — the hook's `statusMessage`, or
2753    /// the file name of its program for a settings hook. One line, at most 80
2754    /// characters, untrusted (CLI 2.1.326+).
2755    #[serde(default, skip_serializing_if = "Option::is_none")]
2756    pub label: Option<String>,
2757    /// With `origin`: the plugin the hook comes from. One line, at most 80
2758    /// characters, untrusted (CLI 2.1.326+).
2759    #[serde(default, skip_serializing_if = "Option::is_none")]
2760    pub plugin_name: Option<String>,
2761    #[serde(default, skip_serializing_if = "Option::is_none")]
2762    pub uuid: Option<String>,
2763    #[serde(default, skip_serializing_if = "Option::is_none")]
2764    pub session_id: Option<String>,
2765}
2766
2767#[derive(Debug, Clone, Serialize, Deserialize)]
2768pub struct HookProgressMessage {
2769    pub hook_id: String,
2770    pub hook_name: String,
2771    pub hook_event: String,
2772    #[serde(default, skip_serializing_if = "Option::is_none")]
2773    pub stdout: Option<String>,
2774    #[serde(default, skip_serializing_if = "Option::is_none")]
2775    pub stderr: Option<String>,
2776    #[serde(default, skip_serializing_if = "Option::is_none")]
2777    pub output: Option<String>,
2778    /// `true` when the hook went to the background and the session no longer
2779    /// waits for it. Sent once, with no output, for a hook whose
2780    /// `hook_started` carried `origin` (CLI 2.1.326+).
2781    #[serde(default, skip_serializing_if = "Option::is_none")]
2782    pub backgrounded: Option<bool>,
2783    #[serde(default, skip_serializing_if = "Option::is_none")]
2784    pub uuid: Option<String>,
2785    #[serde(default, skip_serializing_if = "Option::is_none")]
2786    pub session_id: Option<String>,
2787}
2788
2789#[derive(Debug, Clone, Serialize, Deserialize)]
2790pub struct HookResponseMessage {
2791    pub hook_id: String,
2792    pub hook_name: String,
2793    pub hook_event: String,
2794    #[serde(default, skip_serializing_if = "Option::is_none")]
2795    pub stdout: Option<String>,
2796    #[serde(default, skip_serializing_if = "Option::is_none")]
2797    pub stderr: Option<String>,
2798    #[serde(default, skip_serializing_if = "Option::is_none")]
2799    pub output: Option<String>,
2800    #[serde(default, skip_serializing_if = "Option::is_none")]
2801    pub exit_code: Option<i32>,
2802    pub outcome: String,
2803    #[serde(default, skip_serializing_if = "Option::is_none")]
2804    pub uuid: Option<String>,
2805    #[serde(default, skip_serializing_if = "Option::is_none")]
2806    pub session_id: Option<String>,
2807}
2808
2809#[derive(Debug, Clone, Serialize, Deserialize)]
2810pub struct PluginInstallMessage {
2811    pub status: String,
2812    #[serde(default, skip_serializing_if = "Option::is_none")]
2813    pub name: Option<String>,
2814    #[serde(default, skip_serializing_if = "Option::is_none")]
2815    pub error: Option<String>,
2816    #[serde(default, skip_serializing_if = "Option::is_none")]
2817    pub uuid: Option<String>,
2818    #[serde(default, skip_serializing_if = "Option::is_none")]
2819    pub session_id: Option<String>,
2820}
2821
2822#[derive(Debug, Clone, Serialize, Deserialize)]
2823pub struct BackgroundTasksChangedMessage {
2824    pub tasks: Vec<BackgroundTaskInfo>,
2825    #[serde(default, skip_serializing_if = "Option::is_none")]
2826    pub uuid: Option<String>,
2827    #[serde(default, skip_serializing_if = "Option::is_none")]
2828    pub session_id: Option<String>,
2829}
2830
2831#[derive(Debug, Clone, Serialize, Deserialize)]
2832pub struct BackgroundTaskInfo {
2833    pub task_id: String,
2834    /// Id of the task's current run; see [`TaskStartedMessage::run_id`]
2835    /// (CLI 2.1.292+).
2836    #[serde(default, skip_serializing_if = "Option::is_none")]
2837    pub run_id: Option<String>,
2838    pub task_type: String,
2839    /// Agent type of a `local_agent` task, such as `general-purpose` or a
2840    /// custom agent's name; `main-session` for a backgrounded main session.
2841    /// Not set on other tasks (CLI 2.1.293+).
2842    #[serde(default, skip_serializing_if = "Option::is_none")]
2843    pub subagent_type: Option<String>,
2844    pub description: String,
2845    /// `task_id` of the subagent task that launched this one; see
2846    /// [`TaskStartedMessage::parent_task_id`] (CLI 2.1.292+).
2847    #[serde(default, skip_serializing_if = "Option::is_none")]
2848    pub parent_task_id: Option<String>,
2849    /// True for housekeeping tasks the CLI does not surface as user work;
2850    /// hosts should exclude them from activity indicators (CLI 2.1.259+).
2851    #[serde(default, skip_serializing_if = "Option::is_none")]
2852    pub ambient: Option<bool>,
2853    /// True for an awaited run of a resumed subagent; see
2854    /// [`TaskStartedMessage::awaited`] (CLI 2.1.293+).
2855    #[serde(default, skip_serializing_if = "Option::is_none")]
2856    pub awaited: Option<bool>,
2857    /// True for a task whose work goes on outside this process: show the
2858    /// task as running, but a host need not stay up for it. Marked
2859    /// `@internal` upstream (CLI 2.1.323+).
2860    #[serde(default, skip_serializing_if = "Option::is_none")]
2861    pub off_host: Option<bool>,
2862}
2863
2864#[derive(Debug, Clone, Serialize, Deserialize)]
2865pub struct SessionStateChangedMessage {
2866    pub state: String,
2867    #[serde(default, skip_serializing_if = "Option::is_none")]
2868    pub uuid: Option<String>,
2869    #[serde(default, skip_serializing_if = "Option::is_none")]
2870    pub session_id: Option<String>,
2871}
2872
2873#[derive(Debug, Clone, Serialize, Deserialize)]
2874pub struct WorkerShuttingDownMessage {
2875    pub reason: String,
2876    #[serde(default, skip_serializing_if = "Option::is_none")]
2877    pub uuid: Option<String>,
2878    #[serde(default, skip_serializing_if = "Option::is_none")]
2879    pub session_id: Option<String>,
2880}
2881
2882#[derive(Debug, Clone, Serialize, Deserialize)]
2883pub struct CommandsChangedMessage {
2884    pub commands: Vec<CommandInfo>,
2885    #[serde(default, skip_serializing_if = "Option::is_none")]
2886    pub uuid: Option<String>,
2887    #[serde(default, skip_serializing_if = "Option::is_none")]
2888    pub session_id: Option<String>,
2889}
2890
2891#[derive(Debug, Clone, Serialize, Deserialize)]
2892pub struct CommandInfo {
2893    pub name: String,
2894    pub description: String,
2895    #[serde(rename = "argumentHint")]
2896    pub argument_hint: String,
2897    #[serde(default, skip_serializing_if = "Option::is_none")]
2898    pub aliases: Option<Vec<String>>,
2899    /// True when the command is Claude Code's own; absent for a command
2900    /// defined by a user, project, plugin or MCP server. Rows can share a
2901    /// name: when a marked row carries it, `/name` runs that one, and an
2902    /// unmarked row is the one `/name` runs only when no marked row shares
2903    /// its name (CLI 2.1.278+).
2904    #[serde(default, skip_serializing_if = "Option::is_none")]
2905    pub builtin: Option<bool>,
2906}
2907
2908#[derive(Debug, Clone, Serialize, Deserialize)]
2909pub struct NotificationMessage {
2910    pub key: String,
2911    pub text: String,
2912    pub priority: String,
2913    #[serde(default, skip_serializing_if = "Option::is_none")]
2914    pub color: Option<String>,
2915    #[serde(default, skip_serializing_if = "Option::is_none")]
2916    pub timeout_ms: Option<u64>,
2917    #[serde(default, skip_serializing_if = "Option::is_none")]
2918    pub uuid: Option<String>,
2919    #[serde(default, skip_serializing_if = "Option::is_none")]
2920    pub session_id: Option<String>,
2921}
2922
2923#[derive(Debug, Clone, Serialize, Deserialize)]
2924pub struct FilesPersistedMessage {
2925    pub files: Vec<PersistedFile>,
2926    pub failed: Vec<FailedPersistedFile>,
2927    pub processed_at: String,
2928    #[serde(default, skip_serializing_if = "Option::is_none")]
2929    pub uuid: Option<String>,
2930    #[serde(default, skip_serializing_if = "Option::is_none")]
2931    pub session_id: Option<String>,
2932}
2933
2934#[derive(Debug, Clone, Serialize, Deserialize)]
2935pub struct PersistedFile {
2936    pub filename: String,
2937    pub file_id: String,
2938}
2939
2940#[derive(Debug, Clone, Serialize, Deserialize)]
2941pub struct FailedPersistedFile {
2942    pub filename: String,
2943    pub error: String,
2944}
2945
2946#[derive(Debug, Clone, Serialize, Deserialize)]
2947pub struct MemoryRecallMessage {
2948    pub mode: String,
2949    pub memories: Vec<MemoryRecallItem>,
2950    #[serde(default, skip_serializing_if = "Option::is_none")]
2951    pub uuid: Option<String>,
2952    #[serde(default, skip_serializing_if = "Option::is_none")]
2953    pub session_id: Option<String>,
2954}
2955
2956#[derive(Debug, Clone, Serialize, Deserialize)]
2957pub struct MemoryRecallItem {
2958    pub path: String,
2959    pub scope: String,
2960    #[serde(default, skip_serializing_if = "Option::is_none")]
2961    pub content: Option<String>,
2962}
2963
2964#[derive(Debug, Clone, Serialize, Deserialize)]
2965pub struct ElicitationCompleteMessage {
2966    pub mcp_server_name: String,
2967    pub elicitation_id: String,
2968    #[serde(default, skip_serializing_if = "Option::is_none")]
2969    pub uuid: Option<String>,
2970    #[serde(default, skip_serializing_if = "Option::is_none")]
2971    pub session_id: Option<String>,
2972}
2973
2974#[derive(Debug, Clone, Serialize, Deserialize)]
2975pub struct PermissionDeniedMessage {
2976    pub tool_name: String,
2977    pub tool_use_id: String,
2978    #[serde(default, skip_serializing_if = "Option::is_none")]
2979    pub agent_id: Option<String>,
2980    #[serde(default, skip_serializing_if = "Option::is_none")]
2981    pub decision_reason_type: Option<String>,
2982    /// A closed-set code for a reason a host can act on, beside
2983    /// `decision_reason_type` (whose values are unchanged). Absent for
2984    /// every other reason; new values are additive (CLI 2.1.276+).
2985    #[serde(default, skip_serializing_if = "Option::is_none")]
2986    pub decision_reason_code: Option<PermissionDeniedReasonCode>,
2987    #[serde(default, skip_serializing_if = "Option::is_none")]
2988    pub decision_reason: Option<String>,
2989    pub message: String,
2990    #[serde(default, skip_serializing_if = "Option::is_none")]
2991    pub uuid: Option<String>,
2992    #[serde(default, skip_serializing_if = "Option::is_none")]
2993    pub session_id: Option<String>,
2994}
2995
2996/// An actionable reason behind a `system/permission_denied` frame
2997/// ([`PermissionDeniedMessage::decision_reason_code`]).
2998#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2999pub enum PermissionDeniedReasonCode {
3000    /// The auto-mode classifier's transcript exceeded its context window.
3001    ClassifierTranscriptTooLong,
3002    /// `permissions.blockReadsOutsideWorkingDirectories` refused the path.
3003    OutsideReadsBlocked,
3004    /// `/pause-memory` has memory paused.
3005    MemoryPaused,
3006    /// Auto mode's safety check does not run for this session, so calls
3007    /// that need it are refused. Another permission mode can run such a
3008    /// call unless only the check may allow the tool; the check can come
3009    /// back (CLI 2.1.319+).
3010    AutoModeNoCheckInSession,
3011    /// The denial that ended a turn or subagent run after ten responses in
3012    /// a row with no verdict: the check does not run for this session
3013    /// (CLI 2.1.319+).
3014    AutoModeStopNoCheckInSession,
3015    /// As [`AutoModeStopNoCheckInSession`](Self::AutoModeStopNoCheckInSession),
3016    /// but the call got no result from the check (CLI 2.1.319+).
3017    AutoModeStopNoResultForCalls,
3018    /// As [`AutoModeStopNoCheckInSession`](Self::AutoModeStopNoCheckInSession),
3019    /// but the server returned no usable verdict, as in an outage
3020    /// (CLI 2.1.319+).
3021    AutoModeStopNoVerdict,
3022    /// A code not yet known to this version of the crate.
3023    Unknown(String),
3024}
3025
3026impl PermissionDeniedReasonCode {
3027    pub fn as_str(&self) -> &str {
3028        match self {
3029            Self::ClassifierTranscriptTooLong => "classifier_transcript_too_long",
3030            Self::OutsideReadsBlocked => "outside_reads_blocked",
3031            Self::MemoryPaused => "memory_paused",
3032            Self::AutoModeNoCheckInSession => "auto_mode_no_check_in_session",
3033            Self::AutoModeStopNoCheckInSession => "auto_mode_stop_no_check_in_session",
3034            Self::AutoModeStopNoResultForCalls => "auto_mode_stop_no_result_for_calls",
3035            Self::AutoModeStopNoVerdict => "auto_mode_stop_no_verdict",
3036            Self::Unknown(s) => s.as_str(),
3037        }
3038    }
3039}
3040
3041impl fmt::Display for PermissionDeniedReasonCode {
3042    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3043        f.write_str(self.as_str())
3044    }
3045}
3046
3047impl From<&str> for PermissionDeniedReasonCode {
3048    fn from(s: &str) -> Self {
3049        match s {
3050            "classifier_transcript_too_long" => Self::ClassifierTranscriptTooLong,
3051            "outside_reads_blocked" => Self::OutsideReadsBlocked,
3052            "memory_paused" => Self::MemoryPaused,
3053            "auto_mode_no_check_in_session" => Self::AutoModeNoCheckInSession,
3054            "auto_mode_stop_no_check_in_session" => Self::AutoModeStopNoCheckInSession,
3055            "auto_mode_stop_no_result_for_calls" => Self::AutoModeStopNoResultForCalls,
3056            "auto_mode_stop_no_verdict" => Self::AutoModeStopNoVerdict,
3057            other => Self::Unknown(other.to_string()),
3058        }
3059    }
3060}
3061
3062impl Serialize for PermissionDeniedReasonCode {
3063    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
3064        serializer.serialize_str(self.as_str())
3065    }
3066}
3067
3068impl<'de> Deserialize<'de> for PermissionDeniedReasonCode {
3069    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
3070        let s = String::deserialize(deserializer)?;
3071        Ok(Self::from(s.as_str()))
3072    }
3073}
3074
3075#[derive(Debug, Clone, Serialize, Deserialize)]
3076pub struct MirrorErrorMessage {
3077    pub error: String,
3078    pub key: MirrorErrorKey,
3079    #[serde(default, skip_serializing_if = "Option::is_none")]
3080    pub uuid: Option<String>,
3081    #[serde(default, skip_serializing_if = "Option::is_none")]
3082    pub session_id: Option<String>,
3083}
3084
3085#[derive(Debug, Clone, Serialize, Deserialize)]
3086pub struct MirrorErrorKey {
3087    #[serde(rename = "projectKey")]
3088    pub project_key: String,
3089    #[serde(rename = "sessionId")]
3090    pub session_id: String,
3091    #[serde(default, skip_serializing_if = "Option::is_none")]
3092    pub subpath: Option<String>,
3093}
3094
3095#[derive(Debug, Clone, Serialize, Deserialize)]
3096pub struct InformationalMessage {
3097    pub content: String,
3098    pub level: String,
3099    #[serde(default, skip_serializing_if = "Option::is_none")]
3100    pub tool_use_id: Option<String>,
3101    #[serde(default, skip_serializing_if = "Option::is_none")]
3102    pub prevent_continuation: Option<bool>,
3103    /// Opaque feature tag on a line a host may treat specially; absent on
3104    /// ordinary lines. Hosts ignore values they do not know (CLI 2.1.288+).
3105    #[serde(default, skip_serializing_if = "Option::is_none")]
3106    pub tag: Option<String>,
3107    /// Present on the line that ends a submitted prompt before a model call:
3108    /// how the prompt ended, so a host can write its own message or count
3109    /// endings without matching `content`. A follow-up a hook blocks while a
3110    /// turn runs carries it too, so read it as the end of a turn only when
3111    /// the next result has `num_turns` 0 (CLI 2.1.300+).
3112    #[serde(default, skip_serializing_if = "Option::is_none")]
3113    pub prompt_submit_outcome: Option<PromptSubmitOutcome>,
3114    /// Present on the warning that says a requested model was refused and
3115    /// the session uses another, so a host can word the notice itself
3116    /// instead of reading `content` (CLI 2.1.317+).
3117    #[serde(default, skip_serializing_if = "Option::is_none")]
3118    pub model_restriction: Option<ModelRestriction>,
3119    /// Present on the warning, tagged `hook_no_verdict`, that a PreToolUse
3120    /// hook gave no verdict on a call and that its failure did not refuse
3121    /// the call, so a host can word the notice itself instead of reading
3122    /// `content`. Sent once per hook per session, for the first such call.
3123    /// Marked `@internal` upstream (CLI 2.1.325+).
3124    #[serde(default, skip_serializing_if = "Option::is_none")]
3125    pub hook_no_verdict: Option<HookNoVerdict>,
3126    /// Present on the line tagged `connector_files` when a connector's files
3127    /// were saved on this computer, so a host can link each path. Marked
3128    /// `@internal` upstream (CLI 2.1.328+).
3129    #[serde(default, skip_serializing_if = "Option::is_none")]
3130    pub saved_files: Option<Vec<SavedConnectorFile>>,
3131    #[serde(default, skip_serializing_if = "Option::is_none")]
3132    pub uuid: Option<String>,
3133    #[serde(default, skip_serializing_if = "Option::is_none")]
3134    pub session_id: Option<String>,
3135}
3136
3137/// One entry of [`InformationalMessage::saved_files`]: a connector's file
3138/// saved on this computer (CLI 2.1.328+).
3139#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3140pub struct SavedConnectorFile {
3141    /// The line of `content`, counted from 0, that ends with
3142    /// [`shown`](Self::shown).
3143    pub line: u64,
3144    /// The absolute path of the saved file. A connector can have chosen the
3145    /// file's name.
3146    pub path: String,
3147    /// The absolute path as a person reads it, as written at the end of
3148    /// [`line`](Self::line).
3149    pub shown: String,
3150}
3151
3152/// [`InformationalMessage::hook_no_verdict`]: a PreToolUse hook gave no
3153/// verdict on a tool call, and its failure did not refuse the call. Another
3154/// hook, a rule or the person may still stop that call. Not sent for a hook
3155/// that chose a non-blocking exit, nor where the failure refused the call
3156/// (CLI 2.1.325+).
3157#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3158pub struct HookNoVerdict {
3159    /// The hook event, e.g. `PreToolUse`.
3160    pub hook_event: String,
3161    /// The tool call the hook gave no verdict on.
3162    pub tool_use_id: String,
3163    /// `true` for a hook that ended with no answer, usually at its timeout.
3164    pub timed_out: bool,
3165    /// The plugin that owns the hook, for a plugin's hook.
3166    #[serde(default, skip_serializing_if = "Option::is_none")]
3167    pub plugin_id: Option<String>,
3168    /// The root directory of the plugin that owns the hook.
3169    #[serde(default, skip_serializing_if = "Option::is_none")]
3170    pub plugin_root: Option<String>,
3171}
3172
3173/// [`InformationalMessage::model_restriction`]: a requested model was
3174/// refused and the session uses another. Both names are cleaned as they
3175/// are in `content` (model-id characters only, cut to 128 with a trailing
3176/// `…`, or `(unrecognized model name)` when none are left) but are still
3177/// untrusted text: render them as plain text (CLI 2.1.317+).
3178#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3179pub struct ModelRestriction {
3180    /// The refused model as it was asked for, or the id that a refused
3181    /// Default pick stood for.
3182    pub requested_model: String,
3183    /// The model in use when the line was built; a later switch can
3184    /// outdate it.
3185    pub effective_model: String,
3186    /// `start` for the model the process chose when it started (from
3187    /// `--model`, the environment, settings or `--agent`'s frontmatter);
3188    /// `switch` for anything later. The CLI reads an unknown value as
3189    /// absent, so treat one that way too.
3190    #[serde(default, skip_serializing_if = "Option::is_none")]
3191    pub at: Option<String>,
3192}
3193
3194/// How a submitted prompt ended before a model call, carried as
3195/// [`InformationalMessage::prompt_submit_outcome`] (CLI 2.1.300+).
3196#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3197pub struct PromptSubmitOutcome {
3198    /// What ended the prompt. The CLI drops a kind it does not know, so the
3199    /// key can be absent; treat [`PromptSubmitOutcomeKind::Other`] as absent
3200    /// too, and ignore [`reason`](Self::reason) beside it.
3201    #[serde(default, skip_serializing_if = "Option::is_none")]
3202    pub kind: Option<PromptSubmitOutcomeKind>,
3203    /// Sent with kind `no_verdict`, and says why: `remote_run_failed`,
3204    /// `remote_run_timed_out`, `interrupted`, `remote_runner_refused`,
3205    /// `unsupported_in_cloud_session`, `output_distrusted`,
3206    /// `callback_timed_out`, `hook_failed`, `hook_timed_out`,
3207    /// `hooks_never_ran`, `personal_config_refused` or
3208    /// `rewrite_unplaceable`. Open set — treat an unknown value as absent.
3209    #[serde(default, skip_serializing_if = "Option::is_none")]
3210    pub no_verdict_kind: Option<String>,
3211    /// True when the prompt stays in the conversation, where the model reads
3212    /// it on the next turn. Do not infer it from `kind`.
3213    pub prompt_kept: bool,
3214    /// The hook's text as Claude Code got it, sanitized and possibly cut.
3215    /// Never sent with `no_verdict`; absent when Claude Code got no text.
3216    /// Untrusted and can quote the prompt, so render it as plain text.
3217    #[serde(default, skip_serializing_if = "Option::is_none")]
3218    pub reason: Option<String>,
3219}
3220
3221/// [`PromptSubmitOutcome::kind`] — what ended a submitted prompt.
3222#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3223pub enum PromptSubmitOutcomeKind {
3224    /// A hook answered with a block.
3225    BlockedByHook,
3226    /// A hook answered `continue: false`.
3227    StoppedByHook,
3228    /// A plugin's code module dropped the prompt.
3229    DroppedByHook,
3230    /// A plugin's code module answered and did not pass the prompt on.
3231    NotPassedOn,
3232    /// No hook gave a verdict, and Claude Code ended the prompt itself; see
3233    /// [`PromptSubmitOutcome::no_verdict_kind`].
3234    NoVerdict,
3235    /// A kind not yet known to this version of the crate.
3236    Other(String),
3237}
3238
3239impl PromptSubmitOutcomeKind {
3240    pub fn as_str(&self) -> &str {
3241        match self {
3242            Self::BlockedByHook => "blocked_by_hook",
3243            Self::StoppedByHook => "stopped_by_hook",
3244            Self::DroppedByHook => "dropped_by_hook",
3245            Self::NotPassedOn => "not_passed_on",
3246            Self::NoVerdict => "no_verdict",
3247            Self::Other(s) => s.as_str(),
3248        }
3249    }
3250}
3251
3252impl fmt::Display for PromptSubmitOutcomeKind {
3253    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3254        f.write_str(self.as_str())
3255    }
3256}
3257
3258impl From<&str> for PromptSubmitOutcomeKind {
3259    fn from(s: &str) -> Self {
3260        match s {
3261            "blocked_by_hook" => Self::BlockedByHook,
3262            "stopped_by_hook" => Self::StoppedByHook,
3263            "dropped_by_hook" => Self::DroppedByHook,
3264            "not_passed_on" => Self::NotPassedOn,
3265            "no_verdict" => Self::NoVerdict,
3266            other => Self::Other(other.to_string()),
3267        }
3268    }
3269}
3270
3271impl Serialize for PromptSubmitOutcomeKind {
3272    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
3273        serializer.serialize_str(self.as_str())
3274    }
3275}
3276
3277impl<'de> Deserialize<'de> for PromptSubmitOutcomeKind {
3278    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
3279        let s = String::deserialize(deserializer)?;
3280        Ok(Self::from(s.as_str()))
3281    }
3282}
3283
3284/// Plugin info from the init message
3285#[derive(Debug, Clone, Serialize, Deserialize)]
3286pub struct PluginInfo {
3287    /// Plugin name
3288    pub name: String,
3289    /// Path to the plugin on disk
3290    pub path: String,
3291    /// Plugin registry source (e.g., "rust-analyzer-lsp@claude-plugins-official")
3292    #[serde(skip_serializing_if = "Option::is_none")]
3293    pub source: Option<String>,
3294    /// Installed plugin version (e.g., "1.0.0"). Added in CLI 2.1.219.
3295    #[serde(default, skip_serializing_if = "Option::is_none")]
3296    pub version: Option<String>,
3297}
3298
3299/// Plugin load diagnostic reported by system init.
3300#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3301pub struct PluginDiagnostic {
3302    pub plugin: String,
3303    #[serde(rename = "type")]
3304    pub diagnostic_type: String,
3305    pub message: String,
3306    /// Present only when a `--plugin-dir`, SDK `plugins` or synced directory
3307    /// entry did not load at all: the path of that entry, resolved against
3308    /// the cwd (a `--plugin-url` entry carries none). `plugin` is then the
3309    /// positional `inline[N]` / `synced[N]` tag, so a host that mounts
3310    /// several directories pairs the error to its own by this path.
3311    #[serde(default, skip_serializing_if = "Option::is_none")]
3312    pub path: Option<String>,
3313    /// Present only when a managed-settings `enabledPlugins` entry dropped
3314    /// this directory, SDK, skills-directory or synced copy (CLI 2.1.325+).
3315    #[serde(default, skip_serializing_if = "Option::is_none")]
3316    pub managed_lock: Option<PluginManagedLock>,
3317}
3318
3319/// [`PluginDiagnostic::managed_lock`]: the managed-settings `enabledPlugins`
3320/// entry that dropped a directory copy of a plugin. Neither value stops an
3321/// install of the same name from another marketplace, which can load beside
3322/// it. `name` and `marketplace` are byte-exact and unbounded (control and
3323/// bidi characters are not removed), so clean and bound them before showing
3324/// them (CLI 2.1.325+).
3325#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3326pub struct PluginManagedLock {
3327    /// `true`: the entry turns that plugin on, and Claude Code does not
3328    /// accept this copy as that plugin. `false`: the entry turns it off, and
3329    /// no directory copy of the name may load.
3330    pub plugin_enabled: bool,
3331    /// The plugin name as the entry spells it, which can differ from the
3332    /// copy (case, Unicode form, an earlier name of a built-in).
3333    pub name: String,
3334    /// The entry's marketplace. Absent where the entry names no marketplace
3335    /// that an install could come from.
3336    #[serde(default, skip_serializing_if = "Option::is_none")]
3337    pub marketplace: Option<String>,
3338}
3339
3340/// Memory paths reported by system init.
3341#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3342pub struct MemoryPaths {
3343    #[serde(default, skip_serializing_if = "Option::is_none")]
3344    pub auto: Option<String>,
3345    #[serde(default, skip_serializing_if = "Option::is_none")]
3346    pub team: Option<String>,
3347    #[serde(flatten)]
3348    pub extra: serde_json::Map<String, Value>,
3349}
3350
3351/// An MCP server config entry that failed validation, reported by system
3352/// init (e.g. a `url` entry with no `type`). The affected server is skipped
3353/// and absent from `InitMessage::mcp_servers`.
3354#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3355pub struct McpServerError {
3356    pub name: String,
3357    /// Stable error category.
3358    #[serde(rename = "type")]
3359    pub error_type: String,
3360    pub message: String,
3361}
3362
3363/// Init system message data - sent at session start
3364#[derive(Debug, Clone, Serialize, Deserialize)]
3365pub struct InitMessage {
3366    /// Session identifier
3367    pub session_id: String,
3368    /// Current working directory
3369    #[serde(skip_serializing_if = "Option::is_none")]
3370    pub cwd: Option<String>,
3371    /// Model being used
3372    #[serde(skip_serializing_if = "Option::is_none")]
3373    pub model: Option<String>,
3374    /// List of available tools
3375    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3376    pub tools: Vec<String>,
3377    /// MCP servers configured
3378    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3379    pub mcp_servers: Vec<Value>,
3380    /// Available slash commands (e.g., "compact", "cost", "review")
3381    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3382    pub slash_commands: Vec<String>,
3383    /// Slash commands only meaningful in a terminal context (CLI 2.1.232+,
3384    /// e.g. "doctor", "color")
3385    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3386    pub terminal_slash_commands: Vec<String>,
3387    /// Available agent types (e.g., "Bash", "Explore", "Plan")
3388    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3389    pub agents: Vec<String>,
3390    /// Installed plugins
3391    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3392    pub plugins: Vec<PluginInfo>,
3393    /// Installed skills
3394    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3395    pub skills: Vec<Value>,
3396    /// Claude Code CLI version
3397    #[serde(skip_serializing_if = "Option::is_none")]
3398    pub claude_code_version: Option<String>,
3399    /// Unix socket path for the harness's inter-session messaging bridge
3400    /// (new in CLI 2.1.232; absent on older CLIs and non-bridged runs)
3401    #[serde(skip_serializing_if = "Option::is_none")]
3402    pub messaging_socket_path: Option<String>,
3403    /// How the API key was sourced
3404    #[serde(skip_serializing_if = "Option::is_none", rename = "apiKeySource")]
3405    pub api_key_source: Option<ApiKeySource>,
3406    /// Output style
3407    #[serde(skip_serializing_if = "Option::is_none")]
3408    pub output_style: Option<OutputStyle>,
3409    /// Permission mode
3410    #[serde(skip_serializing_if = "Option::is_none", rename = "permissionMode")]
3411    pub permission_mode: Option<InitPermissionMode>,
3412
3413    /// Message-level unique identifier
3414    #[serde(skip_serializing_if = "Option::is_none")]
3415    pub uuid: Option<String>,
3416
3417    /// Memory storage paths (e.g., {"auto": "/path/to/memory/"})
3418    #[serde(skip_serializing_if = "Option::is_none")]
3419    pub memory_paths: Option<MemoryPaths>,
3420
3421    /// Absolute path of this session's scratchpad directory, for clients
3422    /// that read files from the session. Omitted when the scratchpad is
3423    /// disabled, and from the redacted init sent over the Remote Control
3424    /// bridge and by the hosted worker (CLI 2.1.278+).
3425    #[serde(default, skip_serializing_if = "Option::is_none")]
3426    pub scratchpad_path: Option<String>,
3427
3428    /// Fast mode toggle state (e.g., "off")
3429    #[serde(skip_serializing_if = "Option::is_none")]
3430    pub fast_mode_state: Option<String>,
3431
3432    /// Why fast mode can't serve right now. Absent when nothing blocks it.
3433    #[serde(default, skip_serializing_if = "Option::is_none")]
3434    pub fast_mode_disabled_reason: Option<super::result::FastModeDisabledReason>,
3435
3436    /// MCP server config entries (from `--mcp-config`) that failed validation
3437    /// and were skipped. Affected servers are absent from `mcp_servers`.
3438    #[serde(default, skip_serializing_if = "Option::is_none")]
3439    pub mcp_server_errors: Option<Vec<McpServerError>>,
3440
3441    /// Whether analytics collection is disabled for this session.
3442    #[serde(default, skip_serializing_if = "Option::is_none")]
3443    pub analytics_disabled: Option<bool>,
3444
3445    /// Whether product-feedback prompts are disabled for this session.
3446    #[serde(default, skip_serializing_if = "Option::is_none")]
3447    pub product_feedback_disabled: Option<bool>,
3448
3449    /// True when this session's model requests go to Anthropic's own API:
3450    /// the first-party provider, with no other base URL or socket, and the
3451    /// organization is not set up to use Claude through another provider.
3452    /// Absent where the process can't tell (an SSH child, a server tenant,
3453    /// workload identity, a mod that hooks `http.fetch`) and from CLIs before
3454    /// 2.1.329. It describes routing alone: a host that sends the session's
3455    /// content to Anthropic must also check ZDR, HIPAA and
3456    /// [`analytics_disabled`](Self::analytics_disabled). Marked `@internal`
3457    /// upstream.
3458    #[serde(default, skip_serializing_if = "Option::is_none")]
3459    pub served_by_anthropic: Option<bool>,
3460
3461    /// API beta flags active for the session.
3462    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3463    pub betas: Vec<String>,
3464
3465    /// Open-set protocol capability names supported by this CLI.
3466    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3467    pub capabilities: Vec<String>,
3468
3469    /// Plugin load errors.
3470    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3471    pub plugin_errors: Vec<PluginDiagnostic>,
3472
3473    /// Plugin load warnings.
3474    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3475    pub plugin_warnings: Vec<PluginDiagnostic>,
3476
3477    /// The effort level the session will send on its next request — after env
3478    /// overrides, session state, org caps, and model-support downgrades
3479    /// (`"low"` | `"medium"` | `"high"` | `"xhigh"` | `"max"`). `None` when no
3480    /// effort parameter will be sent, or on CLIs before 2.1.239.
3481    #[serde(default, skip_serializing_if = "Option::is_none")]
3482    pub effort: Option<String>,
3483
3484    /// Only on init frames written by the headless stream-json client of a
3485    /// cloud-hosted session: a per-frame snapshot of the cloud session's id,
3486    /// view URL, device binding, and directory-sync state. Absent in every
3487    /// other mode. Stored as raw JSON (the shape is internal and evolving).
3488    #[serde(default, skip_serializing_if = "Option::is_none")]
3489    pub cloud_session: Option<Value>,
3490
3491    /// The terminal's server-configured `◆ <text>` footer pill, carried so a
3492    /// host UI can render the same pill. Absent when nothing is configured
3493    /// (CLI 2.1.259+).
3494    #[serde(default, skip_serializing_if = "Option::is_none")]
3495    pub footer_indicator: Option<FooterIndicator>,
3496
3497    /// This cloud worker's life (`CLAUDE_CODE_WORKER_EPOCH`): a new number
3498    /// each time the session's worker is started. Absent outside cloud
3499    /// workers and on CLIs before 2.1.259.
3500    #[serde(default, skip_serializing_if = "Option::is_none")]
3501    pub worker_epoch: Option<u64>,
3502
3503    /// Windows only: the absolute path of the PowerShell binary this session
3504    /// runs PowerShell commands with, or `Some(None)` (wire `null`) when
3505    /// none was found. Absent on other platforms and on CLIs before 2.1.259.
3506    #[serde(default, skip_serializing_if = "Option::is_none")]
3507    pub powershell_path: Option<Option<String>>,
3508
3509    /// Cold-start telemetry for hosted (CCR) sessions: named startup phases
3510    /// and resume-hydration counters. Absent elsewhere. Stored as raw JSON
3511    /// (the shape is internal and evolving) (CLI 2.1.266+).
3512    #[serde(default, skip_serializing_if = "Option::is_none")]
3513    pub startup_timing: Option<serde_json::Map<String, Value>>,
3514
3515    /// Whether per-turn effort is active for this frame's `model`. `true`:
3516    /// an effort change keeps the prompt cache, because the effort is sent
3517    /// inside the conversation at the turn where it changes. `false`: the
3518    /// effort is sent only as the top-level parameter, so a change rewrites
3519    /// the cached prefix. Mid-session the CLI reports only a change to
3520    /// `false` (`system/per_turn_effort_changed`); `true` comes only from an
3521    /// init and is provisional after a fresh process or once the
3522    /// conversation's refusals are cleared, so keep listening all session.
3523    /// Absent means unknown (CLI 2.1.281+).
3524    #[serde(default, skip_serializing_if = "Option::is_none")]
3525    pub per_turn_effort_active: Option<bool>,
3526
3527    /// Whether typing `ultrathink` runs the turn at `xhigh` effort on this
3528    /// frame's `model` (and, when the session is already at `xhigh` or
3529    /// `max`, leaves the turn as it is); a host highlights the word only
3530    /// while this is `true`. After `system/per_turn_effort_changed`, treat it
3531    /// as `false` until the next init. The same answer as `get_settings`'
3532    /// `applied.ultrathinkAvailable`. Sent by the stream-json (Agent SDK)
3533    /// host; absent means unknown (CLI 2.1.316+).
3534    #[serde(default, skip_serializing_if = "Option::is_none")]
3535    pub ultrathink_available: Option<bool>,
3536
3537    /// `true` when a user message carrying
3538    /// [`UserMessage::ultrathink_typed`] that passes that field's checks runs
3539    /// its turn at `xhigh` effort on this frame's `model` (and, when the
3540    /// session is already at `xhigh` or `max`, leaves the turn as it is). A
3541    /// client colors the word and sends the statement only while this is
3542    /// `true`. After `system/per_turn_effort_changed`, treat it as `false`
3543    /// until the next init. Absent means unknown: color nothing and send no
3544    /// statement. Sent by the stream-json (Agent SDK) host and on Remote
3545    /// Control bridge init frames (CLI 2.1.317+).
3546    #[serde(default, skip_serializing_if = "Option::is_none")]
3547    pub ultrathink_typed_raises: Option<bool>,
3548
3549    /// Only on a Cowork cloud worker's init: the thinking this turn runs
3550    /// with. Absent when a request changed the session's thinking after the
3551    /// turn's start, or the session has no thinking setting of its own
3552    /// (CLI 2.1.317+).
3553    #[serde(default, skip_serializing_if = "Option::is_none")]
3554    pub client_thinking: Option<ClientThinking>,
3555
3556    /// Only on a Cowork cloud worker's init: `Some(true)` when an
3557    /// `apply_flag_settings` of exactly `{switchModelsOnFlag: true}` would add
3558    /// nothing now (the session holds the value, and no fast mode resync or
3559    /// auto mode check is due). Absent: send the request (CLI 2.1.317+).
3560    #[serde(default, skip_serializing_if = "Option::is_none")]
3561    pub flag_restate_noop: Option<bool>,
3562
3563    /// Absolute path of the one folder of synced skills whose files
3564    /// `read_file` serves in this session; a client may admit paths below it
3565    /// as it admits paths below [`scratchpad_path`](Self::scratchpad_path).
3566    /// Read only; a symbolic link, a dot-named part or a file at its top is
3567    /// refused. Sent by a self-hosted runner's session alone; omitted where
3568    /// the session serves no such folder, and wherever `original_cwd` is
3569    /// withheld (CLI 2.1.317+).
3570    #[serde(default, skip_serializing_if = "Option::is_none")]
3571    pub synced_skills_path: Option<String>,
3572
3573    /// Whether the session's transcript is in focus view. Toggled by
3574    /// `/focus`, including over Remote Control. Present on Remote Control
3575    /// bridge init frames and on the per-turn init of headless stream-json
3576    /// runs; absent on hosts that do not publish it and on CLIs before
3577    /// 2.1.281. Re-emitted inits carry the current value — the newest frame
3578    /// wins.
3579    #[serde(default, skip_serializing_if = "Option::is_none")]
3580    pub view_mode: Option<ViewMode>,
3581
3582    /// Absolute path of the folder the session's file permission checks are
3583    /// anchored at, for clients that read files from the session. Unlike
3584    /// `cwd` it does not follow the shell: it moves only on `/cd`, on
3585    /// entering or leaving a worktree, and on a session restore. Omitted on
3586    /// the redacted Remote Control / hosted-worker inits, in a session with
3587    /// no directory, for HIPAA organizations, and on CLIs before 2.1.301.
3588    #[serde(default, skip_serializing_if = "Option::is_none")]
3589    pub original_cwd: Option<String>,
3590
3591    /// Absolute paths of the folders added to the session (`--add-dir`, the
3592    /// SDK `additionalDirectories` option, settings, a grant, or a host's
3593    /// mid-session request), in no particular order; `Some(vec![])` when
3594    /// there are none. Folders added only by repository-delivered settings
3595    /// files are left out. Grants nothing: the CLI's own check decides every
3596    /// read. `None` means not told (not "none"): omitted on the same lanes as
3597    /// [`original_cwd`](Self::original_cwd), by hosts that have not wired it,
3598    /// and on CLIs before 2.1.301.
3599    #[serde(default, skip_serializing_if = "Option::is_none")]
3600    pub additional_directories: Option<Vec<String>>,
3601
3602    /// Only in a session that Claude Desktop itself started: the variables
3603    /// by which an administrator's managed settings choose a provider or a
3604    /// gateway, where this start dropped them and requests go straight to
3605    /// Anthropic instead. Worked out anew for every init. Omitted when there
3606    /// is nothing to list, on any transport that stores its frames, from the
3607    /// Remote Control bridge's init, and on CLIs before 2.1.327.
3608    #[serde(default, skip_serializing_if = "Option::is_none")]
3609    pub host_dropped_env: Option<Vec<HostDroppedEnv>>,
3610}
3611
3612/// One entry of [`InitMessage::host_dropped_env`] (CLI 2.1.327+).
3613#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3614pub struct HostDroppedEnv {
3615    /// Where the dropped variables came from: `policySettings`. Ignore an
3616    /// entry with any other value.
3617    pub source: String,
3618    /// Upper-case variable names, never values.
3619    pub names: Vec<String>,
3620}
3621
3622/// [`InitMessage::client_thinking`]: the thinking a Cowork cloud worker's
3623/// turn runs with (CLI 2.1.317+).
3624#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3625pub struct ClientThinking {
3626    /// `0` with thinking off, the fixed budget, or `None` (wire `null`) with
3627    /// no fixed budget.
3628    #[serde(default)]
3629    pub max_thinking_tokens: Option<u64>,
3630    /// `summarized`, `omitted` or `highlights`; `None` (wire `null`) with
3631    /// none, with thinking off, and for a `highlights` this session cannot
3632    /// send.
3633    #[serde(default)]
3634    pub thinking_display: Option<String>,
3635}
3636
3637/// The server-configured session indicator that the terminal renders as a
3638/// `◆ <text>` pill in the prompt footer, carried on `system/init` and the
3639/// `initialize` response (CLI 2.1.259+).
3640#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3641pub struct FooterIndicator {
3642    /// The label to show — already sanitized to a single line of plain text,
3643    /// exactly as the terminal footer renders it after its `◆` glyph.
3644    pub text: String,
3645}
3646
3647/// The session's transcript view, carried as [`InitMessage::view_mode`]
3648/// (CLI 2.1.281+).
3649#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3650pub enum ViewMode {
3651    /// The model is told the user sees only its final message per turn, so
3652    /// clients may collapse each turn to the prompt and the final response.
3653    Focus,
3654    /// The ordinary full transcript.
3655    Default,
3656    /// A mode not yet known to this version of the crate.
3657    Unknown(String),
3658}
3659
3660impl ViewMode {
3661    pub fn as_str(&self) -> &str {
3662        match self {
3663            Self::Focus => "focus",
3664            Self::Default => "default",
3665            Self::Unknown(s) => s.as_str(),
3666        }
3667    }
3668}
3669
3670impl fmt::Display for ViewMode {
3671    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3672        f.write_str(self.as_str())
3673    }
3674}
3675
3676impl From<&str> for ViewMode {
3677    fn from(s: &str) -> Self {
3678        match s {
3679            "focus" => Self::Focus,
3680            "default" => Self::Default,
3681            other => Self::Unknown(other.to_string()),
3682        }
3683    }
3684}
3685
3686impl Serialize for ViewMode {
3687    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
3688        serializer.serialize_str(self.as_str())
3689    }
3690}
3691
3692impl<'de> Deserialize<'de> for ViewMode {
3693    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
3694        let s = String::deserialize(deserializer)?;
3695        Ok(Self::from(s.as_str()))
3696    }
3697}
3698
3699/// Status system message - sent during operations like context compaction
3700#[derive(Debug, Clone, Serialize, Deserialize)]
3701pub struct StatusMessage {
3702    /// Session identifier
3703    pub session_id: String,
3704    /// Current status (e.g., compacting) or null when complete
3705    pub status: Option<StatusMessageStatus>,
3706    /// Unique identifier for this message
3707    #[serde(skip_serializing_if = "Option::is_none")]
3708    pub uuid: Option<String>,
3709    /// Current permission mode when changed mid-session.
3710    #[serde(skip_serializing_if = "Option::is_none", rename = "permissionMode")]
3711    pub permission_mode: Option<InitPermissionMode>,
3712    #[serde(skip_serializing_if = "Option::is_none")]
3713    pub compact_result: Option<String>,
3714    #[serde(skip_serializing_if = "Option::is_none")]
3715    pub compact_error: Option<String>,
3716    /// On the `compacting` statuses of an automatic compaction (absent on a
3717    /// typed `/compact`): characters of the summary streamed so far (text
3718    /// and tool-input deltas, not thinking). Returns to 0 at each new attempt
3719    /// and stays 0 while a background summary is awaited. A rising count
3720    /// shows progress; it is not a share of the final length. Absent from
3721    /// CLIs before 2.1.295. Marked `@internal` upstream.
3722    #[serde(default, skip_serializing_if = "Option::is_none")]
3723    pub compact_output_chars: Option<u64>,
3724    /// Present, and true, once at start-up when
3725    /// `CLAUDE_CODE_RESUME_INTERRUPTED_TURN` asked for the interrupted turn
3726    /// to be re-run and this process did not re-run it: the turn ran in plan
3727    /// mode and the process came back in another mode, where the re-run
3728    /// could carry out a plan nobody approved. Marked `@internal` upstream
3729    /// (CLI 2.1.319+).
3730    #[serde(default, skip_serializing_if = "Option::is_none")]
3731    pub resume_held_for_plan: Option<bool>,
3732}
3733
3734/// Compact boundary message - marks where context compaction occurred
3735#[derive(Debug, Clone, Serialize, Deserialize)]
3736pub struct CompactBoundaryMessage {
3737    /// Session identifier
3738    pub session_id: String,
3739    /// Metadata about the compaction
3740    pub compact_metadata: CompactMetadata,
3741    /// Human-readable summary of what was compacted, when the CLI emits one.
3742    ///
3743    /// Also accepted under the `content` / `text` wire keys.
3744    #[serde(
3745        default,
3746        skip_serializing_if = "Option::is_none",
3747        alias = "content",
3748        alias = "text"
3749    )]
3750    pub summary: Option<String>,
3751    /// Number of messages summarized in this compaction pass, when present.
3752    ///
3753    /// Also accepted under the `message_count` wire key.
3754    #[serde(
3755        default,
3756        skip_serializing_if = "Option::is_none",
3757        alias = "message_count"
3758    )]
3759    pub leaf_message_count: Option<u32>,
3760    /// Wall-clock duration of the compaction pass in milliseconds, when present.
3761    #[serde(default, skip_serializing_if = "Option::is_none")]
3762    pub duration_ms: Option<u64>,
3763    /// Unique identifier for this message
3764    #[serde(skip_serializing_if = "Option::is_none")]
3765    pub uuid: Option<String>,
3766    /// Logical parent across the compaction boundary.
3767    #[serde(skip_serializing_if = "Option::is_none")]
3768    pub logical_parent_uuid: Option<Option<String>>,
3769    /// Replayed history rather than a live message, stamped by the Remote
3770    /// Control bridge when it flushes history to the session server
3771    /// (CLI 2.1.266+).
3772    #[serde(default, skip_serializing_if = "Option::is_none")]
3773    pub historical: Option<bool>,
3774}
3775
3776/// Metadata about context compaction
3777#[derive(Debug, Clone, Serialize, Deserialize)]
3778pub struct CompactMetadata {
3779    /// Number of tokens before compaction
3780    pub pre_tokens: u64,
3781    /// What triggered the compaction
3782    pub trigger: CompactionTrigger,
3783    #[serde(default, skip_serializing_if = "Option::is_none")]
3784    pub post_tokens: Option<u64>,
3785    #[serde(default, skip_serializing_if = "Option::is_none")]
3786    pub cumulative_dropped_tokens: Option<u64>,
3787    #[serde(default, skip_serializing_if = "Option::is_none")]
3788    pub duration_ms: Option<u64>,
3789    #[serde(default, skip_serializing_if = "Option::is_none")]
3790    pub user_context: Option<String>,
3791    #[serde(default, skip_serializing_if = "Option::is_none")]
3792    pub messages_summarized: Option<u64>,
3793    #[serde(default, skip_serializing_if = "Option::is_none")]
3794    pub precomputed: Option<bool>,
3795    #[serde(default, skip_serializing_if = "Option::is_none")]
3796    pub pre_compact_discovered_tools: Option<Vec<String>>,
3797    /// The artifact versions the conversation held before this compaction,
3798    /// most recently changed first; empty when it held none. A resumed
3799    /// session replays these so it can update those artifacts without
3800    /// reading them again (CLI 2.1.285+).
3801    #[serde(default, skip_serializing_if = "Option::is_none")]
3802    pub pre_compact_artifact_read_versions: Option<Vec<ArtifactReadVersion>>,
3803    #[serde(default, skip_serializing_if = "Option::is_none")]
3804    pub preserved_segment: Option<PreservedSegment>,
3805    #[serde(default, skip_serializing_if = "Option::is_none")]
3806    pub preserved_messages: Option<PreservedMessages>,
3807}
3808
3809/// One artifact version a conversation held before a compaction, carried in
3810/// [`CompactMetadata::pre_compact_artifact_read_versions`].
3811#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3812pub struct ArtifactReadVersion {
3813    /// The artifact id.
3814    pub slug: String,
3815    /// The version read or published.
3816    pub ver: String,
3817}
3818
3819#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3820pub struct PreservedSegment {
3821    pub head_uuid: String,
3822    pub anchor_uuid: String,
3823    pub tail_uuid: String,
3824}
3825
3826#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3827pub struct PreservedMessages {
3828    pub anchor_uuid: String,
3829    pub uuids: Vec<String>,
3830    #[serde(default, skip_serializing_if = "Option::is_none")]
3831    pub all_uuids: Option<Vec<String>>,
3832}
3833
3834// ---------------------------------------------------------------------------
3835// Task system message types (task_started, task_progress, task_notification)
3836// ---------------------------------------------------------------------------
3837
3838/// Cumulative usage statistics for a background task.
3839#[derive(Debug, Clone, Serialize, Deserialize)]
3840pub struct TaskUsage {
3841    /// Wall-clock milliseconds since the task started.
3842    pub duration_ms: u64,
3843    /// Total number of tool calls made so far.
3844    pub tool_uses: u64,
3845    /// Total tokens consumed so far.
3846    pub total_tokens: u64,
3847}
3848
3849/// The kind of background task.
3850#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3851pub enum TaskType {
3852    /// A sub-agent task (e.g., Explore, Plan).
3853    LocalAgent,
3854    /// A background bash command.
3855    LocalBash,
3856    /// A local workflow task.
3857    LocalWorkflow,
3858    /// A task type not yet known to this version of the crate.
3859    Unknown(String),
3860}
3861
3862impl TaskType {
3863    pub fn as_str(&self) -> &str {
3864        match self {
3865            Self::LocalAgent => "local_agent",
3866            Self::LocalBash => "local_bash",
3867            Self::LocalWorkflow => "local_workflow",
3868            Self::Unknown(s) => s.as_str(),
3869        }
3870    }
3871}
3872
3873impl fmt::Display for TaskType {
3874    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3875        f.write_str(self.as_str())
3876    }
3877}
3878
3879impl From<&str> for TaskType {
3880    fn from(s: &str) -> Self {
3881        match s {
3882            "local_agent" => Self::LocalAgent,
3883            "local_bash" => Self::LocalBash,
3884            "local_workflow" => Self::LocalWorkflow,
3885            other => Self::Unknown(other.to_string()),
3886        }
3887    }
3888}
3889
3890impl Serialize for TaskType {
3891    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
3892        serializer.serialize_str(self.as_str())
3893    }
3894}
3895
3896impl<'de> Deserialize<'de> for TaskType {
3897    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
3898        let s = String::deserialize(deserializer)?;
3899        Ok(Self::from(s.as_str()))
3900    }
3901}
3902
3903/// Completion status of a background task.
3904#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3905pub enum TaskStatus {
3906    Pending,
3907    Running,
3908    Completed,
3909    Failed,
3910    Killed,
3911    Paused,
3912    Stopped,
3913    Unknown(String),
3914}
3915
3916impl TaskStatus {
3917    pub fn as_str(&self) -> &str {
3918        match self {
3919            Self::Pending => "pending",
3920            Self::Running => "running",
3921            Self::Completed => "completed",
3922            Self::Failed => "failed",
3923            Self::Killed => "killed",
3924            Self::Paused => "paused",
3925            Self::Stopped => "stopped",
3926            Self::Unknown(s) => s.as_str(),
3927        }
3928    }
3929}
3930
3931impl fmt::Display for TaskStatus {
3932    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3933        f.write_str(self.as_str())
3934    }
3935}
3936
3937impl From<&str> for TaskStatus {
3938    fn from(s: &str) -> Self {
3939        match s {
3940            "pending" => Self::Pending,
3941            "running" => Self::Running,
3942            "completed" => Self::Completed,
3943            "failed" => Self::Failed,
3944            "killed" => Self::Killed,
3945            "paused" => Self::Paused,
3946            "stopped" => Self::Stopped,
3947            other => Self::Unknown(other.to_string()),
3948        }
3949    }
3950}
3951
3952impl Serialize for TaskStatus {
3953    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
3954        serializer.serialize_str(self.as_str())
3955    }
3956}
3957
3958impl<'de> Deserialize<'de> for TaskStatus {
3959    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
3960        let s = String::deserialize(deserializer)?;
3961        Ok(Self::from(s.as_str()))
3962    }
3963}
3964
3965/// `task_started` system message — emitted once when a background task begins.
3966#[derive(Debug, Clone, Serialize, Deserialize)]
3967pub struct TaskStartedMessage {
3968    pub session_id: String,
3969    pub task_id: String,
3970    /// Id of one run of the task: equal on every `task_*` event and
3971    /// `background_tasks_changed` entry of that run. A resumed task keeps its
3972    /// `task_id` and gets a new `run_id`; the run ids of one task sort, by
3973    /// plain string comparison, in the order the runs opened. Absent for a
3974    /// task this process did not register (CLI 2.1.292+).
3975    #[serde(default, skip_serializing_if = "Option::is_none")]
3976    pub run_id: Option<String>,
3977    /// `task_id` of the subagent (`local_agent`) task whose agent launched
3978    /// this task. Absent when the launcher is the main thread, has no
3979    /// `task_id` of its own, or is no longer tracked. The parent may be a
3980    /// foreground or already-ended task, so treat an unknown id as no parent
3981    /// (CLI 2.1.292+).
3982    #[serde(default, skip_serializing_if = "Option::is_none")]
3983    pub parent_task_id: Option<String>,
3984    #[serde(default, skip_serializing_if = "Option::is_none")]
3985    pub task_type: Option<TaskType>,
3986    #[serde(default, skip_serializing_if = "Option::is_none")]
3987    pub tool_use_id: Option<String>,
3988    pub description: String,
3989    /// The subagent type for `local_agent` tasks (e.g. `general-purpose`,
3990    /// `Explore`). Absent for `local_bash` tasks.
3991    #[serde(default, skip_serializing_if = "Option::is_none")]
3992    pub subagent_type: Option<String>,
3993    /// Whether the task was registered in the background (`true`) or in the
3994    /// foreground with the spawning tool call blocking on it (`false`). A
3995    /// later move to the background arrives as `task_updated`
3996    /// `patch.is_backgrounded`. Set for `local_agent` and `local_bash` tasks
3997    /// (CLI 2.1.239+).
3998    #[serde(default, skip_serializing_if = "Option::is_none")]
3999    pub is_backgrounded: Option<bool>,
4000    /// True for a run of a resumed subagent (`local_agent`) that the tool
4001    /// call which resumed it waits for, as `SendMessage` does when
4002    /// background tasks are disabled; [`tool_use_id`](Self::tool_use_id)
4003    /// then names that call. The run has ended by the time that call
4004    /// returns, and its report goes into that call's result, so expect no
4005    /// follow-up turn when it ends. A later resume that nothing waits for
4006    /// starts a new run without the field (CLI 2.1.293+).
4007    #[serde(default, skip_serializing_if = "Option::is_none")]
4008    pub awaited: Option<bool>,
4009    /// Nesting depth of a spawned subagent (`local_agent`) task: 1 for a
4010    /// top-level spawn, N+1 when spawned from inside a depth-N agent. Not set
4011    /// on other tasks (CLI 2.1.239+).
4012    #[serde(default, skip_serializing_if = "Option::is_none")]
4013    pub spawn_depth: Option<u32>,
4014    /// The prompt handed to the subagent. Present for `local_agent` tasks.
4015    /// Absent on a subagent run that Claude Code resumed with text of its own
4016    /// (such as a background task's notice): keep the prompt an earlier
4017    /// `task_started` gave. On a run that continues an interrupted turn, this
4018    /// is the task's description (CLI 2.1.327+).
4019    #[serde(default, skip_serializing_if = "Option::is_none")]
4020    pub prompt: Option<String>,
4021    #[serde(default, skip_serializing_if = "Option::is_none")]
4022    pub workflow_name: Option<String>,
4023    #[serde(default, skip_serializing_if = "Option::is_none")]
4024    pub skip_transcript: Option<bool>,
4025    /// True for housekeeping tasks the CLI does not surface as user work
4026    /// (every `skip_transcript` task, plus auto-started live-update
4027    /// watchers); hosts should exclude them from activity indicators
4028    /// (CLI 2.1.259+).
4029    #[serde(default, skip_serializing_if = "Option::is_none")]
4030    pub ambient: Option<bool>,
4031    pub uuid: String,
4032}
4033
4034/// `task_updated` system message — emitted when a background task's state
4035/// changes (e.g. transitions to `completed`). Carries a partial `patch` of the
4036/// fields that changed rather than the full task record.
4037#[derive(Debug, Clone, Serialize, Deserialize)]
4038pub struct TaskUpdatedMessage {
4039    pub session_id: String,
4040    pub task_id: String,
4041    /// Id of the task run this update belongs to; see
4042    /// [`TaskStartedMessage::run_id`] (CLI 2.1.292+).
4043    #[serde(default, skip_serializing_if = "Option::is_none")]
4044    pub run_id: Option<String>,
4045    pub patch: TaskPatch,
4046    pub uuid: String,
4047}
4048
4049/// The partial update carried by a [`TaskUpdatedMessage`]. Every field is
4050/// optional because the CLI only sends the keys that changed.
4051#[derive(Debug, Clone, Default, Serialize, Deserialize)]
4052pub struct TaskPatch {
4053    #[serde(default, skip_serializing_if = "Option::is_none")]
4054    pub status: Option<TaskStatus>,
4055    /// Wall-clock epoch milliseconds when the task finished, when the patch
4056    /// reports completion.
4057    #[serde(default, skip_serializing_if = "Option::is_none")]
4058    pub end_time: Option<u64>,
4059    #[serde(default, skip_serializing_if = "Option::is_none")]
4060    pub description: Option<String>,
4061    #[serde(default, skip_serializing_if = "Option::is_none")]
4062    pub total_paused_ms: Option<u64>,
4063    #[serde(default, skip_serializing_if = "Option::is_none")]
4064    pub error: Option<String>,
4065    #[serde(default, skip_serializing_if = "Option::is_none")]
4066    pub is_backgrounded: Option<bool>,
4067}
4068
4069/// `thinking_tokens` system message — emitted as the model streams extended
4070/// thinking, reporting the running estimate of thinking tokens consumed.
4071#[derive(Debug, Clone, Serialize, Deserialize)]
4072pub struct ThinkingTokensMessage {
4073    pub session_id: String,
4074    /// Running estimate of total thinking tokens for the current turn.
4075    pub estimated_tokens: u64,
4076    /// Increase in the estimate since the previous `thinking_tokens` event.
4077    pub estimated_tokens_delta: u64,
4078    /// Client uuid of the user message that triggered this turn, stamped on
4079    /// every `thinking_tokens` frame of a headless turn so a consumer can
4080    /// attribute thinking progress to the send it answers before any reply
4081    /// frame arrives. Absent on synthetic/scheduled (meta) turns, on turns
4082    /// without a client uuid, on Remote Control sessions, and from CLIs
4083    /// before 2.1.261.
4084    #[serde(default, skip_serializing_if = "Option::is_none")]
4085    pub user_message_uuid: Option<String>,
4086    pub uuid: String,
4087}
4088
4089/// `task_progress` system message — emitted periodically as a background
4090/// agent task executes tools. Not emitted for `local_bash` tasks.
4091#[derive(Debug, Clone, Serialize, Deserialize)]
4092pub struct TaskProgressMessage {
4093    pub session_id: String,
4094    pub task_id: String,
4095    /// Id of the task run this progress belongs to; see
4096    /// [`TaskStartedMessage::run_id`] (CLI 2.1.292+).
4097    #[serde(default, skip_serializing_if = "Option::is_none")]
4098    pub run_id: Option<String>,
4099    #[serde(default, skip_serializing_if = "Option::is_none")]
4100    pub tool_use_id: Option<String>,
4101    pub description: String,
4102    #[serde(default, skip_serializing_if = "Option::is_none")]
4103    pub last_tool_name: Option<String>,
4104    pub usage: TaskUsage,
4105    /// Subagent type for `local_agent` tasks (e.g. `Explore`).
4106    #[serde(default, skip_serializing_if = "Option::is_none")]
4107    pub subagent_type: Option<String>,
4108    #[serde(default, skip_serializing_if = "Option::is_none")]
4109    pub summary: Option<String>,
4110    pub uuid: String,
4111}
4112
4113/// `task_notification` system message — emitted once when a background
4114/// task completes or fails.
4115#[derive(Debug, Clone, Serialize, Deserialize)]
4116pub struct TaskNotificationMessage {
4117    pub session_id: String,
4118    pub task_id: String,
4119    /// Id of the task run this notification closes; see
4120    /// [`TaskStartedMessage::run_id`] (CLI 2.1.292+).
4121    #[serde(default, skip_serializing_if = "Option::is_none")]
4122    pub run_id: Option<String>,
4123    pub status: TaskStatus,
4124    /// Machine-readable cause, set only when the task did not end through an
4125    /// ordinary completion, failure, or stop (CLI 2.1.273+).
4126    #[serde(default, skip_serializing_if = "Option::is_none")]
4127    pub reason: Option<TaskEndReason>,
4128    pub summary: String,
4129    /// `true` when `summary` is the final report of a subagent that nothing
4130    /// waits for, with no review to come: show it as the report. A later
4131    /// notification for the same `task_id` replaces it. Absent when the
4132    /// summary may be a description or interim text, under `handback` (see
4133    /// `handback_report`), or in auto mode (CLI 2.1.326+).
4134    #[serde(default, skip_serializing_if = "Option::is_none")]
4135    pub summary_is_report: Option<bool>,
4136    pub output_file: Option<String>,
4137    #[serde(skip_serializing_if = "Option::is_none")]
4138    pub tool_use_id: Option<String>,
4139    #[serde(skip_serializing_if = "Option::is_none")]
4140    pub usage: Option<TaskUsage>,
4141    /// For a backgrounded MCP task that completed, the `resource_link`
4142    /// content blocks of its final result — the files it returned by
4143    /// reference — collected from the raw result before the CLI renders it
4144    /// as text. Join to the originating call via `tool_use_id`. Absent when
4145    /// the result had none or the task is any other type (CLI 2.1.259+).
4146    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4147    pub resource_links: Vec<ResourceLink>,
4148    /// On a `completed` notification of a subagent that reports through the
4149    /// SubagentHandback tool: how its report reached its caller. Left out
4150    /// when the subagent failed, was stopped, or is still waiting on work;
4151    /// `summary` is then not a report. When present, `summary` holds harness
4152    /// notes written for the model. A later notification for the same
4153    /// `task_id` replaces what an earlier one showed (CLI 2.1.292+).
4154    #[serde(default, skip_serializing_if = "Option::is_none")]
4155    pub handback: Option<TaskHandback>,
4156    /// The report a `send` or `flagged` hand-back delivered: when present,
4157    /// render it instead of `summary`, with its `warning`, if any, above its
4158    /// `text`. Absent for `withheld` (CLI 2.1.292+).
4159    #[serde(default, skip_serializing_if = "Option::is_none")]
4160    pub handback_report: Option<HandbackReport>,
4161    #[serde(default, skip_serializing_if = "Option::is_none")]
4162    pub skip_transcript: Option<bool>,
4163    /// True for housekeeping tasks the CLI does not surface as user work;
4164    /// hosts should exclude them from activity indicators (CLI 2.1.259+).
4165    #[serde(default, skip_serializing_if = "Option::is_none")]
4166    pub ambient: Option<bool>,
4167    #[serde(skip_serializing_if = "Option::is_none")]
4168    pub uuid: Option<String>,
4169}
4170
4171/// How a subagent's hand-back report reached its caller
4172/// ([`TaskNotificationMessage::handback`]).
4173#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4174pub enum TaskHandback {
4175    /// The report was delivered.
4176    Send,
4177    /// The report was delivered with an auto-mode warning.
4178    Flagged,
4179    /// The report was held back; no `handback_report` is sent.
4180    Withheld,
4181    /// A value not yet known to this version of the crate.
4182    Unknown(String),
4183}
4184
4185impl TaskHandback {
4186    pub fn as_str(&self) -> &str {
4187        match self {
4188            Self::Send => "send",
4189            Self::Flagged => "flagged",
4190            Self::Withheld => "withheld",
4191            Self::Unknown(s) => s.as_str(),
4192        }
4193    }
4194}
4195
4196impl fmt::Display for TaskHandback {
4197    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4198        f.write_str(self.as_str())
4199    }
4200}
4201
4202impl From<&str> for TaskHandback {
4203    fn from(s: &str) -> Self {
4204        match s {
4205            "send" => Self::Send,
4206            "flagged" => Self::Flagged,
4207            "withheld" => Self::Withheld,
4208            other => Self::Unknown(other.to_string()),
4209        }
4210    }
4211}
4212
4213impl Serialize for TaskHandback {
4214    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4215        serializer.serialize_str(self.as_str())
4216    }
4217}
4218
4219impl<'de> Deserialize<'de> for TaskHandback {
4220    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4221        let s = String::deserialize(deserializer)?;
4222        Ok(Self::from(s.as_str()))
4223    }
4224}
4225
4226/// A subagent's delivered hand-back report
4227/// ([`TaskNotificationMessage::handback_report`]).
4228#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
4229pub struct HandbackReport {
4230    /// The subagent's whole report, never truncated, with a backslash
4231    /// inserted into text that imitates harness markup.
4232    pub text: String,
4233    /// Auto mode's warning to show above `text`: a security warning, or a
4234    /// note that the review could not run.
4235    #[serde(default, skip_serializing_if = "Option::is_none")]
4236    pub warning: Option<String>,
4237    /// Id of the subagent's own `SubagentHandback` `tool_use` block that sent
4238    /// the report, not of the call that started the agent. Copies of one
4239    /// report repeat it; show the report even when no such block is loaded.
4240    /// A hand-back user message's `origin` carries the same id as
4241    /// `handbackToolUseId` (CLI 2.1.327+).
4242    #[serde(default, rename = "toolUseId", skip_serializing_if = "Option::is_none")]
4243    pub tool_use_id: Option<String>,
4244}
4245
4246/// API error category attached to assistant wrapper frames.
4247#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4248pub enum AssistantErrorKind {
4249    AuthenticationFailed,
4250    OauthOrgNotAllowed,
4251    AccountOnHold,
4252    BillingError,
4253    RateLimit,
4254    Overloaded,
4255    InvalidRequest,
4256    ModelNotFound,
4257    ServerError,
4258    UnknownError,
4259    MaxOutputTokens,
4260    Unknown(String),
4261}
4262
4263impl AssistantErrorKind {
4264    pub fn as_str(&self) -> &str {
4265        match self {
4266            Self::AuthenticationFailed => "authentication_failed",
4267            Self::OauthOrgNotAllowed => "oauth_org_not_allowed",
4268            Self::AccountOnHold => "account_on_hold",
4269            Self::BillingError => "billing_error",
4270            Self::RateLimit => "rate_limit",
4271            Self::Overloaded => "overloaded",
4272            Self::InvalidRequest => "invalid_request",
4273            Self::ModelNotFound => "model_not_found",
4274            Self::ServerError => "server_error",
4275            Self::UnknownError => "unknown",
4276            Self::MaxOutputTokens => "max_output_tokens",
4277            Self::Unknown(s) => s.as_str(),
4278        }
4279    }
4280}
4281
4282impl fmt::Display for AssistantErrorKind {
4283    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4284        f.write_str(self.as_str())
4285    }
4286}
4287
4288impl From<&str> for AssistantErrorKind {
4289    fn from(s: &str) -> Self {
4290        match s {
4291            "authentication_failed" => Self::AuthenticationFailed,
4292            "oauth_org_not_allowed" => Self::OauthOrgNotAllowed,
4293            "account_on_hold" => Self::AccountOnHold,
4294            "billing_error" => Self::BillingError,
4295            "rate_limit" => Self::RateLimit,
4296            "overloaded" => Self::Overloaded,
4297            "invalid_request" => Self::InvalidRequest,
4298            "model_not_found" => Self::ModelNotFound,
4299            "server_error" => Self::ServerError,
4300            "unknown" => Self::UnknownError,
4301            "max_output_tokens" => Self::MaxOutputTokens,
4302            other => Self::Unknown(other.to_string()),
4303        }
4304    }
4305}
4306
4307impl Serialize for AssistantErrorKind {
4308    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4309        serializer.serialize_str(self.as_str())
4310    }
4311}
4312
4313impl<'de> Deserialize<'de> for AssistantErrorKind {
4314    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4315        let s = String::deserialize(deserializer)?;
4316        Ok(Self::from(s.as_str()))
4317    }
4318}
4319
4320/// `code_change_published` system message — the session is now associated
4321/// with a published code change (a pull/merge request). Fires on creation and
4322/// whenever the session contributes to an existing one, so bind on every
4323/// event; re-emission for the same URL is possible and idempotent. Values are
4324/// scraped from captured command output — treat them as a binding hint and
4325/// verify against the forge before routing authenticated requests.
4326#[derive(Debug, Clone, Serialize, Deserialize)]
4327pub struct CodeChangePublishedMessage {
4328    /// Forge classification derived from the URL's shape (`github`,
4329    /// `github-enterprise`, `gitlab`, `bitbucket`, `gerrit` today). Open set
4330    /// — treat an unknown value as a valid provider, never as an error.
4331    pub provider: String,
4332    /// Web URL of the pull/merge request. Unverified.
4333    pub url: String,
4334    /// Repository path from the URL (`owner/name` on GitHub; may carry more
4335    /// segments on GitLab).
4336    pub repo: String,
4337    /// Provider-native change identifier — the PR/MR number as a string.
4338    pub identifier: String,
4339    /// What the session did that produced this announcement: the flag-aware
4340    /// `gh pr` verb it ran (`"created"`, `"edited"`, `"merged"`,
4341    /// `"commented"`, `"closed"`, `"reopened"`, `"ready"`, `"draft"`,
4342    /// `"auto-merge-enabled"`, `"auto-merge-disabled"`), `"pushed"` for a
4343    /// push to a branch that has a PR, `"checked-out"` for `gh pr checkout`,
4344    /// or `"started"` for the open change on the branch a Claude Desktop
4345    /// session began on. Always sent by current producers (CLI 2.1.239+),
4346    /// absent only from older ones. Open set — treat unknown values as valid.
4347    #[serde(default, skip_serializing_if = "Option::is_none")]
4348    pub action: Option<String>,
4349    /// The session's working branch when it produced the change. Sent for
4350    /// providers whose changes have no head branch of their own (`gerrit`),
4351    /// so a host can place the change on that checkout, and with `created`
4352    /// on any provider: the branch the create was opened from (its `--head`
4353    /// / `--source-branch` flag, else the working branch), so a host can show
4354    /// the new change before its own forge lookup answers (CLI 2.1.273+).
4355    /// Absent otherwise (CLI 2.1.259+).
4356    #[serde(default, skip_serializing_if = "Option::is_none")]
4357    pub branch: Option<String>,
4358    pub uuid: String,
4359    pub session_id: String,
4360}
4361
4362/// `vcs_state_changed` system message — a harness-observed shell command
4363/// mutated repository state. A cache-invalidation signal, deliberately
4364/// payload-free beyond classification: consumers re-read state (branch, head,
4365/// PR status) instead of decoding the event.
4366#[derive(Debug, Clone, Serialize, Deserialize)]
4367pub struct VcsStateChangedMessage {
4368    /// What class of mutation was observed. New kinds may be added — treat an
4369    /// unrecognized kind exactly like a recognized one (something changed).
4370    pub kind: VcsMutationKind,
4371    /// The session's working directory — a hint, not necessarily the mutated
4372    /// repo's path (`git -C` or an inner `cd` mutates elsewhere).
4373    pub cwd: String,
4374    /// The branch a commit landed on or a push updated. Commit and push
4375    /// events carry it; a command that pushed several branches emits one push
4376    /// event per branch. A best-effort hint: absent whenever attribution is
4377    /// uncertain, and never a required key (CLI 2.1.239+).
4378    #[serde(default, skip_serializing_if = "Option::is_none")]
4379    pub branch: Option<String>,
4380    pub uuid: String,
4381    pub session_id: String,
4382}
4383
4384/// Mutation class carried by a [`VcsStateChangedMessage`].
4385#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4386pub enum VcsMutationKind {
4387    Commit,
4388    Push,
4389    Merge,
4390    Rebase,
4391    /// A kind not yet known to this version of the crate.
4392    Unknown(String),
4393}
4394
4395impl VcsMutationKind {
4396    pub fn as_str(&self) -> &str {
4397        match self {
4398            Self::Commit => "commit",
4399            Self::Push => "push",
4400            Self::Merge => "merge",
4401            Self::Rebase => "rebase",
4402            Self::Unknown(s) => s.as_str(),
4403        }
4404    }
4405}
4406
4407impl fmt::Display for VcsMutationKind {
4408    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4409        f.write_str(self.as_str())
4410    }
4411}
4412
4413impl From<&str> for VcsMutationKind {
4414    fn from(s: &str) -> Self {
4415        match s {
4416            "commit" => Self::Commit,
4417            "push" => Self::Push,
4418            "merge" => Self::Merge,
4419            "rebase" => Self::Rebase,
4420            other => Self::Unknown(other.to_string()),
4421        }
4422    }
4423}
4424
4425impl Serialize for VcsMutationKind {
4426    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4427        serializer.serialize_str(self.as_str())
4428    }
4429}
4430
4431impl<'de> Deserialize<'de> for VcsMutationKind {
4432    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4433        let s = String::deserialize(deserializer)?;
4434        Ok(Self::from(s.as_str()))
4435    }
4436}
4437
4438/// `system/feedback_draft_queued` — a feedback draft was queued for submission.
4439#[derive(Debug, Clone, Serialize, Deserialize)]
4440pub struct FeedbackDraftQueuedMessage {
4441    pub draft_id: String,
4442    pub draft_type: String,
4443    pub title: String,
4444    pub details_preview: String,
4445    #[serde(default, skip_serializing_if = "Option::is_none")]
4446    pub uuid: Option<String>,
4447    #[serde(default, skip_serializing_if = "Option::is_none")]
4448    pub session_id: Option<String>,
4449    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
4450    pub extra: serde_json::Map<String, Value>,
4451}
4452
4453/// `system/cloud_session_delta` — written only by the headless stream-json
4454/// client of a cloud-hosted session (the same client that puts
4455/// `cloud_session` on its init frames): the session's status changed between
4456/// two inits. Only after the first init; at most a few per second; none when
4457/// nothing differs. An init is always a complete snapshot, so a host that
4458/// (re)attaches resynchronises from the first init it reads and applies
4459/// these on top. Display-only (CLI 2.1.260+).
4460#[derive(Debug, Clone, Serialize, Deserialize)]
4461pub struct CloudSessionDeltaMessage {
4462    /// Rises by one with each of these frames this client writes (1 for the
4463    /// first); never reset by an init. A reader keeps the highest it has
4464    /// applied and drops a lower one.
4465    pub seq: u64,
4466    /// The top-level keys of `cloud_session` whose value differs from the
4467    /// last block this client wrote, e.g. `["serving"]`; never empty. A hint
4468    /// for what to redraw — the block is complete either way.
4469    pub changed: Vec<String>,
4470    /// The whole block exactly as the next init would carry it (see
4471    /// [`InitMessage::cloud_session`]): replace the held copy, do not merge.
4472    /// Stored as raw JSON (the shape is internal and evolving).
4473    pub cloud_session: Value,
4474    pub uuid: String,
4475    pub session_id: String,
4476    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
4477    pub extra: serde_json::Map<String, Value>,
4478}
4479
4480/// `system/dev_intent` — the conversation, or the git repository it runs in,
4481/// shows a known kind of development work, for hosts that key tooling on it
4482/// (Claude Code Desktop opens its iOS Simulator entry point on `ios_app`).
4483/// Sent with `trigger` as its only other payload. Per conversation per
4484/// process, each kind is sent at most once from conversation evidence and at
4485/// most once from the project scan: conversation evidence when it first
4486/// completes, or at startup when a resumed conversation already has it;
4487/// project evidence (print-mode CLIs only, which is how the Agent SDK starts
4488/// it) at startup, after each `conversation_reset`, and at the first message
4489/// of a conversation whose earlier scan did not find every kind. Either can
4490/// arrive before `system/init`. A rewind or compaction never retracts it and
4491/// only a `conversation_reset` starts over, so treat each kind as a sticky
4492/// fact about the conversation: a client that needs only the kind can ignore
4493/// repeats, and one that needs to know what set it off reads `trigger`
4494/// (CLI 2.1.266+; `trigger` and the project scan from 2.1.273).
4495#[derive(Debug, Clone, Serialize, Deserialize)]
4496pub struct DevIntentMessage {
4497    /// What kind of development the evidence shows.
4498    pub kind: DevIntentKind,
4499    /// The evidence the detection fired on, for a host's own analytics. From
4500    /// the conversation it is the first platform-specific evidence seen;
4501    /// [`DevIntentTrigger::ProjectScan`] marks a scan of the session's git
4502    /// repository. Absent from CLIs before 2.1.273, which send only
4503    /// conversation evidence.
4504    #[serde(default, skip_serializing_if = "Option::is_none")]
4505    pub trigger: Option<DevIntentTrigger>,
4506    pub uuid: String,
4507    pub session_id: String,
4508    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
4509    pub extra: serde_json::Map<String, Value>,
4510}
4511
4512/// The kind of development a [`DevIntentMessage`] reports. Open set: the CLI
4513/// says "more kinds will be added; ignore a kind you do not recognize", so
4514/// unrecognized values deserialize to [`DevIntentKind::Unknown`].
4515#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4516pub enum DevIntentKind {
4517    /// From the conversation: Claude wrote or edited a `.swift` file and
4518    /// something it wrote, read, or ran is iOS-specific (a macOS-only app or
4519    /// server-side Swift package never qualifies). From the project scan: the
4520    /// session's git repository has an Xcode project whose build settings
4521    /// name an iOS SDK or target iPhone or iPad.
4522    IosApp,
4523    /// From the conversation: Claude wrote or edited a `.kt`, `.kts` or
4524    /// `.java` file and something it wrote, read, or ran is Android-specific
4525    /// (a Kotlin server or a multiplatform module with no Android target
4526    /// never qualifies). From the project scan: the repository has an
4527    /// `AndroidManifest.xml` or the Android Gradle plugin in a build script
4528    /// or version catalog (CLI 2.1.273+).
4529    AndroidApp,
4530    /// A kind not yet known to this version of the crate.
4531    Unknown(String),
4532}
4533
4534impl DevIntentKind {
4535    pub fn as_str(&self) -> &str {
4536        match self {
4537            Self::IosApp => "ios_app",
4538            Self::AndroidApp => "android_app",
4539            Self::Unknown(s) => s.as_str(),
4540        }
4541    }
4542}
4543
4544impl fmt::Display for DevIntentKind {
4545    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4546        f.write_str(self.as_str())
4547    }
4548}
4549
4550impl From<&str> for DevIntentKind {
4551    fn from(s: &str) -> Self {
4552        match s {
4553            "ios_app" => Self::IosApp,
4554            "android_app" => Self::AndroidApp,
4555            other => Self::Unknown(other.to_string()),
4556        }
4557    }
4558}
4559
4560impl Serialize for DevIntentKind {
4561    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4562        serializer.serialize_str(self.as_str())
4563    }
4564}
4565
4566impl<'de> Deserialize<'de> for DevIntentKind {
4567    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4568        let s = String::deserialize(deserializer)?;
4569        Ok(Self::from(s.as_str()))
4570    }
4571}
4572
4573/// The evidence a [`DevIntentMessage`] detection fired on. Open set: the CLI
4574/// says "more values will be added; ignore one you do not recognize", so
4575/// unrecognized values deserialize to [`DevIntentTrigger::Unknown`].
4576#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4577pub enum DevIntentTrigger {
4578    /// Reserved for rules that need no other evidence; no rule sends it yet.
4579    SwiftEdit,
4580    /// `import UIKit` or `.iOS(` in text Claude wrote.
4581    UikitImport,
4582    /// iOS build settings written, or seen in a tool result such as a
4583    /// pbxproj read.
4584    XcodeProject,
4585    /// `simctl`, an iOS SDK or a Simulator destination in a command Claude
4586    /// ran.
4587    IosCommand,
4588    /// Reserved for rules that need no other evidence; no rule sends it yet.
4589    KotlinEdit,
4590    /// Reserved for rules that need no other evidence; no rule sends it yet.
4591    JavaEdit,
4592    /// `import android.` in text Claude wrote.
4593    AndroidImport,
4594    /// A manifest path or body written, or seen in a tool result.
4595    AndroidManifest,
4596    /// The Android Gradle plugin written, or seen in a tool result.
4597    GradlePlugin,
4598    /// `adb`, the emulator, `sdkmanager`, `avdmanager`,
4599    /// `react-native run-android` or a Gradle variant task.
4600    AndroidCommand,
4601    /// For any kind: a scan of the session's git repository rather than
4602    /// conversation evidence.
4603    ProjectScan,
4604    /// A trigger not yet known to this version of the crate.
4605    Unknown(String),
4606}
4607
4608impl DevIntentTrigger {
4609    pub fn as_str(&self) -> &str {
4610        match self {
4611            Self::SwiftEdit => "swift_edit",
4612            Self::UikitImport => "uikit_import",
4613            Self::XcodeProject => "xcode_project",
4614            Self::IosCommand => "ios_command",
4615            Self::KotlinEdit => "kotlin_edit",
4616            Self::JavaEdit => "java_edit",
4617            Self::AndroidImport => "android_import",
4618            Self::AndroidManifest => "android_manifest",
4619            Self::GradlePlugin => "gradle_plugin",
4620            Self::AndroidCommand => "android_command",
4621            Self::ProjectScan => "project_scan",
4622            Self::Unknown(s) => s.as_str(),
4623        }
4624    }
4625}
4626
4627impl fmt::Display for DevIntentTrigger {
4628    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4629        f.write_str(self.as_str())
4630    }
4631}
4632
4633impl From<&str> for DevIntentTrigger {
4634    fn from(s: &str) -> Self {
4635        match s {
4636            "swift_edit" => Self::SwiftEdit,
4637            "uikit_import" => Self::UikitImport,
4638            "xcode_project" => Self::XcodeProject,
4639            "ios_command" => Self::IosCommand,
4640            "kotlin_edit" => Self::KotlinEdit,
4641            "java_edit" => Self::JavaEdit,
4642            "android_import" => Self::AndroidImport,
4643            "android_manifest" => Self::AndroidManifest,
4644            "gradle_plugin" => Self::GradlePlugin,
4645            "android_command" => Self::AndroidCommand,
4646            "project_scan" => Self::ProjectScan,
4647            other => Self::Unknown(other.to_string()),
4648        }
4649    }
4650}
4651
4652impl Serialize for DevIntentTrigger {
4653    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4654        serializer.serialize_str(self.as_str())
4655    }
4656}
4657
4658impl<'de> Deserialize<'de> for DevIntentTrigger {
4659    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4660        let s = String::deserialize(deserializer)?;
4661        Ok(Self::from(s.as_str()))
4662    }
4663}
4664
4665/// Why a [`TaskNotificationMessage`] ended other than through an ordinary
4666/// completion, failure, or stop. Open set: unrecognized values deserialize
4667/// to [`TaskEndReason::Unknown`].
4668#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4669pub enum TaskEndReason {
4670    /// The worker process restarted and the resumed process found the task
4671    /// orphaned (always with status `stopped`).
4672    WorkerRestart,
4673    /// A reason not yet known to this version of the crate.
4674    Unknown(String),
4675}
4676
4677impl TaskEndReason {
4678    pub fn as_str(&self) -> &str {
4679        match self {
4680            Self::WorkerRestart => "worker_restart",
4681            Self::Unknown(s) => s.as_str(),
4682        }
4683    }
4684}
4685
4686impl fmt::Display for TaskEndReason {
4687    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4688        f.write_str(self.as_str())
4689    }
4690}
4691
4692impl From<&str> for TaskEndReason {
4693    fn from(s: &str) -> Self {
4694        match s {
4695            "worker_restart" => Self::WorkerRestart,
4696            other => Self::Unknown(other.to_string()),
4697        }
4698    }
4699}
4700
4701impl Serialize for TaskEndReason {
4702    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4703        serializer.serialize_str(self.as_str())
4704    }
4705}
4706
4707impl<'de> Deserialize<'de> for TaskEndReason {
4708    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4709        let s = String::deserialize(deserializer)?;
4710        Ok(Self::from(s.as_str()))
4711    }
4712}
4713
4714/// `system/turn_handoff_available` — emitted once by a cloud worker that
4715/// accepts the `turn_handoff` control request, right after it registers,
4716/// carrying what its registration wrote to `external_metadata.turn_handoff`.
4717/// Lets a session client learn the capability from the event stream instead
4718/// of reading worker state. Durable in the stream: a reader keeps the entry
4719/// with the newest `worker_epoch` it has seen and ignores older ones; a
4720/// worker life that does not accept `turn_handoff` emits nothing
4721/// (CLI 2.1.273+).
4722#[derive(Debug, Clone, Serialize, Deserialize)]
4723pub struct TurnHandoffAvailableMessage {
4724    /// Contract version of the handoff registration (currently `1`).
4725    pub v: u64,
4726    /// The tools whose calls this worker would accept.
4727    pub tools: Vec<String>,
4728    /// The worker life announcing it.
4729    pub worker_epoch: u64,
4730    /// Present, and true, only when this worker uses the `relay_marker`
4731    /// member of a `turn_handoff` request; a client sends that member to no
4732    /// other worker.
4733    #[serde(default, skip_serializing_if = "Option::is_none")]
4734    pub relay_marker: Option<bool>,
4735    /// Present, and true, when this worker starts a handed-off turn's calls
4736    /// only after every `stage_file` control request it received earlier has
4737    /// finished or failed, or a wait limit has passed; a worker that omits
4738    /// it may start them while files are still downloading (CLI 2.1.278+).
4739    /// Exception: a request with `filestore_path` set (a synced file) is not
4740    /// waited for, so a call that names that file may start before it is
4741    /// synced (CLI 2.1.287+).
4742    #[serde(default, skip_serializing_if = "Option::is_none")]
4743    pub staged_files: Option<bool>,
4744    /// True when user messages with `shouldQuery` false that reach this
4745    /// worker before a `turn_handoff` request are appended, and
4746    /// acknowledged, before the handed-off turn produces any output.
4747    /// Exception: a request that continues a turn whose leading lines an
4748    /// earlier request appended; that turn goes first. A worker that omits
4749    /// it may run the turn first (CLI 2.1.278+).
4750    #[serde(default, skip_serializing_if = "Option::is_none")]
4751    pub no_query_first: Option<bool>,
4752    /// Present, and true, only on a worker that takes a `stage_file` control
4753    /// request whose `mount_path` is `/uploads/.home/<path>` as a file for
4754    /// `/home/claude/<path>`: it writes the file there, answers ok with a
4755    /// noop (`already_present`, `path_occupied`, `refused_name`,
4756    /// `home_files_off`, `unchecked_announcement`, `resent_announcement`)
4757    /// and writes nothing, or answers an error. Any other worker treats that
4758    /// path as an ordinary upload (CLI 2.1.287+).
4759    #[serde(default, skip_serializing_if = "Option::is_none")]
4760    pub home_files: Option<bool>,
4761    /// Present, and true, only when this worker uses the `file_names` member
4762    /// of a `turn_handoff` request; a client sends that member to no other
4763    /// worker (CLI 2.1.287+).
4764    #[serde(default, skip_serializing_if = "Option::is_none")]
4765    pub file_names: Option<bool>,
4766    /// Present, and true, only on a worker that writes the files of the
4767    /// Write calls a `turn_handoff` request brings already answered, where
4768    /// their paths are under `/home/claude`. Before it appends a turn that
4769    /// has calls to run, it writes each such call's content to its path,
4770    /// replacing nothing. If it cannot write them all, it appends and runs
4771    /// nothing: the request is refused with an error that starts
4772    /// `invalid_handoff: carried_writes_`, or it is accepted and the turn
4773    /// ends in a result with `num_turns` 0. Any other worker writes no file
4774    /// for these calls (CLI 2.1.288+).
4775    #[serde(default, skip_serializing_if = "Option::is_none")]
4776    pub carried_writes: Option<bool>,
4777    /// Present, and true, only on a worker that rebuilt the conversation
4778    /// from the session's stored transcript before it read any request, and
4779    /// would not have started without it. A client may send such a worker
4780    /// again a `turn_handoff` request an earlier worker accepted, if the
4781    /// request names no calls (empty `tool_use_ids`), is not stopped, and its
4782    /// messages hold no tool call: the worker appends only the turn's
4783    /// messages its conversation lacks and, once the store confirms them,
4784    /// echoes the turn's last message back as an assistant event. The
4785    /// request can still be accepted or refused (`invalid_handoff:`) with no
4786    /// echo, e.g. after a rewind, a compaction or a Stop; an echo proves
4787    /// nothing if the same worker had the request before. The key promises
4788    /// nothing for a turn that holds a tool call. A worker without it may
4789    /// have started with none of the turn's messages (CLI 2.1.296+).
4790    #[serde(default, skip_serializing_if = "Option::is_none")]
4791    pub hydrates_carried_lines: Option<bool>,
4792    /// Present, and true, when this worker accepts a `turn_handoff` request
4793    /// in which an assistant message repeats the message id of the assistant
4794    /// message before it. A worker that omits it refuses such a request
4795    /// (`invalid_handoff`), so a client gives each message an id of its own
4796    /// there (CLI 2.1.300+).
4797    #[serde(default, skip_serializing_if = "Option::is_none")]
4798    pub shared_message_id: Option<bool>,
4799    /// Present, and true, only on a worker that reads the
4800    /// `requires_rewind_request_id` member of a `turn_handoff` request; a
4801    /// worker without this key ignores the member and appends the turn
4802    /// whether or not the rewind was made (CLI 2.1.311+).
4803    #[serde(default, skip_serializing_if = "Option::is_none")]
4804    pub requires_rewind_request_id: Option<bool>,
4805    /// Present, and true, only on a worker that answers the
4806    /// `comparison_fork` control request; a client sends that request to no
4807    /// other worker (CLI 2.1.327+).
4808    #[serde(default, skip_serializing_if = "Option::is_none")]
4809    pub comparison_fork: Option<bool>,
4810    pub uuid: String,
4811    pub session_id: String,
4812    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
4813    pub extra: serde_json::Map<String, Value>,
4814}
4815
4816/// `system/turn_preempted` — the CLI itself stopped the running turn so a
4817/// user's rapid follow-up message is answered at once, exactly as a priority
4818/// `now` message would have (running shell commands are backgrounded, not
4819/// killed). Sent at the moment of the stop, so it precedes the stopped turn's
4820/// `result` frame (`terminal_reason` `aborted_streaming` or `aborted_tools`)
4821/// and its members' `cancelled` `command_lifecycle` frames: a host renders
4822/// that turn as superseded by the follow-up rather than as interrupted, does
4823/// not resend its messages, and treats only `preempted_by_uuid` as picked
4824/// up. At most one per burst. Emitted in `-p`/SDK sessions only, and only to
4825/// a consumer that declared `rapidFollowupPreempt` on its initialize request
4826/// while the feature's rollout flag is on (CLI 2.1.273+).
4827#[derive(Debug, Clone, Serialize, Deserialize)]
4828pub struct TurnPreemptedMessage {
4829    /// Why the turn was stopped. `rapid_followup`: the user's next message
4830    /// arrived before the running turn showed any output. More reasons may
4831    /// be added; treat an unknown one the same way.
4832    pub reason: String,
4833    /// The client-supplied uuid of the queued user message the turn was
4834    /// stopped for. It runs next, together with any messages queued behind
4835    /// it.
4836    pub preempted_by_uuid: String,
4837    /// The client-supplied uuids of the user messages the stopped turn was
4838    /// running (uuid-less members omitted; may be empty).
4839    #[serde(default)]
4840    pub preempted_message_uuids: Vec<String>,
4841    pub uuid: String,
4842    pub session_id: String,
4843    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
4844    pub extra: serde_json::Map<String, Value>,
4845}
4846
4847/// `system/peer_message_hold` — a cross-session (peer) message this
4848/// session's receive-side policy held rather than queued, and how that hold
4849/// resolved. Lets a host show the human that a message arrived but has not
4850/// reached the model (and may never) instead of nothing at all; the sending
4851/// session is told separately over its own transport where one exists.
4852/// Informational only — there is no host-side approval through this frame.
4853/// Emitted in `-p`/SDK sessions (CLI 2.1.273+).
4854#[derive(Debug, Clone, Serialize, Deserialize)]
4855pub struct PeerMessageHoldMessage {
4856    /// `held` once per message per hold cause (a re-announcement under a
4857    /// different cause emits again); then at most one of `released` (it
4858    /// enters the queue — its `command_lifecycle` `queued` and user replay
4859    /// echo follow under `message_uuid`) or `dropped` (this process will not
4860    /// give it to the model; see `outcome`). A frame for a message the
4861    /// session service delivered is only uploaded to it: it has an empty
4862    /// `from` and no `message_uuid`, a `dropped` one need not follow a
4863    /// `held`, and its `expired` also covers an exit or a full hold buffer
4864    /// (CLI 2.1.328+).
4865    pub state: PeerMessageHoldState,
4866    /// The parked command's uuid — the value its later `command_lifecycle`
4867    /// frames and user replay echo carry. For lane `bridge`/`stdin` it is
4868    /// the id the host supplied on the inbound message; for lane `socket` it
4869    /// was chosen by the sending session, so correlate it only within
4870    /// `peer_message_hold` / peer replay frames, never against the host's
4871    /// own prompts' lifecycle.
4872    #[serde(default, skip_serializing_if = "Option::is_none")]
4873    pub message_uuid: Option<String>,
4874    /// Which ingress delivered it.
4875    pub lane: PeerMessageLane,
4876    /// The sender's address as the envelope will show it — an address-shaped
4877    /// token with control and invisible code points scrubbed; empty when the
4878    /// sender supplied none or an unshaped one. Sender-asserted on the
4879    /// socket lane: a label, not an identity proof.
4880    pub from: String,
4881    /// The sender's display name when it supplied one, normalized and
4882    /// scrubbed the same way. A claim, like `from`.
4883    #[serde(default, skip_serializing_if = "Option::is_none")]
4884    pub from_name: Option<String>,
4885    /// State `held` only: why the policy parked it.
4886    #[serde(default, skip_serializing_if = "Option::is_none")]
4887    pub cause: Option<PeerMessageHoldCause>,
4888    /// State `dropped` only: how the hold ended.
4889    #[serde(default, skip_serializing_if = "Option::is_none")]
4890    pub outcome: Option<PeerMessageHoldOutcome>,
4891    /// Outcome `dropped` only: which check discarded the message, where the
4892    /// frame says (CLI 2.1.328+).
4893    #[serde(default, skip_serializing_if = "Option::is_none")]
4894    pub reason: Option<PeerMessageDropReason>,
4895    pub uuid: String,
4896    pub session_id: String,
4897    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
4898    pub extra: serde_json::Map<String, Value>,
4899}
4900
4901/// Lifecycle state carried by a [`PeerMessageHoldMessage`].
4902#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4903pub enum PeerMessageHoldState {
4904    /// The receive-side policy parked the message instead of queueing it.
4905    Held,
4906    /// The policy now accepts it: it enters the queue.
4907    Released,
4908    /// It will never reach the model in this session.
4909    Dropped,
4910    /// A state not yet known to this version of the crate.
4911    Unknown(String),
4912}
4913
4914impl PeerMessageHoldState {
4915    pub fn as_str(&self) -> &str {
4916        match self {
4917            Self::Held => "held",
4918            Self::Released => "released",
4919            Self::Dropped => "dropped",
4920            Self::Unknown(s) => s.as_str(),
4921        }
4922    }
4923}
4924
4925impl fmt::Display for PeerMessageHoldState {
4926    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4927        f.write_str(self.as_str())
4928    }
4929}
4930
4931impl From<&str> for PeerMessageHoldState {
4932    fn from(s: &str) -> Self {
4933        match s {
4934            "held" => Self::Held,
4935            "released" => Self::Released,
4936            "dropped" => Self::Dropped,
4937            other => Self::Unknown(other.to_string()),
4938        }
4939    }
4940}
4941
4942impl Serialize for PeerMessageHoldState {
4943    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4944        serializer.serialize_str(self.as_str())
4945    }
4946}
4947
4948impl<'de> Deserialize<'de> for PeerMessageHoldState {
4949    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4950        let s = String::deserialize(deserializer)?;
4951        Ok(Self::from(s.as_str()))
4952    }
4953}
4954
4955/// Which ingress delivered the message a [`PeerMessageHoldMessage`] reports.
4956#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4957pub enum PeerMessageLane {
4958    /// The Remote Control bridge.
4959    Bridge,
4960    /// The host's own stdin stream.
4961    Stdin,
4962    /// The local cross-session socket.
4963    Socket,
4964    /// A lane not yet known to this version of the crate.
4965    Unknown(String),
4966}
4967
4968impl PeerMessageLane {
4969    pub fn as_str(&self) -> &str {
4970        match self {
4971            Self::Bridge => "bridge",
4972            Self::Stdin => "stdin",
4973            Self::Socket => "socket",
4974            Self::Unknown(s) => s.as_str(),
4975        }
4976    }
4977}
4978
4979impl fmt::Display for PeerMessageLane {
4980    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4981        f.write_str(self.as_str())
4982    }
4983}
4984
4985impl From<&str> for PeerMessageLane {
4986    fn from(s: &str) -> Self {
4987        match s {
4988            "bridge" => Self::Bridge,
4989            "stdin" => Self::Stdin,
4990            "socket" => Self::Socket,
4991            other => Self::Unknown(other.to_string()),
4992        }
4993    }
4994}
4995
4996impl Serialize for PeerMessageLane {
4997    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4998        serializer.serialize_str(self.as_str())
4999    }
5000}
5001
5002impl<'de> Deserialize<'de> for PeerMessageLane {
5003    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
5004        let s = String::deserialize(deserializer)?;
5005        Ok(Self::from(s.as_str()))
5006    }
5007}
5008
5009/// Why the receive-side policy parked a peer message
5010/// ([`PeerMessageHoldMessage::cause`], state `held` only). The `*Setting`
5011/// causes are a standing `crossSessionInbound: "hold"`; `ModeMismatch` and
5012/// `NoModeAsserted` are the permission-mode parity holds (the sender runs in
5013/// a different permission class, or asserted none while this session
5014/// bypasses permissions).
5015#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5016pub enum PeerMessageHoldCause {
5017    ExplicitSetting,
5018    ManagedSetting,
5019    RepoSetting,
5020    InvalidSetting,
5021    BypassDefault,
5022    ModeUnknown,
5023    ModeMismatch,
5024    NoModeAsserted,
5025    /// A cause not yet known to this version of the crate.
5026    Unknown(String),
5027}
5028
5029impl PeerMessageHoldCause {
5030    pub fn as_str(&self) -> &str {
5031        match self {
5032            Self::ExplicitSetting => "explicit-setting",
5033            Self::ManagedSetting => "managed-setting",
5034            Self::RepoSetting => "repo-setting",
5035            Self::InvalidSetting => "invalid-setting",
5036            Self::BypassDefault => "bypass-default",
5037            Self::ModeUnknown => "mode-unknown",
5038            Self::ModeMismatch => "mode-mismatch",
5039            Self::NoModeAsserted => "no-mode-asserted",
5040            Self::Unknown(s) => s.as_str(),
5041        }
5042    }
5043}
5044
5045impl fmt::Display for PeerMessageHoldCause {
5046    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5047        f.write_str(self.as_str())
5048    }
5049}
5050
5051impl From<&str> for PeerMessageHoldCause {
5052    fn from(s: &str) -> Self {
5053        match s {
5054            "explicit-setting" => Self::ExplicitSetting,
5055            "managed-setting" => Self::ManagedSetting,
5056            "repo-setting" => Self::RepoSetting,
5057            "invalid-setting" => Self::InvalidSetting,
5058            "bypass-default" => Self::BypassDefault,
5059            "mode-unknown" => Self::ModeUnknown,
5060            "mode-mismatch" => Self::ModeMismatch,
5061            "no-mode-asserted" => Self::NoModeAsserted,
5062            other => Self::Unknown(other.to_string()),
5063        }
5064    }
5065}
5066
5067impl Serialize for PeerMessageHoldCause {
5068    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
5069        serializer.serialize_str(self.as_str())
5070    }
5071}
5072
5073impl<'de> Deserialize<'de> for PeerMessageHoldCause {
5074    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
5075        let s = String::deserialize(deserializer)?;
5076        Ok(Self::from(s.as_str()))
5077    }
5078}
5079
5080/// How a peer-message hold ended ([`PeerMessageHoldMessage::outcome`],
5081/// state `dropped` only).
5082#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5083pub enum PeerMessageHoldOutcome {
5084    /// No one approved it before the approval deadline (a headless host has
5085    /// no approval surface, so every parity hold ends this way unless the
5086    /// mode changes first).
5087    Expired,
5088    /// The policy refuses it, on arrival or after it waited.
5089    Refused,
5090    /// The ingress guard (rate limit, duplicate, queue cap) or the device
5091    /// check discarded it; [`PeerMessageHoldMessage::reason`] says which.
5092    Dropped,
5093    /// The session ended with it still parked.
5094    Discarded,
5095    /// The person declined it (CLI 2.1.328+).
5096    Denied,
5097    /// An outcome not yet known to this version of the crate.
5098    Unknown(String),
5099}
5100
5101impl PeerMessageHoldOutcome {
5102    pub fn as_str(&self) -> &str {
5103        match self {
5104            Self::Expired => "expired",
5105            Self::Refused => "refused",
5106            Self::Dropped => "dropped",
5107            Self::Discarded => "discarded",
5108            Self::Denied => "denied",
5109            Self::Unknown(s) => s.as_str(),
5110        }
5111    }
5112}
5113
5114impl fmt::Display for PeerMessageHoldOutcome {
5115    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5116        f.write_str(self.as_str())
5117    }
5118}
5119
5120impl From<&str> for PeerMessageHoldOutcome {
5121    fn from(s: &str) -> Self {
5122        match s {
5123            "expired" => Self::Expired,
5124            "refused" => Self::Refused,
5125            "dropped" => Self::Dropped,
5126            "discarded" => Self::Discarded,
5127            "denied" => Self::Denied,
5128            other => Self::Unknown(other.to_string()),
5129        }
5130    }
5131}
5132
5133impl Serialize for PeerMessageHoldOutcome {
5134    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
5135        serializer.serialize_str(self.as_str())
5136    }
5137}
5138
5139impl<'de> Deserialize<'de> for PeerMessageHoldOutcome {
5140    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
5141        let s = String::deserialize(deserializer)?;
5142        Ok(Self::from(s.as_str()))
5143    }
5144}
5145
5146/// Which check discarded a peer message
5147/// ([`PeerMessageHoldMessage::reason`], outcome `dropped` only; CLI 2.1.328+).
5148#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5149pub enum PeerMessageDropReason {
5150    RateLimited,
5151    Duplicate,
5152    HopLoop,
5153    HopRunaway,
5154    QueueFull,
5155    Unverified,
5156    /// A reason not yet known to this version of the crate.
5157    Unknown(String),
5158}
5159
5160impl PeerMessageDropReason {
5161    pub fn as_str(&self) -> &str {
5162        match self {
5163            Self::RateLimited => "rate-limited",
5164            Self::Duplicate => "duplicate",
5165            Self::HopLoop => "hop-loop",
5166            Self::HopRunaway => "hop-runaway",
5167            Self::QueueFull => "queue-full",
5168            Self::Unverified => "unverified",
5169            Self::Unknown(s) => s.as_str(),
5170        }
5171    }
5172}
5173
5174impl fmt::Display for PeerMessageDropReason {
5175    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5176        f.write_str(self.as_str())
5177    }
5178}
5179
5180impl From<&str> for PeerMessageDropReason {
5181    fn from(s: &str) -> Self {
5182        match s {
5183            "rate-limited" => Self::RateLimited,
5184            "duplicate" => Self::Duplicate,
5185            "hop-loop" => Self::HopLoop,
5186            "hop-runaway" => Self::HopRunaway,
5187            "queue-full" => Self::QueueFull,
5188            "unverified" => Self::Unverified,
5189            other => Self::Unknown(other.to_string()),
5190        }
5191    }
5192}
5193
5194impl Serialize for PeerMessageDropReason {
5195    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
5196        serializer.serialize_str(self.as_str())
5197    }
5198}
5199
5200impl<'de> Deserialize<'de> for PeerMessageDropReason {
5201    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
5202        let s = String::deserialize(deserializer)?;
5203        Ok(Self::from(s.as_str()))
5204    }
5205}
5206
5207/// `system/per_turn_effort_changed` — the conversation stopped sending effort
5208/// per turn, because the server refused its per-turn effort message or a
5209/// `role:"system"` message. From the retried request on, an effort change
5210/// rewrites the cached prefix, for every model, until a later `system/init`
5211/// says otherwise. Sent once, when the conversation first turns per-turn
5212/// effort off, before the retried request's output; sent again only if the
5213/// server refuses again after the conversation's refusals are cleared (for
5214/// example by `/clear` or a compaction). It can repeat a `false` the host
5215/// already holds. Pairs with [`InitMessage::per_turn_effort_active`]
5216/// (CLI 2.1.281+).
5217#[derive(Debug, Clone, Serialize, Deserialize)]
5218pub struct PerTurnEffortChangedMessage {
5219    /// Always `false`: a change to `true` is reported only by `system/init`.
5220    pub per_turn_effort_active: bool,
5221    pub uuid: String,
5222    pub session_id: String,
5223}
5224
5225/// `system/instruction_size_warning` — the session's instruction files
5226/// (CLAUDE.md files, rules files and the files they import) add up to more
5227/// than the recommended limit. Numbers only: the host words the warning in
5228/// the person's language. Sent to Claude Desktop's Code tab alone, at most
5229/// once per process, on a conversation's first turn after `system/init`;
5230/// never stored in the transcript. Safe to ignore (CLI 2.1.288+).
5231#[derive(Debug, Clone, Serialize, Deserialize)]
5232pub struct InstructionSizeWarningMessage {
5233    /// Combined length, in characters, of the instruction files in the
5234    /// session prompt. Always over [`Self::total_limit_chars`].
5235    pub total_chars: u64,
5236    /// The recommended limit for `total_chars` on the turn's model, in
5237    /// characters.
5238    pub total_limit_chars: u64,
5239    /// Number of files counted in `total_chars`. When it is 1, word the
5240    /// warning for a single file rather than a total.
5241    pub file_count: u64,
5242    /// Length of the largest file, in characters. Present only when the
5243    /// warning should mention it: there are several files and this one by
5244    /// itself is over `total_limit_chars`.
5245    #[serde(default, skip_serializing_if = "Option::is_none")]
5246    pub largest_chars: Option<u64>,
5247    pub uuid: String,
5248    pub session_id: String,
5249}
5250
5251/// `system/file_attachments_missing` — some files a user message sent by
5252/// reference (`file_attachments`) did not arrive where Claude can read them,
5253/// and Claude was told so; the turn runs on without them. A host can use it
5254/// to tell the person who sent them. Only sent by a worker connected to
5255/// Claude Code Remote. Each event states the whole list for its message, so
5256/// keep the last one per `message_uuid` (CLI 2.1.290+).
5257#[derive(Debug, Clone, Serialize, Deserialize)]
5258pub struct FileAttachmentsMissingMessage {
5259    /// The uuid of the inbound user message whose `file_attachments` named
5260    /// the files.
5261    pub message_uuid: String,
5262    /// How many well-formed `file_attachments` entries that message had.
5263    pub sent_count: u64,
5264    /// The files Claude was told did not arrive, each once. Never empty.
5265    pub missing: Vec<MissingFileAttachment>,
5266    pub uuid: String,
5267    pub session_id: String,
5268}
5269
5270/// `system/permission_check_status` — a tool call has been waiting on its
5271/// automatic permission check (the auto-mode classifier) for longer than
5272/// usual, so a host can say the step is being checked instead of showing a
5273/// silent pause. Every `checking` is followed by a `done` for the same
5274/// `tool_use_id`; `done` does not say whether the call was allowed (the
5275/// tool's result, `permission_denied` or a `can_use_tool` request does). One
5276/// call can send more than one pair. Display-only and best-effort: also stop
5277/// showing it at any other frame for this `tool_use_id` or at the end of the
5278/// turn (CLI 2.1.292+).
5279#[derive(Debug, Clone, Serialize, Deserialize)]
5280pub struct PermissionCheckStatusMessage {
5281    pub tool_use_id: String,
5282    /// Subagent ID when the tool call originated inside a subagent, as on
5283    /// `permission_denied`.
5284    #[serde(default, skip_serializing_if = "Option::is_none")]
5285    pub agent_id: Option<String>,
5286    pub status: PermissionCheckStatus,
5287    pub uuid: String,
5288    pub session_id: String,
5289}
5290
5291/// `system/inherited_asks_settled` — a cloud worker's report, before its
5292/// first turn, of which asks it inherited from the earlier worker and keeps
5293/// answerable. Any ask stored before this event that it does not name is
5294/// over (CLI 2.1.311+).
5295#[derive(Debug, Clone, Serialize, Deserialize)]
5296pub struct InheritedAsksSettledMessage {
5297    /// The request ids of the earlier worker's asks that this worker keeps
5298    /// answerable.
5299    pub kept_request_ids: Vec<String>,
5300    pub uuid: String,
5301    pub session_id: String,
5302}
5303
5304/// `system/late_allow_not_run` — a cloud worker's report that the call of a
5305/// permission card, which a message had closed and the client kept up (see
5306/// `keeps_request_id` on user messages), will not run on a late Allow: the
5307/// worker refused the person's Allow, a Deny came, or the worker cancels the
5308/// card itself. Sent once the worker has stored that, and again by each later
5309/// worker handed a copy of the Allow (CLI 2.1.326+).
5310#[derive(Debug, Clone, Serialize, Deserialize)]
5311pub struct LateAllowNotRunMessage {
5312    /// The answer's own request id, which is not checked — or the card's, at
5313    /// the worker's own cancel.
5314    pub request_id: String,
5315    /// The id of the card's call.
5316    pub tool_use_id: String,
5317    /// Why no late Allow runs the call. Treat any value as "did not run".
5318    pub reason: LateAllowNotRunReason,
5319    pub uuid: String,
5320    pub session_id: String,
5321}
5322
5323/// `system/shell_cwd` — the folder that a main-thread Bash or PowerShell call
5324/// that did not fail left its shell in, whether or not it moved. Sent only to
5325/// a host that marked a hook matcher `replacedByFrame: 'shell_cwd'`, before
5326/// the call's result and before its PostToolUse hooks; Claude Code does not
5327/// wait for the host. Not sent for a subagent's call or a call served for
5328/// another machine's session (CLI 2.1.327+).
5329#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5330pub struct ShellCwdMessage {
5331    /// The `cwd` a PostToolUse hook on this call is given. A call that
5332    /// overlapped another reports its own folder, so the last frame need not
5333    /// say where the next command starts. The model's own `cd` moves it, so
5334    /// treat it as data.
5335    pub cwd: String,
5336    pub uuid: String,
5337    pub session_id: String,
5338}
5339
5340/// `system/task_list_statuses` — the statuses of tasks on the task list, in
5341/// a session where Claude Code sets them itself and no `TaskUpdate` call
5342/// shows the change. Sent during turns and after their results, when a
5343/// status changes. It sets the tasks it names; a task it leaves out keeps its
5344/// last status. A later `TaskUpdate` result that changes a status wins.
5345/// Marked `@internal` upstream (CLI 2.1.328+).
5346#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5347pub struct TaskListStatusesMessage {
5348    pub statuses: Vec<TaskListStatus>,
5349    pub uuid: String,
5350    pub session_id: String,
5351}
5352
5353/// One entry of [`TaskListStatusesMessage::statuses`] (CLI 2.1.328+).
5354#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5355pub struct TaskListStatus {
5356    /// The task-list task id.
5357    pub id: String,
5358    pub status: TodoStatus,
5359}
5360
5361/// [`LateAllowNotRunMessage::reason`]. Every value, including unknown ones,
5362/// means the call did not run (CLI 2.1.326+).
5363#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5364pub enum LateAllowNotRunReason {
5365    TurnRunning,
5366    CardOpen,
5367    CallGone,
5368    InvalidAnswer,
5369    Limited,
5370    Stopped,
5371    Declined,
5372    AskedAgain,
5373    Withdrawn,
5374    Expired,
5375    NotRun,
5376    /// A reason not yet known to this version of the crate.
5377    Unknown(String),
5378}
5379
5380impl LateAllowNotRunReason {
5381    pub fn as_str(&self) -> &str {
5382        match self {
5383            Self::TurnRunning => "turn_running",
5384            Self::CardOpen => "card_open",
5385            Self::CallGone => "call_gone",
5386            Self::InvalidAnswer => "invalid_answer",
5387            Self::Limited => "limited",
5388            Self::Stopped => "stopped",
5389            Self::Declined => "declined",
5390            Self::AskedAgain => "asked_again",
5391            Self::Withdrawn => "withdrawn",
5392            Self::Expired => "expired",
5393            Self::NotRun => "not_run",
5394            Self::Unknown(s) => s.as_str(),
5395        }
5396    }
5397}
5398
5399impl fmt::Display for LateAllowNotRunReason {
5400    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5401        f.write_str(self.as_str())
5402    }
5403}
5404
5405impl From<&str> for LateAllowNotRunReason {
5406    fn from(s: &str) -> Self {
5407        match s {
5408            "turn_running" => Self::TurnRunning,
5409            "card_open" => Self::CardOpen,
5410            "call_gone" => Self::CallGone,
5411            "invalid_answer" => Self::InvalidAnswer,
5412            "limited" => Self::Limited,
5413            "stopped" => Self::Stopped,
5414            "declined" => Self::Declined,
5415            "asked_again" => Self::AskedAgain,
5416            "withdrawn" => Self::Withdrawn,
5417            "expired" => Self::Expired,
5418            "not_run" => Self::NotRun,
5419            other => Self::Unknown(other.to_string()),
5420        }
5421    }
5422}
5423
5424impl Serialize for LateAllowNotRunReason {
5425    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
5426        serializer.serialize_str(self.as_str())
5427    }
5428}
5429
5430impl<'de> Deserialize<'de> for LateAllowNotRunReason {
5431    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
5432        let s = String::deserialize(deserializer)?;
5433        Ok(Self::from(s.as_str()))
5434    }
5435}
5436
5437/// Phase of a [`PermissionCheckStatusMessage`].
5438#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5439pub enum PermissionCheckStatus {
5440    /// The call has waited about four seconds on its check and is still
5441    /// waiting.
5442    Checking,
5443    /// That wait is over.
5444    Done,
5445    /// A status not yet known to this version of the crate.
5446    Unknown(String),
5447}
5448
5449impl PermissionCheckStatus {
5450    pub fn as_str(&self) -> &str {
5451        match self {
5452            Self::Checking => "checking",
5453            Self::Done => "done",
5454            Self::Unknown(s) => s.as_str(),
5455        }
5456    }
5457}
5458
5459impl fmt::Display for PermissionCheckStatus {
5460    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5461        f.write_str(self.as_str())
5462    }
5463}
5464
5465impl From<&str> for PermissionCheckStatus {
5466    fn from(s: &str) -> Self {
5467        match s {
5468            "checking" => Self::Checking,
5469            "done" => Self::Done,
5470            other => Self::Unknown(other.to_string()),
5471        }
5472    }
5473}
5474
5475impl Serialize for PermissionCheckStatus {
5476    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
5477        serializer.serialize_str(self.as_str())
5478    }
5479}
5480
5481impl<'de> Deserialize<'de> for PermissionCheckStatus {
5482    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
5483        let s = String::deserialize(deserializer)?;
5484        Ok(Self::from(s.as_str()))
5485    }
5486}
5487
5488/// One entry of [`FileAttachmentsMissingMessage::missing`].
5489#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5490pub struct MissingFileAttachment {
5491    /// The `file_uuid` of the message's `file_attachments` entry.
5492    pub file_uuid: String,
5493    /// Why, as a short code: `download`, `too_large`, `not_found` (the
5494    /// files route answered 404 or 410, so sending it again rarely helps;
5495    /// CLI 2.1.293+), `write`, `no_space` (as `write`, and the disk was
5496    /// full, so sending it again helps only once there is room; CLI
5497    /// 2.1.328+), `no_token`, `not_finished` or `count_cap`.
5498    /// More codes may be added; read an unknown one as "did not arrive".
5499    pub reason: String,
5500}
5501
5502/// `system/session_title_changed` — the session's name, for a host that
5503/// shows it (an IDE editor tab, say). A headless session sends it at startup
5504/// when the session already has a name, and again after each change to the
5505/// name (not an AI-generated title), including a rename the host itself sent
5506/// with `rename_session`. A cleared name is not sent. The same name can
5507/// arrive more than once, so treat a repeated name as no change. The frame
5508/// can arrive before the `system/init` that first names its `session_id`
5509/// (at startup or after `/clear`); a host that learns the session id from
5510/// init can hold the name until then (CLI 2.1.285+).
5511#[derive(Debug, Clone, Serialize, Deserialize)]
5512pub struct SessionTitleChangedMessage {
5513    /// The session's current name: control, bidirectional and zero-width
5514    /// characters replaced with single spaces, ends trimmed, at most 200
5515    /// Unicode code points. A suffix can make it unique when another session
5516    /// already has the name.
5517    pub title: String,
5518    pub uuid: String,
5519    pub session_id: String,
5520}
5521
5522/// `system/session_writes_lost` — the CLI could not save lines of a session
5523/// transcript, changes to `~/.claude.json`, or both, because the disk was
5524/// full or its quota was used up. Sent at most once, as the CLI exits with
5525/// status 0, after the last result if there was one. A run that exits 1, as
5526/// after an error result, gets only the line on stderr (CLI 2.1.317 and some
5527/// later releases sent this message there too). The results already received stand,
5528/// and this message does not change the exit status. Sent only with
5529/// stream-json output on stdout, never under `--sdk-url` or a Claude Desktop
5530/// entrypoint. Safe to ignore (CLI 2.1.317+).
5531#[derive(Debug, Clone, Serialize, Deserialize)]
5532pub struct SessionWritesLostMessage {
5533    /// Why the writes failed. When both kinds of write were lost for
5534    /// different reasons, the transcript's.
5535    pub error_code: SessionWriteErrorCode,
5536    /// What was not saved. Never empty.
5537    pub lost: Vec<LostSessionWrite>,
5538    /// The sessions whose transcripts lost lines, in the order each first
5539    /// lost one. Present only when [`LostSessionWrite::Transcript`] is
5540    /// listed; never empty. Usually `session_id` alone; a CLI that started a
5541    /// new session after the loss (as `/clear` does) lists the earlier
5542    /// session, and lists `session_id` only if that session lost lines too.
5543    #[serde(default, skip_serializing_if = "Option::is_none")]
5544    pub transcript_session_ids: Option<Vec<String>>,
5545    pub uuid: String,
5546    /// The session the CLI is in, as on every message; see
5547    /// [`transcript_session_ids`](Self::transcript_session_ids) for whose
5548    /// transcript lost lines.
5549    pub session_id: String,
5550}
5551
5552/// [`SessionWritesLostMessage::error_code`]: why the writes failed.
5553#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5554pub enum SessionWriteErrorCode {
5555    /// `ENOSPC` — the disk was full.
5556    Enospc,
5557    /// `EDQUOT` — the disk quota was used up.
5558    Edquot,
5559    /// A code not yet known to this version of the crate.
5560    Unknown(String),
5561}
5562
5563impl SessionWriteErrorCode {
5564    pub fn as_str(&self) -> &str {
5565        match self {
5566            Self::Enospc => "ENOSPC",
5567            Self::Edquot => "EDQUOT",
5568            Self::Unknown(s) => s.as_str(),
5569        }
5570    }
5571}
5572
5573impl fmt::Display for SessionWriteErrorCode {
5574    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5575        f.write_str(self.as_str())
5576    }
5577}
5578
5579impl From<&str> for SessionWriteErrorCode {
5580    fn from(s: &str) -> Self {
5581        match s {
5582            "ENOSPC" => Self::Enospc,
5583            "EDQUOT" => Self::Edquot,
5584            other => Self::Unknown(other.to_string()),
5585        }
5586    }
5587}
5588
5589impl Serialize for SessionWriteErrorCode {
5590    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
5591        serializer.serialize_str(self.as_str())
5592    }
5593}
5594
5595impl<'de> Deserialize<'de> for SessionWriteErrorCode {
5596    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
5597        let s = String::deserialize(deserializer)?;
5598        Ok(Self::from(s.as_str()))
5599    }
5600}
5601
5602/// One entry of [`SessionWritesLostMessage::lost`]: what was not saved.
5603#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5604pub enum LostSessionWrite {
5605    /// Lines of a session transcript, so resuming a session in
5606    /// `transcript_session_ids` may miss part of its conversation.
5607    Transcript,
5608    /// Changes this run made to `~/.claude.json`.
5609    GlobalConfig,
5610    /// A value not yet known to this version of the crate.
5611    Unknown(String),
5612}
5613
5614impl LostSessionWrite {
5615    pub fn as_str(&self) -> &str {
5616        match self {
5617            Self::Transcript => "transcript",
5618            Self::GlobalConfig => "global_config",
5619            Self::Unknown(s) => s.as_str(),
5620        }
5621    }
5622}
5623
5624impl fmt::Display for LostSessionWrite {
5625    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5626        f.write_str(self.as_str())
5627    }
5628}
5629
5630impl From<&str> for LostSessionWrite {
5631    fn from(s: &str) -> Self {
5632        match s {
5633            "transcript" => Self::Transcript,
5634            "global_config" => Self::GlobalConfig,
5635            other => Self::Unknown(other.to_string()),
5636        }
5637    }
5638}
5639
5640impl Serialize for LostSessionWrite {
5641    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
5642        serializer.serialize_str(self.as_str())
5643    }
5644}
5645
5646impl<'de> Deserialize<'de> for LostSessionWrite {
5647    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
5648        let s = String::deserialize(deserializer)?;
5649        Ok(Self::from(s.as_str()))
5650    }
5651}
5652
5653/// `system/ui_log` — one `$.ui.log(text)` line from a plugin in a headless
5654/// session: what the REPL appends to its transcript as a dim notice under
5655/// the plugin's name. Not sent to the model (CLI 2.1.285+).
5656#[derive(Debug, Clone, Serialize, Deserialize)]
5657pub struct UiLogMessage {
5658    /// The calling plugin's registry name, as the hooks engine knows it.
5659    pub plugin: String,
5660    /// The line the plugin gave: be ready for up to 10000 characters of it
5661    /// and then an ellipsis (4096 before CLI 2.1.289). Plain text: draw it
5662    /// as a text node, never as markup.
5663    pub text: String,
5664    pub uuid: String,
5665    pub session_id: String,
5666}
5667
5668/// `system/ui_notify` — one `$.ui.notify(text)` from a plugin in a headless
5669/// session: a notification for the client to raise under the plugin's name,
5670/// now or later. Nothing limits how often a plugin sends one
5671/// (CLI 2.1.321+).
5672#[derive(Debug, Clone, Serialize, Deserialize)]
5673pub struct UiNotifyMessage {
5674    /// The calling plugin's registry name, as the hooks engine knows it
5675    /// (never plugin-settable). Not cleaned as `title` is, so scrub it, and
5676    /// show it after the host's own word that a mod sent it, so neither it
5677    /// nor the title can pass for the app's own.
5678    pub plugin: String,
5679    /// The plugin's full id, `name@marketplace` (`name@inline` when
5680    /// side-loaded), as the hooks engine loaded it (never plugin-settable).
5681    /// Two plugins sharing a name differ here.
5682    pub source: String,
5683    /// The notification's heading: the plugin's words, cleaned of control
5684    /// characters and cut to 120 characters, or the plugin's name. Plain
5685    /// text, and never the only sign of who sent it.
5686    pub title: String,
5687    /// The body: the plugin's words, cleaned of control characters and cut
5688    /// to 1000 characters. Plain text: draw it as a text node, never as
5689    /// markup.
5690    pub text: String,
5691    /// The plugin's name for this notification: one with the same `source`
5692    /// and key replaces the last. Scope it by `source`, so one mod cannot
5693    /// touch another's. Absent: each frame is its own notification.
5694    #[serde(default, skip_serializing_if = "Option::is_none")]
5695    pub key: Option<String>,
5696    /// How long after this frame arrives to raise it; the client holds it,
5697    /// so it fires with the session out of reach. At most 7 days. Absent
5698    /// (with no [`at`](Self::at)): raise it now.
5699    #[serde(default, skip_serializing_if = "Option::is_none")]
5700    pub delay_ms: Option<u64>,
5701    /// The epoch-millisecond time to raise it, at most 7 days ahead. Never
5702    /// sent beside [`delay_ms`](Self::delay_ms).
5703    #[serde(default, skip_serializing_if = "Option::is_none")]
5704    pub at: Option<u64>,
5705    /// With `delay_ms` or `at`: throw it away if the person returns to the
5706    /// session before it fires.
5707    #[serde(default, skip_serializing_if = "Option::is_none")]
5708    pub until_back: Option<bool>,
5709    /// True when what this frame carries differs from what the sender sent
5710    /// and another plugin's hook was in the chain: its words, timing or key
5711    /// may not be the sender's, so say so beside the sender. Always sent;
5712    /// missing (from an older engine) reads as false. Never plugin-settable.
5713    #[serde(default)]
5714    pub rewritten: bool,
5715    pub uuid: String,
5716    pub session_id: String,
5717}
5718
5719/// `system/ui_notify_cancel` — one `$.ui.cancelNotify(key)` from a plugin in
5720/// a headless session, or the engine removing a plugin: remove the
5721/// notification with this `source` and `key`, shown or still waiting. None
5722/// held under that key: do nothing (CLI 2.1.321+).
5723#[derive(Debug, Clone, Serialize, Deserialize)]
5724pub struct UiNotifyCancelMessage {
5725    /// The plugin's registry name, as the hooks engine knows it (never
5726    /// plugin-settable).
5727    pub plugin: String,
5728    /// The plugin's full id, as on [`UiNotifyMessage::source`] (never
5729    /// plugin-settable). Only notifications of this source are touched.
5730    pub source: String,
5731    /// The [`UiNotifyMessage::key`] of the notification to take back.
5732    /// Absent: the engine removed the plugin from this session, so drop
5733    /// everything this source has waiting for this session. Only the engine
5734    /// sends that.
5735    #[serde(default, skip_serializing_if = "Option::is_none")]
5736    pub key: Option<String>,
5737    pub uuid: String,
5738    pub session_id: String,
5739}
5740
5741/// `system/ui_toast` — one `$.ui.toast(text)` from a plugin in a headless
5742/// session: what the REPL shows on the notification bar under the prompt
5743/// for a few seconds, under the plugin's name. Toasts arrive at no fixed
5744/// rate: CLI 2.1.289 dropped the hooks host's 2 s spacing (CLI 2.1.285+).
5745#[derive(Debug, Clone, Serialize, Deserialize)]
5746pub struct UiToastMessage {
5747    /// The calling plugin's registry name, as the hooks engine knows it.
5748    pub plugin: String,
5749    /// The line the plugin gave: be ready for up to 10000 characters of it
5750    /// and then an ellipsis (4096 before CLI 2.1.289). Plain text: draw it
5751    /// as a text node, never as markup.
5752    pub text: String,
5753    /// How long the REPL would keep it on the notification bar: the plugin's
5754    /// `timeoutMs`, or the engine's default (4000).
5755    pub timeout_ms: u64,
5756    pub uuid: String,
5757    pub session_id: String,
5758}
5759
5760/// `system/ui_status` — one `$.ui.status(text)` from a plugin in a headless
5761/// session: the line the REPL pins under the prompt until the plugin's next
5762/// call replaces or clears it. One status line per plugin (CLI 2.1.285+).
5763#[derive(Debug, Clone, Serialize, Deserialize)]
5764pub struct UiStatusMessage {
5765    /// The calling plugin's registry name, as the hooks engine knows it.
5766    pub plugin: String,
5767    /// The plugin's pinned line, replacing its previous one; `None` (wire
5768    /// `null`) removes it. Be ready for up to 10000 characters of it and
5769    /// then an ellipsis (4096 before CLI 2.1.289). Plain text: draw it as a
5770    /// text node, never as markup.
5771    pub text: Option<String>,
5772    pub uuid: String,
5773    pub session_id: String,
5774}
5775
5776/// `system/ui_invalidate` — a plugin called `$.ui.invalidate("ui.render")`,
5777/// a plugin loaded or reloaded, or (CLI 2.1.318+) a mobile client already
5778/// known to the session named a field (or, on CLI 2.1.323+, `Progress`) in
5779/// `draws` it had not named before:
5780/// every tree a remote surface drew through `ui_render` may be stale, and the surface re-asks each mounted instance.
5781/// Bumps from one plugin fold to at most one per 100 ms (CLI 2.1.285+).
5782#[derive(Debug, Clone, Serialize, Deserialize)]
5783pub struct UiInvalidateMessage {
5784    /// The render event whose version moved — `"ui.render"`; the engine
5785    /// versions it as one event, so no component or instance is named.
5786    pub event: String,
5787    /// Present when a plugin state write, or (CLI 2.1.289+) a `Client`
5788    /// drawn in them that failed and whose plugin heard it (`ui.fault`),
5789    /// made only these instances stale, so the surface may re-ask them
5790    /// alone. The theme of the session being set or cleared
5791    /// (`$.theme.set` / `$.theme.clear` on CLI 2.1.319+), or a client of a
5792    /// surface that draws it joining where one ever stood, names the
5793    /// `Theme` instance (`instance_id` `theme`, CLI 2.1.321+) on each such
5794    /// surface, and the instance whose `instance_id` is `backdrop`; on CLI
5795    /// 2.1.323+ the `backdrop` one only where the scene changed or a client
5796    /// joined.
5797    /// Absent, every mounted instance may be stale.
5798    #[serde(default, skip_serializing_if = "Option::is_none")]
5799    pub instances: Option<Vec<UiInvalidatedInstance>>,
5800    /// Present, and true, while a mod may change what is recorded of a typed
5801    /// line (a hook on `prompt.submit`, `command.run`, `session.append` or
5802    /// `session.receive`, mods not yet known, or an organization policy that
5803    /// lists a plugin or cannot be read): what the `prompts_screened_v1`
5804    /// capability says on `system/init`, sent as soon as a plugin load or
5805    /// reload makes it so. Absent says nothing; the next `system/init` does
5806    /// (CLI 2.1.300+).
5807    #[serde(default, skip_serializing_if = "Option::is_none")]
5808    pub prompts_screened: Option<bool>,
5809    pub uuid: String,
5810    pub session_id: String,
5811}
5812
5813/// One stale instance named by [`UiInvalidateMessage::instances`].
5814#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5815pub struct UiInvalidatedInstance {
5816    /// The surface that drew the instance.
5817    pub surface: String,
5818    /// The component of the instance.
5819    pub component: String,
5820    /// The engine's requestId of the instance, as the `ui_render` that drew
5821    /// it named it.
5822    pub instance_id: String,
5823}
5824
5825/// `system/ui_panes` — the pane roster a remote surface draws changed: a
5826/// plugin opened, retitled or closed a pane, the person showed, focused or
5827/// closed one, or a placing client attached. Deduplicated: an unchanged
5828/// roster is not pushed. A pane opened before the stream armed produces
5829/// none, so read the roster with a `ui_panes` request on mount
5830/// (CLI 2.1.285+).
5831#[derive(Debug, Clone, Serialize, Deserialize)]
5832pub struct UiPanesMessage {
5833    /// The placed open panes in open order (an open appends, a close
5834    /// removes); a pane waiting unplaced is not listed.
5835    pub panes: Vec<UiPane>,
5836    /// The pane the surface shows: the last opened or focused, never
5837    /// displacing one the person holds; `None` with none open.
5838    pub shown_id: Option<String>,
5839    /// The pane the person gave the keyboard; `None` while the composer has
5840    /// it.
5841    pub focused_id: Option<String>,
5842    /// A standing `$.ui.open({ focus: true })` the surface has yet to judge:
5843    /// honour it only while the composer is empty and idle and no dialog is
5844    /// up, else refuse it.
5845    pub focus_requested_id: Option<String>,
5846    pub uuid: String,
5847    pub session_id: String,
5848}
5849
5850/// One placed pane in a [`UiPanesMessage`] roster.
5851#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5852pub struct UiPane {
5853    /// The pane's id as the plugin opened it: 1 to 64 of letters, digits,
5854    /// `_`, `-`.
5855    pub id: String,
5856    /// The pane's tab label: the `title` its latest open gave, else its id.
5857    /// Plugin-authored text: draw it as a text node, never as markup.
5858    pub title: String,
5859    /// The registry name of the plugin that opened it.
5860    pub plugin: String,
5861    /// `true`: Escape while the pane holds the keyboard, or at an idle empty
5862    /// composer, closes it. Absent, Escape only returns the keyboard.
5863    #[serde(default, skip_serializing_if = "Option::is_none")]
5864    pub close_on_escape: Option<bool>,
5865    /// `true`: the surface holds its transient toasts while this pane is
5866    /// the one shown, and shows them once it closes.
5867    #[serde(default, skip_serializing_if = "Option::is_none")]
5868    pub hold_toasts: Option<bool>,
5869    /// What the surface paints under this pane's body while it is the one
5870    /// shown: a theme key, a raw color, or `transparent` for nothing.
5871    /// Plugin-authored: parse it, never write it into a style. Absent, the
5872    /// surface's own look stands (CLI 2.1.311+).
5873    #[serde(default, skip_serializing_if = "Option::is_none")]
5874    pub background_color: Option<String>,
5875    /// The body rows its content asked for while seated inline; a request
5876    /// the person's own sizing overrides.
5877    #[serde(default, skip_serializing_if = "Option::is_none")]
5878    pub rows: Option<u64>,
5879    /// The body columns its content asked for while docked; a request the
5880    /// person's own sizing overrides.
5881    #[serde(default, skip_serializing_if = "Option::is_none")]
5882    pub columns: Option<u64>,
5883    /// `widget` when the pane's latest open asked to start as a widget, the
5884    /// small form of a minimized pane. A request, repeated on every roster
5885    /// while it stands: honour it on first seeing the pane; after that the
5886    /// person's expand or minimize stands. The CLI reads any other value as
5887    /// absent, so treat unrecognized values the same. Marked `@internal`
5888    /// upstream (CLI 2.1.323+).
5889    #[serde(default, skip_serializing_if = "Option::is_none")]
5890    pub placement: Option<String>,
5891}
5892
5893/// `system/ui_placed` — a fire-and-forget push from a headless session when
5894/// a plugin places a row with `$.ui.place`, and to a client as it joins
5895/// (CLI 2.1.314+). A surface inserts each row after
5896/// [`UiPlacedRow::after_uuid`] and asks `ui_render` for it. Display only:
5897/// no message carries these rows. A surface drops the rows it holds with
5898/// the conversation it resets, and a row whose `after_uuid` it no longer
5899/// holds. A compaction ends the rows before it, and no push says so.
5900#[derive(Debug, Clone, Serialize, Deserialize)]
5901pub struct UiPlacedMessage {
5902    /// The main conversation's placed rows, in order.
5903    pub rows: Vec<UiPlacedRow>,
5904    pub uuid: String,
5905    pub session_id: String,
5906}
5907
5908/// One row in a [`UiPlacedMessage`].
5909#[derive(Debug, Clone, Serialize, Deserialize)]
5910pub struct UiPlacedRow {
5911    /// The plugin that placed the row.
5912    pub plugin: String,
5913    /// The row's id among that plugin's rows.
5914    pub id: String,
5915    /// The `instance_id` of the `ui_render` ask, with `component: "Placed"`,
5916    /// that draws it.
5917    pub request_id: String,
5918    /// The conversation message the row follows; absent at the
5919    /// conversation's start. Rows sharing it stand in roster order.
5920    #[serde(default, skip_serializing_if = "Option::is_none")]
5921    pub after_uuid: Option<String>,
5922}
5923
5924/// `system/ui_scroll` — a plugin's `$.ui.scroll` moved the window of a site
5925/// a remote surface draws: the surface scrolls the site's body there. The
5926/// person's own scrolls are never pushed back (CLI 2.1.285+).
5927#[derive(Debug, Clone, Serialize, Deserialize)]
5928pub struct UiScrollMessage {
5929    /// The client drawing the site, as it attached.
5930    pub client_id: String,
5931    /// Which site: a pane's body or the band above the prompt.
5932    pub component: UiSiteComponent,
5933    /// The pane's id, or `above-prompt` for the band.
5934    pub instance_id: String,
5935    /// The first content row the window is to show, 0 at the top, clamped
5936    /// to the tree as the surface last reported it.
5937    pub offset: u64,
5938    /// `true`: keep the window on the tree's last rows through the draws to
5939    /// come, until the person or a plugin next moves it.
5940    #[serde(default, skip_serializing_if = "Option::is_none")]
5941    pub follow_end: Option<bool>,
5942    pub uuid: String,
5943    pub session_id: String,
5944}
5945
5946/// `system/ui_focus` — a plugin's `$.ui.focus` moved the focus ring of a
5947/// site a remote surface draws onto one of its Buttons, Inputs or Selects:
5948/// the surface focuses that element if it still draws it. The person's own
5949/// moves are never pushed back (CLI 2.1.285+).
5950#[derive(Debug, Clone, Serialize, Deserialize)]
5951pub struct UiFocusMessage {
5952    /// The client drawing the site, as it attached.
5953    pub client_id: String,
5954    /// Which site: a pane's body or the band above the prompt.
5955    pub component: UiSiteComponent,
5956    /// The pane's id, or `above-prompt` for the band.
5957    pub instance_id: String,
5958    /// Whose element takes the ring: its `press.plugin`.
5959    pub plugin: String,
5960    /// The element's `props.key`, as `ui.press` names it.
5961    pub key: String,
5962    pub uuid: String,
5963    pub session_id: String,
5964}
5965
5966/// The site a [`UiScrollMessage`] or [`UiFocusMessage`] addresses.
5967#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5968pub enum UiSiteComponent {
5969    /// A pane's body.
5970    Pane,
5971    /// The band above the prompt.
5972    AbovePrompt,
5973    /// A site not yet known to this version of the crate.
5974    Unknown(String),
5975}
5976
5977impl UiSiteComponent {
5978    pub fn as_str(&self) -> &str {
5979        match self {
5980            Self::Pane => "Pane",
5981            Self::AbovePrompt => "AbovePrompt",
5982            Self::Unknown(s) => s.as_str(),
5983        }
5984    }
5985}
5986
5987impl fmt::Display for UiSiteComponent {
5988    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5989        f.write_str(self.as_str())
5990    }
5991}
5992
5993impl From<&str> for UiSiteComponent {
5994    fn from(s: &str) -> Self {
5995        match s {
5996            "Pane" => Self::Pane,
5997            "AbovePrompt" => Self::AbovePrompt,
5998            other => Self::Unknown(other.to_string()),
5999        }
6000    }
6001}
6002
6003impl Serialize for UiSiteComponent {
6004    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
6005        serializer.serialize_str(self.as_str())
6006    }
6007}
6008
6009impl<'de> Deserialize<'de> for UiSiteComponent {
6010    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
6011        let s = String::deserialize(deserializer)?;
6012        Ok(Self::from(s.as_str()))
6013    }
6014}
6015
6016/// The run that printed a local-command row, carried as
6017/// [`AssistantMessage::local_command_run`].
6018#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6019pub struct LocalCommandRun {
6020    /// The command's name as `command.run` carried it (no slash).
6021    pub command: String,
6022    /// Its arguments as the echo shows them (`***` when the command marks
6023    /// them sensitive).
6024    pub args: String,
6025    /// For a command a plugin registered, that plugin's name; for a row
6026    /// whose text plugins' `command.run` hooks answered or retold, the names
6027    /// the text is led by. Untrusted text; absent for the binary's own
6028    /// command in its own words (CLI 2.1.300+).
6029    #[serde(default, skip_serializing_if = "Option::is_none")]
6030    pub plugin: Option<String>,
6031}
6032
6033/// What a local-command row reports, carried as
6034/// [`AssistantMessage::local_command_outcome`] so a host can offer a fix
6035/// instead of relaying the text (CLI 2.1.281+).
6036#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6037pub struct LocalCommandOutcome {
6038    pub kind: LocalCommandOutcomeKind,
6039    /// Kind `unknown` only: the registered command closest to the typed
6040    /// name, no slash.
6041    #[serde(default, skip_serializing_if = "Option::is_none")]
6042    pub suggestion: Option<String>,
6043}
6044
6045/// The outcome a local-command row reports ([`LocalCommandOutcome::kind`]).
6046/// New kinds are additive; the CLI itself drops the whole outcome when it
6047/// meets a kind it does not know, so treat [`Unknown`](Self::Unknown) as
6048/// absent.
6049#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6050pub enum LocalCommandOutcomeKind {
6051    /// An interactive-panel command this (headless) session cannot open.
6052    UnavailableHeadless,
6053    /// No command has the typed name; see
6054    /// [`LocalCommandOutcome::suggestion`].
6055    Unknown,
6056    /// The command ran and failed.
6057    Failed,
6058    /// The change applies after Claude Code restarts.
6059    RestartRequired,
6060    /// A kind not yet known to this version of the crate.
6061    Other(String),
6062}
6063
6064impl LocalCommandOutcomeKind {
6065    pub fn as_str(&self) -> &str {
6066        match self {
6067            Self::UnavailableHeadless => "unavailable_headless",
6068            Self::Unknown => "unknown",
6069            Self::Failed => "failed",
6070            Self::RestartRequired => "restart_required",
6071            Self::Other(s) => s.as_str(),
6072        }
6073    }
6074}
6075
6076impl fmt::Display for LocalCommandOutcomeKind {
6077    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6078        f.write_str(self.as_str())
6079    }
6080}
6081
6082impl From<&str> for LocalCommandOutcomeKind {
6083    fn from(s: &str) -> Self {
6084        match s {
6085            "unavailable_headless" => Self::UnavailableHeadless,
6086            "unknown" => Self::Unknown,
6087            "failed" => Self::Failed,
6088            "restart_required" => Self::RestartRequired,
6089            other => Self::Other(other.to_string()),
6090        }
6091    }
6092}
6093
6094impl Serialize for LocalCommandOutcomeKind {
6095    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
6096        serializer.serialize_str(self.as_str())
6097    }
6098}
6099
6100impl<'de> Deserialize<'de> for LocalCommandOutcomeKind {
6101    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
6102        let s = String::deserialize(deserializer)?;
6103        Ok(Self::from(s.as_str()))
6104    }
6105}
6106
6107/// Structured twin of a `/usage` result, carried as
6108/// [`AssistantMessage::usage_report`]: the session's totals, the plan's
6109/// usage rows as the server sent them and the extra-usage spend, and nothing
6110/// else from the usage body (the `get_usage` control reply carries the
6111/// rest). Experimental — the shape may change.
6112#[derive(Debug, Clone, Serialize, Deserialize)]
6113pub struct UsageReport {
6114    /// Cost and usage accumulated by the current session.
6115    pub session: super::control::UsageSession,
6116    /// The plan's usage rows and extra-usage spend from the claude.ai usage
6117    /// endpoint; `None` when the CLI could not fetch them (no plan on this
6118    /// lane, or a token without the profile scope).
6119    pub rate_limits: Option<UsageReportRateLimits>,
6120    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
6121    pub extra: serde_json::Map<String, Value>,
6122}
6123
6124/// The plan's usage rows and extra-usage spend in a [`UsageReport`].
6125#[derive(Debug, Clone, Serialize, Deserialize)]
6126pub struct UsageReportRateLimits {
6127    /// The server's usage rows (the usage endpoint's `limits[]`), as sent:
6128    /// which meters apply, their scope, labels, severity and order are the
6129    /// server's, so a client renders them verbatim. Empty when the server
6130    /// reported no meters; `None` when the body carried no rows at all (a
6131    /// server that predates them). When the usage fetch failed and the CLI
6132    /// fell back to rate-limit response headers, this holds at most the one
6133    /// row it synthesizes from them.
6134    pub limits: Option<Vec<UsageReportLimit>>,
6135    /// Extra-usage (overage) spend for the billing period, when the plan
6136    /// has it.
6137    #[serde(default, skip_serializing_if = "Option::is_none")]
6138    pub extra_usage: Option<UsageReportExtraUsage>,
6139    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
6140    pub extra: serde_json::Map<String, Value>,
6141}
6142
6143/// One server usage row in [`UsageReportRateLimits::limits`].
6144#[derive(Debug, Clone, Serialize, Deserialize)]
6145pub struct UsageReportLimit {
6146    /// The server's meter kind, e.g. `session`, `weekly_all` or
6147    /// `weekly_scoped`. Classify a row on this, never on a label.
6148    pub kind: String,
6149    /// The server's row group, e.g. `session` or `weekly`; rows render
6150    /// grouped under it, in the server's order.
6151    pub group: String,
6152    /// Share of the window used, 0–100.
6153    pub percent: f64,
6154    /// ISO 8601 timestamp when the window resets.
6155    pub resets_at: Option<String>,
6156    /// What a scoped row is for, a model or a surface, with the server's
6157    /// display label.
6158    #[serde(default, skip_serializing_if = "Option::is_none")]
6159    pub scope: Option<UsageReportScope>,
6160    /// The server's reading of the row for a meter's colour, e.g. `normal`,
6161    /// `warning` or `critical`; a client falls back to its own thresholds
6162    /// without it.
6163    #[serde(default, skip_serializing_if = "Option::is_none")]
6164    pub severity: Option<String>,
6165    /// The server's headline pick: the row a single-value indicator shows.
6166    #[serde(default, skip_serializing_if = "Option::is_none")]
6167    pub is_active: Option<bool>,
6168    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
6169    pub extra: serde_json::Map<String, Value>,
6170}
6171
6172/// What a scoped [`UsageReportLimit`] row is for.
6173#[derive(Debug, Clone, Serialize, Deserialize)]
6174pub struct UsageReportScope {
6175    #[serde(default, skip_serializing_if = "Option::is_none")]
6176    pub model: Option<UsageReportScopeLabel>,
6177    #[serde(default, skip_serializing_if = "Option::is_none")]
6178    pub surface: Option<UsageReportScopeLabel>,
6179    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
6180    pub extra: serde_json::Map<String, Value>,
6181}
6182
6183/// The server's display label for a [`UsageReportScope`] member.
6184#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6185pub struct UsageReportScopeLabel {
6186    pub display_name: String,
6187}
6188
6189/// Extra-usage (overage) spend for the billing period in a
6190/// [`UsageReportRateLimits`]. Amounts are in minor units of `currency`
6191/// (cents for USD).
6192#[derive(Debug, Clone, Serialize, Deserialize)]
6193pub struct UsageReportExtraUsage {
6194    /// `false` while extra usage cannot cover sends.
6195    pub is_enabled: bool,
6196    pub monthly_limit: Option<f64>,
6197    pub used_credits: Option<f64>,
6198    pub utilization: Option<f64>,
6199    #[serde(default, skip_serializing_if = "Option::is_none")]
6200    pub currency: Option<String>,
6201    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
6202    pub extra: serde_json::Map<String, Value>,
6203}
6204
6205/// `{id, name}` of an original `Batch*` tool_use block, carried in
6206/// [`AssistantMessage::batch_tool_uses`].
6207#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6208pub struct BatchToolUse {
6209    pub id: String,
6210    pub name: String,
6211}
6212
6213/// Structured twin of the `/context` report, carried as
6214/// [`AssistantMessage::context_usage`] — the data a client needs to render
6215/// the context-usage card without parsing the markdown table. Evolves
6216/// additively; a breaking reshape would ship as a sibling field.
6217#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6218pub struct ContextUsage {
6219    /// Main-loop model the usage was computed for.
6220    pub model: String,
6221    /// Estimated tokens in use, unclamped — may exceed `raw_max_tokens` when
6222    /// over limit.
6223    pub total_tokens: u64,
6224    /// The window usage is measured against: the resolved autocompact window —
6225    /// the model's believed limit, or a smaller compaction-policy window.
6226    pub raw_max_tokens: u64,
6227    /// Rounded `total_tokens / raw_max_tokens`, 0–100+.
6228    pub percentage: u64,
6229    /// Present when `total_tokens` exceeds `raw_max_tokens`.
6230    #[serde(default, skip_serializing_if = "Option::is_none")]
6231    pub over_limit: Option<ContextOverLimit>,
6232    /// Usage-by-category rows (`Messages`, `System prompt`, …).
6233    #[serde(default)]
6234    pub categories: Vec<ContextCategory>,
6235    /// Per-tool token contributions of MCP tools.
6236    #[serde(default)]
6237    pub mcp_tools: Vec<ContextMcpTool>,
6238    /// Per-file token contributions of memory files.
6239    #[serde(default)]
6240    pub memory_files: Vec<ContextMemoryFile>,
6241    /// Per-agent token contributions of agent definitions.
6242    #[serde(default)]
6243    pub agents: Vec<ContextAgent>,
6244    /// Per-skill token contributions. Omitted when no skills contribute.
6245    #[serde(default, skip_serializing_if = "Option::is_none")]
6246    pub skills: Option<Vec<ContextSkill>>,
6247}
6248
6249/// Why and by how much a [`ContextUsage`] exceeds its window.
6250#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6251pub struct ContextOverLimit {
6252    pub tokens_over: u64,
6253    /// How the window was resolved: `"hard_limit"` (the model's believed
6254    /// limit) or `"compaction_window"` (a compaction-policy window).
6255    pub kind: String,
6256}
6257
6258/// One row of the `/context` usage-by-category breakdown.
6259#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6260pub struct ContextCategory {
6261    /// Display name of the row as the CLI renders it, e.g. `"Messages"`.
6262    /// Use `kind` (not this name) to classify the row.
6263    pub name: String,
6264    pub tokens: u64,
6265    /// What the row is: `"used"` content occupies the window; `"free"` is the
6266    /// remaining window; `"buffer"` is the compaction reserve; `"deferred"`
6267    /// rows are out-of-window tool schemas, excluded from usage math.
6268    pub kind: String,
6269}
6270
6271/// An MCP tool's token contribution, in [`ContextUsage::mcp_tools`].
6272#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6273pub struct ContextMcpTool {
6274    /// Wire name, e.g. `"mcp__linear__create_issue"`.
6275    pub name: String,
6276    pub server_name: String,
6277    pub tokens: u64,
6278}
6279
6280/// A memory file's token contribution, in [`ContextUsage::memory_files`].
6281#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6282pub struct ContextMemoryFile {
6283    pub path: String,
6284    /// Display label of the memory-file source, e.g. `"Project"` or `"User"`.
6285    #[serde(rename = "type")]
6286    pub file_type: String,
6287    pub tokens: u64,
6288}
6289
6290/// An agent definition's token contribution, in [`ContextUsage::agents`].
6291#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6292pub struct ContextAgent {
6293    pub agent_type: String,
6294    /// Raw source identifier, e.g. `"projectSettings"`, `"plugin"`.
6295    pub source: String,
6296    pub tokens: u64,
6297}
6298
6299/// A skill's token contribution, in [`ContextUsage::skills`].
6300#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6301pub struct ContextSkill {
6302    pub name: String,
6303    /// Raw source identifier, e.g. `"userSettings"`, `"plugin"`.
6304    pub source: String,
6305    #[serde(default, skip_serializing_if = "Option::is_none")]
6306    pub plugin_name: Option<String>,
6307    pub tokens: u64,
6308}
6309
6310/// Display metadata for a tool-use block carried on the assistant wrapper.
6311#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6312pub struct ToolUseMeta {
6313    pub id: String,
6314    pub display_name: String,
6315    #[serde(default, skip_serializing_if = "Option::is_none")]
6316    pub server_display_name: Option<String>,
6317    #[serde(default, skip_serializing_if = "Option::is_none")]
6318    pub icon_url: Option<String>,
6319    /// The `mcpsrv_` connector id of a server provisioned by claude.ai, set
6320    /// by the CLI from claude.ai's own connector listing, so a client may
6321    /// show the call as that connector's. Not a permission grant (CLI
6322    /// 2.1.300+).
6323    #[serde(default, skip_serializing_if = "Option::is_none")]
6324    pub server_id: Option<String>,
6325    /// The `X-MCP-Server-ID` header value, lower-cased, of an http entry in
6326    /// the dynamic scope (passed at launch or by a later `mcp_set_servers`
6327    /// push). The CLI checks only its shape, not whose it is: look it up in
6328    /// your own server list, treat a miss as an unknown server (never an
6329    /// error), and show a hit as the entry's claim, not proof. Separate from
6330    /// [`server_id`](Self::server_id); both are absent for plugin, repo,
6331    /// settings and agent entries (CLI 2.1.300+).
6332    #[serde(default, skip_serializing_if = "Option::is_none")]
6333    pub server_id_stamp: Option<String>,
6334    /// The tool's name as its server lists it, without the
6335    /// `mcp__<server>__` prefix (CLI 2.1.300+).
6336    #[serde(default, skip_serializing_if = "Option::is_none")]
6337    pub tool_name: Option<String>,
6338    /// `Some(true)` on a call to a publishing tool of an Artifacts MCP entry
6339    /// that reaches only Anthropic's server, which the CLI tells from the
6340    /// entry itself, never its name. The finished call's `tool_use_result`
6341    /// usually carries the artifact's url at its top level, its title where
6342    /// the server's answer has one, and (CLI 2.1.328+) `type.url`, the link
6343    /// of the Artifact type it was made from, where the CLI knows it. The
6344    /// mark promises none of these, and any of them can come on an unmarked
6345    /// call; all are the worker's word, not proof. Sent only on the main
6346    /// loop's own frames: never for a subagent's call or over Remote Control
6347    /// (CLI 2.1.321+).
6348    #[serde(default, skip_serializing_if = "Option::is_none")]
6349    pub artifact_publish: Option<bool>,
6350}
6351
6352/// Assistant message
6353#[derive(Debug, Clone, Serialize, Deserialize)]
6354pub struct AssistantMessage {
6355    pub message: AssistantMessageContent,
6356    #[serde(alias = "sessionId")]
6357    pub session_id: String,
6358    #[serde(skip_serializing_if = "Option::is_none")]
6359    pub uuid: Option<String>,
6360    #[serde(skip_serializing_if = "Option::is_none")]
6361    pub parent_tool_use_id: Option<String>,
6362    /// Anthropic API request id that produced this message (e.g. `req_...`).
6363    #[serde(skip_serializing_if = "Option::is_none")]
6364    pub request_id: Option<String>,
6365    /// Only on the assistant message that reports a refusal: the API `msg_*`
6366    /// id of the refused response (`message.id` on this message is a local
6367    /// UUID). Absent when the CLI has no well-formed id for it, and on CLIs
6368    /// before 2.1.301.
6369    #[serde(default, skip_serializing_if = "Option::is_none")]
6370    pub refused_message_id: Option<String>,
6371    /// Client uuid of the user message that triggered this turn, stamped on
6372    /// the turn's first top-level assistant message so a consumer can bind
6373    /// the reply to the send it answers without waiting for the result. With
6374    /// `--include-partial-messages` the first non-ping stream event is
6375    /// stamped too, independently (CLI 2.1.269+), so the same uuid may
6376    /// appear on both frames. Absent on every later assistant message of the
6377    /// turn, on subagent frames, on synthetic/scheduled (meta) turns, and
6378    /// from CLIs before 2.1.259.
6379    #[serde(default, skip_serializing_if = "Option::is_none")]
6380    pub user_message_uuid: Option<String>,
6381    /// Client uuids of every user message whose prompt this turn has consumed
6382    /// so far, in consumption order — all members of a prompt batch the host
6383    /// merged into this one turn. Always contains `user_message_uuid`; at
6384    /// most 64 entries. Present exactly when `user_message_uuid` is; absent
6385    /// from CLIs before 2.1.259 (fall back to `user_message_uuid`).
6386    #[serde(default, skip_serializing_if = "Vec::is_empty")]
6387    pub user_message_uuids: Vec<String>,
6388    /// ID of the subagent that produced this message: the `task_id` of its
6389    /// task events, unchanged when the subagent is resumed. Absent on
6390    /// main-thread messages (CLI 2.1.292+).
6391    #[serde(default, skip_serializing_if = "Option::is_none")]
6392    pub agent_id: Option<String>,
6393    /// Subagent type, when this assistant message was produced inside a
6394    /// `local_agent` subagent (e.g. `general-purpose`, `Explore`).
6395    #[serde(skip_serializing_if = "Option::is_none")]
6396    pub subagent_type: Option<String>,
6397    /// Short description of the subagent task, present alongside `subagent_type`.
6398    #[serde(skip_serializing_if = "Option::is_none")]
6399    pub task_description: Option<String>,
6400    #[serde(skip_serializing_if = "Option::is_none")]
6401    pub error: Option<AssistantErrorKind>,
6402    /// True when this message was truncated by an interrupt/abort before the
6403    /// stream completed — `stop_reason` was never received and the content
6404    /// may end mid-word. Absent on normally completed messages.
6405    #[serde(default, skip_serializing_if = "Option::is_none")]
6406    pub aborted: Option<bool>,
6407    /// True when this turn continued the preceding truncated assistant turn
6408    /// inside its trailing signed thinking block (max-output-tokens
6409    /// recovery). Histories replayed through the bridge must carry the flag
6410    /// back so the normalizer keeps the run's prefix on the wire.
6411    #[serde(default, skip_serializing_if = "Option::is_none")]
6412    pub resumed_from_incomplete_thinking: Option<bool>,
6413    /// Uuids of earlier messages that this message replaces: after a refusal
6414    /// fallback, or (CLI 2.1.323+) after a response whose tool call could not
6415    /// be parsed. It can name user messages too, such as a refused attempt's
6416    /// tool results. Remove the named messages when this one arrives. After a
6417    /// refusal fallback it is idempotent with the end-of-turn
6418    /// `system/model_refusal_fallback` notice.
6419    #[serde(default, skip_serializing_if = "Vec::is_empty")]
6420    pub supersedes: Vec<String>,
6421    #[serde(skip_serializing_if = "Option::is_none")]
6422    pub timestamp: Option<String>,
6423    #[serde(default, skip_serializing_if = "Vec::is_empty")]
6424    pub tool_use_meta: Vec<ToolUseMeta>,
6425    /// `{id, name}` of the original `Batch*` tool_use block(s) for a message
6426    /// whose content was decomposed into synthetic v1 tool_use blocks.
6427    /// Round-tripped so a replayed history reassembles the batch block on the
6428    /// wire. Wrapper-level sibling — never inside `message.content`.
6429    #[serde(default, skip_serializing_if = "Vec::is_empty")]
6430    pub batch_tool_uses: Vec<BatchToolUse>,
6431    /// `tool_use.input` exactly as the API produced it, keyed by `tool_use`
6432    /// id, for a message whose `message.content` carries the
6433    /// client-normalized input. Round-tripped so a replayed history echoes
6434    /// each earlier tool call back to the API as the API emitted it.
6435    /// Wrapper-level sibling — never inside `message.content` (CLI 2.1.259+).
6436    #[serde(default, skip_serializing_if = "Option::is_none")]
6437    pub wire_tool_inputs: Option<serde_json::Map<String, Value>>,
6438    /// What the client-side input normalization read from process state for
6439    /// the inputs in [`wire_tool_inputs`](Self::wire_tool_inputs), keyed by
6440    /// the same `tool_use` ids. Round-tripped so a replayed history can verify
6441    /// each recorded input against the normalized one. Wrapper-level sibling —
6442    /// never inside `message.content` (CLI 2.1.266+).
6443    #[serde(default, skip_serializing_if = "Option::is_none")]
6444    pub wire_ingest_context: Option<serde_json::Map<String, Value>>,
6445    /// Replayed history rather than a live message, stamped by the Remote
6446    /// Control bridge when it flushes history to the session server, which
6447    /// also stamps it on deliveries it replays (CLI 2.1.266+).
6448    #[serde(default, skip_serializing_if = "Option::is_none")]
6449    pub historical: Option<bool>,
6450    /// Why this frame's turn is the automatic re-run of a turn a worker
6451    /// restart interrupted: the host's `CLAUDE_CODE_RESUME_REASON` when it set
6452    /// one (`host_draining`, `checkpoint_restore`, `container_recreated`,
6453    /// ...), else `interrupted_turn`. Stamped on the same reply frames as
6454    /// `user_message_uuid`, which on such a re-run names the interrupted
6455    /// turn's own last user prompt. Absent on every other turn and from CLIs
6456    /// before 2.1.268.
6457    #[serde(default, skip_serializing_if = "Option::is_none")]
6458    pub resume_reason: Option<String>,
6459    /// The originating `system/local_command` row's wire-form content,
6460    /// carried on the loop-synthesized local-command twin so a bridge/SDK
6461    /// history replay rebuilds the internal system row instead of dropping
6462    /// the output. Wrapper-level sibling — never inside `message.content`
6463    /// (CLI 2.1.259+).
6464    #[serde(default, skip_serializing_if = "Option::is_none")]
6465    pub local_command_source: Option<String>,
6466    /// Ascending zero-based indexes into `message.content` of the thinking
6467    /// blocks whose signature the server tagged as narration (server
6468    /// summaries of the prose between tool calls, not the model's own
6469    /// reasoning), so a renderer can label them as summaries without decoding
6470    /// the signature envelope. Fail-closed: an unparseable or legacy
6471    /// signature is not listed. Omitted when the frame has no such block and
6472    /// by CLIs before 2.1.260; treat unlisted thinking blocks as ordinary
6473    /// thinking. Wrapper-level sibling — never inside `message.content`.
6474    #[serde(default, skip_serializing_if = "Vec::is_empty")]
6475    pub narration_block_indexes: Vec<usize>,
6476    /// How a renderer should treat this frame's narration blocks:
6477    /// `"hidden"` or `"faint"` on CLI 2.1.280+ (kept open for future
6478    /// values). Omitted when the CLI expresses no preference.
6479    #[serde(default, skip_serializing_if = "Option::is_none")]
6480    pub narration_hint: Option<String>,
6481    /// How long the thinking block in this frame took to stream, in whole
6482    /// milliseconds (at least 1): from its `content_block_start` to its
6483    /// `content_block_stop` (or, on CLI 2.1.321+, to the interrupt that cut
6484    /// it), so the wait for the response's first token is not counted. For display only. Sent only on a frame whose one content
6485    /// block is a thinking block that was streamed; absent from CLIs before
6486    /// 2.1.287 and from a CLI replaying history it rebuilt from SDK frames,
6487    /// so be ready to show the block without a duration. Wrapper-level
6488    /// sibling — never inside `message.content`.
6489    #[serde(default, skip_serializing_if = "Option::is_none")]
6490    pub thinking_duration_ms: Option<u64>,
6491    /// The `thinking.display` value Claude Code put in the API request body
6492    /// for the response that streamed this frame's thinking block; same
6493    /// source and meaning as
6494    /// [`StreamEventMessage::thinking_display`](crate::io::StreamEventMessage::thinking_display).
6495    /// Sent only on a frame whose one content block is a thinking block that
6496    /// was streamed, and only when the request body had a display. Absent
6497    /// from CLIs before 2.1.296 and from a CLI replaying history it rebuilt
6498    /// from SDK frames; an absent key states nothing. Marked `@internal`
6499    /// upstream, so treat the value set as open. Wrapper-level sibling —
6500    /// never inside `message.content`.
6501    #[serde(default, skip_serializing_if = "Option::is_none")]
6502    pub thinking_display: Option<String>,
6503    /// Structured twin of the `/context` report, carried on the synthetic
6504    /// assistant message that delivers the markdown table. Present only on
6505    /// `/context` results from CLIs new enough to attach it (2.1.239+).
6506    #[serde(default, skip_serializing_if = "Option::is_none")]
6507    pub context_usage: Option<ContextUsage>,
6508    /// Structured twin of the `/usage` report, carried on the synthetic
6509    /// assistant message that delivers its text: the session totals, the
6510    /// plan's usage rows and extra-usage spend, for remote clients that
6511    /// render a card from data. Present only on `/usage` results from CLIs
6512    /// new enough to attach it (2.1.273+) and from claude.ai-subscriber
6513    /// sessions; the text in `message.content` remains the canonical
6514    /// fallback. Wrapper-level sibling — never inside `message.content`.
6515    #[serde(default, skip_serializing_if = "Option::is_none")]
6516    pub usage_report: Option<Box<UsageReport>>,
6517    /// On the local-command twin, the run that printed the row: the
6518    /// command's name (no slash) and its arguments as the echo shows them
6519    /// (`***` when the command marks them sensitive). Present when a `local`
6520    /// command's dispatch printed the row or a `command.run` hook answered
6521    /// it, absent on a never-ran notice. Wrapper-level sibling — never inside
6522    /// `message.content` (CLI 2.1.273+).
6523    #[serde(default, skip_serializing_if = "Option::is_none")]
6524    pub local_command_run: Option<LocalCommandRun>,
6525    /// On the local-command twin, what the row reports (`unavailable_headless`,
6526    /// `unknown`, `failed`, `restart_required`), so a host can offer a fix
6527    /// instead of relaying the text. Absent when the row reports none of
6528    /// these; new kinds are additive, so treat an unknown one as absent.
6529    /// Wrapper-level sibling — never inside `message.content` (CLI 2.1.281+).
6530    #[serde(default, skip_serializing_if = "Option::is_none")]
6531    pub local_command_outcome: Option<LocalCommandOutcome>,
6532    #[serde(default, skip_serializing_if = "Option::is_none")]
6533    pub is_meta: Option<bool>,
6534    #[serde(default, skip_serializing_if = "Option::is_none")]
6535    pub is_virtual: Option<bool>,
6536    #[serde(default, skip_serializing_if = "Option::is_none")]
6537    pub is_api_error_message: Option<bool>,
6538    #[serde(skip_serializing_if = "Option::is_none")]
6539    pub api_error_status: Option<u16>,
6540    /// Typed kind of the API error when `is_api_error_message` is true. An
6541    /// open set the CLI grows release to release: 2.1.274 extends the
6542    /// original `max_output_tokens` / `dlp_request_denied` /
6543    /// `claude_code_version_too_old` with `effort_requires_thinking`,
6544    /// `advisor_incompatible`, `tool_history_mismatch`,
6545    /// `autocompact_thrashing`, `pdf_too_large`, `pdf_password_protected`,
6546    /// `media_removed` (CLI 2.1.288+: the API refused an image or a
6547    /// document, so Claude Code leaves it out of the requests that follow),
6548    /// `no_response`, `tls_untrusted_ca`, `gateway_content_type`,
6549    /// `provider_credentials`, `gateway_signin_required`,
6550    /// `gateway_session_expired`, `api_key_auth_disabled`,
6551    /// `org_disabled_credential`, `invalid_credential_header`,
6552    /// `model_requires_usage_credits`, `long_context_credits_required`,
6553    /// `consent_unanswered`, `no_allowed_fallback`,
6554    /// `model_substitution_disabled`, `field_not_granted`, (CLI 2.1.292+)
6555    /// `usage_limit_reached` — the request was refused by the account's own
6556    /// usage limit, a plan limit or a spend cap on usage credits;
6557    /// [`ApiErrorParams::rate_limit_info`] says which and when it resets —
6558    /// and (CLI 2.1.307+) `empty_completion` — the model ended its turn with
6559    /// no visible text and its one retry had no content block, so the turn
6560    /// ends as an error instead of a blank reply — and (CLI 2.1.311+)
6561    /// `unattended_start_limit` — a cloud session's restarted process hit
6562    /// the configured limit of unattended carry-ons within 24 hours, so no
6563    /// request was sent; terminal for the turn, so a consumer replaying
6564    /// history must not re-send the prompt that led to it — and
6565    /// `unattended_start_unconfirmed` — the process could not check whether
6566    /// it was allowed to carry on, so no request was sent; not terminal —
6567    /// and (CLI 2.1.314+) `stored_login_refused` — the stored claude.ai
6568    /// login was about to go out while the API key helper set by the
6569    /// machine's administrator (or, on 2.1.316+, the organization's
6570    /// settings) isn't in effect or its settings couldn't be confirmed, so
6571    /// no request was sent and the message text says who can clear it —
6572    /// `connection_failed` — Claude Code could not reach the
6573    /// API host or lost the connection (never set for a TLS error code) —
6574    /// `stream_idle_timeout` — Claude Code's own idle timer gave up waiting
6575    /// on an open stream, which does not by itself mean the server stalled —
6576    /// and `computer_slept` — the machine slept through the wait for the
6577    /// response (never sent by a claude-code-server session) — and
6578    /// (CLI 2.1.317+) `malformed_tool_use_exhausted` — the model's reply
6579    /// stopped for a tool call and held none, and the loop's retries ran
6580    /// out; terminal for the turn, so a consumer replaying history must not
6581    /// re-send the prompt by itself — and `network_edge_blocked` — the
6582    /// firewall in front of Anthropic's API refused the request for its
6583    /// network location (an unsupported region, or a VPN, proxy or network
6584    /// routing through one) before it reached the API; no sign-in or
6585    /// credential change fixes it — and (CLI 2.1.321+) `hook_denied` — a
6586    /// mod's `http.fetch` hook stopped the request — and (CLI 2.1.326+)
6587    /// `tls_cert_signature_failure` — a certificate the API's server sent
6588    /// failed signature verification (e.g. a CA list holding two same-named
6589    /// certificates after a renewal, or tampering; a host should not offer a
6590    /// way around the check) — and `message_over_context_limit` — the turn's
6591    /// own text exceeds the model's largest context window, so no request
6592    /// was sent and the text did not join the conversation — and (CLI
6593    /// 2.1.329+) `oauth_refresh_store_refused` — the macOS Keychain did not
6594    /// take a write, so the login's refresh token was not sent; the stored
6595    /// login is intact and the message text says what to do.
6596    /// Kinds with parameters carry them in [`Self::api_error_params`].
6597    #[serde(skip_serializing_if = "Option::is_none")]
6598    pub api_error: Option<String>,
6599    /// The server's `error.details.error_code` for this API error, copied
6600    /// through when it is an identifier (`^[a-z][a-z0-9_]{0,63}$`) and
6601    /// dropped otherwise. Carries server gate codes this CLI build has no
6602    /// `api_error` value for, so a host can key on a new gate without a
6603    /// Claude Code release. Absent when the response carried no code and
6604    /// from CLIs before 2.1.274.
6605    #[serde(default, skip_serializing_if = "Option::is_none")]
6606    pub api_error_code: Option<String>,
6607    /// The `error.type` of the response body for this API error (such as
6608    /// `rate_limit_error`, `overloaded_error` or `invalid_request_error`),
6609    /// copied through when it is an identifier (`^[a-z][a-z0-9_]{0,63}$`)
6610    /// and dropped otherwise, so a host can read the class without working
6611    /// it out from `error`, `api_error_status` or the text. The CLI does not
6612    /// check the value: a gateway or third-party provider can send others
6613    /// (see [`Self::api_error_origin`]), and a first-party 503 with
6614    /// `x-should-retry: false` still says `overloaded_error`, so the value
6615    /// alone does not say a retry can help. Bodies Claude Code writes itself
6616    /// carry their own type (a hook's plain refusal is `permission_error`).
6617    /// Marked `@internal` upstream (CLI 2.1.325+).
6618    #[serde(default, skip_serializing_if = "Option::is_none")]
6619    pub api_error_type: Option<String>,
6620    /// `first_party` when this API error was built from a response
6621    /// Anthropic's own API sent: the first-party provider, the default
6622    /// `https://api.anthropic.com` endpoint answering directly, over TLS
6623    /// verified with no added CA, override or socket tunnel. Absent in every
6624    /// other case (a base-URL override, a gateway, a third-party provider, a
6625    /// connection error, an error Claude Code raised itself, any replayed
6626    /// frame); treat absence as unknown origin. It says which endpoint
6627    /// answered, not that the text is the server's verbatim, so render
6628    /// stamped text as plain text. Open set — treat an unknown value as
6629    /// absent (CLI 2.1.300+).
6630    #[serde(default, skip_serializing_if = "Option::is_none")]
6631    pub api_error_origin: Option<String>,
6632    /// Parameters of [`Self::api_error`], present only for the kinds that
6633    /// have any (CLI 2.1.274+).
6634    #[serde(default, skip_serializing_if = "Option::is_none")]
6635    pub api_error_params: Option<ApiErrorParams>,
6636    #[serde(skip_serializing_if = "Option::is_none")]
6637    pub error_details: Option<String>,
6638    #[serde(skip_serializing_if = "Option::is_none")]
6639    pub advisor_model: Option<String>,
6640    #[serde(skip_serializing_if = "Option::is_none")]
6641    pub attribution_agent: Option<String>,
6642    #[serde(skip_serializing_if = "Option::is_none")]
6643    pub attribution_skill: Option<String>,
6644    #[serde(skip_serializing_if = "Option::is_none")]
6645    pub attribution_plugin: Option<String>,
6646    #[serde(skip_serializing_if = "Option::is_none")]
6647    pub attribution_mcp_server: Option<String>,
6648    #[serde(skip_serializing_if = "Option::is_none")]
6649    pub attribution_mcp_tool: Option<String>,
6650}
6651
6652/// Parameters of an assistant frame's `api_error`, carried as
6653/// [`AssistantMessage::api_error_params`] only for the error kinds that have
6654/// any (CLI 2.1.274+).
6655#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
6656pub struct ApiErrorParams {
6657    /// The effort level the API refused (`effort_requires_thinking`).
6658    #[serde(default, skip_serializing_if = "Option::is_none")]
6659    pub effort: Option<String>,
6660    /// The API provider whose credentials failed (`provider_credentials`,
6661    /// `gateway_session_expired`).
6662    #[serde(default, skip_serializing_if = "Option::is_none")]
6663    pub provider: Option<ApiErrorProvider>,
6664    /// How to repair the failed credentials (`provider_credentials`,
6665    /// `gateway_session_expired`).
6666    #[serde(default, skip_serializing_if = "Option::is_none")]
6667    pub remedy: Option<ApiErrorRemedy>,
6668    /// The kind of block the API refused (`media_removed`); absent for
6669    /// [`ApiErrorMediaReason::MediaBudget`] (CLI 2.1.288+).
6670    #[serde(default, skip_serializing_if = "Option::is_none")]
6671    pub media: Option<ApiErrorMedia>,
6672    /// Why the API refused the block (`media_removed`, CLI 2.1.288+).
6673    #[serde(default, skip_serializing_if = "Option::is_none")]
6674    pub media_reason: Option<ApiErrorMediaReason>,
6675    /// What the refused request's own response said about the limit
6676    /// (`usage_limit_reached`), in the shape `rate_limit_event` carries:
6677    /// `status` is rejected and `isUsingOverage` false, `rateLimitType` names
6678    /// the limit, `resetsAt` is when it resets, and the overage fields and
6679    /// `limitScope` say whose spend cap it is. It is that refusal's record
6680    /// and is never updated, so compare `resetsAt` with the clock before
6681    /// calling the limit current (CLI 2.1.292+).
6682    ///
6683    /// On CLI 2.1.316+ also carried for `model_requires_usage_credits`:
6684    /// `status` is rejected and `isUsingOverage` false; `rateLimitType` is
6685    /// the response's claim (`seven_day_overage_included` when an included
6686    /// allowance was used up) and absent when it named none; `resetsAt`,
6687    /// `overageStatus`, `overageResetsAt` and `limitScope` come when the
6688    /// response had them; `errorCode` is `credits_required` when the body
6689    /// said so; `overageDisabledReason`, `canUserPurchaseCredits` and
6690    /// `hasChargeableSavedPaymentMethod` as the response gave them; the
6691    /// person's own cap arrives as `org_level_disabled_until`. No other
6692    /// member is sent.
6693    ///
6694    /// On CLI 2.1.319+ the `usage_limit_reached` record also carries
6695    /// `dailyCapPaused` when usage is paused for the organization.
6696    ///
6697    /// On CLI 2.1.328+ both records carry `memberSpendLimit` when the API
6698    /// reports the member's own spend limit as reached.
6699    #[serde(default, skip_serializing_if = "Option::is_none")]
6700    pub rate_limit_info: Option<RateLimitInfo>,
6701    /// Which API stop reason cut the reply short (`max_output_tokens`),
6702    /// which the kind alone does not say. Absent on the one other error
6703    /// that carries `max_output_tokens`, the API's `tool_use_block_cut_off`,
6704    /// which [`AssistantMessage::api_error_code`] names (CLI 2.1.321+).
6705    #[serde(default, skip_serializing_if = "Option::is_none")]
6706    pub cut: Option<ApiErrorCut>,
6707}
6708
6709/// Which API stop reason cut a reply short ([`ApiErrorParams::cut`]).
6710#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6711pub enum ApiErrorCut {
6712    /// `max_tokens`: the request's output-token maximum.
6713    OutputLimit,
6714    /// `model_context_window_exceeded`: the model's context window.
6715    ContextWindow,
6716    /// A value not yet known to this version of the crate.
6717    Unknown(String),
6718}
6719
6720impl ApiErrorCut {
6721    pub fn as_str(&self) -> &str {
6722        match self {
6723            Self::OutputLimit => "output_limit",
6724            Self::ContextWindow => "context_window",
6725            Self::Unknown(s) => s.as_str(),
6726        }
6727    }
6728}
6729
6730impl fmt::Display for ApiErrorCut {
6731    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6732        f.write_str(self.as_str())
6733    }
6734}
6735
6736impl From<&str> for ApiErrorCut {
6737    fn from(s: &str) -> Self {
6738        match s {
6739            "output_limit" => Self::OutputLimit,
6740            "context_window" => Self::ContextWindow,
6741            other => Self::Unknown(other.to_string()),
6742        }
6743    }
6744}
6745
6746impl Serialize for ApiErrorCut {
6747    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
6748        serializer.serialize_str(self.as_str())
6749    }
6750}
6751
6752impl<'de> Deserialize<'de> for ApiErrorCut {
6753    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
6754        let s = String::deserialize(deserializer)?;
6755        Ok(Self::from(s.as_str()))
6756    }
6757}
6758
6759/// The kind of block the API refused ([`ApiErrorParams::media`]).
6760#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6761pub enum ApiErrorMedia {
6762    Image,
6763    Document,
6764    /// A kind not yet known to this version of the crate.
6765    Unknown(String),
6766}
6767
6768impl ApiErrorMedia {
6769    pub fn as_str(&self) -> &str {
6770        match self {
6771            Self::Image => "image",
6772            Self::Document => "document",
6773            Self::Unknown(s) => s.as_str(),
6774        }
6775    }
6776}
6777
6778impl fmt::Display for ApiErrorMedia {
6779    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6780        f.write_str(self.as_str())
6781    }
6782}
6783
6784impl From<&str> for ApiErrorMedia {
6785    fn from(s: &str) -> Self {
6786        match s {
6787            "image" => Self::Image,
6788            "document" => Self::Document,
6789            other => Self::Unknown(other.to_string()),
6790        }
6791    }
6792}
6793
6794impl Serialize for ApiErrorMedia {
6795    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
6796        serializer.serialize_str(self.as_str())
6797    }
6798}
6799
6800impl<'de> Deserialize<'de> for ApiErrorMedia {
6801    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
6802        let s = String::deserialize(deserializer)?;
6803        Ok(Self::from(s.as_str()))
6804    }
6805}
6806
6807/// Why the API refused an image or document
6808/// ([`ApiErrorParams::media_reason`]).
6809#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6810pub enum ApiErrorMediaReason {
6811    /// Every other refusal, a gateway's report of a model's refusal among
6812    /// them.
6813    Unprocessable,
6814    /// The API said that the model does not accept PDF documents.
6815    UnsupportedByModel,
6816    /// The request's images and documents together exceed the API's limit,
6817    /// and the requests that follow may leave out blocks of either kind.
6818    MediaBudget,
6819    /// A reason not yet known to this version of the crate.
6820    Unknown(String),
6821}
6822
6823impl ApiErrorMediaReason {
6824    pub fn as_str(&self) -> &str {
6825        match self {
6826            Self::Unprocessable => "unprocessable",
6827            Self::UnsupportedByModel => "unsupported_by_model",
6828            Self::MediaBudget => "media_budget",
6829            Self::Unknown(s) => s.as_str(),
6830        }
6831    }
6832}
6833
6834impl fmt::Display for ApiErrorMediaReason {
6835    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6836        f.write_str(self.as_str())
6837    }
6838}
6839
6840impl From<&str> for ApiErrorMediaReason {
6841    fn from(s: &str) -> Self {
6842        match s {
6843            "unprocessable" => Self::Unprocessable,
6844            "unsupported_by_model" => Self::UnsupportedByModel,
6845            "media_budget" => Self::MediaBudget,
6846            other => Self::Unknown(other.to_string()),
6847        }
6848    }
6849}
6850
6851impl Serialize for ApiErrorMediaReason {
6852    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
6853        serializer.serialize_str(self.as_str())
6854    }
6855}
6856
6857impl<'de> Deserialize<'de> for ApiErrorMediaReason {
6858    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
6859        let s = String::deserialize(deserializer)?;
6860        Ok(Self::from(s.as_str()))
6861    }
6862}
6863
6864/// The API provider whose credentials failed ([`ApiErrorParams::provider`]).
6865#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6866pub enum ApiErrorProvider {
6867    Bedrock,
6868    AnthropicAws,
6869    Mantle,
6870    AnthropicGoogleCloud,
6871    Vertex,
6872    Foundry,
6873    Gateway,
6874    /// A provider not yet known to this version of the crate.
6875    Unknown(String),
6876}
6877
6878impl ApiErrorProvider {
6879    pub fn as_str(&self) -> &str {
6880        match self {
6881            Self::Bedrock => "bedrock",
6882            Self::AnthropicAws => "anthropicAws",
6883            Self::Mantle => "mantle",
6884            Self::AnthropicGoogleCloud => "anthropicGoogleCloud",
6885            Self::Vertex => "vertex",
6886            Self::Foundry => "foundry",
6887            Self::Gateway => "gateway",
6888            Self::Unknown(s) => s.as_str(),
6889        }
6890    }
6891}
6892
6893impl fmt::Display for ApiErrorProvider {
6894    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6895        f.write_str(self.as_str())
6896    }
6897}
6898
6899impl From<&str> for ApiErrorProvider {
6900    fn from(s: &str) -> Self {
6901        match s {
6902            "bedrock" => Self::Bedrock,
6903            "anthropicAws" => Self::AnthropicAws,
6904            "mantle" => Self::Mantle,
6905            "anthropicGoogleCloud" => Self::AnthropicGoogleCloud,
6906            "vertex" => Self::Vertex,
6907            "foundry" => Self::Foundry,
6908            "gateway" => Self::Gateway,
6909            other => Self::Unknown(other.to_string()),
6910        }
6911    }
6912}
6913
6914impl Serialize for ApiErrorProvider {
6915    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
6916        serializer.serialize_str(self.as_str())
6917    }
6918}
6919
6920impl<'de> Deserialize<'de> for ApiErrorProvider {
6921    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
6922        let s = String::deserialize(deserializer)?;
6923        Ok(Self::from(s.as_str()))
6924    }
6925}
6926
6927/// How to repair failed provider credentials ([`ApiErrorParams::remedy`]).
6928#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6929pub enum ApiErrorRemedy {
6930    /// A configured refresh command (`awsAuthRefresh` / `gcpAuthRefresh`)
6931    /// refreshes the credentials.
6932    RefreshCommand,
6933    /// Refresh the provider's credentials by hand; no command is configured.
6934    RefreshCredentials,
6935    /// Refresh the Google application default credentials or the
6936    /// `GOOGLE_APPLICATION_CREDENTIALS` key file.
6937    Adc,
6938    /// Replace the gateway token supplied through `ANTHROPIC_AUTH_TOKEN` or
6939    /// `ANTHROPIC_CUSTOM_HEADERS`.
6940    GatewayToken,
6941    /// The host application owns these credentials.
6942    HostManaged,
6943    /// The credentials work but the model is not enabled for this account
6944    /// and region (Amazon Bedrock).
6945    ModelAccess,
6946    /// A remedy not yet known to this version of the crate.
6947    Unknown(String),
6948}
6949
6950impl ApiErrorRemedy {
6951    pub fn as_str(&self) -> &str {
6952        match self {
6953            Self::RefreshCommand => "refresh_command",
6954            Self::RefreshCredentials => "refresh_credentials",
6955            Self::Adc => "adc",
6956            Self::GatewayToken => "gateway_token",
6957            Self::HostManaged => "host_managed",
6958            Self::ModelAccess => "model_access",
6959            Self::Unknown(s) => s.as_str(),
6960        }
6961    }
6962}
6963
6964impl fmt::Display for ApiErrorRemedy {
6965    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6966        f.write_str(self.as_str())
6967    }
6968}
6969
6970impl From<&str> for ApiErrorRemedy {
6971    fn from(s: &str) -> Self {
6972        match s {
6973            "refresh_command" => Self::RefreshCommand,
6974            "refresh_credentials" => Self::RefreshCredentials,
6975            "adc" => Self::Adc,
6976            "gateway_token" => Self::GatewayToken,
6977            "host_managed" => Self::HostManaged,
6978            "model_access" => Self::ModelAccess,
6979            other => Self::Unknown(other.to_string()),
6980        }
6981    }
6982}
6983
6984impl Serialize for ApiErrorRemedy {
6985    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
6986        serializer.serialize_str(self.as_str())
6987    }
6988}
6989
6990impl<'de> Deserialize<'de> for ApiErrorRemedy {
6991    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
6992        let s = String::deserialize(deserializer)?;
6993        Ok(Self::from(s.as_str()))
6994    }
6995}
6996
6997/// Nested message content for assistant messages
6998#[derive(Debug, Clone, Serialize, Deserialize)]
6999pub struct AssistantMessageContent {
7000    pub id: String,
7001    /// The Anthropic API message type — always `"message"`.
7002    #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
7003    pub message_type: Option<String>,
7004    pub role: MessageRole,
7005    pub model: String,
7006    pub content: Vec<ContentBlock>,
7007    #[serde(skip_serializing_if = "Option::is_none")]
7008    pub stop_reason: Option<StopReason>,
7009    #[serde(skip_serializing_if = "Option::is_none")]
7010    pub stop_sequence: Option<String>,
7011    #[serde(skip_serializing_if = "Option::is_none")]
7012    pub usage: Option<AssistantUsage>,
7013    /// Details about why generation stopped
7014    #[serde(skip_serializing_if = "Option::is_none")]
7015    pub stop_details: Option<Value>,
7016    /// Context management metadata
7017    #[serde(skip_serializing_if = "Option::is_none")]
7018    pub context_management: Option<Value>,
7019}
7020
7021/// Usage information for assistant messages
7022#[derive(Debug, Clone, Serialize, Deserialize)]
7023pub struct AssistantUsage {
7024    /// Number of input tokens
7025    #[serde(default)]
7026    pub input_tokens: u32,
7027
7028    /// Number of output tokens
7029    #[serde(default)]
7030    pub output_tokens: u32,
7031
7032    /// Tokens used to create cache
7033    #[serde(default)]
7034    pub cache_creation_input_tokens: u32,
7035
7036    /// Tokens read from cache
7037    #[serde(default)]
7038    pub cache_read_input_tokens: u32,
7039
7040    /// Service tier used (e.g., "standard")
7041    #[serde(skip_serializing_if = "Option::is_none")]
7042    pub service_tier: Option<String>,
7043
7044    /// Detailed cache creation breakdown
7045    #[serde(skip_serializing_if = "Option::is_none")]
7046    pub cache_creation: Option<CacheCreationDetails>,
7047
7048    /// Inference geography (e.g., "not_available")
7049    #[serde(skip_serializing_if = "Option::is_none")]
7050    pub inference_geo: Option<String>,
7051
7052    /// Speed tier the request ran at (`"standard"` or `"fast"`). The API
7053    /// began sending it on per-message usage around CLI 2.1.301.
7054    #[serde(default, skip_serializing_if = "Option::is_none")]
7055    pub speed: Option<String>,
7056
7057    /// Outcome of a fallback-credit token the request presented; `null` on
7058    /// the wire when it presented none (CLI 2.1.285+).
7059    #[serde(default, skip_serializing_if = "Option::is_none")]
7060    pub fallback_credit: Option<Value>,
7061}
7062
7063/// Detailed cache creation information
7064#[derive(Debug, Clone, Serialize, Deserialize)]
7065pub struct CacheCreationDetails {
7066    /// Ephemeral 1-hour input tokens
7067    #[serde(default)]
7068    pub ephemeral_1h_input_tokens: u32,
7069
7070    /// Ephemeral 5-minute input tokens
7071    #[serde(default)]
7072    pub ephemeral_5m_input_tokens: u32,
7073}
7074
7075#[cfg(test)]
7076mod tests {
7077    use crate::io::ClaudeOutput;
7078
7079    #[test]
7080    fn test_subagent_usage_rollup_accumulates_task_results() {
7081        use super::SubagentUsageRollup;
7082
7083        let mut rollup = SubagentUsageRollup::default();
7084
7085        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}}"#;
7086        let output: ClaudeOutput = serde_json::from_str(task_result).unwrap();
7087        assert!(rollup.observe(&output));
7088        assert_eq!(rollup.subagent_tokens, 10201);
7089        assert_eq!(rollup.agent_count, 1);
7090        assert_eq!(rollup.tool_uses, 3);
7091        assert_eq!(rollup.duration_ms, 1853);
7092
7093        // Replayed frame with the same agentId is counted once.
7094        assert!(!rollup.observe(&output));
7095        assert_eq!(rollup.agent_count, 1);
7096        assert_eq!(rollup.subagent_tokens, 10201);
7097
7098        // A second agent accumulates.
7099        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}}"#;
7100        let output: ClaudeOutput = serde_json::from_str(second).unwrap();
7101        assert!(rollup.observe(&output));
7102        assert_eq!(rollup.agent_count, 2);
7103        assert_eq!(rollup.subagent_tokens, 10701);
7104    }
7105
7106    #[test]
7107    fn test_subagent_usage_rollup_ignores_non_task_results() {
7108        use super::SubagentUsageRollup;
7109
7110        let mut rollup = SubagentUsageRollup::default();
7111
7112        // A ToolSearch tool_use_result parses as an all-None SubagentResult;
7113        // it must not count as a subagent.
7114        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}}"#;
7115        let output: ClaudeOutput = serde_json::from_str(tool_search).unwrap();
7116        assert!(!rollup.observe(&output));
7117
7118        // Plain user message without tool_use_result.
7119        let plain = r#"{"type":"user","message":{"role":"user","content":[]},"session_id":"7fbc568e-2bd6-45aa-b217-a1cf80004ba1"}"#;
7120        let output: ClaudeOutput = serde_json::from_str(plain).unwrap();
7121        assert!(!rollup.observe(&output));
7122
7123        // Non-user frames are ignored.
7124        let system = r#"{"type":"system","subtype":"status","status":null,"session_id":"7fbc568e-2bd6-45aa-b217-a1cf80004ba1"}"#;
7125        let output: ClaudeOutput = serde_json::from_str(system).unwrap();
7126        assert!(!rollup.observe(&output));
7127
7128        assert_eq!(rollup, SubagentUsageRollup::default());
7129    }
7130
7131    #[test]
7132    fn test_subagent_usage_rollup_over_captured_session() {
7133        use super::SubagentUsageRollup;
7134
7135        let mut rollup = SubagentUsageRollup::default();
7136        let fixture =
7137            include_str!("../../test_cases/subagent_sessions/general_purpose_compute.jsonl");
7138        for line in fixture.lines().filter(|l| !l.trim().is_empty()) {
7139            if let Ok(output) = serde_json::from_str::<ClaudeOutput>(line) {
7140                rollup.observe(&output);
7141            }
7142        }
7143        assert_eq!(rollup.agent_count, 1);
7144        assert_eq!(rollup.subagent_tokens, 10201);
7145    }
7146
7147    #[test]
7148    fn test_system_message_init() {
7149        let json = r#"{
7150            "type": "system",
7151            "subtype": "init",
7152            "session_id": "test-session-123",
7153            "cwd": "/home/user/project",
7154            "model": "claude-sonnet-4",
7155            "tools": ["Bash", "Read", "Write"],
7156            "mcp_servers": [],
7157            "slash_commands": ["compact", "cost", "review"],
7158            "agents": ["Bash", "Explore", "Plan"],
7159            "plugins": [{"name": "rust-analyzer-lsp", "path": "/home/user/.claude/plugins/rust-analyzer-lsp/1.0.0"}],
7160            "skills": [],
7161            "claude_code_version": "2.1.15",
7162            "apiKeySource": "none",
7163            "output_style": "default",
7164            "permissionMode": "default"
7165        }"#;
7166
7167        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7168        if let ClaudeOutput::System(sys) = output {
7169            assert!(sys.is_init());
7170            assert!(!sys.is_status());
7171            assert!(!sys.is_compact_boundary());
7172
7173            let init = sys.as_init().expect("Should parse as init");
7174            assert_eq!(init.session_id, "test-session-123");
7175            assert_eq!(init.cwd, Some("/home/user/project".to_string()));
7176            assert_eq!(init.model, Some("claude-sonnet-4".to_string()));
7177            assert_eq!(init.tools, vec!["Bash", "Read", "Write"]);
7178            assert_eq!(init.slash_commands, vec!["compact", "cost", "review"]);
7179            assert_eq!(init.agents, vec!["Bash", "Explore", "Plan"]);
7180            assert_eq!(init.plugins.len(), 1);
7181            assert_eq!(init.plugins[0].name, "rust-analyzer-lsp");
7182            assert_eq!(init.claude_code_version, Some("2.1.15".to_string()));
7183            assert_eq!(init.api_key_source, Some(super::ApiKeySource::None));
7184            assert_eq!(init.output_style, Some(super::OutputStyle::Default));
7185            assert_eq!(
7186                init.permission_mode,
7187                Some(super::InitPermissionMode::Default)
7188            );
7189        } else {
7190            panic!("Expected System message");
7191        }
7192    }
7193
7194    #[test]
7195    fn test_system_message_init_from_real_capture() {
7196        let json = include_str!("../../test_cases/tool_use_captures/tool_msg_0.json");
7197        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7198        if let ClaudeOutput::System(sys) = output {
7199            let init = sys.as_init().expect("Should parse real init capture");
7200            assert_eq!(init.slash_commands.len(), 8);
7201            assert!(init.slash_commands.contains(&"compact".to_string()));
7202            assert!(init.slash_commands.contains(&"review".to_string()));
7203            assert_eq!(init.agents.len(), 5);
7204            assert!(init.agents.contains(&"Bash".to_string()));
7205            assert!(init.agents.contains(&"Explore".to_string()));
7206            assert_eq!(init.plugins.len(), 1);
7207            assert_eq!(init.plugins[0].name, "rust-analyzer-lsp");
7208            assert_eq!(init.claude_code_version, Some("2.1.15".to_string()));
7209        } else {
7210            panic!("Expected System message");
7211        }
7212    }
7213
7214    #[test]
7215    fn test_system_message_status() {
7216        let json = r#"{
7217            "type": "system",
7218            "subtype": "status",
7219            "session_id": "879c1a88-3756-4092-aa95-0020c4ed9692",
7220            "status": "compacting",
7221            "uuid": "32eb9f9d-5ef7-47ff-8fce-bbe22fe7ed93"
7222        }"#;
7223
7224        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7225        if let ClaudeOutput::System(sys) = output {
7226            assert!(sys.is_status());
7227            assert!(!sys.is_init());
7228
7229            let status = sys.as_status().expect("Should parse as status");
7230            assert_eq!(status.session_id, "879c1a88-3756-4092-aa95-0020c4ed9692");
7231            assert_eq!(status.status, Some(super::StatusMessageStatus::Compacting));
7232            assert_eq!(
7233                status.uuid,
7234                Some("32eb9f9d-5ef7-47ff-8fce-bbe22fe7ed93".to_string())
7235            );
7236        } else {
7237            panic!("Expected System message");
7238        }
7239    }
7240
7241    #[test]
7242    fn test_system_message_status_null() {
7243        let json = r#"{
7244            "type": "system",
7245            "subtype": "status",
7246            "session_id": "879c1a88-3756-4092-aa95-0020c4ed9692",
7247            "status": null,
7248            "uuid": "92d9637e-d00e-418e-acd2-a504e3861c6a"
7249        }"#;
7250
7251        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7252        if let ClaudeOutput::System(sys) = output {
7253            let status = sys.as_status().expect("Should parse as status");
7254            assert_eq!(status.status, None);
7255        } else {
7256            panic!("Expected System message");
7257        }
7258    }
7259
7260    #[test]
7261    fn test_system_message_task_started() {
7262        let json = r#"{
7263            "type": "system",
7264            "subtype": "task_started",
7265            "session_id": "9abbc466-dad0-4b8e-b6b0-cad5eb7a16b9",
7266            "task_id": "b6daf3f",
7267            "task_type": "local_bash",
7268            "tool_use_id": "toolu_011rfSTFumpJZdCCfzeD7jaS",
7269            "description": "Wait for CI on PR #12",
7270            "uuid": "c4243261-c128-4747-b8c3-5e1c7c10eeb8"
7271        }"#;
7272
7273        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7274        if let ClaudeOutput::System(sys) = output {
7275            assert!(sys.is_task_started());
7276            assert!(!sys.is_task_progress());
7277            assert!(!sys.is_task_notification());
7278
7279            let task = sys.as_task_started().expect("Should parse as task_started");
7280            assert_eq!(task.session_id, "9abbc466-dad0-4b8e-b6b0-cad5eb7a16b9");
7281            assert_eq!(task.task_id, "b6daf3f");
7282            assert_eq!(task.task_type, Some(super::TaskType::LocalBash));
7283            assert_eq!(
7284                task.tool_use_id.as_deref(),
7285                Some("toolu_011rfSTFumpJZdCCfzeD7jaS")
7286            );
7287            assert_eq!(task.description, "Wait for CI on PR #12");
7288        } else {
7289            panic!("Expected System message");
7290        }
7291    }
7292
7293    #[test]
7294    fn test_system_message_task_started_agent() {
7295        let json = r#"{
7296            "type": "system",
7297            "subtype": "task_started",
7298            "session_id": "bff4f716-17c1-4255-ab7b-eea9d33824e3",
7299            "task_id": "a4a7e0906e5fc64cc",
7300            "task_type": "local_agent",
7301            "tool_use_id": "toolu_01SFz9FwZ1cYgCSy8vRM7wep",
7302            "description": "Explore Scene/ArrayScene duplication",
7303            "uuid": "85a39f5a-e4d4-47f7-9a6d-1125f1a8035f"
7304        }"#;
7305
7306        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7307        if let ClaudeOutput::System(sys) = output {
7308            let task = sys.as_task_started().expect("Should parse as task_started");
7309            assert_eq!(task.task_type, Some(super::TaskType::LocalAgent));
7310            assert_eq!(task.task_id, "a4a7e0906e5fc64cc");
7311        } else {
7312            panic!("Expected System message");
7313        }
7314    }
7315
7316    #[test]
7317    fn test_system_message_task_progress() {
7318        let json = r#"{
7319            "type": "system",
7320            "subtype": "task_progress",
7321            "session_id": "bff4f716-17c1-4255-ab7b-eea9d33824e3",
7322            "task_id": "a4a7e0906e5fc64cc",
7323            "tool_use_id": "toolu_01SFz9FwZ1cYgCSy8vRM7wep",
7324            "description": "Reading src/jplephem/chebyshev.rs",
7325            "last_tool_name": "Read",
7326            "usage": {
7327                "duration_ms": 13996,
7328                "tool_uses": 9,
7329                "total_tokens": 38779
7330            },
7331            "uuid": "85a39f5a-e4d4-47f7-9a6d-1125f1a8035f"
7332        }"#;
7333
7334        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7335        if let ClaudeOutput::System(sys) = output {
7336            assert!(sys.is_task_progress());
7337            assert!(!sys.is_task_started());
7338
7339            let progress = sys
7340                .as_task_progress()
7341                .expect("Should parse as task_progress");
7342            assert_eq!(progress.task_id, "a4a7e0906e5fc64cc");
7343            assert_eq!(progress.description, "Reading src/jplephem/chebyshev.rs");
7344            assert_eq!(progress.last_tool_name.as_deref(), Some("Read"));
7345            assert_eq!(progress.usage.duration_ms, 13996);
7346            assert_eq!(progress.usage.tool_uses, 9);
7347            assert_eq!(progress.usage.total_tokens, 38779);
7348        } else {
7349            panic!("Expected System message");
7350        }
7351    }
7352
7353    #[test]
7354    fn test_system_message_task_notification_completed() {
7355        let json = r#"{
7356            "type": "system",
7357            "subtype": "task_notification",
7358            "session_id": "bff4f716-17c1-4255-ab7b-eea9d33824e3",
7359            "task_id": "a0ba761e9dc9c316f",
7360            "tool_use_id": "toolu_01Ho6XVXFLVNjTQ9YqowdBXW",
7361            "status": "completed",
7362            "summary": "Agent \"Write Hipparcos data source doc\" completed",
7363            "output_file": "",
7364            "usage": {
7365                "duration_ms": 172300,
7366                "tool_uses": 11,
7367                "total_tokens": 42005
7368            },
7369            "uuid": "269f49b9-218d-4c8d-9f7e-3a5383a0c5b2"
7370        }"#;
7371
7372        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7373        if let ClaudeOutput::System(sys) = output {
7374            assert!(sys.is_task_notification());
7375
7376            let notif = sys
7377                .as_task_notification()
7378                .expect("Should parse as task_notification");
7379            assert_eq!(notif.status, super::TaskStatus::Completed);
7380            assert_eq!(
7381                notif.summary,
7382                "Agent \"Write Hipparcos data source doc\" completed"
7383            );
7384            assert_eq!(notif.output_file, Some("".to_string()));
7385            assert_eq!(
7386                notif.tool_use_id,
7387                Some("toolu_01Ho6XVXFLVNjTQ9YqowdBXW".to_string())
7388            );
7389            let usage = notif.usage.expect("Should have usage");
7390            assert_eq!(usage.duration_ms, 172300);
7391            assert_eq!(usage.tool_uses, 11);
7392            assert_eq!(usage.total_tokens, 42005);
7393        } else {
7394            panic!("Expected System message");
7395        }
7396    }
7397
7398    #[test]
7399    fn test_system_message_task_notification_failed_no_usage() {
7400        let json = r#"{
7401            "type": "system",
7402            "subtype": "task_notification",
7403            "session_id": "ea629737-3c36-48a8-a1c4-ad761ad35784",
7404            "task_id": "b98f6a3",
7405            "status": "failed",
7406            "summary": "Background command \"Run FSM calibration\" failed with exit code 1",
7407            "output_file": "/tmp/claude-1000/tasks/b98f6a3.output"
7408        }"#;
7409
7410        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7411        if let ClaudeOutput::System(sys) = output {
7412            let notif = sys
7413                .as_task_notification()
7414                .expect("Should parse as task_notification");
7415            assert_eq!(notif.status, super::TaskStatus::Failed);
7416            assert!(notif.tool_use_id.is_none());
7417            assert!(notif.usage.is_none());
7418            assert_eq!(
7419                notif.output_file,
7420                Some("/tmp/claude-1000/tasks/b98f6a3.output".to_string())
7421            );
7422        } else {
7423            panic!("Expected System message");
7424        }
7425    }
7426
7427    /// Task system messages survive a `to_value` → `from_value` round-trip
7428    /// with their typed accessors still resolving. Mirrors the proxy/relay
7429    /// path where output is reparsed from a `serde_json::Value` rather than
7430    /// straight from the CLI's stdout, so a silently dropped or renamed field
7431    /// surfaces here instead of as a `None` downstream.
7432    #[test]
7433    fn test_task_messages_roundtrip_through_value() {
7434        let cases = [
7435            r#"{"type":"system","subtype":"task_started","session_id":"s1",
7436                "task_id":"t1","task_type":"local_bash","tool_use_id":"tu1",
7437                "description":"Sleep 3s","uuid":"u1"}"#,
7438            r#"{"type":"system","subtype":"task_progress","session_id":"s1",
7439                "task_id":"t1","tool_use_id":"tu1","description":"Running ls",
7440                "last_tool_name":"Bash",
7441                "usage":{"duration_ms":100,"tool_uses":1,"total_tokens":500},
7442                "uuid":"u2"}"#,
7443            r#"{"type":"system","subtype":"task_notification","session_id":"s1",
7444                "task_id":"t1","tool_use_id":"tu1","status":"completed",
7445                "summary":"done","output_file":"",
7446                "usage":{"duration_ms":100,"tool_uses":1,"total_tokens":500},
7447                "uuid":"u3"}"#,
7448        ];
7449
7450        for json in cases {
7451            let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7452            let value = serde_json::to_value(&output).unwrap();
7453            let reparsed: ClaudeOutput = serde_json::from_value(value).unwrap();
7454
7455            let ClaudeOutput::System(sys) = reparsed else {
7456                panic!("Expected System variant after round-trip");
7457            };
7458
7459            match sys.subtype {
7460                super::SystemSubtype::TaskStarted => {
7461                    assert!(
7462                        sys.as_task_started().is_some(),
7463                        "as_task_started failed after round-trip"
7464                    );
7465                }
7466                super::SystemSubtype::TaskProgress => {
7467                    assert!(
7468                        sys.as_task_progress().is_some(),
7469                        "as_task_progress failed after round-trip"
7470                    );
7471                }
7472                super::SystemSubtype::TaskNotification => {
7473                    assert!(
7474                        sys.as_task_notification().is_some(),
7475                        "as_task_notification failed after round-trip"
7476                    );
7477                }
7478                other => panic!("unexpected subtype after round-trip: {other:?}"),
7479            }
7480        }
7481    }
7482
7483    #[test]
7484    fn test_system_message_compact_boundary() {
7485        let json = r#"{
7486            "type": "system",
7487            "subtype": "compact_boundary",
7488            "session_id": "879c1a88-3756-4092-aa95-0020c4ed9692",
7489            "compact_metadata": {
7490                "pre_tokens": 155285,
7491                "trigger": "auto"
7492            },
7493            "uuid": "a67780d5-74cb-48b1-9137-7a6e7cee45d7"
7494        }"#;
7495
7496        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7497        if let ClaudeOutput::System(sys) = output {
7498            assert!(sys.is_compact_boundary());
7499            assert!(!sys.is_init());
7500            assert!(!sys.is_status());
7501
7502            let compact = sys
7503                .as_compact_boundary()
7504                .expect("Should parse as compact_boundary");
7505            assert_eq!(compact.session_id, "879c1a88-3756-4092-aa95-0020c4ed9692");
7506            assert_eq!(compact.compact_metadata.pre_tokens, 155285);
7507            assert_eq!(
7508                compact.compact_metadata.trigger,
7509                super::CompactionTrigger::Auto
7510            );
7511            // Per-compaction stats are optional and absent here.
7512            assert!(compact.summary.is_none());
7513            assert!(compact.leaf_message_count.is_none());
7514            assert!(compact.duration_ms.is_none());
7515        } else {
7516            panic!("Expected System message");
7517        }
7518    }
7519
7520    #[test]
7521    fn test_compact_boundary_with_summary_stats() {
7522        // Canonical keys.
7523        let json = r#"{
7524            "type": "system",
7525            "subtype": "compact_boundary",
7526            "session_id": "s1",
7527            "compact_metadata": { "pre_tokens": 1000, "trigger": "manual" },
7528            "summary": "Summarized the earlier exploration.",
7529            "leaf_message_count": 42,
7530            "duration_ms": 1234,
7531            "uuid": "u1"
7532        }"#;
7533        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7534        let ClaudeOutput::System(sys) = output else {
7535            panic!("Expected System message");
7536        };
7537        let compact = sys.as_compact_boundary().expect("compact_boundary");
7538        assert_eq!(
7539            compact.summary.as_deref(),
7540            Some("Summarized the earlier exploration.")
7541        );
7542        assert_eq!(compact.leaf_message_count, Some(42));
7543        assert_eq!(compact.duration_ms, Some(1234));
7544
7545        // Alternate wire keys (`content` for summary, `message_count` for count)
7546        // deserialize into the same fields.
7547        let json_alt = r#"{
7548            "type": "system",
7549            "subtype": "compact_boundary",
7550            "session_id": "s2",
7551            "compact_metadata": { "pre_tokens": 2000, "trigger": "auto" },
7552            "content": "alt-key summary",
7553            "message_count": 7
7554        }"#;
7555        let output: ClaudeOutput = serde_json::from_str(json_alt).unwrap();
7556        let ClaudeOutput::System(sys) = output else {
7557            panic!("Expected System message");
7558        };
7559        let compact = sys.as_compact_boundary().expect("compact_boundary");
7560        assert_eq!(compact.summary.as_deref(), Some("alt-key summary"));
7561        assert_eq!(compact.leaf_message_count, Some(7));
7562    }
7563
7564    #[test]
7565    fn test_init_message_with_new_fields() {
7566        let json = r#"{
7567            "type": "system",
7568            "subtype": "init",
7569            "session_id": "test-session",
7570            "cwd": "/home/user",
7571            "model": "claude-opus-4-7",
7572            "tools": ["Bash"],
7573            "mcp_servers": [],
7574            "permissionMode": "default",
7575            "apiKeySource": "none",
7576            "uuid": "44841a0d-182d-493a-86b5-79800d3d9665",
7577            "memory_paths": {"auto": "/home/user/.claude/projects/memory/"},
7578            "fast_mode_state": "off",
7579            "plugins": [{"name": "lsp", "path": "/plugins/lsp", "source": "lsp@official"}],
7580            "claude_code_version": "2.1.117"
7581        }"#;
7582
7583        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7584        if let ClaudeOutput::System(sys) = output {
7585            let init = sys.as_init().expect("Should parse as init");
7586            assert_eq!(
7587                init.uuid.as_deref(),
7588                Some("44841a0d-182d-493a-86b5-79800d3d9665")
7589            );
7590            assert!(init.memory_paths.is_some());
7591            assert_eq!(init.fast_mode_state.as_deref(), Some("off"));
7592            assert_eq!(init.plugins[0].source.as_deref(), Some("lsp@official"));
7593            assert_eq!(init.claude_code_version.as_deref(), Some("2.1.117"));
7594        } else {
7595            panic!("Expected System message");
7596        }
7597    }
7598
7599    #[test]
7600    fn test_assistant_message_with_new_fields() {
7601        let json = r#"{
7602            "type": "assistant",
7603            "message": {
7604                "id": "msg_1",
7605                "type": "message",
7606                "role": "assistant",
7607                "model": "claude-opus-4-7",
7608                "content": [{"type": "text", "text": "Hello"}],
7609                "stop_reason": "end_turn",
7610                "stop_details": null,
7611                "context_management": null,
7612                "usage": {
7613                    "input_tokens": 100,
7614                    "output_tokens": 10,
7615                    "cache_creation_input_tokens": 50,
7616                    "cache_read_input_tokens": 0,
7617                    "service_tier": "standard",
7618                    "inference_geo": "not_available"
7619                }
7620            },
7621            "session_id": "abc",
7622            "uuid": "msg-uuid-123"
7623        }"#;
7624
7625        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7626        if let ClaudeOutput::Assistant(asst) = output {
7627            assert_eq!(asst.message.stop_details, None);
7628            assert_eq!(asst.message.context_management, None);
7629            let usage = asst.message.usage.unwrap();
7630            assert_eq!(usage.inference_geo.as_deref(), Some("not_available"));
7631        } else {
7632            panic!("Expected Assistant message");
7633        }
7634    }
7635
7636    #[test]
7637    fn test_user_message_with_new_fields() {
7638        let json = r#"{
7639            "type": "user",
7640            "message": {
7641                "role": "user",
7642                "content": [{"type": "text", "text": "Hello"}]
7643            },
7644            "session_id": "9abbc466-dad0-4b8e-b6b0-cad5eb7a16b9",
7645            "parent_tool_use_id": "toolu_123",
7646            "uuid": "user-msg-456"
7647        }"#;
7648
7649        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7650        if let ClaudeOutput::User(user) = output {
7651            assert_eq!(user.parent_tool_use_id.as_deref(), Some("toolu_123"));
7652            assert_eq!(user.uuid.as_deref(), Some("user-msg-456"));
7653        } else {
7654            panic!("Expected User message");
7655        }
7656    }
7657
7658    /// Real wire payload captured from the CLI after answering an
7659    /// AskUserQuestion via the permission control protocol. The top-level
7660    /// `tool_use_result` and `timestamp` fields must round-trip without loss —
7661    /// proxies using this crate to relay messages to a viewer rely on those
7662    /// fields being preserved (the viewer reads `tool_use_result.answers`).
7663    #[test]
7664    fn test_user_message_preserves_tool_use_result_and_timestamp() {
7665        let json = r#"{
7666            "type":"user",
7667            "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"}]},
7668            "parent_tool_use_id":null,
7669            "session_id":"622ae0c3-3d50-4fa7-9ee0-69d691238c6d",
7670            "uuid":"8ef6e997-a849-4d15-bed3-2837c3d3f4cd",
7671            "timestamp":"2026-05-12T23:12:04.121Z",
7672            "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"}}
7673        }"#;
7674
7675        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7676        let user = match output {
7677            ClaudeOutput::User(u) => u,
7678            other => panic!("Expected User message, got {:?}", other.message_type()),
7679        };
7680
7681        assert_eq!(user.timestamp.as_deref(), Some("2026-05-12T23:12:04.121Z"));
7682        let raw = user
7683            .tool_use_result
7684            .as_ref()
7685            .expect("tool_use_result must be captured");
7686        assert_eq!(raw["answers"]["Color"], "Blue");
7687        assert_eq!(raw["questions"][0]["header"], "Color");
7688
7689        // Round-trip: re-serialize and confirm tool_use_result + timestamp
7690        // survive — the bug we're guarding against is that the proxy silently
7691        // drops these fields when relaying user messages.
7692        let reser: serde_json::Value = serde_json::to_value(&user).unwrap();
7693        assert_eq!(reser["timestamp"], "2026-05-12T23:12:04.121Z");
7694        assert_eq!(reser["tool_use_result"]["answers"]["Color"], "Blue");
7695        assert_eq!(
7696            reser["tool_use_result"]["questions"][0]["question"],
7697            "Which color do you prefer?"
7698        );
7699
7700        // Typed accessor: AskUserQuestionInput has the same shape as the
7701        // AskUserQuestion tool_use_result.
7702        let typed: crate::AskUserQuestionInput = user
7703            .tool_use_result_as::<crate::AskUserQuestionInput>()
7704            .expect("tool_use_result present")
7705            .expect("AskUserQuestionInput parses");
7706        assert_eq!(typed.questions.len(), 1);
7707        assert_eq!(typed.questions[0].header, "Color");
7708        let answers = typed.answers.expect("answers populated");
7709        assert_eq!(answers.get("Color").map(String::as_str), Some("Blue"));
7710    }
7711
7712    /// User messages without `tool_use_result` / `timestamp` must still
7713    /// deserialize fine and serialize back without spuriously emitting nulls.
7714    #[test]
7715    fn test_user_message_without_tool_use_result_omits_field() {
7716        let json = r#"{
7717            "type":"user",
7718            "message":{"role":"user","content":[{"type":"text","text":"hello"}]},
7719            "session_id":"622ae0c3-3d50-4fa7-9ee0-69d691238c6d"
7720        }"#;
7721
7722        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7723        let user = match output {
7724            ClaudeOutput::User(u) => u,
7725            _ => panic!("Expected User message"),
7726        };
7727        assert!(user.tool_use_result.is_none());
7728        assert!(user.timestamp.is_none());
7729
7730        let reser = serde_json::to_value(&user).unwrap();
7731        assert!(reser.get("tool_use_result").is_none());
7732        assert!(reser.get("timestamp").is_none());
7733    }
7734
7735    /// A `Task` tool result must expose subagent token / timing / tool-use
7736    /// accounting through the typed [`UserMessage::subagent_result`] accessor,
7737    /// including the nested per-model `usage` breakdown and `toolStats`.
7738    #[test]
7739    fn test_subagent_result_exposes_token_accounting() {
7740        let json = r#"{
7741            "type":"user",
7742            "message":{"role":"user","content":[{"tool_use_id":"toolu_01","type":"tool_result","content":[{"type":"text","text":"21"}]}]},
7743            "session_id":"d3fc5942-75e5-4aa1-a87d-b9484a176541",
7744            "tool_use_result":{
7745                "status":"completed",
7746                "prompt":"Count the .rs files.",
7747                "agentId":"ac4f0276e9d4b6232",
7748                "agentType":"Explore",
7749                "content":[{"type":"text","text":"21"}],
7750                "resolvedModel":"claude-haiku-4-5-20251001",
7751                "totalDurationMs":6869,
7752                "totalTokens":7834,
7753                "totalToolUseCount":1,
7754                "usage":{"input_tokens":6,"cache_creation_input_tokens":125,"cache_read_input_tokens":7699,"output_tokens":4,"service_tier":"standard"},
7755                "toolStats":{"readCount":0,"searchCount":0,"bashCount":1,"editFileCount":0,"linesAdded":0,"linesRemoved":0,"otherToolCount":0}
7756            }
7757        }"#;
7758
7759        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7760        let user = match output {
7761            ClaudeOutput::User(u) => u,
7762            _ => panic!("Expected User message"),
7763        };
7764
7765        let result = user.subagent_result().expect("subagent result parses");
7766        assert_eq!(result.agent_type.as_deref(), Some("Explore"));
7767        assert_eq!(
7768            result.resolved_model.as_deref(),
7769            Some("claude-haiku-4-5-20251001")
7770        );
7771        assert_eq!(result.total_tokens, Some(7834));
7772        assert_eq!(result.total_duration_ms, Some(6869));
7773        assert_eq!(result.total_tool_use_count, Some(1));
7774
7775        let usage = result.usage.expect("nested usage present");
7776        assert_eq!(usage.input_tokens, 6);
7777        assert_eq!(usage.cache_read_input_tokens, 7699);
7778
7779        let stats = result.tool_stats.expect("toolStats present");
7780        assert_eq!(stats.bash_count, 1);
7781    }
7782
7783    /// `tool_use_result` shapes that aren't subagent runs (e.g. AskUserQuestion)
7784    /// parse leniently into the all-`Option` [`SubagentResult`] with empty
7785    /// accounting rather than failing, so callers can probe without panicking.
7786    #[test]
7787    fn test_subagent_result_absent_for_non_task_result() {
7788        let json = r#"{
7789            "type":"user",
7790            "message":{"role":"user","content":[{"type":"text","text":"hi"}]},
7791            "session_id":"622ae0c3-3d50-4fa7-9ee0-69d691238c6d",
7792            "tool_use_result":{"questions":[],"answers":{"Color":"Blue"}}
7793        }"#;
7794
7795        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7796        let user = match output {
7797            ClaudeOutput::User(u) => u,
7798            _ => panic!("Expected User message"),
7799        };
7800
7801        let result = user.subagent_result().expect("lenient parse");
7802        assert_eq!(result.total_tokens, None);
7803        assert_eq!(result.agent_type, None);
7804    }
7805
7806    #[test]
7807    fn test_init_fast_mode_reason_and_mcp_server_errors_fully_wrapped() {
7808        use serde_json::Value;
7809
7810        let raw: Value = serde_json::from_str(
7811            r#"{
7812            "type":"system","subtype":"init","session_id":"s1","uuid":"u1",
7813            "fast_mode_state":"off",
7814            "fast_mode_disabled_reason":"not_first_party",
7815            "mcp_server_errors":[{"name":"broken","type":"invalid_config","message":"url entry with no type"}]
7816        }"#,
7817        )
7818        .unwrap();
7819        crate::io::assert_fully_wrapped(&raw);
7820
7821        let output: ClaudeOutput = serde_json::from_value(raw).unwrap();
7822        let ClaudeOutput::System(sys) = output else {
7823            panic!("expected System");
7824        };
7825        let init = sys.as_init().expect("parses as init");
7826        assert_eq!(
7827            init.fast_mode_disabled_reason,
7828            Some(crate::FastModeDisabledReason::NotFirstParty)
7829        );
7830        let errs = init.mcp_server_errors.unwrap();
7831        assert_eq!(errs.len(), 1);
7832        assert_eq!(errs[0].name, "broken");
7833        assert_eq!(errs[0].error_type, "invalid_config");
7834    }
7835
7836    #[test]
7837    fn test_code_change_published_fully_wrapped() {
7838        use super::{KnownSystemEvent, SystemSubtype};
7839        use serde_json::Value;
7840
7841        let raw: Value = serde_json::from_str(
7842            r#"{
7843            "type":"system","subtype":"code_change_published",
7844            "provider":"github","url":"https://github.com/owner/repo/pull/42",
7845            "repo":"owner/repo","identifier":"42",
7846            "uuid":"u1","session_id":"s1"
7847        }"#,
7848        )
7849        .unwrap();
7850        crate::io::assert_fully_wrapped(&raw);
7851
7852        let output: ClaudeOutput = serde_json::from_value(raw).unwrap();
7853        let ClaudeOutput::System(sys) = output else {
7854            panic!("expected System");
7855        };
7856        assert_eq!(sys.subtype, SystemSubtype::CodeChangePublished);
7857        let Some(KnownSystemEvent::CodeChangePublished(msg)) = sys.as_known_system_event() else {
7858            panic!("expected CodeChangePublished event");
7859        };
7860        assert_eq!(msg.provider, "github");
7861        assert_eq!(msg.repo, "owner/repo");
7862        assert_eq!(msg.identifier, "42");
7863
7864        assert!(sys.is_code_change_published());
7865        assert!(!sys.is_vcs_state_changed());
7866        let direct = sys.as_code_change_published().expect("direct accessor");
7867        assert_eq!(direct.url, "https://github.com/owner/repo/pull/42");
7868        assert!(sys.as_vcs_state_changed().is_none());
7869    }
7870
7871    #[test]
7872    fn test_feedback_draft_queued_fully_wrapped() {
7873        use super::{KnownSystemEvent, SystemSubtype};
7874        use serde_json::Value;
7875
7876        let raw: Value = serde_json::from_str(
7877            r#"{
7878            "type":"system","subtype":"feedback_draft_queued",
7879            "draft_id":"draft-1","draft_type":"bug_report",
7880            "title":"Tool output was truncated",
7881            "details_preview":"The last command omitted its final lines",
7882            "uuid":"u1","session_id":"s1","future_field":"preserved"
7883        }"#,
7884        )
7885        .unwrap();
7886        crate::io::assert_fully_wrapped(&raw);
7887
7888        let output: ClaudeOutput = serde_json::from_value(raw).unwrap();
7889        let ClaudeOutput::System(sys) = output else {
7890            panic!("expected System");
7891        };
7892        assert_eq!(sys.subtype, SystemSubtype::FeedbackDraftQueued);
7893        assert!(sys.is_feedback_draft_queued());
7894        assert!(!sys.is_vcs_state_changed());
7895
7896        let direct = sys
7897            .as_feedback_draft_queued()
7898            .expect("direct typed accessor");
7899        assert_eq!(direct.draft_id, "draft-1");
7900        assert_eq!(direct.draft_type, "bug_report");
7901        assert_eq!(direct.extra["future_field"], "preserved");
7902
7903        let Some(KnownSystemEvent::FeedbackDraftQueued(known)) = sys.as_known_system_event() else {
7904            panic!("expected FeedbackDraftQueued event");
7905        };
7906        assert_eq!(known.title, "Tool output was truncated");
7907        assert_eq!(
7908            sys.typed_value().expect("typed value")["future_field"],
7909            "preserved"
7910        );
7911    }
7912
7913    #[test]
7914    fn test_cloud_session_delta_fully_wrapped() {
7915        use super::{KnownSystemEvent, SystemSubtype};
7916        use serde_json::Value;
7917
7918        let raw: Value = serde_json::from_str(
7919            r#"{
7920            "type":"system","subtype":"cloud_session_delta",
7921            "seq":3,"changed":["serving","connection"],
7922            "cloud_session":{"id":"session_abc","view_url":"https://example.invalid/s/abc",
7923                "serving":{"state":"on"},"connection":{"state":"live"}},
7924            "uuid":"u1","session_id":"s1","future_field":"preserved"
7925        }"#,
7926        )
7927        .unwrap();
7928        crate::io::assert_fully_wrapped(&raw);
7929
7930        let output: ClaudeOutput = serde_json::from_value(raw).unwrap();
7931        let ClaudeOutput::System(sys) = output else {
7932            panic!("expected System");
7933        };
7934        assert_eq!(sys.subtype, SystemSubtype::CloudSessionDelta);
7935        assert!(sys.is_cloud_session_delta());
7936        assert!(!sys.is_feedback_draft_queued());
7937
7938        let direct = sys.as_cloud_session_delta().expect("direct typed accessor");
7939        assert_eq!(direct.seq, 3);
7940        assert_eq!(direct.changed, vec!["serving", "connection"]);
7941        assert_eq!(direct.cloud_session["id"], "session_abc");
7942        assert_eq!(direct.extra["future_field"], "preserved");
7943
7944        let Some(KnownSystemEvent::CloudSessionDelta(known)) = sys.as_known_system_event() else {
7945            panic!("expected CloudSessionDelta event");
7946        };
7947        assert_eq!(known.session_id, "s1");
7948        assert_eq!(
7949            sys.typed_value().expect("typed value")["future_field"],
7950            "preserved"
7951        );
7952    }
7953
7954    #[test]
7955    fn test_vcs_state_changed_fully_wrapped() {
7956        use super::{KnownSystemEvent, VcsMutationKind};
7957        use serde_json::Value;
7958
7959        for kind in ["commit", "push", "merge", "rebase"] {
7960            let raw: Value = serde_json::from_str(&format!(
7961                r#"{{"type":"system","subtype":"vcs_state_changed","kind":"{}","cwd":"/repo","uuid":"u1","session_id":"s1"}}"#,
7962                kind
7963            ))
7964            .unwrap();
7965            crate::io::assert_fully_wrapped(&raw);
7966
7967            let output: ClaudeOutput = serde_json::from_value(raw).unwrap();
7968            let ClaudeOutput::System(sys) = output else {
7969                panic!("expected System");
7970            };
7971            let Some(KnownSystemEvent::VcsStateChanged(msg)) = sys.as_known_system_event() else {
7972                panic!("expected VcsStateChanged event");
7973            };
7974            assert_eq!(msg.kind.as_str(), kind);
7975            assert!(!matches!(msg.kind, VcsMutationKind::Unknown(_)));
7976        }
7977
7978        // Unknown kinds are valid per the wire contract.
7979        let raw: Value = serde_json::from_str(
7980            r#"{"type":"system","subtype":"vcs_state_changed","kind":"tag","cwd":"/repo","uuid":"u2","session_id":"s2"}"#,
7981        )
7982        .unwrap();
7983        crate::io::assert_fully_wrapped(&raw);
7984        let output: ClaudeOutput = serde_json::from_value(raw).unwrap();
7985        let ClaudeOutput::System(sys) = output else {
7986            panic!("expected System");
7987        };
7988        let Some(KnownSystemEvent::VcsStateChanged(msg)) = sys.as_known_system_event() else {
7989            panic!("expected VcsStateChanged event");
7990        };
7991        assert_eq!(msg.kind, VcsMutationKind::Unknown("tag".to_string()));
7992
7993        assert!(sys.is_vcs_state_changed());
7994        let direct = sys.as_vcs_state_changed().expect("direct accessor");
7995        assert_eq!(direct.cwd, "/repo");
7996        assert!(sys.as_code_change_published().is_none());
7997    }
7998
7999    #[test]
8000    fn test_assistant_aborted_and_resume_flags_roundtrip() {
8001        let json = r#"{
8002            "type":"assistant",
8003            "message":{"id":"msg_1","role":"assistant","model":"claude-3","content":[{"type":"text","text":"partial"}]},
8004            "session_id":"s1",
8005            "aborted":true,
8006            "resumed_from_incomplete_thinking":true
8007        }"#;
8008        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
8009        let ClaudeOutput::Assistant(msg) = &output else {
8010            panic!("expected Assistant");
8011        };
8012        assert_eq!(msg.aborted, Some(true));
8013        assert_eq!(msg.resumed_from_incomplete_thinking, Some(true));
8014        let reserialized = serde_json::to_string(&output).unwrap();
8015        assert!(reserialized.contains("\"aborted\":true"));
8016        assert!(reserialized.contains("\"resumed_from_incomplete_thinking\":true"));
8017
8018        // Absent flags stay absent on the wire.
8019        let json = r#"{
8020            "type":"assistant",
8021            "message":{"id":"msg_2","role":"assistant","model":"claude-3","content":[]},
8022            "session_id":"s2"
8023        }"#;
8024        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
8025        let reserialized = serde_json::to_string(&output).unwrap();
8026        assert!(!reserialized.contains("aborted"));
8027        assert!(!reserialized.contains("resumed_from_incomplete_thinking"));
8028    }
8029
8030    #[test]
8031    fn test_user_tool_result_meta_roundtrip() {
8032        let json = r#"{
8033            "type":"user",
8034            "message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_1","content":"denied"}]},
8035            "session_id":"622ae0c3-3d50-4fa7-9ee0-69d691238c6d",
8036            "tool_result_meta":[
8037                {"id":"toolu_1","non_execution_kind":"user-rejected","user_feedback":"use the staging db"},
8038                {"id":"toolu_2","non_execution_kind":"permission-rule"}
8039            ]
8040        }"#;
8041        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
8042        let ClaudeOutput::User(user) = &output else {
8043            panic!("expected User");
8044        };
8045        let meta = user.tool_result_meta.as_ref().unwrap();
8046        assert_eq!(meta.len(), 2);
8047        assert_eq!(meta[0].non_execution_kind.as_deref(), Some("user-rejected"));
8048        assert_eq!(meta[0].user_feedback.as_deref(), Some("use the staging db"));
8049        assert_eq!(meta[1].user_feedback, None);
8050
8051        let reserialized = serde_json::to_string(&output).unwrap();
8052        assert!(reserialized.contains("\"non_execution_kind\":\"user-rejected\""));
8053        assert!(!reserialized.contains("\"user_feedback\":null"));
8054    }
8055
8056    /// CLI 2.1.222 added `scope` to `system/model_refusal_fallback`:
8057    /// "session" (main-thread swap, also the meaning when absent on older
8058    /// CLIs) vs "local" (subagent/side-question fallback only).
8059    #[test]
8060    fn model_refusal_fallback_scope_roundtrips_and_defaults() {
8061        use super::{ModelRefusalFallbackMessage, RefusalFallbackScope};
8062        let with_scope = serde_json::json!({
8063            "trigger": "refusal",
8064            "direction": "retry",
8065            "scope": "local",
8066            "original_model": "claude-fable-5",
8067            "fallback_model": "claude-opus-5",
8068            "request_id": null,
8069            "content": "Refused; retried on fallback model.",
8070            "uuid": "u1",
8071            "session_id": "s1"
8072        });
8073        let msg: ModelRefusalFallbackMessage = serde_json::from_value(with_scope.clone()).unwrap();
8074        assert_eq!(msg.scope, Some(RefusalFallbackScope::Local));
8075        assert_eq!(serde_json::to_value(&msg).unwrap(), with_scope);
8076
8077        // Older CLIs omit scope — absent, not null, and treated as session
8078        // by consumers per the wire docs.
8079        let mut without = with_scope.clone();
8080        without.as_object_mut().unwrap().remove("scope");
8081        let msg: ModelRefusalFallbackMessage = serde_json::from_value(without.clone()).unwrap();
8082        assert_eq!(msg.scope, None);
8083        assert_eq!(serde_json::to_value(&msg).unwrap(), without);
8084
8085        // Open enum: unknown scopes pass through verbatim.
8086        assert_eq!(
8087            RefusalFallbackScope::from("workspace").as_str(),
8088            "workspace"
8089        );
8090    }
8091}