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    /// The same id as on the task's `task_notification`. Set only beside
2863    /// [`off_host`](Self::off_host), since such a task may have no
2864    /// `task_started`. For a script's call it names no `tool_use` block.
2865    /// Marked `@internal` upstream (CLI 2.1.330+).
2866    #[serde(default, skip_serializing_if = "Option::is_none")]
2867    pub tool_use_id: Option<String>,
2868}
2869
2870#[derive(Debug, Clone, Serialize, Deserialize)]
2871pub struct SessionStateChangedMessage {
2872    pub state: String,
2873    #[serde(default, skip_serializing_if = "Option::is_none")]
2874    pub uuid: Option<String>,
2875    #[serde(default, skip_serializing_if = "Option::is_none")]
2876    pub session_id: Option<String>,
2877}
2878
2879#[derive(Debug, Clone, Serialize, Deserialize)]
2880pub struct WorkerShuttingDownMessage {
2881    pub reason: String,
2882    #[serde(default, skip_serializing_if = "Option::is_none")]
2883    pub uuid: Option<String>,
2884    #[serde(default, skip_serializing_if = "Option::is_none")]
2885    pub session_id: Option<String>,
2886}
2887
2888#[derive(Debug, Clone, Serialize, Deserialize)]
2889pub struct CommandsChangedMessage {
2890    pub commands: Vec<CommandInfo>,
2891    #[serde(default, skip_serializing_if = "Option::is_none")]
2892    pub uuid: Option<String>,
2893    #[serde(default, skip_serializing_if = "Option::is_none")]
2894    pub session_id: Option<String>,
2895}
2896
2897#[derive(Debug, Clone, Serialize, Deserialize)]
2898pub struct CommandInfo {
2899    pub name: String,
2900    pub description: String,
2901    #[serde(rename = "argumentHint")]
2902    pub argument_hint: String,
2903    #[serde(default, skip_serializing_if = "Option::is_none")]
2904    pub aliases: Option<Vec<String>>,
2905    /// True when the command is Claude Code's own; absent for a command
2906    /// defined by a user, project, plugin or MCP server. Rows can share a
2907    /// name: when a marked row carries it, `/name` runs that one, and an
2908    /// unmarked row is the one `/name` runs only when no marked row shares
2909    /// its name (CLI 2.1.278+).
2910    #[serde(default, skip_serializing_if = "Option::is_none")]
2911    pub builtin: Option<bool>,
2912}
2913
2914#[derive(Debug, Clone, Serialize, Deserialize)]
2915pub struct NotificationMessage {
2916    pub key: String,
2917    pub text: String,
2918    pub priority: String,
2919    #[serde(default, skip_serializing_if = "Option::is_none")]
2920    pub color: Option<String>,
2921    #[serde(default, skip_serializing_if = "Option::is_none")]
2922    pub timeout_ms: Option<u64>,
2923    #[serde(default, skip_serializing_if = "Option::is_none")]
2924    pub uuid: Option<String>,
2925    #[serde(default, skip_serializing_if = "Option::is_none")]
2926    pub session_id: Option<String>,
2927}
2928
2929#[derive(Debug, Clone, Serialize, Deserialize)]
2930pub struct FilesPersistedMessage {
2931    pub files: Vec<PersistedFile>,
2932    pub failed: Vec<FailedPersistedFile>,
2933    pub processed_at: String,
2934    #[serde(default, skip_serializing_if = "Option::is_none")]
2935    pub uuid: Option<String>,
2936    #[serde(default, skip_serializing_if = "Option::is_none")]
2937    pub session_id: Option<String>,
2938}
2939
2940#[derive(Debug, Clone, Serialize, Deserialize)]
2941pub struct PersistedFile {
2942    pub filename: String,
2943    pub file_id: String,
2944}
2945
2946#[derive(Debug, Clone, Serialize, Deserialize)]
2947pub struct FailedPersistedFile {
2948    pub filename: String,
2949    pub error: String,
2950}
2951
2952#[derive(Debug, Clone, Serialize, Deserialize)]
2953pub struct MemoryRecallMessage {
2954    pub mode: String,
2955    pub memories: Vec<MemoryRecallItem>,
2956    #[serde(default, skip_serializing_if = "Option::is_none")]
2957    pub uuid: Option<String>,
2958    #[serde(default, skip_serializing_if = "Option::is_none")]
2959    pub session_id: Option<String>,
2960}
2961
2962#[derive(Debug, Clone, Serialize, Deserialize)]
2963pub struct MemoryRecallItem {
2964    pub path: String,
2965    pub scope: String,
2966    #[serde(default, skip_serializing_if = "Option::is_none")]
2967    pub content: Option<String>,
2968}
2969
2970#[derive(Debug, Clone, Serialize, Deserialize)]
2971pub struct ElicitationCompleteMessage {
2972    pub mcp_server_name: String,
2973    pub elicitation_id: String,
2974    #[serde(default, skip_serializing_if = "Option::is_none")]
2975    pub uuid: Option<String>,
2976    #[serde(default, skip_serializing_if = "Option::is_none")]
2977    pub session_id: Option<String>,
2978}
2979
2980#[derive(Debug, Clone, Serialize, Deserialize)]
2981pub struct PermissionDeniedMessage {
2982    pub tool_name: String,
2983    pub tool_use_id: String,
2984    #[serde(default, skip_serializing_if = "Option::is_none")]
2985    pub agent_id: Option<String>,
2986    #[serde(default, skip_serializing_if = "Option::is_none")]
2987    pub decision_reason_type: Option<String>,
2988    /// A closed-set code for a reason a host can act on, beside
2989    /// `decision_reason_type` (whose values are unchanged). Absent for
2990    /// every other reason; new values are additive (CLI 2.1.276+).
2991    #[serde(default, skip_serializing_if = "Option::is_none")]
2992    pub decision_reason_code: Option<PermissionDeniedReasonCode>,
2993    #[serde(default, skip_serializing_if = "Option::is_none")]
2994    pub decision_reason: Option<String>,
2995    pub message: String,
2996    #[serde(default, skip_serializing_if = "Option::is_none")]
2997    pub uuid: Option<String>,
2998    #[serde(default, skip_serializing_if = "Option::is_none")]
2999    pub session_id: Option<String>,
3000}
3001
3002/// An actionable reason behind a `system/permission_denied` frame
3003/// ([`PermissionDeniedMessage::decision_reason_code`]).
3004#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3005pub enum PermissionDeniedReasonCode {
3006    /// The auto-mode classifier's transcript exceeded its context window.
3007    ClassifierTranscriptTooLong,
3008    /// `permissions.blockReadsOutsideWorkingDirectories` refused the path.
3009    OutsideReadsBlocked,
3010    /// `/pause-memory` has memory paused.
3011    MemoryPaused,
3012    /// Auto mode's safety check does not run for this session, so calls
3013    /// that need it are refused. Another permission mode can run such a
3014    /// call unless only the check may allow the tool; the check can come
3015    /// back (CLI 2.1.319+).
3016    AutoModeNoCheckInSession,
3017    /// The denial that ended a turn or subagent run after ten responses in
3018    /// a row with no verdict: the check does not run for this session
3019    /// (CLI 2.1.319+).
3020    AutoModeStopNoCheckInSession,
3021    /// As [`AutoModeStopNoCheckInSession`](Self::AutoModeStopNoCheckInSession),
3022    /// but the call got no result from the check (CLI 2.1.319+).
3023    AutoModeStopNoResultForCalls,
3024    /// As [`AutoModeStopNoCheckInSession`](Self::AutoModeStopNoCheckInSession),
3025    /// but the server returned no usable verdict, as in an outage
3026    /// (CLI 2.1.319+).
3027    AutoModeStopNoVerdict,
3028    /// A code not yet known to this version of the crate.
3029    Unknown(String),
3030}
3031
3032impl PermissionDeniedReasonCode {
3033    pub fn as_str(&self) -> &str {
3034        match self {
3035            Self::ClassifierTranscriptTooLong => "classifier_transcript_too_long",
3036            Self::OutsideReadsBlocked => "outside_reads_blocked",
3037            Self::MemoryPaused => "memory_paused",
3038            Self::AutoModeNoCheckInSession => "auto_mode_no_check_in_session",
3039            Self::AutoModeStopNoCheckInSession => "auto_mode_stop_no_check_in_session",
3040            Self::AutoModeStopNoResultForCalls => "auto_mode_stop_no_result_for_calls",
3041            Self::AutoModeStopNoVerdict => "auto_mode_stop_no_verdict",
3042            Self::Unknown(s) => s.as_str(),
3043        }
3044    }
3045}
3046
3047impl fmt::Display for PermissionDeniedReasonCode {
3048    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3049        f.write_str(self.as_str())
3050    }
3051}
3052
3053impl From<&str> for PermissionDeniedReasonCode {
3054    fn from(s: &str) -> Self {
3055        match s {
3056            "classifier_transcript_too_long" => Self::ClassifierTranscriptTooLong,
3057            "outside_reads_blocked" => Self::OutsideReadsBlocked,
3058            "memory_paused" => Self::MemoryPaused,
3059            "auto_mode_no_check_in_session" => Self::AutoModeNoCheckInSession,
3060            "auto_mode_stop_no_check_in_session" => Self::AutoModeStopNoCheckInSession,
3061            "auto_mode_stop_no_result_for_calls" => Self::AutoModeStopNoResultForCalls,
3062            "auto_mode_stop_no_verdict" => Self::AutoModeStopNoVerdict,
3063            other => Self::Unknown(other.to_string()),
3064        }
3065    }
3066}
3067
3068impl Serialize for PermissionDeniedReasonCode {
3069    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
3070        serializer.serialize_str(self.as_str())
3071    }
3072}
3073
3074impl<'de> Deserialize<'de> for PermissionDeniedReasonCode {
3075    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
3076        let s = String::deserialize(deserializer)?;
3077        Ok(Self::from(s.as_str()))
3078    }
3079}
3080
3081#[derive(Debug, Clone, Serialize, Deserialize)]
3082pub struct MirrorErrorMessage {
3083    pub error: String,
3084    pub key: MirrorErrorKey,
3085    #[serde(default, skip_serializing_if = "Option::is_none")]
3086    pub uuid: Option<String>,
3087    #[serde(default, skip_serializing_if = "Option::is_none")]
3088    pub session_id: Option<String>,
3089}
3090
3091#[derive(Debug, Clone, Serialize, Deserialize)]
3092pub struct MirrorErrorKey {
3093    #[serde(rename = "projectKey")]
3094    pub project_key: String,
3095    #[serde(rename = "sessionId")]
3096    pub session_id: String,
3097    #[serde(default, skip_serializing_if = "Option::is_none")]
3098    pub subpath: Option<String>,
3099}
3100
3101#[derive(Debug, Clone, Serialize, Deserialize)]
3102pub struct InformationalMessage {
3103    pub content: String,
3104    pub level: String,
3105    #[serde(default, skip_serializing_if = "Option::is_none")]
3106    pub tool_use_id: Option<String>,
3107    #[serde(default, skip_serializing_if = "Option::is_none")]
3108    pub prevent_continuation: Option<bool>,
3109    /// Opaque feature tag on a line a host may treat specially; absent on
3110    /// ordinary lines. Hosts ignore values they do not know (CLI 2.1.288+).
3111    #[serde(default, skip_serializing_if = "Option::is_none")]
3112    pub tag: Option<String>,
3113    /// Present on the line that ends a submitted prompt before a model call:
3114    /// how the prompt ended, so a host can write its own message or count
3115    /// endings without matching `content`. A follow-up a hook blocks while a
3116    /// turn runs carries it too, so read it as the end of a turn only when
3117    /// the next result has `num_turns` 0 (CLI 2.1.300+).
3118    #[serde(default, skip_serializing_if = "Option::is_none")]
3119    pub prompt_submit_outcome: Option<PromptSubmitOutcome>,
3120    /// Present on the warning that says a requested model was refused and
3121    /// the session uses another, so a host can word the notice itself
3122    /// instead of reading `content` (CLI 2.1.317+).
3123    #[serde(default, skip_serializing_if = "Option::is_none")]
3124    pub model_restriction: Option<ModelRestriction>,
3125    /// Present on the warning, tagged `hook_no_verdict`, that a PreToolUse
3126    /// hook gave no verdict on a call and that its failure did not refuse
3127    /// the call, so a host can word the notice itself instead of reading
3128    /// `content`. Sent once per hook per session, for the first such call.
3129    /// Marked `@internal` upstream (CLI 2.1.325+).
3130    #[serde(default, skip_serializing_if = "Option::is_none")]
3131    pub hook_no_verdict: Option<HookNoVerdict>,
3132    /// Present on the line tagged `connector_files` when a connector's files
3133    /// were saved on this computer, so a host can link each path. Marked
3134    /// `@internal` upstream (CLI 2.1.328+).
3135    #[serde(default, skip_serializing_if = "Option::is_none")]
3136    pub saved_files: Option<Vec<SavedConnectorFile>>,
3137    /// Present on the line tagged `connector_files` when all that it says is
3138    /// that a connector's files were saved, so a host can word that itself
3139    /// instead of reading `content`. Marked `@internal` upstream
3140    /// (CLI 2.1.330+).
3141    #[serde(default, skip_serializing_if = "Option::is_none")]
3142    pub saved_from: Option<ConnectorFilesSaved>,
3143    #[serde(default, skip_serializing_if = "Option::is_none")]
3144    pub uuid: Option<String>,
3145    #[serde(default, skip_serializing_if = "Option::is_none")]
3146    pub session_id: Option<String>,
3147}
3148
3149/// One entry of [`InformationalMessage::saved_files`]: a connector's file
3150/// saved on this computer (CLI 2.1.328+).
3151#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3152pub struct SavedConnectorFile {
3153    /// The line of `content`, counted from 0, that ends with
3154    /// [`shown`](Self::shown).
3155    pub line: u64,
3156    /// The absolute path of the saved file. A connector can have chosen the
3157    /// file's name.
3158    pub path: String,
3159    /// The absolute path as a person reads it, as written at the end of
3160    /// [`line`](Self::line).
3161    pub shown: String,
3162}
3163
3164/// [`InformationalMessage::saved_from`]: what a `connector_files` line says
3165/// when all it reports is that a connector's files were saved (CLI 2.1.330+).
3166///
3167/// Each name is cleaned as in `content` and absent where nothing is left of
3168/// it. A connector can have chosen them: render them as plain text.
3169#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3170pub struct ConnectorFilesSaved {
3171    /// How many files were saved.
3172    pub files: u64,
3173    /// The file's name, when one file was saved.
3174    #[serde(default, skip_serializing_if = "Option::is_none")]
3175    pub file: Option<String>,
3176    /// The connector's name.
3177    #[serde(default, skip_serializing_if = "Option::is_none")]
3178    pub app: Option<String>,
3179}
3180
3181/// [`InformationalMessage::hook_no_verdict`]: a PreToolUse hook gave no
3182/// verdict on a tool call, and its failure did not refuse the call. Another
3183/// hook, a rule or the person may still stop that call. Not sent for a hook
3184/// that chose a non-blocking exit, nor where the failure refused the call
3185/// (CLI 2.1.325+).
3186#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3187pub struct HookNoVerdict {
3188    /// The hook event, e.g. `PreToolUse`.
3189    pub hook_event: String,
3190    /// The tool call the hook gave no verdict on.
3191    pub tool_use_id: String,
3192    /// `true` for a hook that ended with no answer, usually at its timeout.
3193    pub timed_out: bool,
3194    /// The plugin that owns the hook, for a plugin's hook.
3195    #[serde(default, skip_serializing_if = "Option::is_none")]
3196    pub plugin_id: Option<String>,
3197    /// The root directory of the plugin that owns the hook.
3198    #[serde(default, skip_serializing_if = "Option::is_none")]
3199    pub plugin_root: Option<String>,
3200}
3201
3202/// [`InformationalMessage::model_restriction`]: a requested model was
3203/// refused and the session uses another. Both names are cleaned as they
3204/// are in `content` (model-id characters only, cut to 128 with a trailing
3205/// `…`, or `(unrecognized model name)` when none are left) but are still
3206/// untrusted text: render them as plain text (CLI 2.1.317+).
3207#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3208pub struct ModelRestriction {
3209    /// The refused model as it was asked for, or the id that a refused
3210    /// Default pick stood for.
3211    pub requested_model: String,
3212    /// The model in use when the line was built; a later switch can
3213    /// outdate it.
3214    pub effective_model: String,
3215    /// `start` for the model the process chose when it started (from
3216    /// `--model`, the environment, settings or `--agent`'s frontmatter);
3217    /// `switch` for anything later. The CLI reads an unknown value as
3218    /// absent, so treat one that way too.
3219    #[serde(default, skip_serializing_if = "Option::is_none")]
3220    pub at: Option<String>,
3221}
3222
3223/// How a submitted prompt ended before a model call, carried as
3224/// [`InformationalMessage::prompt_submit_outcome`] (CLI 2.1.300+).
3225#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3226pub struct PromptSubmitOutcome {
3227    /// What ended the prompt. The CLI drops a kind it does not know, so the
3228    /// key can be absent; treat [`PromptSubmitOutcomeKind::Other`] as absent
3229    /// too, and ignore [`reason`](Self::reason) beside it.
3230    #[serde(default, skip_serializing_if = "Option::is_none")]
3231    pub kind: Option<PromptSubmitOutcomeKind>,
3232    /// Sent with kind `no_verdict`, and says why: `remote_run_failed`,
3233    /// `remote_run_timed_out`, `interrupted`, `remote_runner_refused`,
3234    /// `unsupported_in_cloud_session`, `output_distrusted`,
3235    /// `callback_timed_out`, `hook_failed`, `hook_timed_out`,
3236    /// `hooks_never_ran`, `personal_config_refused` or
3237    /// `rewrite_unplaceable`. Open set — treat an unknown value as absent.
3238    #[serde(default, skip_serializing_if = "Option::is_none")]
3239    pub no_verdict_kind: Option<String>,
3240    /// True when the prompt stays in the conversation, where the model reads
3241    /// it on the next turn. Do not infer it from `kind`.
3242    pub prompt_kept: bool,
3243    /// The hook's text as Claude Code got it, sanitized and possibly cut.
3244    /// Never sent with `no_verdict`; absent when Claude Code got no text.
3245    /// Untrusted and can quote the prompt, so render it as plain text.
3246    #[serde(default, skip_serializing_if = "Option::is_none")]
3247    pub reason: Option<String>,
3248}
3249
3250/// [`PromptSubmitOutcome::kind`] — what ended a submitted prompt.
3251#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3252pub enum PromptSubmitOutcomeKind {
3253    /// A hook answered with a block.
3254    BlockedByHook,
3255    /// A hook answered `continue: false`.
3256    StoppedByHook,
3257    /// A plugin's code module dropped the prompt.
3258    DroppedByHook,
3259    /// A plugin's code module answered and did not pass the prompt on.
3260    NotPassedOn,
3261    /// No hook gave a verdict, and Claude Code ended the prompt itself; see
3262    /// [`PromptSubmitOutcome::no_verdict_kind`].
3263    NoVerdict,
3264    /// A kind not yet known to this version of the crate.
3265    Other(String),
3266}
3267
3268impl PromptSubmitOutcomeKind {
3269    pub fn as_str(&self) -> &str {
3270        match self {
3271            Self::BlockedByHook => "blocked_by_hook",
3272            Self::StoppedByHook => "stopped_by_hook",
3273            Self::DroppedByHook => "dropped_by_hook",
3274            Self::NotPassedOn => "not_passed_on",
3275            Self::NoVerdict => "no_verdict",
3276            Self::Other(s) => s.as_str(),
3277        }
3278    }
3279}
3280
3281impl fmt::Display for PromptSubmitOutcomeKind {
3282    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3283        f.write_str(self.as_str())
3284    }
3285}
3286
3287impl From<&str> for PromptSubmitOutcomeKind {
3288    fn from(s: &str) -> Self {
3289        match s {
3290            "blocked_by_hook" => Self::BlockedByHook,
3291            "stopped_by_hook" => Self::StoppedByHook,
3292            "dropped_by_hook" => Self::DroppedByHook,
3293            "not_passed_on" => Self::NotPassedOn,
3294            "no_verdict" => Self::NoVerdict,
3295            other => Self::Other(other.to_string()),
3296        }
3297    }
3298}
3299
3300impl Serialize for PromptSubmitOutcomeKind {
3301    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
3302        serializer.serialize_str(self.as_str())
3303    }
3304}
3305
3306impl<'de> Deserialize<'de> for PromptSubmitOutcomeKind {
3307    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
3308        let s = String::deserialize(deserializer)?;
3309        Ok(Self::from(s.as_str()))
3310    }
3311}
3312
3313/// Plugin info from the init message
3314#[derive(Debug, Clone, Serialize, Deserialize)]
3315pub struct PluginInfo {
3316    /// Plugin name
3317    pub name: String,
3318    /// Path to the plugin on disk
3319    pub path: String,
3320    /// Plugin registry source (e.g., "rust-analyzer-lsp@claude-plugins-official")
3321    #[serde(skip_serializing_if = "Option::is_none")]
3322    pub source: Option<String>,
3323    /// Installed plugin version (e.g., "1.0.0"). Added in CLI 2.1.219.
3324    #[serde(default, skip_serializing_if = "Option::is_none")]
3325    pub version: Option<String>,
3326}
3327
3328/// Plugin load diagnostic reported by system init.
3329#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3330pub struct PluginDiagnostic {
3331    pub plugin: String,
3332    #[serde(rename = "type")]
3333    pub diagnostic_type: String,
3334    pub message: String,
3335    /// Present only when a `--plugin-dir`, SDK `plugins` or synced directory
3336    /// entry did not load at all: the path of that entry, resolved against
3337    /// the cwd (a `--plugin-url` entry carries none). `plugin` is then the
3338    /// positional `inline[N]` / `synced[N]` tag, so a host that mounts
3339    /// several directories pairs the error to its own by this path.
3340    #[serde(default, skip_serializing_if = "Option::is_none")]
3341    pub path: Option<String>,
3342    /// Present only when a managed-settings `enabledPlugins` entry dropped
3343    /// this directory, SDK, skills-directory or synced copy (CLI 2.1.325+).
3344    #[serde(default, skip_serializing_if = "Option::is_none")]
3345    pub managed_lock: Option<PluginManagedLock>,
3346}
3347
3348/// [`PluginDiagnostic::managed_lock`]: the managed-settings `enabledPlugins`
3349/// entry that dropped a directory copy of a plugin. Neither value stops an
3350/// install of the same name from another marketplace, which can load beside
3351/// it. `name` and `marketplace` are byte-exact and unbounded (control and
3352/// bidi characters are not removed), so clean and bound them before showing
3353/// them (CLI 2.1.325+).
3354#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3355pub struct PluginManagedLock {
3356    /// `true`: the entry turns that plugin on, and Claude Code does not
3357    /// accept this copy as that plugin. `false`: the entry turns it off, and
3358    /// no directory copy of the name may load.
3359    pub plugin_enabled: bool,
3360    /// The plugin name as the entry spells it, which can differ from the
3361    /// copy (case, Unicode form, an earlier name of a built-in).
3362    pub name: String,
3363    /// The entry's marketplace. Absent where the entry names no marketplace
3364    /// that an install could come from.
3365    #[serde(default, skip_serializing_if = "Option::is_none")]
3366    pub marketplace: Option<String>,
3367}
3368
3369/// Memory paths reported by system init.
3370#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3371pub struct MemoryPaths {
3372    #[serde(default, skip_serializing_if = "Option::is_none")]
3373    pub auto: Option<String>,
3374    #[serde(default, skip_serializing_if = "Option::is_none")]
3375    pub team: Option<String>,
3376    #[serde(flatten)]
3377    pub extra: serde_json::Map<String, Value>,
3378}
3379
3380/// An MCP server config entry that failed validation, reported by system
3381/// init (e.g. a `url` entry with no `type`). The affected server is skipped
3382/// and absent from `InitMessage::mcp_servers`.
3383#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3384pub struct McpServerError {
3385    pub name: String,
3386    /// Stable error category.
3387    #[serde(rename = "type")]
3388    pub error_type: String,
3389    pub message: String,
3390}
3391
3392/// Init system message data - sent at session start
3393#[derive(Debug, Clone, Serialize, Deserialize)]
3394pub struct InitMessage {
3395    /// Session identifier
3396    pub session_id: String,
3397    /// Current working directory
3398    #[serde(skip_serializing_if = "Option::is_none")]
3399    pub cwd: Option<String>,
3400    /// Model being used
3401    #[serde(skip_serializing_if = "Option::is_none")]
3402    pub model: Option<String>,
3403    /// List of available tools
3404    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3405    pub tools: Vec<String>,
3406    /// MCP servers configured
3407    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3408    pub mcp_servers: Vec<Value>,
3409    /// Available slash commands (e.g., "compact", "cost", "review")
3410    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3411    pub slash_commands: Vec<String>,
3412    /// Slash commands only meaningful in a terminal context (CLI 2.1.232+,
3413    /// e.g. "doctor", "color")
3414    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3415    pub terminal_slash_commands: Vec<String>,
3416    /// Available agent types (e.g., "Bash", "Explore", "Plan")
3417    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3418    pub agents: Vec<String>,
3419    /// Installed plugins
3420    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3421    pub plugins: Vec<PluginInfo>,
3422    /// Installed skills
3423    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3424    pub skills: Vec<Value>,
3425    /// Claude Code CLI version
3426    #[serde(skip_serializing_if = "Option::is_none")]
3427    pub claude_code_version: Option<String>,
3428    /// Unix socket path for the harness's inter-session messaging bridge
3429    /// (new in CLI 2.1.232; absent on older CLIs and non-bridged runs)
3430    #[serde(skip_serializing_if = "Option::is_none")]
3431    pub messaging_socket_path: Option<String>,
3432    /// How the API key was sourced
3433    #[serde(skip_serializing_if = "Option::is_none", rename = "apiKeySource")]
3434    pub api_key_source: Option<ApiKeySource>,
3435    /// Output style
3436    #[serde(skip_serializing_if = "Option::is_none")]
3437    pub output_style: Option<OutputStyle>,
3438    /// Permission mode
3439    #[serde(skip_serializing_if = "Option::is_none", rename = "permissionMode")]
3440    pub permission_mode: Option<InitPermissionMode>,
3441
3442    /// Message-level unique identifier
3443    #[serde(skip_serializing_if = "Option::is_none")]
3444    pub uuid: Option<String>,
3445
3446    /// Memory storage paths (e.g., {"auto": "/path/to/memory/"})
3447    #[serde(skip_serializing_if = "Option::is_none")]
3448    pub memory_paths: Option<MemoryPaths>,
3449
3450    /// Absolute path of this session's scratchpad directory, for clients
3451    /// that read files from the session. Omitted when the scratchpad is
3452    /// disabled, and from the redacted init sent over the Remote Control
3453    /// bridge and by the hosted worker (CLI 2.1.278+).
3454    #[serde(default, skip_serializing_if = "Option::is_none")]
3455    pub scratchpad_path: Option<String>,
3456
3457    /// Fast mode toggle state (e.g., "off")
3458    #[serde(skip_serializing_if = "Option::is_none")]
3459    pub fast_mode_state: Option<String>,
3460
3461    /// Why fast mode can't serve right now. Absent when nothing blocks it.
3462    #[serde(default, skip_serializing_if = "Option::is_none")]
3463    pub fast_mode_disabled_reason: Option<super::result::FastModeDisabledReason>,
3464
3465    /// MCP server config entries (from `--mcp-config`) that failed validation
3466    /// and were skipped. Affected servers are absent from `mcp_servers`.
3467    #[serde(default, skip_serializing_if = "Option::is_none")]
3468    pub mcp_server_errors: Option<Vec<McpServerError>>,
3469
3470    /// Whether analytics collection is disabled for this session.
3471    #[serde(default, skip_serializing_if = "Option::is_none")]
3472    pub analytics_disabled: Option<bool>,
3473
3474    /// Whether product-feedback prompts are disabled for this session.
3475    #[serde(default, skip_serializing_if = "Option::is_none")]
3476    pub product_feedback_disabled: Option<bool>,
3477
3478    /// True when this session's model requests go to Anthropic's own API:
3479    /// the first-party provider, with no other base URL or socket, and the
3480    /// organization is not set up to use Claude through another provider.
3481    /// Absent where the process can't tell (an SSH child, a server tenant,
3482    /// workload identity, a mod that hooks `http.fetch`) and from CLIs before
3483    /// 2.1.329. It describes routing alone: a host that sends the session's
3484    /// content to Anthropic must also check ZDR, HIPAA and
3485    /// [`analytics_disabled`](Self::analytics_disabled). Marked `@internal`
3486    /// upstream.
3487    #[serde(default, skip_serializing_if = "Option::is_none")]
3488    pub served_by_anthropic: Option<bool>,
3489
3490    /// API beta flags active for the session.
3491    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3492    pub betas: Vec<String>,
3493
3494    /// Open-set protocol capability names supported by this CLI.
3495    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3496    pub capabilities: Vec<String>,
3497
3498    /// Plugin load errors.
3499    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3500    pub plugin_errors: Vec<PluginDiagnostic>,
3501
3502    /// Plugin load warnings.
3503    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3504    pub plugin_warnings: Vec<PluginDiagnostic>,
3505
3506    /// The effort level the session will send on its next request — after env
3507    /// overrides, session state, org caps, and model-support downgrades
3508    /// (`"low"` | `"medium"` | `"high"` | `"xhigh"` | `"max"`). `None` when no
3509    /// effort parameter will be sent, or on CLIs before 2.1.239.
3510    #[serde(default, skip_serializing_if = "Option::is_none")]
3511    pub effort: Option<String>,
3512
3513    /// Only on init frames written by the headless stream-json client of a
3514    /// cloud-hosted session: a per-frame snapshot of the cloud session's id,
3515    /// view URL, device binding, and directory-sync state. Absent in every
3516    /// other mode. Stored as raw JSON (the shape is internal and evolving).
3517    #[serde(default, skip_serializing_if = "Option::is_none")]
3518    pub cloud_session: Option<Value>,
3519
3520    /// The terminal's server-configured `◆ <text>` footer pill, carried so a
3521    /// host UI can render the same pill. Absent when nothing is configured
3522    /// (CLI 2.1.259+).
3523    #[serde(default, skip_serializing_if = "Option::is_none")]
3524    pub footer_indicator: Option<FooterIndicator>,
3525
3526    /// This cloud worker's life (`CLAUDE_CODE_WORKER_EPOCH`): a new number
3527    /// each time the session's worker is started. Absent outside cloud
3528    /// workers and on CLIs before 2.1.259.
3529    #[serde(default, skip_serializing_if = "Option::is_none")]
3530    pub worker_epoch: Option<u64>,
3531
3532    /// Windows only: the absolute path of the PowerShell binary this session
3533    /// runs PowerShell commands with, or `Some(None)` (wire `null`) when
3534    /// none was found. Absent on other platforms and on CLIs before 2.1.259.
3535    #[serde(default, skip_serializing_if = "Option::is_none")]
3536    pub powershell_path: Option<Option<String>>,
3537
3538    /// Cold-start telemetry for hosted (CCR) sessions: named startup phases
3539    /// and resume-hydration counters. Absent elsewhere. Stored as raw JSON
3540    /// (the shape is internal and evolving) (CLI 2.1.266+).
3541    #[serde(default, skip_serializing_if = "Option::is_none")]
3542    pub startup_timing: Option<serde_json::Map<String, Value>>,
3543
3544    /// Whether per-turn effort is active for this frame's `model`. `true`:
3545    /// an effort change keeps the prompt cache, because the effort is sent
3546    /// inside the conversation at the turn where it changes. `false`: the
3547    /// effort is sent only as the top-level parameter, so a change rewrites
3548    /// the cached prefix. Mid-session the CLI reports only a change to
3549    /// `false` (`system/per_turn_effort_changed`); `true` comes only from an
3550    /// init and is provisional after a fresh process or once the
3551    /// conversation's refusals are cleared, so keep listening all session.
3552    /// Absent means unknown (CLI 2.1.281+).
3553    #[serde(default, skip_serializing_if = "Option::is_none")]
3554    pub per_turn_effort_active: Option<bool>,
3555
3556    /// Whether typing `ultrathink` runs the turn at `xhigh` effort on this
3557    /// frame's `model` (and, when the session is already at `xhigh` or
3558    /// `max`, leaves the turn as it is); a host highlights the word only
3559    /// while this is `true`. After `system/per_turn_effort_changed`, treat it
3560    /// as `false` until the next init. The same answer as `get_settings`'
3561    /// `applied.ultrathinkAvailable`. Sent by the stream-json (Agent SDK)
3562    /// host; absent means unknown (CLI 2.1.316+).
3563    #[serde(default, skip_serializing_if = "Option::is_none")]
3564    pub ultrathink_available: Option<bool>,
3565
3566    /// `true` when a user message carrying
3567    /// [`UserMessage::ultrathink_typed`] that passes that field's checks runs
3568    /// its turn at `xhigh` effort on this frame's `model` (and, when the
3569    /// session is already at `xhigh` or `max`, leaves the turn as it is). A
3570    /// client colors the word and sends the statement only while this is
3571    /// `true`. After `system/per_turn_effort_changed`, treat it as `false`
3572    /// until the next init. Absent means unknown: color nothing and send no
3573    /// statement. Sent by the stream-json (Agent SDK) host and on Remote
3574    /// Control bridge init frames (CLI 2.1.317+).
3575    #[serde(default, skip_serializing_if = "Option::is_none")]
3576    pub ultrathink_typed_raises: Option<bool>,
3577
3578    /// Only on a Cowork cloud worker's init: the thinking this turn runs
3579    /// with. Absent when a request changed the session's thinking after the
3580    /// turn's start, or the session has no thinking setting of its own
3581    /// (CLI 2.1.317+).
3582    #[serde(default, skip_serializing_if = "Option::is_none")]
3583    pub client_thinking: Option<ClientThinking>,
3584
3585    /// Only on a Cowork cloud worker's init: `Some(true)` when an
3586    /// `apply_flag_settings` of exactly `{switchModelsOnFlag: true}` would add
3587    /// nothing now (the session holds the value, and no fast mode resync or
3588    /// auto mode check is due). Absent: send the request (CLI 2.1.317+).
3589    #[serde(default, skip_serializing_if = "Option::is_none")]
3590    pub flag_restate_noop: Option<bool>,
3591
3592    /// Absolute path of the one folder of synced skills whose files
3593    /// `read_file` serves in this session; a client may admit paths below it
3594    /// as it admits paths below [`scratchpad_path`](Self::scratchpad_path).
3595    /// Read only; a symbolic link, a dot-named part or a file at its top is
3596    /// refused. Sent by a self-hosted runner's session alone; omitted where
3597    /// the session serves no such folder, and wherever `original_cwd` is
3598    /// withheld (CLI 2.1.317+).
3599    #[serde(default, skip_serializing_if = "Option::is_none")]
3600    pub synced_skills_path: Option<String>,
3601
3602    /// Whether the session's transcript is in focus view. Toggled by
3603    /// `/focus`, including over Remote Control. Present on Remote Control
3604    /// bridge init frames and on the per-turn init of headless stream-json
3605    /// runs; absent on hosts that do not publish it and on CLIs before
3606    /// 2.1.281. Re-emitted inits carry the current value — the newest frame
3607    /// wins.
3608    #[serde(default, skip_serializing_if = "Option::is_none")]
3609    pub view_mode: Option<ViewMode>,
3610
3611    /// Absolute path of the folder the session's file permission checks are
3612    /// anchored at, for clients that read files from the session. Unlike
3613    /// `cwd` it does not follow the shell: it moves only on `/cd`, on
3614    /// entering or leaving a worktree, and on a session restore. Omitted on
3615    /// the redacted Remote Control / hosted-worker inits, in a session with
3616    /// no directory, for HIPAA organizations, and on CLIs before 2.1.301.
3617    #[serde(default, skip_serializing_if = "Option::is_none")]
3618    pub original_cwd: Option<String>,
3619
3620    /// Absolute paths of the folders added to the session (`--add-dir`, the
3621    /// SDK `additionalDirectories` option, settings, a grant, or a host's
3622    /// mid-session request), in no particular order; `Some(vec![])` when
3623    /// there are none. Folders added only by repository-delivered settings
3624    /// files are left out. Grants nothing: the CLI's own check decides every
3625    /// read. `None` means not told (not "none"): omitted on the same lanes as
3626    /// [`original_cwd`](Self::original_cwd), by hosts that have not wired it,
3627    /// and on CLIs before 2.1.301.
3628    #[serde(default, skip_serializing_if = "Option::is_none")]
3629    pub additional_directories: Option<Vec<String>>,
3630
3631    /// Only in a session that Claude Desktop itself started: the variables
3632    /// by which an administrator's managed settings choose a provider or a
3633    /// gateway, where this start dropped them and requests go straight to
3634    /// Anthropic instead. Worked out anew for every init. Omitted when there
3635    /// is nothing to list, on any transport that stores its frames, from the
3636    /// Remote Control bridge's init, and on CLIs before 2.1.327.
3637    #[serde(default, skip_serializing_if = "Option::is_none")]
3638    pub host_dropped_env: Option<Vec<HostDroppedEnv>>,
3639}
3640
3641/// One entry of [`InitMessage::host_dropped_env`] (CLI 2.1.327+).
3642#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3643pub struct HostDroppedEnv {
3644    /// Where the dropped variables came from: `policySettings`. Ignore an
3645    /// entry with any other value.
3646    pub source: String,
3647    /// Upper-case variable names, never values.
3648    pub names: Vec<String>,
3649}
3650
3651/// [`InitMessage::client_thinking`]: the thinking a Cowork cloud worker's
3652/// turn runs with (CLI 2.1.317+).
3653#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3654pub struct ClientThinking {
3655    /// `0` with thinking off, the fixed budget, or `None` (wire `null`) with
3656    /// no fixed budget.
3657    #[serde(default)]
3658    pub max_thinking_tokens: Option<u64>,
3659    /// `summarized`, `omitted` or `highlights`; `None` (wire `null`) with
3660    /// none, with thinking off, and for a `highlights` this session cannot
3661    /// send.
3662    #[serde(default)]
3663    pub thinking_display: Option<String>,
3664}
3665
3666/// The server-configured session indicator that the terminal renders as a
3667/// `◆ <text>` pill in the prompt footer, carried on `system/init` and the
3668/// `initialize` response (CLI 2.1.259+).
3669#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3670pub struct FooterIndicator {
3671    /// The label to show — already sanitized to a single line of plain text,
3672    /// exactly as the terminal footer renders it after its `◆` glyph.
3673    pub text: String,
3674}
3675
3676/// The session's transcript view, carried as [`InitMessage::view_mode`]
3677/// (CLI 2.1.281+).
3678#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3679pub enum ViewMode {
3680    /// The model is told the user sees only its final message per turn, so
3681    /// clients may collapse each turn to the prompt and the final response.
3682    Focus,
3683    /// The ordinary full transcript.
3684    Default,
3685    /// A mode not yet known to this version of the crate.
3686    Unknown(String),
3687}
3688
3689impl ViewMode {
3690    pub fn as_str(&self) -> &str {
3691        match self {
3692            Self::Focus => "focus",
3693            Self::Default => "default",
3694            Self::Unknown(s) => s.as_str(),
3695        }
3696    }
3697}
3698
3699impl fmt::Display for ViewMode {
3700    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3701        f.write_str(self.as_str())
3702    }
3703}
3704
3705impl From<&str> for ViewMode {
3706    fn from(s: &str) -> Self {
3707        match s {
3708            "focus" => Self::Focus,
3709            "default" => Self::Default,
3710            other => Self::Unknown(other.to_string()),
3711        }
3712    }
3713}
3714
3715impl Serialize for ViewMode {
3716    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
3717        serializer.serialize_str(self.as_str())
3718    }
3719}
3720
3721impl<'de> Deserialize<'de> for ViewMode {
3722    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
3723        let s = String::deserialize(deserializer)?;
3724        Ok(Self::from(s.as_str()))
3725    }
3726}
3727
3728/// Status system message - sent during operations like context compaction
3729#[derive(Debug, Clone, Serialize, Deserialize)]
3730pub struct StatusMessage {
3731    /// Session identifier
3732    pub session_id: String,
3733    /// Current status (e.g., compacting) or null when complete
3734    pub status: Option<StatusMessageStatus>,
3735    /// Unique identifier for this message
3736    #[serde(skip_serializing_if = "Option::is_none")]
3737    pub uuid: Option<String>,
3738    /// Current permission mode when changed mid-session.
3739    #[serde(skip_serializing_if = "Option::is_none", rename = "permissionMode")]
3740    pub permission_mode: Option<InitPermissionMode>,
3741    #[serde(skip_serializing_if = "Option::is_none")]
3742    pub compact_result: Option<String>,
3743    #[serde(skip_serializing_if = "Option::is_none")]
3744    pub compact_error: Option<String>,
3745    /// On the `compacting` statuses of an automatic compaction (absent on a
3746    /// typed `/compact`): characters of the summary streamed so far (text
3747    /// and tool-input deltas, not thinking). Returns to 0 at each new attempt
3748    /// and stays 0 while a background summary is awaited. A rising count
3749    /// shows progress; it is not a share of the final length. Absent from
3750    /// CLIs before 2.1.295. Marked `@internal` upstream.
3751    #[serde(default, skip_serializing_if = "Option::is_none")]
3752    pub compact_output_chars: Option<u64>,
3753    /// Present, and true, once at start-up when
3754    /// `CLAUDE_CODE_RESUME_INTERRUPTED_TURN` asked for the interrupted turn
3755    /// to be re-run and this process did not re-run it: the turn ran in plan
3756    /// mode and the process came back in another mode, where the re-run
3757    /// could carry out a plan nobody approved. Marked `@internal` upstream
3758    /// (CLI 2.1.319+).
3759    #[serde(default, skip_serializing_if = "Option::is_none")]
3760    pub resume_held_for_plan: Option<bool>,
3761}
3762
3763/// Compact boundary message - marks where context compaction occurred
3764#[derive(Debug, Clone, Serialize, Deserialize)]
3765pub struct CompactBoundaryMessage {
3766    /// Session identifier
3767    pub session_id: String,
3768    /// Metadata about the compaction
3769    pub compact_metadata: CompactMetadata,
3770    /// Human-readable summary of what was compacted, when the CLI emits one.
3771    ///
3772    /// Also accepted under the `content` / `text` wire keys.
3773    #[serde(
3774        default,
3775        skip_serializing_if = "Option::is_none",
3776        alias = "content",
3777        alias = "text"
3778    )]
3779    pub summary: Option<String>,
3780    /// Number of messages summarized in this compaction pass, when present.
3781    ///
3782    /// Also accepted under the `message_count` wire key.
3783    #[serde(
3784        default,
3785        skip_serializing_if = "Option::is_none",
3786        alias = "message_count"
3787    )]
3788    pub leaf_message_count: Option<u32>,
3789    /// Wall-clock duration of the compaction pass in milliseconds, when present.
3790    #[serde(default, skip_serializing_if = "Option::is_none")]
3791    pub duration_ms: Option<u64>,
3792    /// Unique identifier for this message
3793    #[serde(skip_serializing_if = "Option::is_none")]
3794    pub uuid: Option<String>,
3795    /// Logical parent across the compaction boundary.
3796    #[serde(skip_serializing_if = "Option::is_none")]
3797    pub logical_parent_uuid: Option<Option<String>>,
3798    /// Replayed history rather than a live message, stamped by the Remote
3799    /// Control bridge when it flushes history to the session server
3800    /// (CLI 2.1.266+).
3801    #[serde(default, skip_serializing_if = "Option::is_none")]
3802    pub historical: Option<bool>,
3803}
3804
3805/// Metadata about context compaction
3806#[derive(Debug, Clone, Serialize, Deserialize)]
3807pub struct CompactMetadata {
3808    /// Number of tokens before compaction
3809    pub pre_tokens: u64,
3810    /// What triggered the compaction
3811    pub trigger: CompactionTrigger,
3812    #[serde(default, skip_serializing_if = "Option::is_none")]
3813    pub post_tokens: Option<u64>,
3814    #[serde(default, skip_serializing_if = "Option::is_none")]
3815    pub cumulative_dropped_tokens: Option<u64>,
3816    #[serde(default, skip_serializing_if = "Option::is_none")]
3817    pub duration_ms: Option<u64>,
3818    #[serde(default, skip_serializing_if = "Option::is_none")]
3819    pub user_context: Option<String>,
3820    #[serde(default, skip_serializing_if = "Option::is_none")]
3821    pub messages_summarized: Option<u64>,
3822    #[serde(default, skip_serializing_if = "Option::is_none")]
3823    pub precomputed: Option<bool>,
3824    #[serde(default, skip_serializing_if = "Option::is_none")]
3825    pub pre_compact_discovered_tools: Option<Vec<String>>,
3826    /// The artifact versions the conversation held before this compaction,
3827    /// most recently changed first; empty when it held none. A resumed
3828    /// session replays these so it can update those artifacts without
3829    /// reading them again (CLI 2.1.285+).
3830    #[serde(default, skip_serializing_if = "Option::is_none")]
3831    pub pre_compact_artifact_read_versions: Option<Vec<ArtifactReadVersion>>,
3832    #[serde(default, skip_serializing_if = "Option::is_none")]
3833    pub preserved_segment: Option<PreservedSegment>,
3834    #[serde(default, skip_serializing_if = "Option::is_none")]
3835    pub preserved_messages: Option<PreservedMessages>,
3836}
3837
3838/// One artifact version a conversation held before a compaction, carried in
3839/// [`CompactMetadata::pre_compact_artifact_read_versions`].
3840#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3841pub struct ArtifactReadVersion {
3842    /// The artifact id.
3843    pub slug: String,
3844    /// The version read or published.
3845    pub ver: String,
3846}
3847
3848#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3849pub struct PreservedSegment {
3850    pub head_uuid: String,
3851    pub anchor_uuid: String,
3852    pub tail_uuid: String,
3853}
3854
3855#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3856pub struct PreservedMessages {
3857    pub anchor_uuid: String,
3858    pub uuids: Vec<String>,
3859    #[serde(default, skip_serializing_if = "Option::is_none")]
3860    pub all_uuids: Option<Vec<String>>,
3861}
3862
3863// ---------------------------------------------------------------------------
3864// Task system message types (task_started, task_progress, task_notification)
3865// ---------------------------------------------------------------------------
3866
3867/// Cumulative usage statistics for a background task.
3868#[derive(Debug, Clone, Serialize, Deserialize)]
3869pub struct TaskUsage {
3870    /// Wall-clock milliseconds since the task started.
3871    pub duration_ms: u64,
3872    /// Total number of tool calls made so far.
3873    pub tool_uses: u64,
3874    /// Total tokens consumed so far.
3875    pub total_tokens: u64,
3876}
3877
3878/// The kind of background task.
3879#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3880pub enum TaskType {
3881    /// A sub-agent task (e.g., Explore, Plan).
3882    LocalAgent,
3883    /// A background bash command.
3884    LocalBash,
3885    /// A local workflow task.
3886    LocalWorkflow,
3887    /// A task type not yet known to this version of the crate.
3888    Unknown(String),
3889}
3890
3891impl TaskType {
3892    pub fn as_str(&self) -> &str {
3893        match self {
3894            Self::LocalAgent => "local_agent",
3895            Self::LocalBash => "local_bash",
3896            Self::LocalWorkflow => "local_workflow",
3897            Self::Unknown(s) => s.as_str(),
3898        }
3899    }
3900}
3901
3902impl fmt::Display for TaskType {
3903    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3904        f.write_str(self.as_str())
3905    }
3906}
3907
3908impl From<&str> for TaskType {
3909    fn from(s: &str) -> Self {
3910        match s {
3911            "local_agent" => Self::LocalAgent,
3912            "local_bash" => Self::LocalBash,
3913            "local_workflow" => Self::LocalWorkflow,
3914            other => Self::Unknown(other.to_string()),
3915        }
3916    }
3917}
3918
3919impl Serialize for TaskType {
3920    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
3921        serializer.serialize_str(self.as_str())
3922    }
3923}
3924
3925impl<'de> Deserialize<'de> for TaskType {
3926    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
3927        let s = String::deserialize(deserializer)?;
3928        Ok(Self::from(s.as_str()))
3929    }
3930}
3931
3932/// Completion status of a background task.
3933#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3934pub enum TaskStatus {
3935    Pending,
3936    Running,
3937    Completed,
3938    Failed,
3939    Killed,
3940    Paused,
3941    Stopped,
3942    Unknown(String),
3943}
3944
3945impl TaskStatus {
3946    pub fn as_str(&self) -> &str {
3947        match self {
3948            Self::Pending => "pending",
3949            Self::Running => "running",
3950            Self::Completed => "completed",
3951            Self::Failed => "failed",
3952            Self::Killed => "killed",
3953            Self::Paused => "paused",
3954            Self::Stopped => "stopped",
3955            Self::Unknown(s) => s.as_str(),
3956        }
3957    }
3958}
3959
3960impl fmt::Display for TaskStatus {
3961    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3962        f.write_str(self.as_str())
3963    }
3964}
3965
3966impl From<&str> for TaskStatus {
3967    fn from(s: &str) -> Self {
3968        match s {
3969            "pending" => Self::Pending,
3970            "running" => Self::Running,
3971            "completed" => Self::Completed,
3972            "failed" => Self::Failed,
3973            "killed" => Self::Killed,
3974            "paused" => Self::Paused,
3975            "stopped" => Self::Stopped,
3976            other => Self::Unknown(other.to_string()),
3977        }
3978    }
3979}
3980
3981impl Serialize for TaskStatus {
3982    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
3983        serializer.serialize_str(self.as_str())
3984    }
3985}
3986
3987impl<'de> Deserialize<'de> for TaskStatus {
3988    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
3989        let s = String::deserialize(deserializer)?;
3990        Ok(Self::from(s.as_str()))
3991    }
3992}
3993
3994/// `task_started` system message — emitted once when a background task begins.
3995#[derive(Debug, Clone, Serialize, Deserialize)]
3996pub struct TaskStartedMessage {
3997    pub session_id: String,
3998    pub task_id: String,
3999    /// Id of one run of the task: equal on every `task_*` event and
4000    /// `background_tasks_changed` entry of that run. A resumed task keeps its
4001    /// `task_id` and gets a new `run_id`; the run ids of one task sort, by
4002    /// plain string comparison, in the order the runs opened. Absent for a
4003    /// task this process did not register (CLI 2.1.292+).
4004    #[serde(default, skip_serializing_if = "Option::is_none")]
4005    pub run_id: Option<String>,
4006    /// `task_id` of the subagent (`local_agent`) task whose agent launched
4007    /// this task. Absent when the launcher is the main thread, has no
4008    /// `task_id` of its own, or is no longer tracked. The parent may be a
4009    /// foreground or already-ended task, so treat an unknown id as no parent
4010    /// (CLI 2.1.292+).
4011    #[serde(default, skip_serializing_if = "Option::is_none")]
4012    pub parent_task_id: Option<String>,
4013    #[serde(default, skip_serializing_if = "Option::is_none")]
4014    pub task_type: Option<TaskType>,
4015    #[serde(default, skip_serializing_if = "Option::is_none")]
4016    pub tool_use_id: Option<String>,
4017    pub description: String,
4018    /// The subagent type for `local_agent` tasks (e.g. `general-purpose`,
4019    /// `Explore`). Absent for `local_bash` tasks.
4020    #[serde(default, skip_serializing_if = "Option::is_none")]
4021    pub subagent_type: Option<String>,
4022    /// Whether the task was registered in the background (`true`) or in the
4023    /// foreground with the spawning tool call blocking on it (`false`). A
4024    /// later move to the background arrives as `task_updated`
4025    /// `patch.is_backgrounded`. Set for `local_agent` and `local_bash` tasks
4026    /// (CLI 2.1.239+).
4027    #[serde(default, skip_serializing_if = "Option::is_none")]
4028    pub is_backgrounded: Option<bool>,
4029    /// True for a run of a resumed subagent (`local_agent`) that the tool
4030    /// call which resumed it waits for, as `SendMessage` does when
4031    /// background tasks are disabled; [`tool_use_id`](Self::tool_use_id)
4032    /// then names that call. The run has ended by the time that call
4033    /// returns, and its report goes into that call's result, so expect no
4034    /// follow-up turn when it ends. A later resume that nothing waits for
4035    /// starts a new run without the field (CLI 2.1.293+).
4036    #[serde(default, skip_serializing_if = "Option::is_none")]
4037    pub awaited: Option<bool>,
4038    /// Nesting depth of a spawned subagent (`local_agent`) task: 1 for a
4039    /// top-level spawn, N+1 when spawned from inside a depth-N agent. Not set
4040    /// on other tasks (CLI 2.1.239+).
4041    #[serde(default, skip_serializing_if = "Option::is_none")]
4042    pub spawn_depth: Option<u32>,
4043    /// The prompt handed to the subagent. Present for `local_agent` tasks.
4044    /// Absent on a subagent run that Claude Code resumed with text of its own
4045    /// (such as a background task's notice): keep the prompt an earlier
4046    /// `task_started` gave. On a run that continues an interrupted turn, this
4047    /// is the task's description (CLI 2.1.327+).
4048    #[serde(default, skip_serializing_if = "Option::is_none")]
4049    pub prompt: Option<String>,
4050    #[serde(default, skip_serializing_if = "Option::is_none")]
4051    pub workflow_name: Option<String>,
4052    #[serde(default, skip_serializing_if = "Option::is_none")]
4053    pub skip_transcript: Option<bool>,
4054    /// True for housekeeping tasks the CLI does not surface as user work
4055    /// (every `skip_transcript` task, plus auto-started live-update
4056    /// watchers); hosts should exclude them from activity indicators
4057    /// (CLI 2.1.259+).
4058    #[serde(default, skip_serializing_if = "Option::is_none")]
4059    pub ambient: Option<bool>,
4060    pub uuid: String,
4061}
4062
4063/// `task_updated` system message — emitted when a background task's state
4064/// changes (e.g. transitions to `completed`). Carries a partial `patch` of the
4065/// fields that changed rather than the full task record.
4066#[derive(Debug, Clone, Serialize, Deserialize)]
4067pub struct TaskUpdatedMessage {
4068    pub session_id: String,
4069    pub task_id: String,
4070    /// Id of the task run this update belongs to; see
4071    /// [`TaskStartedMessage::run_id`] (CLI 2.1.292+).
4072    #[serde(default, skip_serializing_if = "Option::is_none")]
4073    pub run_id: Option<String>,
4074    pub patch: TaskPatch,
4075    pub uuid: String,
4076}
4077
4078/// The partial update carried by a [`TaskUpdatedMessage`]. Every field is
4079/// optional because the CLI only sends the keys that changed.
4080#[derive(Debug, Clone, Default, Serialize, Deserialize)]
4081pub struct TaskPatch {
4082    #[serde(default, skip_serializing_if = "Option::is_none")]
4083    pub status: Option<TaskStatus>,
4084    /// Wall-clock epoch milliseconds when the task finished, when the patch
4085    /// reports completion.
4086    #[serde(default, skip_serializing_if = "Option::is_none")]
4087    pub end_time: Option<u64>,
4088    #[serde(default, skip_serializing_if = "Option::is_none")]
4089    pub description: Option<String>,
4090    #[serde(default, skip_serializing_if = "Option::is_none")]
4091    pub total_paused_ms: Option<u64>,
4092    #[serde(default, skip_serializing_if = "Option::is_none")]
4093    pub error: Option<String>,
4094    #[serde(default, skip_serializing_if = "Option::is_none")]
4095    pub is_backgrounded: Option<bool>,
4096}
4097
4098/// `thinking_tokens` system message — emitted as the model streams extended
4099/// thinking, reporting the running estimate of thinking tokens consumed.
4100#[derive(Debug, Clone, Serialize, Deserialize)]
4101pub struct ThinkingTokensMessage {
4102    pub session_id: String,
4103    /// Running estimate of total thinking tokens for the current turn.
4104    pub estimated_tokens: u64,
4105    /// Increase in the estimate since the previous `thinking_tokens` event.
4106    pub estimated_tokens_delta: u64,
4107    /// Client uuid of the user message that triggered this turn, stamped on
4108    /// every `thinking_tokens` frame of a headless turn so a consumer can
4109    /// attribute thinking progress to the send it answers before any reply
4110    /// frame arrives. Absent on synthetic/scheduled (meta) turns, on turns
4111    /// without a client uuid, on Remote Control sessions, and from CLIs
4112    /// before 2.1.261.
4113    #[serde(default, skip_serializing_if = "Option::is_none")]
4114    pub user_message_uuid: Option<String>,
4115    pub uuid: String,
4116}
4117
4118/// `task_progress` system message — emitted periodically as a background
4119/// agent task executes tools. Not emitted for `local_bash` tasks.
4120#[derive(Debug, Clone, Serialize, Deserialize)]
4121pub struct TaskProgressMessage {
4122    pub session_id: String,
4123    pub task_id: String,
4124    /// Id of the task run this progress belongs to; see
4125    /// [`TaskStartedMessage::run_id`] (CLI 2.1.292+).
4126    #[serde(default, skip_serializing_if = "Option::is_none")]
4127    pub run_id: Option<String>,
4128    #[serde(default, skip_serializing_if = "Option::is_none")]
4129    pub tool_use_id: Option<String>,
4130    pub description: String,
4131    #[serde(default, skip_serializing_if = "Option::is_none")]
4132    pub last_tool_name: Option<String>,
4133    pub usage: TaskUsage,
4134    /// Subagent type for `local_agent` tasks (e.g. `Explore`).
4135    #[serde(default, skip_serializing_if = "Option::is_none")]
4136    pub subagent_type: Option<String>,
4137    #[serde(default, skip_serializing_if = "Option::is_none")]
4138    pub summary: Option<String>,
4139    pub uuid: String,
4140}
4141
4142/// `task_notification` system message — emitted once when a background
4143/// task completes or fails.
4144#[derive(Debug, Clone, Serialize, Deserialize)]
4145pub struct TaskNotificationMessage {
4146    pub session_id: String,
4147    pub task_id: String,
4148    /// Id of the task run this notification closes; see
4149    /// [`TaskStartedMessage::run_id`] (CLI 2.1.292+).
4150    #[serde(default, skip_serializing_if = "Option::is_none")]
4151    pub run_id: Option<String>,
4152    pub status: TaskStatus,
4153    /// Machine-readable cause, set only when the task did not end through an
4154    /// ordinary completion, failure, or stop (CLI 2.1.273+).
4155    #[serde(default, skip_serializing_if = "Option::is_none")]
4156    pub reason: Option<TaskEndReason>,
4157    pub summary: String,
4158    /// `true` when `summary` is the final report of a subagent that nothing
4159    /// waits for, with no review to come: show it as the report. A later
4160    /// notification for the same `task_id` replaces it. Absent when the
4161    /// summary may be a description or interim text, under `handback` (see
4162    /// `handback_report`), or in auto mode (CLI 2.1.326+).
4163    #[serde(default, skip_serializing_if = "Option::is_none")]
4164    pub summary_is_report: Option<bool>,
4165    pub output_file: Option<String>,
4166    #[serde(skip_serializing_if = "Option::is_none")]
4167    pub tool_use_id: Option<String>,
4168    #[serde(skip_serializing_if = "Option::is_none")]
4169    pub usage: Option<TaskUsage>,
4170    /// For a backgrounded MCP task that completed, the `resource_link`
4171    /// content blocks of its final result — the files it returned by
4172    /// reference — collected from the raw result before the CLI renders it
4173    /// as text. Join to the originating call via `tool_use_id`. Absent when
4174    /// the result had none or the task is any other type (CLI 2.1.259+).
4175    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4176    pub resource_links: Vec<ResourceLink>,
4177    /// On a `completed` notification of a subagent that reports through the
4178    /// SubagentHandback tool: how its report reached its caller. Left out
4179    /// when the subagent failed, was stopped, or is still waiting on work;
4180    /// `summary` is then not a report. When present, `summary` holds harness
4181    /// notes written for the model. A later notification for the same
4182    /// `task_id` replaces what an earlier one showed (CLI 2.1.292+).
4183    #[serde(default, skip_serializing_if = "Option::is_none")]
4184    pub handback: Option<TaskHandback>,
4185    /// The report a `send` or `flagged` hand-back delivered: when present,
4186    /// render it instead of `summary`, with its `warning`, if any, above its
4187    /// `text`. Absent for `withheld` (CLI 2.1.292+).
4188    #[serde(default, skip_serializing_if = "Option::is_none")]
4189    pub handback_report: Option<HandbackReport>,
4190    #[serde(default, skip_serializing_if = "Option::is_none")]
4191    pub skip_transcript: Option<bool>,
4192    /// True for housekeeping tasks the CLI does not surface as user work;
4193    /// hosts should exclude them from activity indicators (CLI 2.1.259+).
4194    #[serde(default, skip_serializing_if = "Option::is_none")]
4195    pub ambient: Option<bool>,
4196    #[serde(skip_serializing_if = "Option::is_none")]
4197    pub uuid: Option<String>,
4198}
4199
4200/// How a subagent's hand-back report reached its caller
4201/// ([`TaskNotificationMessage::handback`]).
4202#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4203pub enum TaskHandback {
4204    /// The report was delivered.
4205    Send,
4206    /// The report was delivered with an auto-mode warning.
4207    Flagged,
4208    /// The report was held back; no `handback_report` is sent.
4209    Withheld,
4210    /// A value not yet known to this version of the crate.
4211    Unknown(String),
4212}
4213
4214impl TaskHandback {
4215    pub fn as_str(&self) -> &str {
4216        match self {
4217            Self::Send => "send",
4218            Self::Flagged => "flagged",
4219            Self::Withheld => "withheld",
4220            Self::Unknown(s) => s.as_str(),
4221        }
4222    }
4223}
4224
4225impl fmt::Display for TaskHandback {
4226    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4227        f.write_str(self.as_str())
4228    }
4229}
4230
4231impl From<&str> for TaskHandback {
4232    fn from(s: &str) -> Self {
4233        match s {
4234            "send" => Self::Send,
4235            "flagged" => Self::Flagged,
4236            "withheld" => Self::Withheld,
4237            other => Self::Unknown(other.to_string()),
4238        }
4239    }
4240}
4241
4242impl Serialize for TaskHandback {
4243    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4244        serializer.serialize_str(self.as_str())
4245    }
4246}
4247
4248impl<'de> Deserialize<'de> for TaskHandback {
4249    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4250        let s = String::deserialize(deserializer)?;
4251        Ok(Self::from(s.as_str()))
4252    }
4253}
4254
4255/// A subagent's delivered hand-back report
4256/// ([`TaskNotificationMessage::handback_report`]).
4257#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
4258pub struct HandbackReport {
4259    /// The subagent's whole report, never truncated, with a backslash
4260    /// inserted into text that imitates harness markup.
4261    pub text: String,
4262    /// Auto mode's warning to show above `text`: a security warning, or a
4263    /// note that the review could not run.
4264    #[serde(default, skip_serializing_if = "Option::is_none")]
4265    pub warning: Option<String>,
4266    /// Id of the subagent's own `SubagentHandback` `tool_use` block that sent
4267    /// the report, not of the call that started the agent. Copies of one
4268    /// report repeat it; show the report even when no such block is loaded.
4269    /// A hand-back user message's `origin` carries the same id as
4270    /// `handbackToolUseId` (CLI 2.1.327+).
4271    #[serde(default, rename = "toolUseId", skip_serializing_if = "Option::is_none")]
4272    pub tool_use_id: Option<String>,
4273}
4274
4275/// API error category attached to assistant wrapper frames.
4276#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4277pub enum AssistantErrorKind {
4278    AuthenticationFailed,
4279    OauthOrgNotAllowed,
4280    AccountOnHold,
4281    BillingError,
4282    RateLimit,
4283    Overloaded,
4284    InvalidRequest,
4285    ModelNotFound,
4286    ServerError,
4287    UnknownError,
4288    MaxOutputTokens,
4289    Unknown(String),
4290}
4291
4292impl AssistantErrorKind {
4293    pub fn as_str(&self) -> &str {
4294        match self {
4295            Self::AuthenticationFailed => "authentication_failed",
4296            Self::OauthOrgNotAllowed => "oauth_org_not_allowed",
4297            Self::AccountOnHold => "account_on_hold",
4298            Self::BillingError => "billing_error",
4299            Self::RateLimit => "rate_limit",
4300            Self::Overloaded => "overloaded",
4301            Self::InvalidRequest => "invalid_request",
4302            Self::ModelNotFound => "model_not_found",
4303            Self::ServerError => "server_error",
4304            Self::UnknownError => "unknown",
4305            Self::MaxOutputTokens => "max_output_tokens",
4306            Self::Unknown(s) => s.as_str(),
4307        }
4308    }
4309}
4310
4311impl fmt::Display for AssistantErrorKind {
4312    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4313        f.write_str(self.as_str())
4314    }
4315}
4316
4317impl From<&str> for AssistantErrorKind {
4318    fn from(s: &str) -> Self {
4319        match s {
4320            "authentication_failed" => Self::AuthenticationFailed,
4321            "oauth_org_not_allowed" => Self::OauthOrgNotAllowed,
4322            "account_on_hold" => Self::AccountOnHold,
4323            "billing_error" => Self::BillingError,
4324            "rate_limit" => Self::RateLimit,
4325            "overloaded" => Self::Overloaded,
4326            "invalid_request" => Self::InvalidRequest,
4327            "model_not_found" => Self::ModelNotFound,
4328            "server_error" => Self::ServerError,
4329            "unknown" => Self::UnknownError,
4330            "max_output_tokens" => Self::MaxOutputTokens,
4331            other => Self::Unknown(other.to_string()),
4332        }
4333    }
4334}
4335
4336impl Serialize for AssistantErrorKind {
4337    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4338        serializer.serialize_str(self.as_str())
4339    }
4340}
4341
4342impl<'de> Deserialize<'de> for AssistantErrorKind {
4343    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4344        let s = String::deserialize(deserializer)?;
4345        Ok(Self::from(s.as_str()))
4346    }
4347}
4348
4349/// `code_change_published` system message — the session is now associated
4350/// with a published code change (a pull/merge request). Fires on creation and
4351/// whenever the session contributes to an existing one, so bind on every
4352/// event; re-emission for the same URL is possible and idempotent. Values are
4353/// scraped from captured command output — treat them as a binding hint and
4354/// verify against the forge before routing authenticated requests.
4355#[derive(Debug, Clone, Serialize, Deserialize)]
4356pub struct CodeChangePublishedMessage {
4357    /// Forge classification derived from the URL's shape (`github`,
4358    /// `github-enterprise`, `gitlab`, `bitbucket`, `gerrit` today). Open set
4359    /// — treat an unknown value as a valid provider, never as an error.
4360    pub provider: String,
4361    /// Web URL of the pull/merge request. Unverified.
4362    pub url: String,
4363    /// Repository path from the URL (`owner/name` on GitHub; may carry more
4364    /// segments on GitLab).
4365    pub repo: String,
4366    /// Provider-native change identifier — the PR/MR number as a string.
4367    pub identifier: String,
4368    /// What the session did that produced this announcement: the flag-aware
4369    /// `gh pr` verb it ran (`"created"`, `"edited"`, `"merged"`,
4370    /// `"commented"`, `"closed"`, `"reopened"`, `"ready"`, `"draft"`,
4371    /// `"auto-merge-enabled"`, `"auto-merge-disabled"`), `"pushed"` for a
4372    /// push to a branch that has a PR, `"checked-out"` for `gh pr checkout`,
4373    /// or `"started"` for the open change on the branch a Claude Desktop
4374    /// session began on. Always sent by current producers (CLI 2.1.239+),
4375    /// absent only from older ones. Open set — treat unknown values as valid.
4376    #[serde(default, skip_serializing_if = "Option::is_none")]
4377    pub action: Option<String>,
4378    /// The session's working branch when it produced the change. Sent for
4379    /// providers whose changes have no head branch of their own (`gerrit`),
4380    /// so a host can place the change on that checkout, and with `created`
4381    /// on any provider: the branch the create was opened from (its `--head`
4382    /// / `--source-branch` flag, else the working branch), so a host can show
4383    /// the new change before its own forge lookup answers (CLI 2.1.273+).
4384    /// Absent otherwise (CLI 2.1.259+).
4385    #[serde(default, skip_serializing_if = "Option::is_none")]
4386    pub branch: Option<String>,
4387    pub uuid: String,
4388    pub session_id: String,
4389}
4390
4391/// `vcs_state_changed` system message — a harness-observed shell command
4392/// mutated repository state. A cache-invalidation signal, deliberately
4393/// payload-free beyond classification: consumers re-read state (branch, head,
4394/// PR status) instead of decoding the event.
4395#[derive(Debug, Clone, Serialize, Deserialize)]
4396pub struct VcsStateChangedMessage {
4397    /// What class of mutation was observed. New kinds may be added — treat an
4398    /// unrecognized kind exactly like a recognized one (something changed).
4399    pub kind: VcsMutationKind,
4400    /// The session's working directory — a hint, not necessarily the mutated
4401    /// repo's path (`git -C` or an inner `cd` mutates elsewhere).
4402    pub cwd: String,
4403    /// The branch a commit landed on or a push updated. Commit and push
4404    /// events carry it; a command that pushed several branches emits one push
4405    /// event per branch. A best-effort hint: absent whenever attribution is
4406    /// uncertain, and never a required key (CLI 2.1.239+).
4407    #[serde(default, skip_serializing_if = "Option::is_none")]
4408    pub branch: Option<String>,
4409    pub uuid: String,
4410    pub session_id: String,
4411}
4412
4413/// Mutation class carried by a [`VcsStateChangedMessage`].
4414#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4415pub enum VcsMutationKind {
4416    Commit,
4417    Push,
4418    Merge,
4419    Rebase,
4420    /// A kind not yet known to this version of the crate.
4421    Unknown(String),
4422}
4423
4424impl VcsMutationKind {
4425    pub fn as_str(&self) -> &str {
4426        match self {
4427            Self::Commit => "commit",
4428            Self::Push => "push",
4429            Self::Merge => "merge",
4430            Self::Rebase => "rebase",
4431            Self::Unknown(s) => s.as_str(),
4432        }
4433    }
4434}
4435
4436impl fmt::Display for VcsMutationKind {
4437    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4438        f.write_str(self.as_str())
4439    }
4440}
4441
4442impl From<&str> for VcsMutationKind {
4443    fn from(s: &str) -> Self {
4444        match s {
4445            "commit" => Self::Commit,
4446            "push" => Self::Push,
4447            "merge" => Self::Merge,
4448            "rebase" => Self::Rebase,
4449            other => Self::Unknown(other.to_string()),
4450        }
4451    }
4452}
4453
4454impl Serialize for VcsMutationKind {
4455    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4456        serializer.serialize_str(self.as_str())
4457    }
4458}
4459
4460impl<'de> Deserialize<'de> for VcsMutationKind {
4461    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4462        let s = String::deserialize(deserializer)?;
4463        Ok(Self::from(s.as_str()))
4464    }
4465}
4466
4467/// `system/feedback_draft_queued` — a feedback draft was queued for submission.
4468#[derive(Debug, Clone, Serialize, Deserialize)]
4469pub struct FeedbackDraftQueuedMessage {
4470    pub draft_id: String,
4471    pub draft_type: String,
4472    pub title: String,
4473    pub details_preview: String,
4474    #[serde(default, skip_serializing_if = "Option::is_none")]
4475    pub uuid: Option<String>,
4476    #[serde(default, skip_serializing_if = "Option::is_none")]
4477    pub session_id: Option<String>,
4478    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
4479    pub extra: serde_json::Map<String, Value>,
4480}
4481
4482/// `system/cloud_session_delta` — written only by the headless stream-json
4483/// client of a cloud-hosted session (the same client that puts
4484/// `cloud_session` on its init frames): the session's status changed between
4485/// two inits. Only after the first init; at most a few per second; none when
4486/// nothing differs. An init is always a complete snapshot, so a host that
4487/// (re)attaches resynchronises from the first init it reads and applies
4488/// these on top. Display-only (CLI 2.1.260+).
4489#[derive(Debug, Clone, Serialize, Deserialize)]
4490pub struct CloudSessionDeltaMessage {
4491    /// Rises by one with each of these frames this client writes (1 for the
4492    /// first); never reset by an init. A reader keeps the highest it has
4493    /// applied and drops a lower one.
4494    pub seq: u64,
4495    /// The top-level keys of `cloud_session` whose value differs from the
4496    /// last block this client wrote, e.g. `["serving"]`; never empty. A hint
4497    /// for what to redraw — the block is complete either way.
4498    pub changed: Vec<String>,
4499    /// The whole block exactly as the next init would carry it (see
4500    /// [`InitMessage::cloud_session`]): replace the held copy, do not merge.
4501    /// Stored as raw JSON (the shape is internal and evolving).
4502    pub cloud_session: Value,
4503    pub uuid: String,
4504    pub session_id: String,
4505    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
4506    pub extra: serde_json::Map<String, Value>,
4507}
4508
4509/// `system/dev_intent` — the conversation, or the git repository it runs in,
4510/// shows a known kind of development work, for hosts that key tooling on it
4511/// (Claude Code Desktop opens its iOS Simulator entry point on `ios_app`).
4512/// Sent with `trigger` as its only other payload. Per conversation per
4513/// process, each kind is sent at most once from conversation evidence and at
4514/// most once from the project scan: conversation evidence when it first
4515/// completes, or at startup when a resumed conversation already has it;
4516/// project evidence (print-mode CLIs only, which is how the Agent SDK starts
4517/// it) at startup, after each `conversation_reset`, and at the first message
4518/// of a conversation whose earlier scan did not find every kind. Either can
4519/// arrive before `system/init`. A rewind or compaction never retracts it and
4520/// only a `conversation_reset` starts over, so treat each kind as a sticky
4521/// fact about the conversation: a client that needs only the kind can ignore
4522/// repeats, and one that needs to know what set it off reads `trigger`
4523/// (CLI 2.1.266+; `trigger` and the project scan from 2.1.273).
4524#[derive(Debug, Clone, Serialize, Deserialize)]
4525pub struct DevIntentMessage {
4526    /// What kind of development the evidence shows.
4527    pub kind: DevIntentKind,
4528    /// The evidence the detection fired on, for a host's own analytics. From
4529    /// the conversation it is the first platform-specific evidence seen;
4530    /// [`DevIntentTrigger::ProjectScan`] marks a scan of the session's git
4531    /// repository. Absent from CLIs before 2.1.273, which send only
4532    /// conversation evidence.
4533    #[serde(default, skip_serializing_if = "Option::is_none")]
4534    pub trigger: Option<DevIntentTrigger>,
4535    pub uuid: String,
4536    pub session_id: String,
4537    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
4538    pub extra: serde_json::Map<String, Value>,
4539}
4540
4541/// The kind of development a [`DevIntentMessage`] reports. Open set: the CLI
4542/// says "more kinds will be added; ignore a kind you do not recognize", so
4543/// unrecognized values deserialize to [`DevIntentKind::Unknown`].
4544#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4545pub enum DevIntentKind {
4546    /// From the conversation: Claude wrote or edited a `.swift` file and
4547    /// something it wrote, read, or ran is iOS-specific (a macOS-only app or
4548    /// server-side Swift package never qualifies). From the project scan: the
4549    /// session's git repository has an Xcode project whose build settings
4550    /// name an iOS SDK or target iPhone or iPad.
4551    IosApp,
4552    /// From the conversation: Claude wrote or edited a `.kt`, `.kts` or
4553    /// `.java` file and something it wrote, read, or ran is Android-specific
4554    /// (a Kotlin server or a multiplatform module with no Android target
4555    /// never qualifies). From the project scan: the repository has an
4556    /// `AndroidManifest.xml` or the Android Gradle plugin in a build script
4557    /// or version catalog (CLI 2.1.273+).
4558    AndroidApp,
4559    /// A kind not yet known to this version of the crate.
4560    Unknown(String),
4561}
4562
4563impl DevIntentKind {
4564    pub fn as_str(&self) -> &str {
4565        match self {
4566            Self::IosApp => "ios_app",
4567            Self::AndroidApp => "android_app",
4568            Self::Unknown(s) => s.as_str(),
4569        }
4570    }
4571}
4572
4573impl fmt::Display for DevIntentKind {
4574    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4575        f.write_str(self.as_str())
4576    }
4577}
4578
4579impl From<&str> for DevIntentKind {
4580    fn from(s: &str) -> Self {
4581        match s {
4582            "ios_app" => Self::IosApp,
4583            "android_app" => Self::AndroidApp,
4584            other => Self::Unknown(other.to_string()),
4585        }
4586    }
4587}
4588
4589impl Serialize for DevIntentKind {
4590    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4591        serializer.serialize_str(self.as_str())
4592    }
4593}
4594
4595impl<'de> Deserialize<'de> for DevIntentKind {
4596    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4597        let s = String::deserialize(deserializer)?;
4598        Ok(Self::from(s.as_str()))
4599    }
4600}
4601
4602/// The evidence a [`DevIntentMessage`] detection fired on. Open set: the CLI
4603/// says "more values will be added; ignore one you do not recognize", so
4604/// unrecognized values deserialize to [`DevIntentTrigger::Unknown`].
4605#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4606pub enum DevIntentTrigger {
4607    /// Reserved for rules that need no other evidence; no rule sends it yet.
4608    SwiftEdit,
4609    /// `import UIKit` or `.iOS(` in text Claude wrote.
4610    UikitImport,
4611    /// iOS build settings written, or seen in a tool result such as a
4612    /// pbxproj read.
4613    XcodeProject,
4614    /// `simctl`, an iOS SDK or a Simulator destination in a command Claude
4615    /// ran.
4616    IosCommand,
4617    /// Reserved for rules that need no other evidence; no rule sends it yet.
4618    KotlinEdit,
4619    /// Reserved for rules that need no other evidence; no rule sends it yet.
4620    JavaEdit,
4621    /// `import android.` in text Claude wrote.
4622    AndroidImport,
4623    /// A manifest path or body written, or seen in a tool result.
4624    AndroidManifest,
4625    /// The Android Gradle plugin written, or seen in a tool result.
4626    GradlePlugin,
4627    /// `adb`, the emulator, `sdkmanager`, `avdmanager`,
4628    /// `react-native run-android` or a Gradle variant task.
4629    AndroidCommand,
4630    /// For any kind: a scan of the session's git repository rather than
4631    /// conversation evidence.
4632    ProjectScan,
4633    /// A trigger not yet known to this version of the crate.
4634    Unknown(String),
4635}
4636
4637impl DevIntentTrigger {
4638    pub fn as_str(&self) -> &str {
4639        match self {
4640            Self::SwiftEdit => "swift_edit",
4641            Self::UikitImport => "uikit_import",
4642            Self::XcodeProject => "xcode_project",
4643            Self::IosCommand => "ios_command",
4644            Self::KotlinEdit => "kotlin_edit",
4645            Self::JavaEdit => "java_edit",
4646            Self::AndroidImport => "android_import",
4647            Self::AndroidManifest => "android_manifest",
4648            Self::GradlePlugin => "gradle_plugin",
4649            Self::AndroidCommand => "android_command",
4650            Self::ProjectScan => "project_scan",
4651            Self::Unknown(s) => s.as_str(),
4652        }
4653    }
4654}
4655
4656impl fmt::Display for DevIntentTrigger {
4657    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4658        f.write_str(self.as_str())
4659    }
4660}
4661
4662impl From<&str> for DevIntentTrigger {
4663    fn from(s: &str) -> Self {
4664        match s {
4665            "swift_edit" => Self::SwiftEdit,
4666            "uikit_import" => Self::UikitImport,
4667            "xcode_project" => Self::XcodeProject,
4668            "ios_command" => Self::IosCommand,
4669            "kotlin_edit" => Self::KotlinEdit,
4670            "java_edit" => Self::JavaEdit,
4671            "android_import" => Self::AndroidImport,
4672            "android_manifest" => Self::AndroidManifest,
4673            "gradle_plugin" => Self::GradlePlugin,
4674            "android_command" => Self::AndroidCommand,
4675            "project_scan" => Self::ProjectScan,
4676            other => Self::Unknown(other.to_string()),
4677        }
4678    }
4679}
4680
4681impl Serialize for DevIntentTrigger {
4682    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4683        serializer.serialize_str(self.as_str())
4684    }
4685}
4686
4687impl<'de> Deserialize<'de> for DevIntentTrigger {
4688    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4689        let s = String::deserialize(deserializer)?;
4690        Ok(Self::from(s.as_str()))
4691    }
4692}
4693
4694/// Why a [`TaskNotificationMessage`] ended other than through an ordinary
4695/// completion, failure, or stop. Open set: unrecognized values deserialize
4696/// to [`TaskEndReason::Unknown`].
4697#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4698pub enum TaskEndReason {
4699    /// The worker process restarted and the resumed process found the task
4700    /// orphaned (always with status `stopped`).
4701    WorkerRestart,
4702    /// A reason not yet known to this version of the crate.
4703    Unknown(String),
4704}
4705
4706impl TaskEndReason {
4707    pub fn as_str(&self) -> &str {
4708        match self {
4709            Self::WorkerRestart => "worker_restart",
4710            Self::Unknown(s) => s.as_str(),
4711        }
4712    }
4713}
4714
4715impl fmt::Display for TaskEndReason {
4716    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4717        f.write_str(self.as_str())
4718    }
4719}
4720
4721impl From<&str> for TaskEndReason {
4722    fn from(s: &str) -> Self {
4723        match s {
4724            "worker_restart" => Self::WorkerRestart,
4725            other => Self::Unknown(other.to_string()),
4726        }
4727    }
4728}
4729
4730impl Serialize for TaskEndReason {
4731    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4732        serializer.serialize_str(self.as_str())
4733    }
4734}
4735
4736impl<'de> Deserialize<'de> for TaskEndReason {
4737    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4738        let s = String::deserialize(deserializer)?;
4739        Ok(Self::from(s.as_str()))
4740    }
4741}
4742
4743/// `system/turn_handoff_available` — emitted once by a cloud worker that
4744/// accepts the `turn_handoff` control request, right after it registers,
4745/// carrying what its registration wrote to `external_metadata.turn_handoff`.
4746/// Lets a session client learn the capability from the event stream instead
4747/// of reading worker state. Durable in the stream: a reader keeps the entry
4748/// with the newest `worker_epoch` it has seen and ignores older ones; a
4749/// worker life that does not accept `turn_handoff` emits nothing
4750/// (CLI 2.1.273+).
4751#[derive(Debug, Clone, Serialize, Deserialize)]
4752pub struct TurnHandoffAvailableMessage {
4753    /// Contract version of the handoff registration (currently `1`).
4754    pub v: u64,
4755    /// The tools whose calls this worker would accept.
4756    pub tools: Vec<String>,
4757    /// The worker life announcing it.
4758    pub worker_epoch: u64,
4759    /// Present, and true, only when this worker uses the `relay_marker`
4760    /// member of a `turn_handoff` request; a client sends that member to no
4761    /// other worker.
4762    #[serde(default, skip_serializing_if = "Option::is_none")]
4763    pub relay_marker: Option<bool>,
4764    /// Present, and true, when this worker starts a handed-off turn's calls
4765    /// only after every `stage_file` control request it received earlier has
4766    /// finished or failed, or a wait limit has passed; a worker that omits
4767    /// it may start them while files are still downloading (CLI 2.1.278+).
4768    /// Exception: a request with `filestore_path` set (a synced file) is not
4769    /// waited for, so a call that names that file may start before it is
4770    /// synced (CLI 2.1.287+).
4771    #[serde(default, skip_serializing_if = "Option::is_none")]
4772    pub staged_files: Option<bool>,
4773    /// True when user messages with `shouldQuery` false that reach this
4774    /// worker before a `turn_handoff` request are appended, and
4775    /// acknowledged, before the handed-off turn produces any output.
4776    /// Exception: a request that continues a turn whose leading lines an
4777    /// earlier request appended; that turn goes first. A worker that omits
4778    /// it may run the turn first (CLI 2.1.278+).
4779    #[serde(default, skip_serializing_if = "Option::is_none")]
4780    pub no_query_first: Option<bool>,
4781    /// Present, and true, only on a worker that takes a `stage_file` control
4782    /// request whose `mount_path` is `/uploads/.home/<path>` as a file for
4783    /// `/home/claude/<path>`: it writes the file there, answers ok with a
4784    /// noop (`already_present`, `path_occupied`, `refused_name`,
4785    /// `home_files_off`, `unchecked_announcement`, `resent_announcement`)
4786    /// and writes nothing, or answers an error. Any other worker treats that
4787    /// path as an ordinary upload (CLI 2.1.287+).
4788    #[serde(default, skip_serializing_if = "Option::is_none")]
4789    pub home_files: Option<bool>,
4790    /// Present, and true, only when this worker uses the `file_names` member
4791    /// of a `turn_handoff` request; a client sends that member to no other
4792    /// worker (CLI 2.1.287+).
4793    #[serde(default, skip_serializing_if = "Option::is_none")]
4794    pub file_names: Option<bool>,
4795    /// Present, and true, only on a worker that writes the files of the
4796    /// Write calls a `turn_handoff` request brings already answered, where
4797    /// their paths are under `/home/claude`. Before it appends a turn that
4798    /// has calls to run, it writes each such call's content to its path,
4799    /// replacing nothing. If it cannot write them all, it appends and runs
4800    /// nothing: the request is refused with an error that starts
4801    /// `invalid_handoff: carried_writes_`, or it is accepted and the turn
4802    /// ends in a result with `num_turns` 0. Any other worker writes no file
4803    /// for these calls (CLI 2.1.288+).
4804    #[serde(default, skip_serializing_if = "Option::is_none")]
4805    pub carried_writes: Option<bool>,
4806    /// Present, and true, only on a worker that rebuilt the conversation
4807    /// from the session's stored transcript before it read any request, and
4808    /// would not have started without it. A client may send such a worker
4809    /// again a `turn_handoff` request an earlier worker accepted, if the
4810    /// request names no calls (empty `tool_use_ids`), is not stopped, and its
4811    /// messages hold no tool call: the worker appends only the turn's
4812    /// messages its conversation lacks and, once the store confirms them,
4813    /// echoes the turn's last message back as an assistant event. The
4814    /// request can still be accepted or refused (`invalid_handoff:`) with no
4815    /// echo, e.g. after a rewind, a compaction or a Stop; an echo proves
4816    /// nothing if the same worker had the request before. The key promises
4817    /// nothing for a turn that holds a tool call. A worker without it may
4818    /// have started with none of the turn's messages (CLI 2.1.296+).
4819    #[serde(default, skip_serializing_if = "Option::is_none")]
4820    pub hydrates_carried_lines: Option<bool>,
4821    /// Present, and true, when this worker accepts a `turn_handoff` request
4822    /// in which an assistant message repeats the message id of the assistant
4823    /// message before it. A worker that omits it refuses such a request
4824    /// (`invalid_handoff`), so a client gives each message an id of its own
4825    /// there (CLI 2.1.300+).
4826    #[serde(default, skip_serializing_if = "Option::is_none")]
4827    pub shared_message_id: Option<bool>,
4828    /// Present, and true, only on a worker that reads the
4829    /// `requires_rewind_request_id` member of a `turn_handoff` request; a
4830    /// worker without this key ignores the member and appends the turn
4831    /// whether or not the rewind was made (CLI 2.1.311+).
4832    #[serde(default, skip_serializing_if = "Option::is_none")]
4833    pub requires_rewind_request_id: Option<bool>,
4834    /// Present, and true, only on a worker that answers the
4835    /// `comparison_fork` control request; a client sends that request to no
4836    /// other worker (CLI 2.1.327+).
4837    #[serde(default, skip_serializing_if = "Option::is_none")]
4838    pub comparison_fork: Option<bool>,
4839    pub uuid: String,
4840    pub session_id: String,
4841    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
4842    pub extra: serde_json::Map<String, Value>,
4843}
4844
4845/// `system/turn_preempted` — the CLI itself stopped the running turn so a
4846/// user's rapid follow-up message is answered at once, exactly as a priority
4847/// `now` message would have (running shell commands are backgrounded, not
4848/// killed). Sent at the moment of the stop, so it precedes the stopped turn's
4849/// `result` frame (`terminal_reason` `aborted_streaming` or `aborted_tools`)
4850/// and its members' `cancelled` `command_lifecycle` frames: a host renders
4851/// that turn as superseded by the follow-up rather than as interrupted, does
4852/// not resend its messages, and treats only `preempted_by_uuid` as picked
4853/// up. At most one per burst. Emitted in `-p`/SDK sessions only, and only to
4854/// a consumer that declared `rapidFollowupPreempt` on its initialize request
4855/// while the feature's rollout flag is on (CLI 2.1.273+).
4856#[derive(Debug, Clone, Serialize, Deserialize)]
4857pub struct TurnPreemptedMessage {
4858    /// Why the turn was stopped. `rapid_followup`: the user's next message
4859    /// arrived before the running turn showed any output. More reasons may
4860    /// be added; treat an unknown one the same way.
4861    pub reason: String,
4862    /// The client-supplied uuid of the queued user message the turn was
4863    /// stopped for. It runs next, together with any messages queued behind
4864    /// it.
4865    pub preempted_by_uuid: String,
4866    /// The client-supplied uuids of the user messages the stopped turn was
4867    /// running (uuid-less members omitted; may be empty).
4868    #[serde(default)]
4869    pub preempted_message_uuids: Vec<String>,
4870    pub uuid: String,
4871    pub session_id: String,
4872    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
4873    pub extra: serde_json::Map<String, Value>,
4874}
4875
4876/// `system/peer_message_hold` — a cross-session (peer) message this
4877/// session's receive-side policy held rather than queued, and how that hold
4878/// resolved. Lets a host show the human that a message arrived but has not
4879/// reached the model (and may never) instead of nothing at all; the sending
4880/// session is told separately over its own transport where one exists.
4881/// Informational only — there is no host-side approval through this frame.
4882/// Emitted in `-p`/SDK sessions (CLI 2.1.273+).
4883#[derive(Debug, Clone, Serialize, Deserialize)]
4884pub struct PeerMessageHoldMessage {
4885    /// `held` once per message per hold cause (a re-announcement under a
4886    /// different cause emits again); then at most one of `released` (it
4887    /// enters the queue — its `command_lifecycle` `queued` and user replay
4888    /// echo follow under `message_uuid`) or `dropped` (this process will not
4889    /// give it to the model; see `outcome`). A frame for a message the
4890    /// session service delivered is only uploaded to it: it has an empty
4891    /// `from` and no `message_uuid`, a `dropped` one need not follow a
4892    /// `held`, and its `expired` also covers an exit or a full hold buffer
4893    /// (CLI 2.1.328+).
4894    pub state: PeerMessageHoldState,
4895    /// The parked command's uuid — the value its later `command_lifecycle`
4896    /// frames and user replay echo carry. For lane `bridge`/`stdin` it is
4897    /// the id the host supplied on the inbound message; for lane `socket` it
4898    /// was chosen by the sending session, so correlate it only within
4899    /// `peer_message_hold` / peer replay frames, never against the host's
4900    /// own prompts' lifecycle.
4901    #[serde(default, skip_serializing_if = "Option::is_none")]
4902    pub message_uuid: Option<String>,
4903    /// Which ingress delivered it.
4904    pub lane: PeerMessageLane,
4905    /// The sender's address as the envelope will show it — an address-shaped
4906    /// token with control and invisible code points scrubbed; empty when the
4907    /// sender supplied none or an unshaped one. Sender-asserted on the
4908    /// socket lane: a label, not an identity proof.
4909    pub from: String,
4910    /// The sender's display name when it supplied one, normalized and
4911    /// scrubbed the same way. A claim, like `from`.
4912    #[serde(default, skip_serializing_if = "Option::is_none")]
4913    pub from_name: Option<String>,
4914    /// State `held` only: why the policy parked it.
4915    #[serde(default, skip_serializing_if = "Option::is_none")]
4916    pub cause: Option<PeerMessageHoldCause>,
4917    /// State `dropped` only: how the hold ended.
4918    #[serde(default, skip_serializing_if = "Option::is_none")]
4919    pub outcome: Option<PeerMessageHoldOutcome>,
4920    /// Outcome `dropped` only: which check discarded the message, where the
4921    /// frame says (CLI 2.1.328+).
4922    #[serde(default, skip_serializing_if = "Option::is_none")]
4923    pub reason: Option<PeerMessageDropReason>,
4924    pub uuid: String,
4925    pub session_id: String,
4926    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
4927    pub extra: serde_json::Map<String, Value>,
4928}
4929
4930/// Lifecycle state carried by a [`PeerMessageHoldMessage`].
4931#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4932pub enum PeerMessageHoldState {
4933    /// The receive-side policy parked the message instead of queueing it.
4934    Held,
4935    /// The policy now accepts it: it enters the queue.
4936    Released,
4937    /// It will never reach the model in this session.
4938    Dropped,
4939    /// A state not yet known to this version of the crate.
4940    Unknown(String),
4941}
4942
4943impl PeerMessageHoldState {
4944    pub fn as_str(&self) -> &str {
4945        match self {
4946            Self::Held => "held",
4947            Self::Released => "released",
4948            Self::Dropped => "dropped",
4949            Self::Unknown(s) => s.as_str(),
4950        }
4951    }
4952}
4953
4954impl fmt::Display for PeerMessageHoldState {
4955    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4956        f.write_str(self.as_str())
4957    }
4958}
4959
4960impl From<&str> for PeerMessageHoldState {
4961    fn from(s: &str) -> Self {
4962        match s {
4963            "held" => Self::Held,
4964            "released" => Self::Released,
4965            "dropped" => Self::Dropped,
4966            other => Self::Unknown(other.to_string()),
4967        }
4968    }
4969}
4970
4971impl Serialize for PeerMessageHoldState {
4972    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4973        serializer.serialize_str(self.as_str())
4974    }
4975}
4976
4977impl<'de> Deserialize<'de> for PeerMessageHoldState {
4978    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4979        let s = String::deserialize(deserializer)?;
4980        Ok(Self::from(s.as_str()))
4981    }
4982}
4983
4984/// Which ingress delivered the message a [`PeerMessageHoldMessage`] reports.
4985#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4986pub enum PeerMessageLane {
4987    /// The Remote Control bridge.
4988    Bridge,
4989    /// The host's own stdin stream.
4990    Stdin,
4991    /// The local cross-session socket.
4992    Socket,
4993    /// A lane not yet known to this version of the crate.
4994    Unknown(String),
4995}
4996
4997impl PeerMessageLane {
4998    pub fn as_str(&self) -> &str {
4999        match self {
5000            Self::Bridge => "bridge",
5001            Self::Stdin => "stdin",
5002            Self::Socket => "socket",
5003            Self::Unknown(s) => s.as_str(),
5004        }
5005    }
5006}
5007
5008impl fmt::Display for PeerMessageLane {
5009    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5010        f.write_str(self.as_str())
5011    }
5012}
5013
5014impl From<&str> for PeerMessageLane {
5015    fn from(s: &str) -> Self {
5016        match s {
5017            "bridge" => Self::Bridge,
5018            "stdin" => Self::Stdin,
5019            "socket" => Self::Socket,
5020            other => Self::Unknown(other.to_string()),
5021        }
5022    }
5023}
5024
5025impl Serialize for PeerMessageLane {
5026    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
5027        serializer.serialize_str(self.as_str())
5028    }
5029}
5030
5031impl<'de> Deserialize<'de> for PeerMessageLane {
5032    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
5033        let s = String::deserialize(deserializer)?;
5034        Ok(Self::from(s.as_str()))
5035    }
5036}
5037
5038/// Why the receive-side policy parked a peer message
5039/// ([`PeerMessageHoldMessage::cause`], state `held` only). The `*Setting`
5040/// causes are a standing `crossSessionInbound: "hold"`; `ModeMismatch` and
5041/// `NoModeAsserted` are the permission-mode parity holds (the sender runs in
5042/// a different permission class, or asserted none while this session
5043/// bypasses permissions).
5044#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5045pub enum PeerMessageHoldCause {
5046    ExplicitSetting,
5047    ManagedSetting,
5048    RepoSetting,
5049    InvalidSetting,
5050    BypassDefault,
5051    ModeUnknown,
5052    ModeMismatch,
5053    NoModeAsserted,
5054    /// A cause not yet known to this version of the crate.
5055    Unknown(String),
5056}
5057
5058impl PeerMessageHoldCause {
5059    pub fn as_str(&self) -> &str {
5060        match self {
5061            Self::ExplicitSetting => "explicit-setting",
5062            Self::ManagedSetting => "managed-setting",
5063            Self::RepoSetting => "repo-setting",
5064            Self::InvalidSetting => "invalid-setting",
5065            Self::BypassDefault => "bypass-default",
5066            Self::ModeUnknown => "mode-unknown",
5067            Self::ModeMismatch => "mode-mismatch",
5068            Self::NoModeAsserted => "no-mode-asserted",
5069            Self::Unknown(s) => s.as_str(),
5070        }
5071    }
5072}
5073
5074impl fmt::Display for PeerMessageHoldCause {
5075    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5076        f.write_str(self.as_str())
5077    }
5078}
5079
5080impl From<&str> for PeerMessageHoldCause {
5081    fn from(s: &str) -> Self {
5082        match s {
5083            "explicit-setting" => Self::ExplicitSetting,
5084            "managed-setting" => Self::ManagedSetting,
5085            "repo-setting" => Self::RepoSetting,
5086            "invalid-setting" => Self::InvalidSetting,
5087            "bypass-default" => Self::BypassDefault,
5088            "mode-unknown" => Self::ModeUnknown,
5089            "mode-mismatch" => Self::ModeMismatch,
5090            "no-mode-asserted" => Self::NoModeAsserted,
5091            other => Self::Unknown(other.to_string()),
5092        }
5093    }
5094}
5095
5096impl Serialize for PeerMessageHoldCause {
5097    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
5098        serializer.serialize_str(self.as_str())
5099    }
5100}
5101
5102impl<'de> Deserialize<'de> for PeerMessageHoldCause {
5103    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
5104        let s = String::deserialize(deserializer)?;
5105        Ok(Self::from(s.as_str()))
5106    }
5107}
5108
5109/// How a peer-message hold ended ([`PeerMessageHoldMessage::outcome`],
5110/// state `dropped` only).
5111#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5112pub enum PeerMessageHoldOutcome {
5113    /// No one approved it before the approval deadline (a headless host has
5114    /// no approval surface, so every parity hold ends this way unless the
5115    /// mode changes first).
5116    Expired,
5117    /// The policy refuses it, on arrival or after it waited.
5118    Refused,
5119    /// The ingress guard (rate limit, duplicate, queue cap) or the device
5120    /// check discarded it; [`PeerMessageHoldMessage::reason`] says which.
5121    Dropped,
5122    /// The session ended with it still parked.
5123    Discarded,
5124    /// The person declined it (CLI 2.1.328+).
5125    Denied,
5126    /// An outcome not yet known to this version of the crate.
5127    Unknown(String),
5128}
5129
5130impl PeerMessageHoldOutcome {
5131    pub fn as_str(&self) -> &str {
5132        match self {
5133            Self::Expired => "expired",
5134            Self::Refused => "refused",
5135            Self::Dropped => "dropped",
5136            Self::Discarded => "discarded",
5137            Self::Denied => "denied",
5138            Self::Unknown(s) => s.as_str(),
5139        }
5140    }
5141}
5142
5143impl fmt::Display for PeerMessageHoldOutcome {
5144    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5145        f.write_str(self.as_str())
5146    }
5147}
5148
5149impl From<&str> for PeerMessageHoldOutcome {
5150    fn from(s: &str) -> Self {
5151        match s {
5152            "expired" => Self::Expired,
5153            "refused" => Self::Refused,
5154            "dropped" => Self::Dropped,
5155            "discarded" => Self::Discarded,
5156            "denied" => Self::Denied,
5157            other => Self::Unknown(other.to_string()),
5158        }
5159    }
5160}
5161
5162impl Serialize for PeerMessageHoldOutcome {
5163    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
5164        serializer.serialize_str(self.as_str())
5165    }
5166}
5167
5168impl<'de> Deserialize<'de> for PeerMessageHoldOutcome {
5169    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
5170        let s = String::deserialize(deserializer)?;
5171        Ok(Self::from(s.as_str()))
5172    }
5173}
5174
5175/// Which check discarded a peer message
5176/// ([`PeerMessageHoldMessage::reason`], outcome `dropped` only; CLI 2.1.328+).
5177#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5178pub enum PeerMessageDropReason {
5179    RateLimited,
5180    Duplicate,
5181    HopLoop,
5182    HopRunaway,
5183    QueueFull,
5184    Unverified,
5185    /// A reason not yet known to this version of the crate.
5186    Unknown(String),
5187}
5188
5189impl PeerMessageDropReason {
5190    pub fn as_str(&self) -> &str {
5191        match self {
5192            Self::RateLimited => "rate-limited",
5193            Self::Duplicate => "duplicate",
5194            Self::HopLoop => "hop-loop",
5195            Self::HopRunaway => "hop-runaway",
5196            Self::QueueFull => "queue-full",
5197            Self::Unverified => "unverified",
5198            Self::Unknown(s) => s.as_str(),
5199        }
5200    }
5201}
5202
5203impl fmt::Display for PeerMessageDropReason {
5204    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5205        f.write_str(self.as_str())
5206    }
5207}
5208
5209impl From<&str> for PeerMessageDropReason {
5210    fn from(s: &str) -> Self {
5211        match s {
5212            "rate-limited" => Self::RateLimited,
5213            "duplicate" => Self::Duplicate,
5214            "hop-loop" => Self::HopLoop,
5215            "hop-runaway" => Self::HopRunaway,
5216            "queue-full" => Self::QueueFull,
5217            "unverified" => Self::Unverified,
5218            other => Self::Unknown(other.to_string()),
5219        }
5220    }
5221}
5222
5223impl Serialize for PeerMessageDropReason {
5224    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
5225        serializer.serialize_str(self.as_str())
5226    }
5227}
5228
5229impl<'de> Deserialize<'de> for PeerMessageDropReason {
5230    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
5231        let s = String::deserialize(deserializer)?;
5232        Ok(Self::from(s.as_str()))
5233    }
5234}
5235
5236/// `system/per_turn_effort_changed` — the conversation stopped sending effort
5237/// per turn, because the server refused its per-turn effort message or a
5238/// `role:"system"` message. From the retried request on, an effort change
5239/// rewrites the cached prefix, for every model, until a later `system/init`
5240/// says otherwise. Sent once, when the conversation first turns per-turn
5241/// effort off, before the retried request's output; sent again only if the
5242/// server refuses again after the conversation's refusals are cleared (for
5243/// example by `/clear` or a compaction). It can repeat a `false` the host
5244/// already holds. Pairs with [`InitMessage::per_turn_effort_active`]
5245/// (CLI 2.1.281+).
5246#[derive(Debug, Clone, Serialize, Deserialize)]
5247pub struct PerTurnEffortChangedMessage {
5248    /// Always `false`: a change to `true` is reported only by `system/init`.
5249    pub per_turn_effort_active: bool,
5250    pub uuid: String,
5251    pub session_id: String,
5252}
5253
5254/// `system/instruction_size_warning` — the session's instruction files
5255/// (CLAUDE.md files, rules files and the files they import) add up to more
5256/// than the recommended limit. Numbers only: the host words the warning in
5257/// the person's language. Sent to Claude Desktop's Code tab alone, at most
5258/// once per process, on a conversation's first turn after `system/init`;
5259/// never stored in the transcript. Safe to ignore (CLI 2.1.288+).
5260#[derive(Debug, Clone, Serialize, Deserialize)]
5261pub struct InstructionSizeWarningMessage {
5262    /// Combined length, in characters, of the instruction files in the
5263    /// session prompt. Always over [`Self::total_limit_chars`].
5264    pub total_chars: u64,
5265    /// The recommended limit for `total_chars` on the turn's model, in
5266    /// characters.
5267    pub total_limit_chars: u64,
5268    /// Number of files counted in `total_chars`. When it is 1, word the
5269    /// warning for a single file rather than a total.
5270    pub file_count: u64,
5271    /// Length of the largest file, in characters. Present only when the
5272    /// warning should mention it: there are several files and this one by
5273    /// itself is over `total_limit_chars`.
5274    #[serde(default, skip_serializing_if = "Option::is_none")]
5275    pub largest_chars: Option<u64>,
5276    pub uuid: String,
5277    pub session_id: String,
5278}
5279
5280/// `system/file_attachments_missing` — some files a user message sent by
5281/// reference (`file_attachments`) did not arrive where Claude can read them,
5282/// and Claude was told so; the turn runs on without them. A host can use it
5283/// to tell the person who sent them. Only sent by a worker connected to
5284/// Claude Code Remote. Each event states the whole list for its message, so
5285/// keep the last one per `message_uuid` (CLI 2.1.290+).
5286#[derive(Debug, Clone, Serialize, Deserialize)]
5287pub struct FileAttachmentsMissingMessage {
5288    /// The uuid of the inbound user message whose `file_attachments` named
5289    /// the files.
5290    pub message_uuid: String,
5291    /// How many well-formed `file_attachments` entries that message had.
5292    pub sent_count: u64,
5293    /// The files Claude was told did not arrive, each once. Never empty.
5294    pub missing: Vec<MissingFileAttachment>,
5295    pub uuid: String,
5296    pub session_id: String,
5297}
5298
5299/// `system/permission_check_status` — a tool call has been waiting on its
5300/// automatic permission check (the auto-mode classifier) for longer than
5301/// usual, so a host can say the step is being checked instead of showing a
5302/// silent pause. Every `checking` is followed by a `done` for the same
5303/// `tool_use_id`; `done` does not say whether the call was allowed (the
5304/// tool's result, `permission_denied` or a `can_use_tool` request does). One
5305/// call can send more than one pair. Display-only and best-effort: also stop
5306/// showing it at any other frame for this `tool_use_id` or at the end of the
5307/// turn (CLI 2.1.292+).
5308#[derive(Debug, Clone, Serialize, Deserialize)]
5309pub struct PermissionCheckStatusMessage {
5310    pub tool_use_id: String,
5311    /// Subagent ID when the tool call originated inside a subagent, as on
5312    /// `permission_denied`.
5313    #[serde(default, skip_serializing_if = "Option::is_none")]
5314    pub agent_id: Option<String>,
5315    pub status: PermissionCheckStatus,
5316    pub uuid: String,
5317    pub session_id: String,
5318}
5319
5320/// `system/inherited_asks_settled` — a cloud worker's report, before its
5321/// first turn, of which asks it inherited from the earlier worker and keeps
5322/// answerable. Any ask stored before this event that it does not name is
5323/// over (CLI 2.1.311+).
5324#[derive(Debug, Clone, Serialize, Deserialize)]
5325pub struct InheritedAsksSettledMessage {
5326    /// The request ids of the earlier worker's asks that this worker keeps
5327    /// answerable.
5328    pub kept_request_ids: Vec<String>,
5329    pub uuid: String,
5330    pub session_id: String,
5331}
5332
5333/// `system/late_allow_not_run` — a cloud worker's report that the call of a
5334/// permission card, which a message had closed and the client kept up (see
5335/// `keeps_request_id` on user messages), will not run on a late Allow: the
5336/// worker refused the person's Allow, a Deny came, or the worker cancels the
5337/// card itself. Sent once the worker has stored that, and again by each later
5338/// worker handed a copy of the Allow (CLI 2.1.326+).
5339#[derive(Debug, Clone, Serialize, Deserialize)]
5340pub struct LateAllowNotRunMessage {
5341    /// The answer's own request id, which is not checked — or the card's, at
5342    /// the worker's own cancel.
5343    pub request_id: String,
5344    /// The id of the card's call.
5345    pub tool_use_id: String,
5346    /// Why no late Allow runs the call. Treat any value as "did not run".
5347    pub reason: LateAllowNotRunReason,
5348    pub uuid: String,
5349    pub session_id: String,
5350}
5351
5352/// `system/shell_cwd` — the folder that a main-thread Bash or PowerShell call
5353/// that did not fail left its shell in, whether or not it moved. Sent only to
5354/// a host that marked a hook matcher `replacedByFrame: 'shell_cwd'`, before
5355/// the call's result and before its PostToolUse hooks; Claude Code does not
5356/// wait for the host. Not sent for a subagent's call or a call served for
5357/// another machine's session (CLI 2.1.327+).
5358#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5359pub struct ShellCwdMessage {
5360    /// The `cwd` a PostToolUse hook on this call is given. A call that
5361    /// overlapped another reports its own folder, so the last frame need not
5362    /// say where the next command starts. The model's own `cd` moves it, so
5363    /// treat it as data.
5364    pub cwd: String,
5365    pub uuid: String,
5366    pub session_id: String,
5367}
5368
5369/// `system/task_list_statuses` — the statuses of tasks on the task list, in
5370/// a session where Claude Code sets them itself and no `TaskUpdate` call
5371/// shows the change. Sent during turns and after their results, when a
5372/// status changes. It sets the tasks it names; a task it leaves out keeps its
5373/// last status. A later `TaskUpdate` result that changes a status wins.
5374/// Marked `@internal` upstream (CLI 2.1.328+).
5375#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5376pub struct TaskListStatusesMessage {
5377    pub statuses: Vec<TaskListStatus>,
5378    pub uuid: String,
5379    pub session_id: String,
5380}
5381
5382/// One entry of [`TaskListStatusesMessage::statuses`] (CLI 2.1.328+).
5383#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5384pub struct TaskListStatus {
5385    /// The task-list task id.
5386    pub id: String,
5387    pub status: TodoStatus,
5388}
5389
5390/// [`LateAllowNotRunMessage::reason`]. Every value, including unknown ones,
5391/// means the call did not run (CLI 2.1.326+).
5392#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5393pub enum LateAllowNotRunReason {
5394    TurnRunning,
5395    CardOpen,
5396    CallGone,
5397    InvalidAnswer,
5398    Limited,
5399    Stopped,
5400    Declined,
5401    AskedAgain,
5402    Withdrawn,
5403    Expired,
5404    NotRun,
5405    /// A reason not yet known to this version of the crate.
5406    Unknown(String),
5407}
5408
5409impl LateAllowNotRunReason {
5410    pub fn as_str(&self) -> &str {
5411        match self {
5412            Self::TurnRunning => "turn_running",
5413            Self::CardOpen => "card_open",
5414            Self::CallGone => "call_gone",
5415            Self::InvalidAnswer => "invalid_answer",
5416            Self::Limited => "limited",
5417            Self::Stopped => "stopped",
5418            Self::Declined => "declined",
5419            Self::AskedAgain => "asked_again",
5420            Self::Withdrawn => "withdrawn",
5421            Self::Expired => "expired",
5422            Self::NotRun => "not_run",
5423            Self::Unknown(s) => s.as_str(),
5424        }
5425    }
5426}
5427
5428impl fmt::Display for LateAllowNotRunReason {
5429    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5430        f.write_str(self.as_str())
5431    }
5432}
5433
5434impl From<&str> for LateAllowNotRunReason {
5435    fn from(s: &str) -> Self {
5436        match s {
5437            "turn_running" => Self::TurnRunning,
5438            "card_open" => Self::CardOpen,
5439            "call_gone" => Self::CallGone,
5440            "invalid_answer" => Self::InvalidAnswer,
5441            "limited" => Self::Limited,
5442            "stopped" => Self::Stopped,
5443            "declined" => Self::Declined,
5444            "asked_again" => Self::AskedAgain,
5445            "withdrawn" => Self::Withdrawn,
5446            "expired" => Self::Expired,
5447            "not_run" => Self::NotRun,
5448            other => Self::Unknown(other.to_string()),
5449        }
5450    }
5451}
5452
5453impl Serialize for LateAllowNotRunReason {
5454    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
5455        serializer.serialize_str(self.as_str())
5456    }
5457}
5458
5459impl<'de> Deserialize<'de> for LateAllowNotRunReason {
5460    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
5461        let s = String::deserialize(deserializer)?;
5462        Ok(Self::from(s.as_str()))
5463    }
5464}
5465
5466/// Phase of a [`PermissionCheckStatusMessage`].
5467#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5468pub enum PermissionCheckStatus {
5469    /// The call has waited about four seconds on its check and is still
5470    /// waiting.
5471    Checking,
5472    /// That wait is over.
5473    Done,
5474    /// A status not yet known to this version of the crate.
5475    Unknown(String),
5476}
5477
5478impl PermissionCheckStatus {
5479    pub fn as_str(&self) -> &str {
5480        match self {
5481            Self::Checking => "checking",
5482            Self::Done => "done",
5483            Self::Unknown(s) => s.as_str(),
5484        }
5485    }
5486}
5487
5488impl fmt::Display for PermissionCheckStatus {
5489    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5490        f.write_str(self.as_str())
5491    }
5492}
5493
5494impl From<&str> for PermissionCheckStatus {
5495    fn from(s: &str) -> Self {
5496        match s {
5497            "checking" => Self::Checking,
5498            "done" => Self::Done,
5499            other => Self::Unknown(other.to_string()),
5500        }
5501    }
5502}
5503
5504impl Serialize for PermissionCheckStatus {
5505    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
5506        serializer.serialize_str(self.as_str())
5507    }
5508}
5509
5510impl<'de> Deserialize<'de> for PermissionCheckStatus {
5511    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
5512        let s = String::deserialize(deserializer)?;
5513        Ok(Self::from(s.as_str()))
5514    }
5515}
5516
5517/// One entry of [`FileAttachmentsMissingMessage::missing`].
5518#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5519pub struct MissingFileAttachment {
5520    /// The `file_uuid` of the message's `file_attachments` entry.
5521    pub file_uuid: String,
5522    /// Why, as a short code: `download`, `too_large`, `not_found` (the
5523    /// files route answered 404 or 410, so sending it again rarely helps;
5524    /// CLI 2.1.293+), `write`, `no_space` (as `write`, and the disk was
5525    /// full, so sending it again helps only once there is room; CLI
5526    /// 2.1.328+), `no_token`, `not_finished` or `count_cap`.
5527    /// More codes may be added; read an unknown one as "did not arrive".
5528    pub reason: String,
5529}
5530
5531/// `system/session_title_changed` — the session's name, for a host that
5532/// shows it (an IDE editor tab, say). A headless session sends it at startup
5533/// when the session already has a name, and again after each change to the
5534/// name (not an AI-generated title), including a rename the host itself sent
5535/// with `rename_session`. A cleared name is not sent. The same name can
5536/// arrive more than once, so treat a repeated name as no change. The frame
5537/// can arrive before the `system/init` that first names its `session_id`
5538/// (at startup or after `/clear`); a host that learns the session id from
5539/// init can hold the name until then (CLI 2.1.285+).
5540#[derive(Debug, Clone, Serialize, Deserialize)]
5541pub struct SessionTitleChangedMessage {
5542    /// The session's current name: control, bidirectional and zero-width
5543    /// characters replaced with single spaces, ends trimmed, at most 200
5544    /// Unicode code points. A suffix can make it unique when another session
5545    /// already has the name.
5546    pub title: String,
5547    pub uuid: String,
5548    pub session_id: String,
5549}
5550
5551/// `system/session_writes_lost` — the CLI could not save lines of a session
5552/// transcript, changes to `~/.claude.json`, or both, because the disk was
5553/// full or its quota was used up. Sent at most once, as the CLI exits with
5554/// status 0, after the last result if there was one. A run that exits 1, as
5555/// after an error result, gets only the line on stderr (CLI 2.1.317 and some
5556/// later releases sent this message there too). The results already received stand,
5557/// and this message does not change the exit status. Sent only with
5558/// stream-json output on stdout, never under `--sdk-url` or a Claude Desktop
5559/// entrypoint. Safe to ignore (CLI 2.1.317+).
5560#[derive(Debug, Clone, Serialize, Deserialize)]
5561pub struct SessionWritesLostMessage {
5562    /// Why the writes failed. When both kinds of write were lost for
5563    /// different reasons, the transcript's.
5564    pub error_code: SessionWriteErrorCode,
5565    /// What was not saved. Never empty.
5566    pub lost: Vec<LostSessionWrite>,
5567    /// The sessions whose transcripts lost lines, in the order each first
5568    /// lost one. Present only when [`LostSessionWrite::Transcript`] is
5569    /// listed; never empty. Usually `session_id` alone; a CLI that started a
5570    /// new session after the loss (as `/clear` does) lists the earlier
5571    /// session, and lists `session_id` only if that session lost lines too.
5572    #[serde(default, skip_serializing_if = "Option::is_none")]
5573    pub transcript_session_ids: Option<Vec<String>>,
5574    pub uuid: String,
5575    /// The session the CLI is in, as on every message; see
5576    /// [`transcript_session_ids`](Self::transcript_session_ids) for whose
5577    /// transcript lost lines.
5578    pub session_id: String,
5579}
5580
5581/// [`SessionWritesLostMessage::error_code`]: why the writes failed.
5582#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5583pub enum SessionWriteErrorCode {
5584    /// `ENOSPC` — the disk was full.
5585    Enospc,
5586    /// `EDQUOT` — the disk quota was used up.
5587    Edquot,
5588    /// A code not yet known to this version of the crate.
5589    Unknown(String),
5590}
5591
5592impl SessionWriteErrorCode {
5593    pub fn as_str(&self) -> &str {
5594        match self {
5595            Self::Enospc => "ENOSPC",
5596            Self::Edquot => "EDQUOT",
5597            Self::Unknown(s) => s.as_str(),
5598        }
5599    }
5600}
5601
5602impl fmt::Display for SessionWriteErrorCode {
5603    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5604        f.write_str(self.as_str())
5605    }
5606}
5607
5608impl From<&str> for SessionWriteErrorCode {
5609    fn from(s: &str) -> Self {
5610        match s {
5611            "ENOSPC" => Self::Enospc,
5612            "EDQUOT" => Self::Edquot,
5613            other => Self::Unknown(other.to_string()),
5614        }
5615    }
5616}
5617
5618impl Serialize for SessionWriteErrorCode {
5619    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
5620        serializer.serialize_str(self.as_str())
5621    }
5622}
5623
5624impl<'de> Deserialize<'de> for SessionWriteErrorCode {
5625    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
5626        let s = String::deserialize(deserializer)?;
5627        Ok(Self::from(s.as_str()))
5628    }
5629}
5630
5631/// One entry of [`SessionWritesLostMessage::lost`]: what was not saved.
5632#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5633pub enum LostSessionWrite {
5634    /// Lines of a session transcript, so resuming a session in
5635    /// `transcript_session_ids` may miss part of its conversation.
5636    Transcript,
5637    /// Changes this run made to `~/.claude.json`.
5638    GlobalConfig,
5639    /// A value not yet known to this version of the crate.
5640    Unknown(String),
5641}
5642
5643impl LostSessionWrite {
5644    pub fn as_str(&self) -> &str {
5645        match self {
5646            Self::Transcript => "transcript",
5647            Self::GlobalConfig => "global_config",
5648            Self::Unknown(s) => s.as_str(),
5649        }
5650    }
5651}
5652
5653impl fmt::Display for LostSessionWrite {
5654    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5655        f.write_str(self.as_str())
5656    }
5657}
5658
5659impl From<&str> for LostSessionWrite {
5660    fn from(s: &str) -> Self {
5661        match s {
5662            "transcript" => Self::Transcript,
5663            "global_config" => Self::GlobalConfig,
5664            other => Self::Unknown(other.to_string()),
5665        }
5666    }
5667}
5668
5669impl Serialize for LostSessionWrite {
5670    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
5671        serializer.serialize_str(self.as_str())
5672    }
5673}
5674
5675impl<'de> Deserialize<'de> for LostSessionWrite {
5676    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
5677        let s = String::deserialize(deserializer)?;
5678        Ok(Self::from(s.as_str()))
5679    }
5680}
5681
5682/// `system/ui_log` — one `$.ui.log(text)` line from a plugin in a headless
5683/// session: what the REPL appends to its transcript as a dim notice under
5684/// the plugin's name. Not sent to the model (CLI 2.1.285+).
5685#[derive(Debug, Clone, Serialize, Deserialize)]
5686pub struct UiLogMessage {
5687    /// The calling plugin's registry name, as the hooks engine knows it.
5688    pub plugin: String,
5689    /// The line the plugin gave: be ready for up to 10000 characters of it
5690    /// and then an ellipsis (4096 before CLI 2.1.289). Plain text: draw it
5691    /// as a text node, never as markup.
5692    pub text: String,
5693    pub uuid: String,
5694    pub session_id: String,
5695}
5696
5697/// `system/ui_notify` — one `$.ui.notify(text)` from a plugin in a headless
5698/// session: a notification for the client to raise under the plugin's name,
5699/// now or later. Nothing limits how often a plugin sends one
5700/// (CLI 2.1.321+).
5701#[derive(Debug, Clone, Serialize, Deserialize)]
5702pub struct UiNotifyMessage {
5703    /// The calling plugin's registry name, as the hooks engine knows it
5704    /// (never plugin-settable). Not cleaned as `title` is, so scrub it, and
5705    /// show it after the host's own word that a mod sent it, so neither it
5706    /// nor the title can pass for the app's own.
5707    pub plugin: String,
5708    /// The plugin's full id, `name@marketplace` (`name@inline` when
5709    /// side-loaded), as the hooks engine loaded it (never plugin-settable).
5710    /// Two plugins sharing a name differ here.
5711    pub source: String,
5712    /// The notification's heading: the plugin's words, cleaned of control
5713    /// characters and cut to 120 characters, or the plugin's name. Plain
5714    /// text, and never the only sign of who sent it.
5715    pub title: String,
5716    /// The body: the plugin's words, cleaned of control characters and cut
5717    /// to 1000 characters. Plain text: draw it as a text node, never as
5718    /// markup.
5719    pub text: String,
5720    /// The plugin's name for this notification: one with the same `source`
5721    /// and key replaces the last. Scope it by `source`, so one mod cannot
5722    /// touch another's. Absent: each frame is its own notification.
5723    #[serde(default, skip_serializing_if = "Option::is_none")]
5724    pub key: Option<String>,
5725    /// How long after this frame arrives to raise it; the client holds it,
5726    /// so it fires with the session out of reach. At most 7 days. Absent
5727    /// (with no [`at`](Self::at)): raise it now.
5728    #[serde(default, skip_serializing_if = "Option::is_none")]
5729    pub delay_ms: Option<u64>,
5730    /// The epoch-millisecond time to raise it, at most 7 days ahead. Never
5731    /// sent beside [`delay_ms`](Self::delay_ms).
5732    #[serde(default, skip_serializing_if = "Option::is_none")]
5733    pub at: Option<u64>,
5734    /// With `delay_ms` or `at`: throw it away if the person returns to the
5735    /// session before it fires.
5736    #[serde(default, skip_serializing_if = "Option::is_none")]
5737    pub until_back: Option<bool>,
5738    /// True when what this frame carries differs from what the sender sent
5739    /// and another plugin's hook was in the chain: its words, timing or key
5740    /// may not be the sender's, so say so beside the sender. Always sent;
5741    /// missing (from an older engine) reads as false. Never plugin-settable.
5742    #[serde(default)]
5743    pub rewritten: bool,
5744    pub uuid: String,
5745    pub session_id: String,
5746}
5747
5748/// `system/ui_notify_cancel` — one `$.ui.cancelNotify(key)` from a plugin in
5749/// a headless session, or the engine removing a plugin: remove the
5750/// notification with this `source` and `key`, shown or still waiting. None
5751/// held under that key: do nothing (CLI 2.1.321+).
5752#[derive(Debug, Clone, Serialize, Deserialize)]
5753pub struct UiNotifyCancelMessage {
5754    /// The plugin's registry name, as the hooks engine knows it (never
5755    /// plugin-settable).
5756    pub plugin: String,
5757    /// The plugin's full id, as on [`UiNotifyMessage::source`] (never
5758    /// plugin-settable). Only notifications of this source are touched.
5759    pub source: String,
5760    /// The [`UiNotifyMessage::key`] of the notification to take back.
5761    /// Absent: the engine removed the plugin from this session, so drop
5762    /// everything this source has waiting for this session. Only the engine
5763    /// sends that.
5764    #[serde(default, skip_serializing_if = "Option::is_none")]
5765    pub key: Option<String>,
5766    pub uuid: String,
5767    pub session_id: String,
5768}
5769
5770/// `system/ui_toast` — one `$.ui.toast(text)` from a plugin in a headless
5771/// session: what the REPL shows on the notification bar under the prompt
5772/// for a few seconds, under the plugin's name. Toasts arrive at no fixed
5773/// rate: CLI 2.1.289 dropped the hooks host's 2 s spacing (CLI 2.1.285+).
5774#[derive(Debug, Clone, Serialize, Deserialize)]
5775pub struct UiToastMessage {
5776    /// The calling plugin's registry name, as the hooks engine knows it.
5777    pub plugin: String,
5778    /// The line the plugin gave: be ready for up to 10000 characters of it
5779    /// and then an ellipsis (4096 before CLI 2.1.289). Plain text: draw it
5780    /// as a text node, never as markup.
5781    pub text: String,
5782    /// How long the REPL would keep it on the notification bar: the plugin's
5783    /// `timeoutMs`, or the engine's default (4000).
5784    pub timeout_ms: u64,
5785    pub uuid: String,
5786    pub session_id: String,
5787}
5788
5789/// `system/ui_status` — one `$.ui.status(text)` from a plugin in a headless
5790/// session: the line the REPL pins under the prompt until the plugin's next
5791/// call replaces or clears it. One status line per plugin (CLI 2.1.285+).
5792#[derive(Debug, Clone, Serialize, Deserialize)]
5793pub struct UiStatusMessage {
5794    /// The calling plugin's registry name, as the hooks engine knows it.
5795    pub plugin: String,
5796    /// The plugin's pinned line, replacing its previous one; `None` (wire
5797    /// `null`) removes it. Be ready for up to 10000 characters of it and
5798    /// then an ellipsis (4096 before CLI 2.1.289). Plain text: draw it as a
5799    /// text node, never as markup.
5800    pub text: Option<String>,
5801    pub uuid: String,
5802    pub session_id: String,
5803}
5804
5805/// `system/ui_invalidate` — a plugin called `$.ui.invalidate("ui.render")`,
5806/// a plugin loaded or reloaded, or (CLI 2.1.318+) a mobile client already
5807/// known to the session named a field (or, on CLI 2.1.323+, `Progress`) in
5808/// `draws` it had not named before:
5809/// every tree a remote surface drew through `ui_render` may be stale, and the surface re-asks each mounted instance.
5810/// Bumps from one plugin fold to at most one per 100 ms (CLI 2.1.285+).
5811#[derive(Debug, Clone, Serialize, Deserialize)]
5812pub struct UiInvalidateMessage {
5813    /// The render event whose version moved — `"ui.render"`; the engine
5814    /// versions it as one event, so no component or instance is named.
5815    pub event: String,
5816    /// Present when a plugin state write, or (CLI 2.1.289+) a `Client`
5817    /// drawn in them that failed and whose plugin heard it (`ui.fault`),
5818    /// made only these instances stale, so the surface may re-ask them
5819    /// alone. The theme of the session being set or cleared
5820    /// (`$.theme.set` / `$.theme.clear` on CLI 2.1.319+), or a client of a
5821    /// surface that draws it joining where one ever stood, names the
5822    /// `Theme` instance (`instance_id` `theme`, CLI 2.1.321+) on each such
5823    /// surface, and the instance whose `instance_id` is `backdrop`; on CLI
5824    /// 2.1.323+ the `backdrop` one only where the scene changed or a client
5825    /// joined.
5826    /// Absent, every mounted instance may be stale.
5827    #[serde(default, skip_serializing_if = "Option::is_none")]
5828    pub instances: Option<Vec<UiInvalidatedInstance>>,
5829    /// Present, and true, while a mod may change what is recorded of a typed
5830    /// line (a hook on `prompt.submit`, `command.run`, `session.append` or
5831    /// `session.receive`, mods not yet known, or an organization policy that
5832    /// lists a plugin or cannot be read): what the `prompts_screened_v1`
5833    /// capability says on `system/init`, sent as soon as a plugin load or
5834    /// reload makes it so. Absent says nothing; the next `system/init` does
5835    /// (CLI 2.1.300+).
5836    #[serde(default, skip_serializing_if = "Option::is_none")]
5837    pub prompts_screened: Option<bool>,
5838    /// On a push with no [`instances`](Self::instances): the list the
5839    /// `ui_attach` answer carries under this name, as it stands now,
5840    /// replacing the last one sent. If absent, the surface asks as before.
5841    /// Marked `@internal` upstream (CLI 2.1.330+).
5842    #[serde(default, skip_serializing_if = "Option::is_none")]
5843    pub unhooked: Option<Vec<String>>,
5844    pub uuid: String,
5845    pub session_id: String,
5846}
5847
5848/// One stale instance named by [`UiInvalidateMessage::instances`].
5849#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5850pub struct UiInvalidatedInstance {
5851    /// The surface that drew the instance.
5852    pub surface: String,
5853    /// The component of the instance.
5854    pub component: String,
5855    /// The engine's requestId of the instance, as the `ui_render` that drew
5856    /// it named it.
5857    pub instance_id: String,
5858}
5859
5860/// `system/ui_panes` — the pane roster a remote surface draws changed: a
5861/// plugin opened, retitled or closed a pane, the person showed, focused or
5862/// closed one, or a placing client attached. Deduplicated: an unchanged
5863/// roster is not pushed. A pane opened before the stream armed produces
5864/// none, so read the roster with a `ui_panes` request on mount
5865/// (CLI 2.1.285+).
5866#[derive(Debug, Clone, Serialize, Deserialize)]
5867pub struct UiPanesMessage {
5868    /// The placed open panes in open order (an open appends, a close
5869    /// removes); a pane waiting unplaced is not listed.
5870    pub panes: Vec<UiPane>,
5871    /// The pane the surface shows: the last opened or focused, never
5872    /// displacing one the person holds; `None` with none open.
5873    pub shown_id: Option<String>,
5874    /// The pane the person gave the keyboard; `None` while the composer has
5875    /// it.
5876    pub focused_id: Option<String>,
5877    /// A standing `$.ui.open({ focus: true })` the surface has yet to judge:
5878    /// honour it only while the composer is empty and idle and no dialog is
5879    /// up, else refuse it.
5880    pub focus_requested_id: Option<String>,
5881    pub uuid: String,
5882    pub session_id: String,
5883}
5884
5885/// One placed pane in a [`UiPanesMessage`] roster.
5886#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5887pub struct UiPane {
5888    /// The pane's id as the plugin opened it: 1 to 64 of letters, digits,
5889    /// `_`, `-`.
5890    pub id: String,
5891    /// The pane's tab label: the `title` its latest open gave, else its id.
5892    /// Plugin-authored text: draw it as a text node, never as markup.
5893    pub title: String,
5894    /// The registry name of the plugin that opened it.
5895    pub plugin: String,
5896    /// `true`: Escape while the pane holds the keyboard, or at an idle empty
5897    /// composer, closes it. Absent, Escape only returns the keyboard.
5898    #[serde(default, skip_serializing_if = "Option::is_none")]
5899    pub close_on_escape: Option<bool>,
5900    /// `true`: the surface holds its transient toasts while this pane is
5901    /// the one shown, and shows them once it closes.
5902    #[serde(default, skip_serializing_if = "Option::is_none")]
5903    pub hold_toasts: Option<bool>,
5904    /// What the surface paints under this pane's body while it is the one
5905    /// shown: a theme key, a raw color, or `transparent` for nothing.
5906    /// Plugin-authored: parse it, never write it into a style. Absent, the
5907    /// surface's own look stands (CLI 2.1.311+).
5908    #[serde(default, skip_serializing_if = "Option::is_none")]
5909    pub background_color: Option<String>,
5910    /// The body rows its content asked for while seated inline; a request
5911    /// the person's own sizing overrides.
5912    #[serde(default, skip_serializing_if = "Option::is_none")]
5913    pub rows: Option<u64>,
5914    /// The body columns its content asked for while docked; a request the
5915    /// person's own sizing overrides.
5916    #[serde(default, skip_serializing_if = "Option::is_none")]
5917    pub columns: Option<u64>,
5918    /// `widget` when the pane's latest open asked to start as a widget, the
5919    /// small form of a minimized pane. A request, repeated on every roster
5920    /// while it stands: honour it on first seeing the pane; after that the
5921    /// person's expand or minimize stands. The CLI reads any other value as
5922    /// absent, so treat unrecognized values the same. Marked `@internal`
5923    /// upstream (CLI 2.1.323+).
5924    #[serde(default, skip_serializing_if = "Option::is_none")]
5925    pub placement: Option<String>,
5926}
5927
5928/// `system/ui_placed` — a fire-and-forget push from a headless session when
5929/// a plugin places a row with `$.ui.place`, and to a client as it joins
5930/// (CLI 2.1.314+). A surface inserts each row after
5931/// [`UiPlacedRow::after_uuid`] and asks `ui_render` for it. Display only:
5932/// no message carries these rows. A surface drops the rows it holds with
5933/// the conversation it resets, and a row whose `after_uuid` it no longer
5934/// holds. A compaction ends the rows before it, and no push says so.
5935#[derive(Debug, Clone, Serialize, Deserialize)]
5936pub struct UiPlacedMessage {
5937    /// The main conversation's placed rows, in order.
5938    pub rows: Vec<UiPlacedRow>,
5939    pub uuid: String,
5940    pub session_id: String,
5941}
5942
5943/// One row in a [`UiPlacedMessage`].
5944#[derive(Debug, Clone, Serialize, Deserialize)]
5945pub struct UiPlacedRow {
5946    /// The plugin that placed the row.
5947    pub plugin: String,
5948    /// The row's id among that plugin's rows.
5949    pub id: String,
5950    /// The `instance_id` of the `ui_render` ask, with `component: "Placed"`,
5951    /// that draws it.
5952    pub request_id: String,
5953    /// The conversation message the row follows; absent at the
5954    /// conversation's start. Rows sharing it stand in roster order.
5955    #[serde(default, skip_serializing_if = "Option::is_none")]
5956    pub after_uuid: Option<String>,
5957}
5958
5959/// `system/ui_scroll` — a plugin's `$.ui.scroll` moved the window of a site
5960/// a remote surface draws: the surface scrolls the site's body there. The
5961/// person's own scrolls are never pushed back (CLI 2.1.285+).
5962#[derive(Debug, Clone, Serialize, Deserialize)]
5963pub struct UiScrollMessage {
5964    /// The client drawing the site, as it attached.
5965    pub client_id: String,
5966    /// Which site: a pane's body or the band above the prompt.
5967    pub component: UiSiteComponent,
5968    /// The pane's id, or `above-prompt` for the band.
5969    pub instance_id: String,
5970    /// The first content row the window is to show, 0 at the top, clamped
5971    /// to the tree as the surface last reported it.
5972    pub offset: u64,
5973    /// `true`: keep the window on the tree's last rows through the draws to
5974    /// come, until the person or a plugin next moves it.
5975    #[serde(default, skip_serializing_if = "Option::is_none")]
5976    pub follow_end: Option<bool>,
5977    pub uuid: String,
5978    pub session_id: String,
5979}
5980
5981/// `system/ui_focus` — a plugin's `$.ui.focus` moved the focus ring of a
5982/// site a remote surface draws onto one of its Buttons, Inputs or Selects:
5983/// the surface focuses that element if it still draws it. The person's own
5984/// moves are never pushed back (CLI 2.1.285+).
5985#[derive(Debug, Clone, Serialize, Deserialize)]
5986pub struct UiFocusMessage {
5987    /// The client drawing the site, as it attached.
5988    pub client_id: String,
5989    /// Which site: a pane's body or the band above the prompt.
5990    pub component: UiSiteComponent,
5991    /// The pane's id, or `above-prompt` for the band.
5992    pub instance_id: String,
5993    /// Whose element takes the ring: its `press.plugin`.
5994    pub plugin: String,
5995    /// The element's `props.key`, as `ui.press` names it.
5996    pub key: String,
5997    pub uuid: String,
5998    pub session_id: String,
5999}
6000
6001/// The site a [`UiScrollMessage`] or [`UiFocusMessage`] addresses.
6002#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6003pub enum UiSiteComponent {
6004    /// A pane's body.
6005    Pane,
6006    /// The band above the prompt.
6007    AbovePrompt,
6008    /// A site not yet known to this version of the crate.
6009    Unknown(String),
6010}
6011
6012impl UiSiteComponent {
6013    pub fn as_str(&self) -> &str {
6014        match self {
6015            Self::Pane => "Pane",
6016            Self::AbovePrompt => "AbovePrompt",
6017            Self::Unknown(s) => s.as_str(),
6018        }
6019    }
6020}
6021
6022impl fmt::Display for UiSiteComponent {
6023    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6024        f.write_str(self.as_str())
6025    }
6026}
6027
6028impl From<&str> for UiSiteComponent {
6029    fn from(s: &str) -> Self {
6030        match s {
6031            "Pane" => Self::Pane,
6032            "AbovePrompt" => Self::AbovePrompt,
6033            other => Self::Unknown(other.to_string()),
6034        }
6035    }
6036}
6037
6038impl Serialize for UiSiteComponent {
6039    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
6040        serializer.serialize_str(self.as_str())
6041    }
6042}
6043
6044impl<'de> Deserialize<'de> for UiSiteComponent {
6045    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
6046        let s = String::deserialize(deserializer)?;
6047        Ok(Self::from(s.as_str()))
6048    }
6049}
6050
6051/// The run that printed a local-command row, carried as
6052/// [`AssistantMessage::local_command_run`].
6053#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6054pub struct LocalCommandRun {
6055    /// The command's name as `command.run` carried it (no slash).
6056    pub command: String,
6057    /// Its arguments as the echo shows them (`***` when the command marks
6058    /// them sensitive).
6059    pub args: String,
6060    /// For a command a plugin registered, that plugin's name; for a row
6061    /// whose text plugins' `command.run` hooks answered or retold, the names
6062    /// the text is led by. Untrusted text; absent for the binary's own
6063    /// command in its own words (CLI 2.1.300+).
6064    #[serde(default, skip_serializing_if = "Option::is_none")]
6065    pub plugin: Option<String>,
6066}
6067
6068/// What a local-command row reports, carried as
6069/// [`AssistantMessage::local_command_outcome`] so a host can offer a fix
6070/// instead of relaying the text (CLI 2.1.281+).
6071#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6072pub struct LocalCommandOutcome {
6073    pub kind: LocalCommandOutcomeKind,
6074    /// Kind `unknown` only: the registered command closest to the typed
6075    /// name, no slash.
6076    #[serde(default, skip_serializing_if = "Option::is_none")]
6077    pub suggestion: Option<String>,
6078}
6079
6080/// The outcome a local-command row reports ([`LocalCommandOutcome::kind`]).
6081/// New kinds are additive; the CLI itself drops the whole outcome when it
6082/// meets a kind it does not know, so treat [`Unknown`](Self::Unknown) as
6083/// absent.
6084#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6085pub enum LocalCommandOutcomeKind {
6086    /// An interactive-panel command this (headless) session cannot open.
6087    UnavailableHeadless,
6088    /// No command has the typed name; see
6089    /// [`LocalCommandOutcome::suggestion`].
6090    Unknown,
6091    /// The command ran and failed.
6092    Failed,
6093    /// The change applies after Claude Code restarts.
6094    RestartRequired,
6095    /// A kind not yet known to this version of the crate.
6096    Other(String),
6097}
6098
6099impl LocalCommandOutcomeKind {
6100    pub fn as_str(&self) -> &str {
6101        match self {
6102            Self::UnavailableHeadless => "unavailable_headless",
6103            Self::Unknown => "unknown",
6104            Self::Failed => "failed",
6105            Self::RestartRequired => "restart_required",
6106            Self::Other(s) => s.as_str(),
6107        }
6108    }
6109}
6110
6111impl fmt::Display for LocalCommandOutcomeKind {
6112    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6113        f.write_str(self.as_str())
6114    }
6115}
6116
6117impl From<&str> for LocalCommandOutcomeKind {
6118    fn from(s: &str) -> Self {
6119        match s {
6120            "unavailable_headless" => Self::UnavailableHeadless,
6121            "unknown" => Self::Unknown,
6122            "failed" => Self::Failed,
6123            "restart_required" => Self::RestartRequired,
6124            other => Self::Other(other.to_string()),
6125        }
6126    }
6127}
6128
6129impl Serialize for LocalCommandOutcomeKind {
6130    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
6131        serializer.serialize_str(self.as_str())
6132    }
6133}
6134
6135impl<'de> Deserialize<'de> for LocalCommandOutcomeKind {
6136    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
6137        let s = String::deserialize(deserializer)?;
6138        Ok(Self::from(s.as_str()))
6139    }
6140}
6141
6142/// Structured twin of a `/usage` result, carried as
6143/// [`AssistantMessage::usage_report`]: the session's totals, the plan's
6144/// usage rows as the server sent them and the extra-usage spend, and nothing
6145/// else from the usage body (the `get_usage` control reply carries the
6146/// rest). Experimental — the shape may change.
6147#[derive(Debug, Clone, Serialize, Deserialize)]
6148pub struct UsageReport {
6149    /// Cost and usage accumulated by the current session.
6150    pub session: super::control::UsageSession,
6151    /// The plan's usage rows and extra-usage spend from the claude.ai usage
6152    /// endpoint; `None` when the CLI could not fetch them (no plan on this
6153    /// lane, or a token without the profile scope).
6154    pub rate_limits: Option<UsageReportRateLimits>,
6155    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
6156    pub extra: serde_json::Map<String, Value>,
6157}
6158
6159/// The plan's usage rows and extra-usage spend in a [`UsageReport`].
6160#[derive(Debug, Clone, Serialize, Deserialize)]
6161pub struct UsageReportRateLimits {
6162    /// The server's usage rows (the usage endpoint's `limits[]`), as sent:
6163    /// which meters apply, their scope, labels, severity and order are the
6164    /// server's, so a client renders them verbatim. Empty when the server
6165    /// reported no meters; `None` when the body carried no rows at all (a
6166    /// server that predates them). When the usage fetch failed and the CLI
6167    /// fell back to rate-limit response headers, this holds at most the one
6168    /// row it synthesizes from them.
6169    pub limits: Option<Vec<UsageReportLimit>>,
6170    /// Extra-usage (overage) spend for the billing period, when the plan
6171    /// has it.
6172    #[serde(default, skip_serializing_if = "Option::is_none")]
6173    pub extra_usage: Option<UsageReportExtraUsage>,
6174    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
6175    pub extra: serde_json::Map<String, Value>,
6176}
6177
6178/// One server usage row in [`UsageReportRateLimits::limits`].
6179#[derive(Debug, Clone, Serialize, Deserialize)]
6180pub struct UsageReportLimit {
6181    /// The server's meter kind, e.g. `session`, `weekly_all` or
6182    /// `weekly_scoped`. Classify a row on this, never on a label.
6183    pub kind: String,
6184    /// The server's row group, e.g. `session` or `weekly`; rows render
6185    /// grouped under it, in the server's order.
6186    pub group: String,
6187    /// Share of the window used, 0–100.
6188    pub percent: f64,
6189    /// ISO 8601 timestamp when the window resets.
6190    pub resets_at: Option<String>,
6191    /// What a scoped row is for, a model or a surface, with the server's
6192    /// display label.
6193    #[serde(default, skip_serializing_if = "Option::is_none")]
6194    pub scope: Option<UsageReportScope>,
6195    /// The server's reading of the row for a meter's colour, e.g. `normal`,
6196    /// `warning` or `critical`; a client falls back to its own thresholds
6197    /// without it.
6198    #[serde(default, skip_serializing_if = "Option::is_none")]
6199    pub severity: Option<String>,
6200    /// The server's headline pick: the row a single-value indicator shows.
6201    #[serde(default, skip_serializing_if = "Option::is_none")]
6202    pub is_active: Option<bool>,
6203    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
6204    pub extra: serde_json::Map<String, Value>,
6205}
6206
6207/// What a scoped [`UsageReportLimit`] row is for.
6208#[derive(Debug, Clone, Serialize, Deserialize)]
6209pub struct UsageReportScope {
6210    #[serde(default, skip_serializing_if = "Option::is_none")]
6211    pub model: Option<UsageReportScopeLabel>,
6212    #[serde(default, skip_serializing_if = "Option::is_none")]
6213    pub surface: Option<UsageReportScopeLabel>,
6214    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
6215    pub extra: serde_json::Map<String, Value>,
6216}
6217
6218/// The server's display label for a [`UsageReportScope`] member.
6219#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6220pub struct UsageReportScopeLabel {
6221    pub display_name: String,
6222}
6223
6224/// Extra-usage (overage) spend for the billing period in a
6225/// [`UsageReportRateLimits`]. Amounts are in minor units of `currency`
6226/// (cents for USD).
6227#[derive(Debug, Clone, Serialize, Deserialize)]
6228pub struct UsageReportExtraUsage {
6229    /// `false` while extra usage cannot cover sends.
6230    pub is_enabled: bool,
6231    pub monthly_limit: Option<f64>,
6232    pub used_credits: Option<f64>,
6233    pub utilization: Option<f64>,
6234    #[serde(default, skip_serializing_if = "Option::is_none")]
6235    pub currency: Option<String>,
6236    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
6237    pub extra: serde_json::Map<String, Value>,
6238}
6239
6240/// `{id, name}` of an original `Batch*` tool_use block, carried in
6241/// [`AssistantMessage::batch_tool_uses`].
6242#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6243pub struct BatchToolUse {
6244    pub id: String,
6245    pub name: String,
6246}
6247
6248/// Structured twin of the `/context` report, carried as
6249/// [`AssistantMessage::context_usage`] — the data a client needs to render
6250/// the context-usage card without parsing the markdown table. Evolves
6251/// additively; a breaking reshape would ship as a sibling field.
6252#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6253pub struct ContextUsage {
6254    /// Main-loop model the usage was computed for.
6255    pub model: String,
6256    /// Estimated tokens in use, unclamped — may exceed `raw_max_tokens` when
6257    /// over limit.
6258    pub total_tokens: u64,
6259    /// The window usage is measured against: the resolved autocompact window —
6260    /// the model's believed limit, or a smaller compaction-policy window.
6261    pub raw_max_tokens: u64,
6262    /// Rounded `total_tokens / raw_max_tokens`, 0–100+.
6263    pub percentage: u64,
6264    /// Present when `total_tokens` exceeds `raw_max_tokens`.
6265    #[serde(default, skip_serializing_if = "Option::is_none")]
6266    pub over_limit: Option<ContextOverLimit>,
6267    /// Usage-by-category rows (`Messages`, `System prompt`, …).
6268    #[serde(default)]
6269    pub categories: Vec<ContextCategory>,
6270    /// Per-tool token contributions of MCP tools.
6271    #[serde(default)]
6272    pub mcp_tools: Vec<ContextMcpTool>,
6273    /// Per-file token contributions of memory files.
6274    #[serde(default)]
6275    pub memory_files: Vec<ContextMemoryFile>,
6276    /// Per-agent token contributions of agent definitions.
6277    #[serde(default)]
6278    pub agents: Vec<ContextAgent>,
6279    /// Per-skill token contributions. Omitted when no skills contribute.
6280    #[serde(default, skip_serializing_if = "Option::is_none")]
6281    pub skills: Option<Vec<ContextSkill>>,
6282}
6283
6284/// Why and by how much a [`ContextUsage`] exceeds its window.
6285#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6286pub struct ContextOverLimit {
6287    pub tokens_over: u64,
6288    /// How the window was resolved: `"hard_limit"` (the model's believed
6289    /// limit) or `"compaction_window"` (a compaction-policy window).
6290    pub kind: String,
6291}
6292
6293/// One row of the `/context` usage-by-category breakdown.
6294#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6295pub struct ContextCategory {
6296    /// Display name of the row as the CLI renders it, e.g. `"Messages"`.
6297    /// Use `kind` (not this name) to classify the row.
6298    pub name: String,
6299    pub tokens: u64,
6300    /// What the row is: `"used"` content occupies the window; `"free"` is the
6301    /// remaining window; `"buffer"` is the compaction reserve; `"deferred"`
6302    /// rows are out-of-window tool schemas, excluded from usage math.
6303    pub kind: String,
6304}
6305
6306/// An MCP tool's token contribution, in [`ContextUsage::mcp_tools`].
6307#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6308pub struct ContextMcpTool {
6309    /// Wire name, e.g. `"mcp__linear__create_issue"`.
6310    pub name: String,
6311    pub server_name: String,
6312    pub tokens: u64,
6313}
6314
6315/// A memory file's token contribution, in [`ContextUsage::memory_files`].
6316#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6317pub struct ContextMemoryFile {
6318    pub path: String,
6319    /// Display label of the memory-file source, e.g. `"Project"` or `"User"`.
6320    #[serde(rename = "type")]
6321    pub file_type: String,
6322    pub tokens: u64,
6323}
6324
6325/// An agent definition's token contribution, in [`ContextUsage::agents`].
6326#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6327pub struct ContextAgent {
6328    pub agent_type: String,
6329    /// Raw source identifier, e.g. `"projectSettings"`, `"plugin"`.
6330    pub source: String,
6331    pub tokens: u64,
6332}
6333
6334/// A skill's token contribution, in [`ContextUsage::skills`].
6335#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6336pub struct ContextSkill {
6337    pub name: String,
6338    /// Raw source identifier, e.g. `"userSettings"`, `"plugin"`.
6339    pub source: String,
6340    #[serde(default, skip_serializing_if = "Option::is_none")]
6341    pub plugin_name: Option<String>,
6342    pub tokens: u64,
6343}
6344
6345/// Display metadata for a tool-use block carried on the assistant wrapper.
6346#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6347pub struct ToolUseMeta {
6348    pub id: String,
6349    pub display_name: String,
6350    #[serde(default, skip_serializing_if = "Option::is_none")]
6351    pub server_display_name: Option<String>,
6352    #[serde(default, skip_serializing_if = "Option::is_none")]
6353    pub icon_url: Option<String>,
6354    /// The `mcpsrv_` connector id of a server provisioned by claude.ai, set
6355    /// by the CLI from claude.ai's own connector listing, so a client may
6356    /// show the call as that connector's. Not a permission grant (CLI
6357    /// 2.1.300+).
6358    #[serde(default, skip_serializing_if = "Option::is_none")]
6359    pub server_id: Option<String>,
6360    /// The `X-MCP-Server-ID` header value, lower-cased, of an http entry in
6361    /// the dynamic scope (passed at launch or by a later `mcp_set_servers`
6362    /// push). The CLI checks only its shape, not whose it is: look it up in
6363    /// your own server list, treat a miss as an unknown server (never an
6364    /// error), and show a hit as the entry's claim, not proof. Separate from
6365    /// [`server_id`](Self::server_id); both are absent for plugin, repo,
6366    /// settings and agent entries (CLI 2.1.300+).
6367    #[serde(default, skip_serializing_if = "Option::is_none")]
6368    pub server_id_stamp: Option<String>,
6369    /// The tool's name as its server lists it, without the
6370    /// `mcp__<server>__` prefix (CLI 2.1.300+).
6371    #[serde(default, skip_serializing_if = "Option::is_none")]
6372    pub tool_name: Option<String>,
6373    /// `Some(true)` on a call to a publishing tool of an Artifacts MCP entry
6374    /// that reaches only Anthropic's server, which the CLI tells from the
6375    /// entry itself, never its name. The finished call's `tool_use_result`
6376    /// usually carries the artifact's url at its top level, its title where
6377    /// the server's answer has one, and (CLI 2.1.328+) `type.url`, the link
6378    /// of the Artifact type it was made from, where the CLI knows it. The
6379    /// mark promises none of these, and any of them can come on an unmarked
6380    /// call; all are the worker's word, not proof. Sent only on the main
6381    /// loop's own frames: never for a subagent's call or over Remote Control
6382    /// (CLI 2.1.321+).
6383    #[serde(default, skip_serializing_if = "Option::is_none")]
6384    pub artifact_publish: Option<bool>,
6385}
6386
6387/// Assistant message
6388#[derive(Debug, Clone, Serialize, Deserialize)]
6389pub struct AssistantMessage {
6390    pub message: AssistantMessageContent,
6391    #[serde(alias = "sessionId")]
6392    pub session_id: String,
6393    #[serde(skip_serializing_if = "Option::is_none")]
6394    pub uuid: Option<String>,
6395    #[serde(skip_serializing_if = "Option::is_none")]
6396    pub parent_tool_use_id: Option<String>,
6397    /// Anthropic API request id that produced this message (e.g. `req_...`).
6398    #[serde(skip_serializing_if = "Option::is_none")]
6399    pub request_id: Option<String>,
6400    /// Only on the assistant message that reports a refusal: the API `msg_*`
6401    /// id of the refused response (`message.id` on this message is a local
6402    /// UUID). Absent when the CLI has no well-formed id for it, and on CLIs
6403    /// before 2.1.301.
6404    #[serde(default, skip_serializing_if = "Option::is_none")]
6405    pub refused_message_id: Option<String>,
6406    /// Client uuid of the user message that triggered this turn, stamped on
6407    /// the turn's first top-level assistant message so a consumer can bind
6408    /// the reply to the send it answers without waiting for the result. With
6409    /// `--include-partial-messages` the first non-ping stream event is
6410    /// stamped too, independently (CLI 2.1.269+), so the same uuid may
6411    /// appear on both frames. Absent on every later assistant message of the
6412    /// turn, on subagent frames, on synthetic/scheduled (meta) turns, and
6413    /// from CLIs before 2.1.259.
6414    #[serde(default, skip_serializing_if = "Option::is_none")]
6415    pub user_message_uuid: Option<String>,
6416    /// Client uuids of every user message whose prompt this turn has consumed
6417    /// so far, in consumption order — all members of a prompt batch the host
6418    /// merged into this one turn. Always contains `user_message_uuid`; at
6419    /// most 64 entries. Present exactly when `user_message_uuid` is; absent
6420    /// from CLIs before 2.1.259 (fall back to `user_message_uuid`).
6421    #[serde(default, skip_serializing_if = "Vec::is_empty")]
6422    pub user_message_uuids: Vec<String>,
6423    /// ID of the subagent that produced this message: the `task_id` of its
6424    /// task events, unchanged when the subagent is resumed. Absent on
6425    /// main-thread messages (CLI 2.1.292+).
6426    #[serde(default, skip_serializing_if = "Option::is_none")]
6427    pub agent_id: Option<String>,
6428    /// Subagent type, when this assistant message was produced inside a
6429    /// `local_agent` subagent (e.g. `general-purpose`, `Explore`).
6430    #[serde(skip_serializing_if = "Option::is_none")]
6431    pub subagent_type: Option<String>,
6432    /// Short description of the subagent task, present alongside `subagent_type`.
6433    #[serde(skip_serializing_if = "Option::is_none")]
6434    pub task_description: Option<String>,
6435    #[serde(skip_serializing_if = "Option::is_none")]
6436    pub error: Option<AssistantErrorKind>,
6437    /// True when this message was truncated by an interrupt/abort before the
6438    /// stream completed — `stop_reason` was never received and the content
6439    /// may end mid-word. Absent on normally completed messages.
6440    #[serde(default, skip_serializing_if = "Option::is_none")]
6441    pub aborted: Option<bool>,
6442    /// True when this turn continued the preceding truncated assistant turn
6443    /// inside its trailing signed thinking block (max-output-tokens
6444    /// recovery). Histories replayed through the bridge must carry the flag
6445    /// back so the normalizer keeps the run's prefix on the wire.
6446    #[serde(default, skip_serializing_if = "Option::is_none")]
6447    pub resumed_from_incomplete_thinking: Option<bool>,
6448    /// Uuids of earlier messages that this message replaces: after a refusal
6449    /// fallback, or (CLI 2.1.323+) after a response whose tool call could not
6450    /// be parsed. It can name user messages too, such as a refused attempt's
6451    /// tool results. Remove the named messages when this one arrives. After a
6452    /// refusal fallback it is idempotent with the end-of-turn
6453    /// `system/model_refusal_fallback` notice.
6454    #[serde(default, skip_serializing_if = "Vec::is_empty")]
6455    pub supersedes: Vec<String>,
6456    #[serde(skip_serializing_if = "Option::is_none")]
6457    pub timestamp: Option<String>,
6458    #[serde(default, skip_serializing_if = "Vec::is_empty")]
6459    pub tool_use_meta: Vec<ToolUseMeta>,
6460    /// `{id, name}` of the original `Batch*` tool_use block(s) for a message
6461    /// whose content was decomposed into synthetic v1 tool_use blocks.
6462    /// Round-tripped so a replayed history reassembles the batch block on the
6463    /// wire. Wrapper-level sibling — never inside `message.content`.
6464    #[serde(default, skip_serializing_if = "Vec::is_empty")]
6465    pub batch_tool_uses: Vec<BatchToolUse>,
6466    /// `tool_use.input` exactly as the API produced it, keyed by `tool_use`
6467    /// id, for a message whose `message.content` carries the
6468    /// client-normalized input. Round-tripped so a replayed history echoes
6469    /// each earlier tool call back to the API as the API emitted it.
6470    /// Wrapper-level sibling — never inside `message.content` (CLI 2.1.259+).
6471    #[serde(default, skip_serializing_if = "Option::is_none")]
6472    pub wire_tool_inputs: Option<serde_json::Map<String, Value>>,
6473    /// What the client-side input normalization read from process state for
6474    /// the inputs in [`wire_tool_inputs`](Self::wire_tool_inputs), keyed by
6475    /// the same `tool_use` ids. Round-tripped so a replayed history can verify
6476    /// each recorded input against the normalized one. Wrapper-level sibling —
6477    /// never inside `message.content` (CLI 2.1.266+).
6478    #[serde(default, skip_serializing_if = "Option::is_none")]
6479    pub wire_ingest_context: Option<serde_json::Map<String, Value>>,
6480    /// Replayed history rather than a live message, stamped by the Remote
6481    /// Control bridge when it flushes history to the session server, which
6482    /// also stamps it on deliveries it replays (CLI 2.1.266+).
6483    #[serde(default, skip_serializing_if = "Option::is_none")]
6484    pub historical: Option<bool>,
6485    /// Why this frame's turn is the automatic re-run of a turn a worker
6486    /// restart interrupted: the host's `CLAUDE_CODE_RESUME_REASON` when it set
6487    /// one (`host_draining`, `checkpoint_restore`, `container_recreated`,
6488    /// ...), else `interrupted_turn`. Stamped on the same reply frames as
6489    /// `user_message_uuid`, which on such a re-run names the interrupted
6490    /// turn's own last user prompt. Absent on every other turn and from CLIs
6491    /// before 2.1.268.
6492    #[serde(default, skip_serializing_if = "Option::is_none")]
6493    pub resume_reason: Option<String>,
6494    /// The originating `system/local_command` row's wire-form content,
6495    /// carried on the loop-synthesized local-command twin so a bridge/SDK
6496    /// history replay rebuilds the internal system row instead of dropping
6497    /// the output. Wrapper-level sibling — never inside `message.content`
6498    /// (CLI 2.1.259+).
6499    #[serde(default, skip_serializing_if = "Option::is_none")]
6500    pub local_command_source: Option<String>,
6501    /// Ascending zero-based indexes into `message.content` of the thinking
6502    /// blocks whose signature the server tagged as narration (server
6503    /// summaries of the prose between tool calls, not the model's own
6504    /// reasoning), so a renderer can label them as summaries without decoding
6505    /// the signature envelope. Fail-closed: an unparseable or legacy
6506    /// signature is not listed. Omitted when the frame has no such block and
6507    /// by CLIs before 2.1.260; treat unlisted thinking blocks as ordinary
6508    /// thinking. Wrapper-level sibling — never inside `message.content`.
6509    #[serde(default, skip_serializing_if = "Vec::is_empty")]
6510    pub narration_block_indexes: Vec<usize>,
6511    /// How a renderer should treat this frame's narration blocks:
6512    /// `"hidden"` or `"faint"` on CLI 2.1.280+ (kept open for future
6513    /// values). Omitted when the CLI expresses no preference.
6514    #[serde(default, skip_serializing_if = "Option::is_none")]
6515    pub narration_hint: Option<String>,
6516    /// How long the thinking block in this frame took to stream, in whole
6517    /// milliseconds (at least 1): from its `content_block_start` to its
6518    /// `content_block_stop` (or, on CLI 2.1.321+, to the interrupt that cut
6519    /// it), so the wait for the response's first token is not counted. For display only. Sent only on a frame whose one content
6520    /// block is a thinking block that was streamed; absent from CLIs before
6521    /// 2.1.287 and from a CLI replaying history it rebuilt from SDK frames,
6522    /// so be ready to show the block without a duration. Wrapper-level
6523    /// sibling — never inside `message.content`.
6524    #[serde(default, skip_serializing_if = "Option::is_none")]
6525    pub thinking_duration_ms: Option<u64>,
6526    /// The `thinking.display` value Claude Code put in the API request body
6527    /// for the response that streamed this frame's thinking block; same
6528    /// source and meaning as
6529    /// [`StreamEventMessage::thinking_display`](crate::io::StreamEventMessage::thinking_display).
6530    /// Sent only on a frame whose one content block is a thinking block that
6531    /// was streamed, and only when the request body had a display. Absent
6532    /// from CLIs before 2.1.296 and from a CLI replaying history it rebuilt
6533    /// from SDK frames; an absent key states nothing. Marked `@internal`
6534    /// upstream, so treat the value set as open. Wrapper-level sibling —
6535    /// never inside `message.content`.
6536    #[serde(default, skip_serializing_if = "Option::is_none")]
6537    pub thinking_display: Option<String>,
6538    /// Structured twin of the `/context` report, carried on the synthetic
6539    /// assistant message that delivers the markdown table. Present only on
6540    /// `/context` results from CLIs new enough to attach it (2.1.239+).
6541    #[serde(default, skip_serializing_if = "Option::is_none")]
6542    pub context_usage: Option<ContextUsage>,
6543    /// Structured twin of the `/usage` report, carried on the synthetic
6544    /// assistant message that delivers its text: the session totals, the
6545    /// plan's usage rows and extra-usage spend, for remote clients that
6546    /// render a card from data. Present only on `/usage` results from CLIs
6547    /// new enough to attach it (2.1.273+) and from claude.ai-subscriber
6548    /// sessions; the text in `message.content` remains the canonical
6549    /// fallback. Wrapper-level sibling — never inside `message.content`.
6550    #[serde(default, skip_serializing_if = "Option::is_none")]
6551    pub usage_report: Option<Box<UsageReport>>,
6552    /// On the local-command twin, the run that printed the row: the
6553    /// command's name (no slash) and its arguments as the echo shows them
6554    /// (`***` when the command marks them sensitive). Present when a `local`
6555    /// command's dispatch printed the row or a `command.run` hook answered
6556    /// it, absent on a never-ran notice. Wrapper-level sibling — never inside
6557    /// `message.content` (CLI 2.1.273+).
6558    #[serde(default, skip_serializing_if = "Option::is_none")]
6559    pub local_command_run: Option<LocalCommandRun>,
6560    /// On the local-command twin, what the row reports (`unavailable_headless`,
6561    /// `unknown`, `failed`, `restart_required`), so a host can offer a fix
6562    /// instead of relaying the text. Absent when the row reports none of
6563    /// these; new kinds are additive, so treat an unknown one as absent.
6564    /// Wrapper-level sibling — never inside `message.content` (CLI 2.1.281+).
6565    #[serde(default, skip_serializing_if = "Option::is_none")]
6566    pub local_command_outcome: Option<LocalCommandOutcome>,
6567    #[serde(default, skip_serializing_if = "Option::is_none")]
6568    pub is_meta: Option<bool>,
6569    #[serde(default, skip_serializing_if = "Option::is_none")]
6570    pub is_virtual: Option<bool>,
6571    #[serde(default, skip_serializing_if = "Option::is_none")]
6572    pub is_api_error_message: Option<bool>,
6573    #[serde(skip_serializing_if = "Option::is_none")]
6574    pub api_error_status: Option<u16>,
6575    /// Typed kind of the API error when `is_api_error_message` is true. An
6576    /// open set the CLI grows release to release: 2.1.274 extends the
6577    /// original `max_output_tokens` / `dlp_request_denied` /
6578    /// `claude_code_version_too_old` with `effort_requires_thinking`,
6579    /// `advisor_incompatible`, `tool_history_mismatch`,
6580    /// `autocompact_thrashing`, `pdf_too_large`, `pdf_password_protected`,
6581    /// `media_removed` (CLI 2.1.288+: the API refused an image or a
6582    /// document, so Claude Code leaves it out of the requests that follow),
6583    /// `no_response`, `tls_untrusted_ca`, `gateway_content_type`,
6584    /// `provider_credentials`, `gateway_signin_required`,
6585    /// `gateway_session_expired`, `api_key_auth_disabled`,
6586    /// `org_disabled_credential`, `invalid_credential_header`,
6587    /// `model_requires_usage_credits`, `long_context_credits_required`,
6588    /// `consent_unanswered`, `no_allowed_fallback`,
6589    /// `model_substitution_disabled`, `field_not_granted`, (CLI 2.1.292+)
6590    /// `usage_limit_reached` — the request was refused by the account's own
6591    /// usage limit, a plan limit or a spend cap on usage credits;
6592    /// [`ApiErrorParams::rate_limit_info`] says which and when it resets —
6593    /// and (CLI 2.1.307+) `empty_completion` — the model ended its turn with
6594    /// no visible text and its one retry had no content block, so the turn
6595    /// ends as an error instead of a blank reply — and (CLI 2.1.311+)
6596    /// `unattended_start_limit` — a cloud session's restarted process hit
6597    /// the configured limit of unattended carry-ons within 24 hours, so no
6598    /// request was sent; terminal for the turn, so a consumer replaying
6599    /// history must not re-send the prompt that led to it — and
6600    /// `unattended_start_unconfirmed` — the process could not check whether
6601    /// it was allowed to carry on, so no request was sent; not terminal —
6602    /// and (CLI 2.1.314+) `stored_login_refused` — the stored claude.ai
6603    /// login was about to go out while the API key helper set by the
6604    /// machine's administrator (or, on 2.1.316+, the organization's
6605    /// settings) isn't in effect or its settings couldn't be confirmed, so
6606    /// no request was sent and the message text says who can clear it —
6607    /// `connection_failed` — Claude Code could not reach the
6608    /// API host or lost the connection (never set for a TLS error code) —
6609    /// `stream_idle_timeout` — Claude Code's own idle timer gave up waiting
6610    /// on an open stream, which does not by itself mean the server stalled —
6611    /// and `computer_slept` — the machine slept through the wait for the
6612    /// response (never sent by a claude-code-server session) — and
6613    /// (CLI 2.1.317+) `malformed_tool_use_exhausted` — the model's reply
6614    /// stopped for a tool call and held none, and the loop's retries ran
6615    /// out; terminal for the turn, so a consumer replaying history must not
6616    /// re-send the prompt by itself — and `network_edge_blocked` — the
6617    /// firewall in front of Anthropic's API refused the request for its
6618    /// network location (an unsupported region, or a VPN, proxy or network
6619    /// routing through one) before it reached the API; no sign-in or
6620    /// credential change fixes it — and (CLI 2.1.321+) `hook_denied` — a
6621    /// mod's `http.fetch` hook stopped the request — and (CLI 2.1.326+)
6622    /// `tls_cert_signature_failure` — a certificate the API's server sent
6623    /// failed signature verification (e.g. a CA list holding two same-named
6624    /// certificates after a renewal, or tampering; a host should not offer a
6625    /// way around the check) — and `message_over_context_limit` — the turn's
6626    /// own text exceeds the model's largest context window, so no request
6627    /// was sent and the text did not join the conversation — and (CLI
6628    /// 2.1.329+) `oauth_refresh_store_refused` — the macOS Keychain did not
6629    /// take a write, so the login's refresh token was not sent; the stored
6630    /// login is intact and the message text says what to do — and (CLI
6631    /// 2.1.330+) `named_profile_unusable` — `ANTHROPIC_PROFILE` names a
6632    /// profile that gives no credential (missing, unusable or signed out),
6633    /// and Claude Code does not fall back to the `/login` sign-in; no request
6634    /// was sent, and the message text says what is wrong and what to do.
6635    /// Kinds with parameters carry them in [`Self::api_error_params`].
6636    #[serde(skip_serializing_if = "Option::is_none")]
6637    pub api_error: Option<String>,
6638    /// The server's `error.details.error_code` for this API error, copied
6639    /// through when it is an identifier (`^[a-z][a-z0-9_]{0,63}$`) and
6640    /// dropped otherwise. Carries server gate codes this CLI build has no
6641    /// `api_error` value for, so a host can key on a new gate without a
6642    /// Claude Code release. Absent when the response carried no code and
6643    /// from CLIs before 2.1.274.
6644    #[serde(default, skip_serializing_if = "Option::is_none")]
6645    pub api_error_code: Option<String>,
6646    /// The `error.type` of the response body for this API error (such as
6647    /// `rate_limit_error`, `overloaded_error` or `invalid_request_error`),
6648    /// copied through when it is an identifier (`^[a-z][a-z0-9_]{0,63}$`)
6649    /// and dropped otherwise, so a host can read the class without working
6650    /// it out from `error`, `api_error_status` or the text. The CLI does not
6651    /// check the value: a gateway or third-party provider can send others
6652    /// (see [`Self::api_error_origin`]), and a first-party 503 with
6653    /// `x-should-retry: false` still says `overloaded_error`, so the value
6654    /// alone does not say a retry can help. Bodies Claude Code writes itself
6655    /// carry their own type (a hook's plain refusal is `permission_error`).
6656    /// Marked `@internal` upstream (CLI 2.1.325+).
6657    #[serde(default, skip_serializing_if = "Option::is_none")]
6658    pub api_error_type: Option<String>,
6659    /// `first_party` when this API error was built from a response
6660    /// Anthropic's own API sent: the first-party provider, the default
6661    /// `https://api.anthropic.com` endpoint answering directly, over TLS
6662    /// verified with no added CA, override or socket tunnel. Absent in every
6663    /// other case (a base-URL override, a gateway, a third-party provider, a
6664    /// connection error, an error Claude Code raised itself, any replayed
6665    /// frame); treat absence as unknown origin. It says which endpoint
6666    /// answered, not that the text is the server's verbatim, so render
6667    /// stamped text as plain text. Open set — treat an unknown value as
6668    /// absent (CLI 2.1.300+).
6669    #[serde(default, skip_serializing_if = "Option::is_none")]
6670    pub api_error_origin: Option<String>,
6671    /// Parameters of [`Self::api_error`], present only for the kinds that
6672    /// have any (CLI 2.1.274+).
6673    #[serde(default, skip_serializing_if = "Option::is_none")]
6674    pub api_error_params: Option<ApiErrorParams>,
6675    #[serde(skip_serializing_if = "Option::is_none")]
6676    pub error_details: Option<String>,
6677    #[serde(skip_serializing_if = "Option::is_none")]
6678    pub advisor_model: Option<String>,
6679    #[serde(skip_serializing_if = "Option::is_none")]
6680    pub attribution_agent: Option<String>,
6681    #[serde(skip_serializing_if = "Option::is_none")]
6682    pub attribution_skill: Option<String>,
6683    #[serde(skip_serializing_if = "Option::is_none")]
6684    pub attribution_plugin: Option<String>,
6685    #[serde(skip_serializing_if = "Option::is_none")]
6686    pub attribution_mcp_server: Option<String>,
6687    #[serde(skip_serializing_if = "Option::is_none")]
6688    pub attribution_mcp_tool: Option<String>,
6689}
6690
6691/// Parameters of an assistant frame's `api_error`, carried as
6692/// [`AssistantMessage::api_error_params`] only for the error kinds that have
6693/// any (CLI 2.1.274+).
6694#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
6695pub struct ApiErrorParams {
6696    /// The effort level the API refused (`effort_requires_thinking`).
6697    #[serde(default, skip_serializing_if = "Option::is_none")]
6698    pub effort: Option<String>,
6699    /// The API provider whose credentials failed (`provider_credentials`,
6700    /// `gateway_session_expired`).
6701    #[serde(default, skip_serializing_if = "Option::is_none")]
6702    pub provider: Option<ApiErrorProvider>,
6703    /// How to repair the failed credentials (`provider_credentials`,
6704    /// `gateway_session_expired`).
6705    #[serde(default, skip_serializing_if = "Option::is_none")]
6706    pub remedy: Option<ApiErrorRemedy>,
6707    /// The kind of block the API refused (`media_removed`); absent for
6708    /// [`ApiErrorMediaReason::MediaBudget`] (CLI 2.1.288+).
6709    #[serde(default, skip_serializing_if = "Option::is_none")]
6710    pub media: Option<ApiErrorMedia>,
6711    /// Why the API refused the block (`media_removed`, CLI 2.1.288+).
6712    #[serde(default, skip_serializing_if = "Option::is_none")]
6713    pub media_reason: Option<ApiErrorMediaReason>,
6714    /// What the refused request's own response said about the limit
6715    /// (`usage_limit_reached`), in the shape `rate_limit_event` carries:
6716    /// `status` is rejected and `isUsingOverage` false, `rateLimitType` names
6717    /// the limit, `resetsAt` is when it resets, and the overage fields and
6718    /// `limitScope` say whose spend cap it is. It is that refusal's record
6719    /// and is never updated, so compare `resetsAt` with the clock before
6720    /// calling the limit current (CLI 2.1.292+).
6721    ///
6722    /// On CLI 2.1.316+ also carried for `model_requires_usage_credits`:
6723    /// `status` is rejected and `isUsingOverage` false; `rateLimitType` is
6724    /// the response's claim (`seven_day_overage_included` when an included
6725    /// allowance was used up) and absent when it named none; `resetsAt`,
6726    /// `overageStatus`, `overageResetsAt` and `limitScope` come when the
6727    /// response had them; `errorCode` is `credits_required` when the body
6728    /// said so; `overageDisabledReason`, `canUserPurchaseCredits` and
6729    /// `hasChargeableSavedPaymentMethod` as the response gave them; the
6730    /// person's own cap arrives as `org_level_disabled_until`. No other
6731    /// member is sent.
6732    ///
6733    /// On CLI 2.1.319+ the `usage_limit_reached` record also carries
6734    /// `dailyCapPaused` when usage is paused for the organization.
6735    ///
6736    /// On CLI 2.1.328+ both records carry `memberSpendLimit` when the API
6737    /// reports the member's own spend limit as reached.
6738    #[serde(default, skip_serializing_if = "Option::is_none")]
6739    pub rate_limit_info: Option<RateLimitInfo>,
6740    /// Which API stop reason cut the reply short (`max_output_tokens`),
6741    /// which the kind alone does not say. Absent on the one other error
6742    /// that carries `max_output_tokens`, the API's `tool_use_block_cut_off`,
6743    /// which [`AssistantMessage::api_error_code`] names (CLI 2.1.321+).
6744    #[serde(default, skip_serializing_if = "Option::is_none")]
6745    pub cut: Option<ApiErrorCut>,
6746}
6747
6748/// Which API stop reason cut a reply short ([`ApiErrorParams::cut`]).
6749#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6750pub enum ApiErrorCut {
6751    /// `max_tokens`: the request's output-token maximum.
6752    OutputLimit,
6753    /// `model_context_window_exceeded`: the model's context window.
6754    ContextWindow,
6755    /// A value not yet known to this version of the crate.
6756    Unknown(String),
6757}
6758
6759impl ApiErrorCut {
6760    pub fn as_str(&self) -> &str {
6761        match self {
6762            Self::OutputLimit => "output_limit",
6763            Self::ContextWindow => "context_window",
6764            Self::Unknown(s) => s.as_str(),
6765        }
6766    }
6767}
6768
6769impl fmt::Display for ApiErrorCut {
6770    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6771        f.write_str(self.as_str())
6772    }
6773}
6774
6775impl From<&str> for ApiErrorCut {
6776    fn from(s: &str) -> Self {
6777        match s {
6778            "output_limit" => Self::OutputLimit,
6779            "context_window" => Self::ContextWindow,
6780            other => Self::Unknown(other.to_string()),
6781        }
6782    }
6783}
6784
6785impl Serialize for ApiErrorCut {
6786    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
6787        serializer.serialize_str(self.as_str())
6788    }
6789}
6790
6791impl<'de> Deserialize<'de> for ApiErrorCut {
6792    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
6793        let s = String::deserialize(deserializer)?;
6794        Ok(Self::from(s.as_str()))
6795    }
6796}
6797
6798/// The kind of block the API refused ([`ApiErrorParams::media`]).
6799#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6800pub enum ApiErrorMedia {
6801    Image,
6802    Document,
6803    /// A kind not yet known to this version of the crate.
6804    Unknown(String),
6805}
6806
6807impl ApiErrorMedia {
6808    pub fn as_str(&self) -> &str {
6809        match self {
6810            Self::Image => "image",
6811            Self::Document => "document",
6812            Self::Unknown(s) => s.as_str(),
6813        }
6814    }
6815}
6816
6817impl fmt::Display for ApiErrorMedia {
6818    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6819        f.write_str(self.as_str())
6820    }
6821}
6822
6823impl From<&str> for ApiErrorMedia {
6824    fn from(s: &str) -> Self {
6825        match s {
6826            "image" => Self::Image,
6827            "document" => Self::Document,
6828            other => Self::Unknown(other.to_string()),
6829        }
6830    }
6831}
6832
6833impl Serialize for ApiErrorMedia {
6834    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
6835        serializer.serialize_str(self.as_str())
6836    }
6837}
6838
6839impl<'de> Deserialize<'de> for ApiErrorMedia {
6840    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
6841        let s = String::deserialize(deserializer)?;
6842        Ok(Self::from(s.as_str()))
6843    }
6844}
6845
6846/// Why the API refused an image or document
6847/// ([`ApiErrorParams::media_reason`]).
6848#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6849pub enum ApiErrorMediaReason {
6850    /// Every other refusal, a gateway's report of a model's refusal among
6851    /// them.
6852    Unprocessable,
6853    /// The API said that the model does not accept PDF documents.
6854    UnsupportedByModel,
6855    /// The request's images and documents together exceed the API's limit,
6856    /// and the requests that follow may leave out blocks of either kind.
6857    MediaBudget,
6858    /// A reason not yet known to this version of the crate.
6859    Unknown(String),
6860}
6861
6862impl ApiErrorMediaReason {
6863    pub fn as_str(&self) -> &str {
6864        match self {
6865            Self::Unprocessable => "unprocessable",
6866            Self::UnsupportedByModel => "unsupported_by_model",
6867            Self::MediaBudget => "media_budget",
6868            Self::Unknown(s) => s.as_str(),
6869        }
6870    }
6871}
6872
6873impl fmt::Display for ApiErrorMediaReason {
6874    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6875        f.write_str(self.as_str())
6876    }
6877}
6878
6879impl From<&str> for ApiErrorMediaReason {
6880    fn from(s: &str) -> Self {
6881        match s {
6882            "unprocessable" => Self::Unprocessable,
6883            "unsupported_by_model" => Self::UnsupportedByModel,
6884            "media_budget" => Self::MediaBudget,
6885            other => Self::Unknown(other.to_string()),
6886        }
6887    }
6888}
6889
6890impl Serialize for ApiErrorMediaReason {
6891    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
6892        serializer.serialize_str(self.as_str())
6893    }
6894}
6895
6896impl<'de> Deserialize<'de> for ApiErrorMediaReason {
6897    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
6898        let s = String::deserialize(deserializer)?;
6899        Ok(Self::from(s.as_str()))
6900    }
6901}
6902
6903/// The API provider whose credentials failed ([`ApiErrorParams::provider`]).
6904#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6905pub enum ApiErrorProvider {
6906    Bedrock,
6907    AnthropicAws,
6908    Mantle,
6909    AnthropicGoogleCloud,
6910    Vertex,
6911    Foundry,
6912    Gateway,
6913    /// A provider not yet known to this version of the crate.
6914    Unknown(String),
6915}
6916
6917impl ApiErrorProvider {
6918    pub fn as_str(&self) -> &str {
6919        match self {
6920            Self::Bedrock => "bedrock",
6921            Self::AnthropicAws => "anthropicAws",
6922            Self::Mantle => "mantle",
6923            Self::AnthropicGoogleCloud => "anthropicGoogleCloud",
6924            Self::Vertex => "vertex",
6925            Self::Foundry => "foundry",
6926            Self::Gateway => "gateway",
6927            Self::Unknown(s) => s.as_str(),
6928        }
6929    }
6930}
6931
6932impl fmt::Display for ApiErrorProvider {
6933    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6934        f.write_str(self.as_str())
6935    }
6936}
6937
6938impl From<&str> for ApiErrorProvider {
6939    fn from(s: &str) -> Self {
6940        match s {
6941            "bedrock" => Self::Bedrock,
6942            "anthropicAws" => Self::AnthropicAws,
6943            "mantle" => Self::Mantle,
6944            "anthropicGoogleCloud" => Self::AnthropicGoogleCloud,
6945            "vertex" => Self::Vertex,
6946            "foundry" => Self::Foundry,
6947            "gateway" => Self::Gateway,
6948            other => Self::Unknown(other.to_string()),
6949        }
6950    }
6951}
6952
6953impl Serialize for ApiErrorProvider {
6954    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
6955        serializer.serialize_str(self.as_str())
6956    }
6957}
6958
6959impl<'de> Deserialize<'de> for ApiErrorProvider {
6960    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
6961        let s = String::deserialize(deserializer)?;
6962        Ok(Self::from(s.as_str()))
6963    }
6964}
6965
6966/// How to repair failed provider credentials ([`ApiErrorParams::remedy`]).
6967#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6968pub enum ApiErrorRemedy {
6969    /// A configured refresh command (`awsAuthRefresh` / `gcpAuthRefresh`)
6970    /// refreshes the credentials.
6971    RefreshCommand,
6972    /// Refresh the provider's credentials by hand; no command is configured.
6973    RefreshCredentials,
6974    /// Refresh the Google application default credentials or the
6975    /// `GOOGLE_APPLICATION_CREDENTIALS` key file.
6976    Adc,
6977    /// Replace the gateway token supplied through `ANTHROPIC_AUTH_TOKEN` or
6978    /// `ANTHROPIC_CUSTOM_HEADERS`.
6979    GatewayToken,
6980    /// The host application owns these credentials.
6981    HostManaged,
6982    /// The credentials work but the model is not enabled for this account
6983    /// and region (Amazon Bedrock).
6984    ModelAccess,
6985    /// A remedy not yet known to this version of the crate.
6986    Unknown(String),
6987}
6988
6989impl ApiErrorRemedy {
6990    pub fn as_str(&self) -> &str {
6991        match self {
6992            Self::RefreshCommand => "refresh_command",
6993            Self::RefreshCredentials => "refresh_credentials",
6994            Self::Adc => "adc",
6995            Self::GatewayToken => "gateway_token",
6996            Self::HostManaged => "host_managed",
6997            Self::ModelAccess => "model_access",
6998            Self::Unknown(s) => s.as_str(),
6999        }
7000    }
7001}
7002
7003impl fmt::Display for ApiErrorRemedy {
7004    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7005        f.write_str(self.as_str())
7006    }
7007}
7008
7009impl From<&str> for ApiErrorRemedy {
7010    fn from(s: &str) -> Self {
7011        match s {
7012            "refresh_command" => Self::RefreshCommand,
7013            "refresh_credentials" => Self::RefreshCredentials,
7014            "adc" => Self::Adc,
7015            "gateway_token" => Self::GatewayToken,
7016            "host_managed" => Self::HostManaged,
7017            "model_access" => Self::ModelAccess,
7018            other => Self::Unknown(other.to_string()),
7019        }
7020    }
7021}
7022
7023impl Serialize for ApiErrorRemedy {
7024    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
7025        serializer.serialize_str(self.as_str())
7026    }
7027}
7028
7029impl<'de> Deserialize<'de> for ApiErrorRemedy {
7030    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
7031        let s = String::deserialize(deserializer)?;
7032        Ok(Self::from(s.as_str()))
7033    }
7034}
7035
7036/// Nested message content for assistant messages
7037#[derive(Debug, Clone, Serialize, Deserialize)]
7038pub struct AssistantMessageContent {
7039    pub id: String,
7040    /// The Anthropic API message type — always `"message"`.
7041    #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
7042    pub message_type: Option<String>,
7043    pub role: MessageRole,
7044    pub model: String,
7045    pub content: Vec<ContentBlock>,
7046    #[serde(skip_serializing_if = "Option::is_none")]
7047    pub stop_reason: Option<StopReason>,
7048    #[serde(skip_serializing_if = "Option::is_none")]
7049    pub stop_sequence: Option<String>,
7050    #[serde(skip_serializing_if = "Option::is_none")]
7051    pub usage: Option<AssistantUsage>,
7052    /// Details about why generation stopped
7053    #[serde(skip_serializing_if = "Option::is_none")]
7054    pub stop_details: Option<Value>,
7055    /// Context management metadata
7056    #[serde(skip_serializing_if = "Option::is_none")]
7057    pub context_management: Option<Value>,
7058}
7059
7060/// Usage information for assistant messages
7061#[derive(Debug, Clone, Serialize, Deserialize)]
7062pub struct AssistantUsage {
7063    /// Number of input tokens
7064    #[serde(default)]
7065    pub input_tokens: u32,
7066
7067    /// Number of output tokens
7068    #[serde(default)]
7069    pub output_tokens: u32,
7070
7071    /// Tokens used to create cache
7072    #[serde(default)]
7073    pub cache_creation_input_tokens: u32,
7074
7075    /// Tokens read from cache
7076    #[serde(default)]
7077    pub cache_read_input_tokens: u32,
7078
7079    /// Service tier used (e.g., "standard")
7080    #[serde(skip_serializing_if = "Option::is_none")]
7081    pub service_tier: Option<String>,
7082
7083    /// Detailed cache creation breakdown
7084    #[serde(skip_serializing_if = "Option::is_none")]
7085    pub cache_creation: Option<CacheCreationDetails>,
7086
7087    /// Inference geography (e.g., "not_available")
7088    #[serde(skip_serializing_if = "Option::is_none")]
7089    pub inference_geo: Option<String>,
7090
7091    /// Speed tier the request ran at (`"standard"` or `"fast"`). The API
7092    /// began sending it on per-message usage around CLI 2.1.301.
7093    #[serde(default, skip_serializing_if = "Option::is_none")]
7094    pub speed: Option<String>,
7095
7096    /// Outcome of a fallback-credit token the request presented; `null` on
7097    /// the wire when it presented none (CLI 2.1.285+).
7098    #[serde(default, skip_serializing_if = "Option::is_none")]
7099    pub fallback_credit: Option<Value>,
7100}
7101
7102/// Detailed cache creation information
7103#[derive(Debug, Clone, Serialize, Deserialize)]
7104pub struct CacheCreationDetails {
7105    /// Ephemeral 1-hour input tokens
7106    #[serde(default)]
7107    pub ephemeral_1h_input_tokens: u32,
7108
7109    /// Ephemeral 5-minute input tokens
7110    #[serde(default)]
7111    pub ephemeral_5m_input_tokens: u32,
7112}
7113
7114#[cfg(test)]
7115mod tests {
7116    use crate::io::ClaudeOutput;
7117
7118    #[test]
7119    fn test_subagent_usage_rollup_accumulates_task_results() {
7120        use super::SubagentUsageRollup;
7121
7122        let mut rollup = SubagentUsageRollup::default();
7123
7124        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}}"#;
7125        let output: ClaudeOutput = serde_json::from_str(task_result).unwrap();
7126        assert!(rollup.observe(&output));
7127        assert_eq!(rollup.subagent_tokens, 10201);
7128        assert_eq!(rollup.agent_count, 1);
7129        assert_eq!(rollup.tool_uses, 3);
7130        assert_eq!(rollup.duration_ms, 1853);
7131
7132        // Replayed frame with the same agentId is counted once.
7133        assert!(!rollup.observe(&output));
7134        assert_eq!(rollup.agent_count, 1);
7135        assert_eq!(rollup.subagent_tokens, 10201);
7136
7137        // A second agent accumulates.
7138        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}}"#;
7139        let output: ClaudeOutput = serde_json::from_str(second).unwrap();
7140        assert!(rollup.observe(&output));
7141        assert_eq!(rollup.agent_count, 2);
7142        assert_eq!(rollup.subagent_tokens, 10701);
7143    }
7144
7145    #[test]
7146    fn test_subagent_usage_rollup_ignores_non_task_results() {
7147        use super::SubagentUsageRollup;
7148
7149        let mut rollup = SubagentUsageRollup::default();
7150
7151        // A ToolSearch tool_use_result parses as an all-None SubagentResult;
7152        // it must not count as a subagent.
7153        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}}"#;
7154        let output: ClaudeOutput = serde_json::from_str(tool_search).unwrap();
7155        assert!(!rollup.observe(&output));
7156
7157        // Plain user message without tool_use_result.
7158        let plain = r#"{"type":"user","message":{"role":"user","content":[]},"session_id":"7fbc568e-2bd6-45aa-b217-a1cf80004ba1"}"#;
7159        let output: ClaudeOutput = serde_json::from_str(plain).unwrap();
7160        assert!(!rollup.observe(&output));
7161
7162        // Non-user frames are ignored.
7163        let system = r#"{"type":"system","subtype":"status","status":null,"session_id":"7fbc568e-2bd6-45aa-b217-a1cf80004ba1"}"#;
7164        let output: ClaudeOutput = serde_json::from_str(system).unwrap();
7165        assert!(!rollup.observe(&output));
7166
7167        assert_eq!(rollup, SubagentUsageRollup::default());
7168    }
7169
7170    #[test]
7171    fn test_subagent_usage_rollup_over_captured_session() {
7172        use super::SubagentUsageRollup;
7173
7174        let mut rollup = SubagentUsageRollup::default();
7175        let fixture =
7176            include_str!("../../test_cases/subagent_sessions/general_purpose_compute.jsonl");
7177        for line in fixture.lines().filter(|l| !l.trim().is_empty()) {
7178            if let Ok(output) = serde_json::from_str::<ClaudeOutput>(line) {
7179                rollup.observe(&output);
7180            }
7181        }
7182        assert_eq!(rollup.agent_count, 1);
7183        assert_eq!(rollup.subagent_tokens, 10201);
7184    }
7185
7186    #[test]
7187    fn test_system_message_init() {
7188        let json = r#"{
7189            "type": "system",
7190            "subtype": "init",
7191            "session_id": "test-session-123",
7192            "cwd": "/home/user/project",
7193            "model": "claude-sonnet-4",
7194            "tools": ["Bash", "Read", "Write"],
7195            "mcp_servers": [],
7196            "slash_commands": ["compact", "cost", "review"],
7197            "agents": ["Bash", "Explore", "Plan"],
7198            "plugins": [{"name": "rust-analyzer-lsp", "path": "/home/user/.claude/plugins/rust-analyzer-lsp/1.0.0"}],
7199            "skills": [],
7200            "claude_code_version": "2.1.15",
7201            "apiKeySource": "none",
7202            "output_style": "default",
7203            "permissionMode": "default"
7204        }"#;
7205
7206        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7207        if let ClaudeOutput::System(sys) = output {
7208            assert!(sys.is_init());
7209            assert!(!sys.is_status());
7210            assert!(!sys.is_compact_boundary());
7211
7212            let init = sys.as_init().expect("Should parse as init");
7213            assert_eq!(init.session_id, "test-session-123");
7214            assert_eq!(init.cwd, Some("/home/user/project".to_string()));
7215            assert_eq!(init.model, Some("claude-sonnet-4".to_string()));
7216            assert_eq!(init.tools, vec!["Bash", "Read", "Write"]);
7217            assert_eq!(init.slash_commands, vec!["compact", "cost", "review"]);
7218            assert_eq!(init.agents, vec!["Bash", "Explore", "Plan"]);
7219            assert_eq!(init.plugins.len(), 1);
7220            assert_eq!(init.plugins[0].name, "rust-analyzer-lsp");
7221            assert_eq!(init.claude_code_version, Some("2.1.15".to_string()));
7222            assert_eq!(init.api_key_source, Some(super::ApiKeySource::None));
7223            assert_eq!(init.output_style, Some(super::OutputStyle::Default));
7224            assert_eq!(
7225                init.permission_mode,
7226                Some(super::InitPermissionMode::Default)
7227            );
7228        } else {
7229            panic!("Expected System message");
7230        }
7231    }
7232
7233    #[test]
7234    fn test_system_message_init_from_real_capture() {
7235        let json = include_str!("../../test_cases/tool_use_captures/tool_msg_0.json");
7236        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7237        if let ClaudeOutput::System(sys) = output {
7238            let init = sys.as_init().expect("Should parse real init capture");
7239            assert_eq!(init.slash_commands.len(), 8);
7240            assert!(init.slash_commands.contains(&"compact".to_string()));
7241            assert!(init.slash_commands.contains(&"review".to_string()));
7242            assert_eq!(init.agents.len(), 5);
7243            assert!(init.agents.contains(&"Bash".to_string()));
7244            assert!(init.agents.contains(&"Explore".to_string()));
7245            assert_eq!(init.plugins.len(), 1);
7246            assert_eq!(init.plugins[0].name, "rust-analyzer-lsp");
7247            assert_eq!(init.claude_code_version, Some("2.1.15".to_string()));
7248        } else {
7249            panic!("Expected System message");
7250        }
7251    }
7252
7253    #[test]
7254    fn test_system_message_status() {
7255        let json = r#"{
7256            "type": "system",
7257            "subtype": "status",
7258            "session_id": "879c1a88-3756-4092-aa95-0020c4ed9692",
7259            "status": "compacting",
7260            "uuid": "32eb9f9d-5ef7-47ff-8fce-bbe22fe7ed93"
7261        }"#;
7262
7263        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7264        if let ClaudeOutput::System(sys) = output {
7265            assert!(sys.is_status());
7266            assert!(!sys.is_init());
7267
7268            let status = sys.as_status().expect("Should parse as status");
7269            assert_eq!(status.session_id, "879c1a88-3756-4092-aa95-0020c4ed9692");
7270            assert_eq!(status.status, Some(super::StatusMessageStatus::Compacting));
7271            assert_eq!(
7272                status.uuid,
7273                Some("32eb9f9d-5ef7-47ff-8fce-bbe22fe7ed93".to_string())
7274            );
7275        } else {
7276            panic!("Expected System message");
7277        }
7278    }
7279
7280    #[test]
7281    fn test_system_message_status_null() {
7282        let json = r#"{
7283            "type": "system",
7284            "subtype": "status",
7285            "session_id": "879c1a88-3756-4092-aa95-0020c4ed9692",
7286            "status": null,
7287            "uuid": "92d9637e-d00e-418e-acd2-a504e3861c6a"
7288        }"#;
7289
7290        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7291        if let ClaudeOutput::System(sys) = output {
7292            let status = sys.as_status().expect("Should parse as status");
7293            assert_eq!(status.status, None);
7294        } else {
7295            panic!("Expected System message");
7296        }
7297    }
7298
7299    #[test]
7300    fn test_system_message_task_started() {
7301        let json = r#"{
7302            "type": "system",
7303            "subtype": "task_started",
7304            "session_id": "9abbc466-dad0-4b8e-b6b0-cad5eb7a16b9",
7305            "task_id": "b6daf3f",
7306            "task_type": "local_bash",
7307            "tool_use_id": "toolu_011rfSTFumpJZdCCfzeD7jaS",
7308            "description": "Wait for CI on PR #12",
7309            "uuid": "c4243261-c128-4747-b8c3-5e1c7c10eeb8"
7310        }"#;
7311
7312        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7313        if let ClaudeOutput::System(sys) = output {
7314            assert!(sys.is_task_started());
7315            assert!(!sys.is_task_progress());
7316            assert!(!sys.is_task_notification());
7317
7318            let task = sys.as_task_started().expect("Should parse as task_started");
7319            assert_eq!(task.session_id, "9abbc466-dad0-4b8e-b6b0-cad5eb7a16b9");
7320            assert_eq!(task.task_id, "b6daf3f");
7321            assert_eq!(task.task_type, Some(super::TaskType::LocalBash));
7322            assert_eq!(
7323                task.tool_use_id.as_deref(),
7324                Some("toolu_011rfSTFumpJZdCCfzeD7jaS")
7325            );
7326            assert_eq!(task.description, "Wait for CI on PR #12");
7327        } else {
7328            panic!("Expected System message");
7329        }
7330    }
7331
7332    #[test]
7333    fn test_system_message_task_started_agent() {
7334        let json = r#"{
7335            "type": "system",
7336            "subtype": "task_started",
7337            "session_id": "bff4f716-17c1-4255-ab7b-eea9d33824e3",
7338            "task_id": "a4a7e0906e5fc64cc",
7339            "task_type": "local_agent",
7340            "tool_use_id": "toolu_01SFz9FwZ1cYgCSy8vRM7wep",
7341            "description": "Explore Scene/ArrayScene duplication",
7342            "uuid": "85a39f5a-e4d4-47f7-9a6d-1125f1a8035f"
7343        }"#;
7344
7345        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7346        if let ClaudeOutput::System(sys) = output {
7347            let task = sys.as_task_started().expect("Should parse as task_started");
7348            assert_eq!(task.task_type, Some(super::TaskType::LocalAgent));
7349            assert_eq!(task.task_id, "a4a7e0906e5fc64cc");
7350        } else {
7351            panic!("Expected System message");
7352        }
7353    }
7354
7355    #[test]
7356    fn test_system_message_task_progress() {
7357        let json = r#"{
7358            "type": "system",
7359            "subtype": "task_progress",
7360            "session_id": "bff4f716-17c1-4255-ab7b-eea9d33824e3",
7361            "task_id": "a4a7e0906e5fc64cc",
7362            "tool_use_id": "toolu_01SFz9FwZ1cYgCSy8vRM7wep",
7363            "description": "Reading src/jplephem/chebyshev.rs",
7364            "last_tool_name": "Read",
7365            "usage": {
7366                "duration_ms": 13996,
7367                "tool_uses": 9,
7368                "total_tokens": 38779
7369            },
7370            "uuid": "85a39f5a-e4d4-47f7-9a6d-1125f1a8035f"
7371        }"#;
7372
7373        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7374        if let ClaudeOutput::System(sys) = output {
7375            assert!(sys.is_task_progress());
7376            assert!(!sys.is_task_started());
7377
7378            let progress = sys
7379                .as_task_progress()
7380                .expect("Should parse as task_progress");
7381            assert_eq!(progress.task_id, "a4a7e0906e5fc64cc");
7382            assert_eq!(progress.description, "Reading src/jplephem/chebyshev.rs");
7383            assert_eq!(progress.last_tool_name.as_deref(), Some("Read"));
7384            assert_eq!(progress.usage.duration_ms, 13996);
7385            assert_eq!(progress.usage.tool_uses, 9);
7386            assert_eq!(progress.usage.total_tokens, 38779);
7387        } else {
7388            panic!("Expected System message");
7389        }
7390    }
7391
7392    #[test]
7393    fn test_system_message_task_notification_completed() {
7394        let json = r#"{
7395            "type": "system",
7396            "subtype": "task_notification",
7397            "session_id": "bff4f716-17c1-4255-ab7b-eea9d33824e3",
7398            "task_id": "a0ba761e9dc9c316f",
7399            "tool_use_id": "toolu_01Ho6XVXFLVNjTQ9YqowdBXW",
7400            "status": "completed",
7401            "summary": "Agent \"Write Hipparcos data source doc\" completed",
7402            "output_file": "",
7403            "usage": {
7404                "duration_ms": 172300,
7405                "tool_uses": 11,
7406                "total_tokens": 42005
7407            },
7408            "uuid": "269f49b9-218d-4c8d-9f7e-3a5383a0c5b2"
7409        }"#;
7410
7411        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7412        if let ClaudeOutput::System(sys) = output {
7413            assert!(sys.is_task_notification());
7414
7415            let notif = sys
7416                .as_task_notification()
7417                .expect("Should parse as task_notification");
7418            assert_eq!(notif.status, super::TaskStatus::Completed);
7419            assert_eq!(
7420                notif.summary,
7421                "Agent \"Write Hipparcos data source doc\" completed"
7422            );
7423            assert_eq!(notif.output_file, Some("".to_string()));
7424            assert_eq!(
7425                notif.tool_use_id,
7426                Some("toolu_01Ho6XVXFLVNjTQ9YqowdBXW".to_string())
7427            );
7428            let usage = notif.usage.expect("Should have usage");
7429            assert_eq!(usage.duration_ms, 172300);
7430            assert_eq!(usage.tool_uses, 11);
7431            assert_eq!(usage.total_tokens, 42005);
7432        } else {
7433            panic!("Expected System message");
7434        }
7435    }
7436
7437    #[test]
7438    fn test_system_message_task_notification_failed_no_usage() {
7439        let json = r#"{
7440            "type": "system",
7441            "subtype": "task_notification",
7442            "session_id": "ea629737-3c36-48a8-a1c4-ad761ad35784",
7443            "task_id": "b98f6a3",
7444            "status": "failed",
7445            "summary": "Background command \"Run FSM calibration\" failed with exit code 1",
7446            "output_file": "/tmp/claude-1000/tasks/b98f6a3.output"
7447        }"#;
7448
7449        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7450        if let ClaudeOutput::System(sys) = output {
7451            let notif = sys
7452                .as_task_notification()
7453                .expect("Should parse as task_notification");
7454            assert_eq!(notif.status, super::TaskStatus::Failed);
7455            assert!(notif.tool_use_id.is_none());
7456            assert!(notif.usage.is_none());
7457            assert_eq!(
7458                notif.output_file,
7459                Some("/tmp/claude-1000/tasks/b98f6a3.output".to_string())
7460            );
7461        } else {
7462            panic!("Expected System message");
7463        }
7464    }
7465
7466    /// Task system messages survive a `to_value` → `from_value` round-trip
7467    /// with their typed accessors still resolving. Mirrors the proxy/relay
7468    /// path where output is reparsed from a `serde_json::Value` rather than
7469    /// straight from the CLI's stdout, so a silently dropped or renamed field
7470    /// surfaces here instead of as a `None` downstream.
7471    #[test]
7472    fn test_task_messages_roundtrip_through_value() {
7473        let cases = [
7474            r#"{"type":"system","subtype":"task_started","session_id":"s1",
7475                "task_id":"t1","task_type":"local_bash","tool_use_id":"tu1",
7476                "description":"Sleep 3s","uuid":"u1"}"#,
7477            r#"{"type":"system","subtype":"task_progress","session_id":"s1",
7478                "task_id":"t1","tool_use_id":"tu1","description":"Running ls",
7479                "last_tool_name":"Bash",
7480                "usage":{"duration_ms":100,"tool_uses":1,"total_tokens":500},
7481                "uuid":"u2"}"#,
7482            r#"{"type":"system","subtype":"task_notification","session_id":"s1",
7483                "task_id":"t1","tool_use_id":"tu1","status":"completed",
7484                "summary":"done","output_file":"",
7485                "usage":{"duration_ms":100,"tool_uses":1,"total_tokens":500},
7486                "uuid":"u3"}"#,
7487        ];
7488
7489        for json in cases {
7490            let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7491            let value = serde_json::to_value(&output).unwrap();
7492            let reparsed: ClaudeOutput = serde_json::from_value(value).unwrap();
7493
7494            let ClaudeOutput::System(sys) = reparsed else {
7495                panic!("Expected System variant after round-trip");
7496            };
7497
7498            match sys.subtype {
7499                super::SystemSubtype::TaskStarted => {
7500                    assert!(
7501                        sys.as_task_started().is_some(),
7502                        "as_task_started failed after round-trip"
7503                    );
7504                }
7505                super::SystemSubtype::TaskProgress => {
7506                    assert!(
7507                        sys.as_task_progress().is_some(),
7508                        "as_task_progress failed after round-trip"
7509                    );
7510                }
7511                super::SystemSubtype::TaskNotification => {
7512                    assert!(
7513                        sys.as_task_notification().is_some(),
7514                        "as_task_notification failed after round-trip"
7515                    );
7516                }
7517                other => panic!("unexpected subtype after round-trip: {other:?}"),
7518            }
7519        }
7520    }
7521
7522    #[test]
7523    fn test_system_message_compact_boundary() {
7524        let json = r#"{
7525            "type": "system",
7526            "subtype": "compact_boundary",
7527            "session_id": "879c1a88-3756-4092-aa95-0020c4ed9692",
7528            "compact_metadata": {
7529                "pre_tokens": 155285,
7530                "trigger": "auto"
7531            },
7532            "uuid": "a67780d5-74cb-48b1-9137-7a6e7cee45d7"
7533        }"#;
7534
7535        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7536        if let ClaudeOutput::System(sys) = output {
7537            assert!(sys.is_compact_boundary());
7538            assert!(!sys.is_init());
7539            assert!(!sys.is_status());
7540
7541            let compact = sys
7542                .as_compact_boundary()
7543                .expect("Should parse as compact_boundary");
7544            assert_eq!(compact.session_id, "879c1a88-3756-4092-aa95-0020c4ed9692");
7545            assert_eq!(compact.compact_metadata.pre_tokens, 155285);
7546            assert_eq!(
7547                compact.compact_metadata.trigger,
7548                super::CompactionTrigger::Auto
7549            );
7550            // Per-compaction stats are optional and absent here.
7551            assert!(compact.summary.is_none());
7552            assert!(compact.leaf_message_count.is_none());
7553            assert!(compact.duration_ms.is_none());
7554        } else {
7555            panic!("Expected System message");
7556        }
7557    }
7558
7559    #[test]
7560    fn test_compact_boundary_with_summary_stats() {
7561        // Canonical keys.
7562        let json = r#"{
7563            "type": "system",
7564            "subtype": "compact_boundary",
7565            "session_id": "s1",
7566            "compact_metadata": { "pre_tokens": 1000, "trigger": "manual" },
7567            "summary": "Summarized the earlier exploration.",
7568            "leaf_message_count": 42,
7569            "duration_ms": 1234,
7570            "uuid": "u1"
7571        }"#;
7572        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7573        let ClaudeOutput::System(sys) = output else {
7574            panic!("Expected System message");
7575        };
7576        let compact = sys.as_compact_boundary().expect("compact_boundary");
7577        assert_eq!(
7578            compact.summary.as_deref(),
7579            Some("Summarized the earlier exploration.")
7580        );
7581        assert_eq!(compact.leaf_message_count, Some(42));
7582        assert_eq!(compact.duration_ms, Some(1234));
7583
7584        // Alternate wire keys (`content` for summary, `message_count` for count)
7585        // deserialize into the same fields.
7586        let json_alt = r#"{
7587            "type": "system",
7588            "subtype": "compact_boundary",
7589            "session_id": "s2",
7590            "compact_metadata": { "pre_tokens": 2000, "trigger": "auto" },
7591            "content": "alt-key summary",
7592            "message_count": 7
7593        }"#;
7594        let output: ClaudeOutput = serde_json::from_str(json_alt).unwrap();
7595        let ClaudeOutput::System(sys) = output else {
7596            panic!("Expected System message");
7597        };
7598        let compact = sys.as_compact_boundary().expect("compact_boundary");
7599        assert_eq!(compact.summary.as_deref(), Some("alt-key summary"));
7600        assert_eq!(compact.leaf_message_count, Some(7));
7601    }
7602
7603    #[test]
7604    fn test_init_message_with_new_fields() {
7605        let json = r#"{
7606            "type": "system",
7607            "subtype": "init",
7608            "session_id": "test-session",
7609            "cwd": "/home/user",
7610            "model": "claude-opus-4-7",
7611            "tools": ["Bash"],
7612            "mcp_servers": [],
7613            "permissionMode": "default",
7614            "apiKeySource": "none",
7615            "uuid": "44841a0d-182d-493a-86b5-79800d3d9665",
7616            "memory_paths": {"auto": "/home/user/.claude/projects/memory/"},
7617            "fast_mode_state": "off",
7618            "plugins": [{"name": "lsp", "path": "/plugins/lsp", "source": "lsp@official"}],
7619            "claude_code_version": "2.1.117"
7620        }"#;
7621
7622        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7623        if let ClaudeOutput::System(sys) = output {
7624            let init = sys.as_init().expect("Should parse as init");
7625            assert_eq!(
7626                init.uuid.as_deref(),
7627                Some("44841a0d-182d-493a-86b5-79800d3d9665")
7628            );
7629            assert!(init.memory_paths.is_some());
7630            assert_eq!(init.fast_mode_state.as_deref(), Some("off"));
7631            assert_eq!(init.plugins[0].source.as_deref(), Some("lsp@official"));
7632            assert_eq!(init.claude_code_version.as_deref(), Some("2.1.117"));
7633        } else {
7634            panic!("Expected System message");
7635        }
7636    }
7637
7638    #[test]
7639    fn test_assistant_message_with_new_fields() {
7640        let json = r#"{
7641            "type": "assistant",
7642            "message": {
7643                "id": "msg_1",
7644                "type": "message",
7645                "role": "assistant",
7646                "model": "claude-opus-4-7",
7647                "content": [{"type": "text", "text": "Hello"}],
7648                "stop_reason": "end_turn",
7649                "stop_details": null,
7650                "context_management": null,
7651                "usage": {
7652                    "input_tokens": 100,
7653                    "output_tokens": 10,
7654                    "cache_creation_input_tokens": 50,
7655                    "cache_read_input_tokens": 0,
7656                    "service_tier": "standard",
7657                    "inference_geo": "not_available"
7658                }
7659            },
7660            "session_id": "abc",
7661            "uuid": "msg-uuid-123"
7662        }"#;
7663
7664        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7665        if let ClaudeOutput::Assistant(asst) = output {
7666            assert_eq!(asst.message.stop_details, None);
7667            assert_eq!(asst.message.context_management, None);
7668            let usage = asst.message.usage.unwrap();
7669            assert_eq!(usage.inference_geo.as_deref(), Some("not_available"));
7670        } else {
7671            panic!("Expected Assistant message");
7672        }
7673    }
7674
7675    #[test]
7676    fn test_user_message_with_new_fields() {
7677        let json = r#"{
7678            "type": "user",
7679            "message": {
7680                "role": "user",
7681                "content": [{"type": "text", "text": "Hello"}]
7682            },
7683            "session_id": "9abbc466-dad0-4b8e-b6b0-cad5eb7a16b9",
7684            "parent_tool_use_id": "toolu_123",
7685            "uuid": "user-msg-456"
7686        }"#;
7687
7688        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7689        if let ClaudeOutput::User(user) = output {
7690            assert_eq!(user.parent_tool_use_id.as_deref(), Some("toolu_123"));
7691            assert_eq!(user.uuid.as_deref(), Some("user-msg-456"));
7692        } else {
7693            panic!("Expected User message");
7694        }
7695    }
7696
7697    /// Real wire payload captured from the CLI after answering an
7698    /// AskUserQuestion via the permission control protocol. The top-level
7699    /// `tool_use_result` and `timestamp` fields must round-trip without loss —
7700    /// proxies using this crate to relay messages to a viewer rely on those
7701    /// fields being preserved (the viewer reads `tool_use_result.answers`).
7702    #[test]
7703    fn test_user_message_preserves_tool_use_result_and_timestamp() {
7704        let json = r#"{
7705            "type":"user",
7706            "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"}]},
7707            "parent_tool_use_id":null,
7708            "session_id":"622ae0c3-3d50-4fa7-9ee0-69d691238c6d",
7709            "uuid":"8ef6e997-a849-4d15-bed3-2837c3d3f4cd",
7710            "timestamp":"2026-05-12T23:12:04.121Z",
7711            "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"}}
7712        }"#;
7713
7714        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7715        let user = match output {
7716            ClaudeOutput::User(u) => u,
7717            other => panic!("Expected User message, got {:?}", other.message_type()),
7718        };
7719
7720        assert_eq!(user.timestamp.as_deref(), Some("2026-05-12T23:12:04.121Z"));
7721        let raw = user
7722            .tool_use_result
7723            .as_ref()
7724            .expect("tool_use_result must be captured");
7725        assert_eq!(raw["answers"]["Color"], "Blue");
7726        assert_eq!(raw["questions"][0]["header"], "Color");
7727
7728        // Round-trip: re-serialize and confirm tool_use_result + timestamp
7729        // survive — the bug we're guarding against is that the proxy silently
7730        // drops these fields when relaying user messages.
7731        let reser: serde_json::Value = serde_json::to_value(&user).unwrap();
7732        assert_eq!(reser["timestamp"], "2026-05-12T23:12:04.121Z");
7733        assert_eq!(reser["tool_use_result"]["answers"]["Color"], "Blue");
7734        assert_eq!(
7735            reser["tool_use_result"]["questions"][0]["question"],
7736            "Which color do you prefer?"
7737        );
7738
7739        // Typed accessor: AskUserQuestionInput has the same shape as the
7740        // AskUserQuestion tool_use_result.
7741        let typed: crate::AskUserQuestionInput = user
7742            .tool_use_result_as::<crate::AskUserQuestionInput>()
7743            .expect("tool_use_result present")
7744            .expect("AskUserQuestionInput parses");
7745        assert_eq!(typed.questions.len(), 1);
7746        assert_eq!(typed.questions[0].header, "Color");
7747        let answers = typed.answers.expect("answers populated");
7748        assert_eq!(answers.get("Color").map(String::as_str), Some("Blue"));
7749    }
7750
7751    /// User messages without `tool_use_result` / `timestamp` must still
7752    /// deserialize fine and serialize back without spuriously emitting nulls.
7753    #[test]
7754    fn test_user_message_without_tool_use_result_omits_field() {
7755        let json = r#"{
7756            "type":"user",
7757            "message":{"role":"user","content":[{"type":"text","text":"hello"}]},
7758            "session_id":"622ae0c3-3d50-4fa7-9ee0-69d691238c6d"
7759        }"#;
7760
7761        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7762        let user = match output {
7763            ClaudeOutput::User(u) => u,
7764            _ => panic!("Expected User message"),
7765        };
7766        assert!(user.tool_use_result.is_none());
7767        assert!(user.timestamp.is_none());
7768
7769        let reser = serde_json::to_value(&user).unwrap();
7770        assert!(reser.get("tool_use_result").is_none());
7771        assert!(reser.get("timestamp").is_none());
7772    }
7773
7774    /// A `Task` tool result must expose subagent token / timing / tool-use
7775    /// accounting through the typed [`UserMessage::subagent_result`] accessor,
7776    /// including the nested per-model `usage` breakdown and `toolStats`.
7777    #[test]
7778    fn test_subagent_result_exposes_token_accounting() {
7779        let json = r#"{
7780            "type":"user",
7781            "message":{"role":"user","content":[{"tool_use_id":"toolu_01","type":"tool_result","content":[{"type":"text","text":"21"}]}]},
7782            "session_id":"d3fc5942-75e5-4aa1-a87d-b9484a176541",
7783            "tool_use_result":{
7784                "status":"completed",
7785                "prompt":"Count the .rs files.",
7786                "agentId":"ac4f0276e9d4b6232",
7787                "agentType":"Explore",
7788                "content":[{"type":"text","text":"21"}],
7789                "resolvedModel":"claude-haiku-4-5-20251001",
7790                "totalDurationMs":6869,
7791                "totalTokens":7834,
7792                "totalToolUseCount":1,
7793                "usage":{"input_tokens":6,"cache_creation_input_tokens":125,"cache_read_input_tokens":7699,"output_tokens":4,"service_tier":"standard"},
7794                "toolStats":{"readCount":0,"searchCount":0,"bashCount":1,"editFileCount":0,"linesAdded":0,"linesRemoved":0,"otherToolCount":0}
7795            }
7796        }"#;
7797
7798        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7799        let user = match output {
7800            ClaudeOutput::User(u) => u,
7801            _ => panic!("Expected User message"),
7802        };
7803
7804        let result = user.subagent_result().expect("subagent result parses");
7805        assert_eq!(result.agent_type.as_deref(), Some("Explore"));
7806        assert_eq!(
7807            result.resolved_model.as_deref(),
7808            Some("claude-haiku-4-5-20251001")
7809        );
7810        assert_eq!(result.total_tokens, Some(7834));
7811        assert_eq!(result.total_duration_ms, Some(6869));
7812        assert_eq!(result.total_tool_use_count, Some(1));
7813
7814        let usage = result.usage.expect("nested usage present");
7815        assert_eq!(usage.input_tokens, 6);
7816        assert_eq!(usage.cache_read_input_tokens, 7699);
7817
7818        let stats = result.tool_stats.expect("toolStats present");
7819        assert_eq!(stats.bash_count, 1);
7820    }
7821
7822    /// `tool_use_result` shapes that aren't subagent runs (e.g. AskUserQuestion)
7823    /// parse leniently into the all-`Option` [`SubagentResult`] with empty
7824    /// accounting rather than failing, so callers can probe without panicking.
7825    #[test]
7826    fn test_subagent_result_absent_for_non_task_result() {
7827        let json = r#"{
7828            "type":"user",
7829            "message":{"role":"user","content":[{"type":"text","text":"hi"}]},
7830            "session_id":"622ae0c3-3d50-4fa7-9ee0-69d691238c6d",
7831            "tool_use_result":{"questions":[],"answers":{"Color":"Blue"}}
7832        }"#;
7833
7834        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7835        let user = match output {
7836            ClaudeOutput::User(u) => u,
7837            _ => panic!("Expected User message"),
7838        };
7839
7840        let result = user.subagent_result().expect("lenient parse");
7841        assert_eq!(result.total_tokens, None);
7842        assert_eq!(result.agent_type, None);
7843    }
7844
7845    #[test]
7846    fn test_init_fast_mode_reason_and_mcp_server_errors_fully_wrapped() {
7847        use serde_json::Value;
7848
7849        let raw: Value = serde_json::from_str(
7850            r#"{
7851            "type":"system","subtype":"init","session_id":"s1","uuid":"u1",
7852            "fast_mode_state":"off",
7853            "fast_mode_disabled_reason":"not_first_party",
7854            "mcp_server_errors":[{"name":"broken","type":"invalid_config","message":"url entry with no type"}]
7855        }"#,
7856        )
7857        .unwrap();
7858        crate::io::assert_fully_wrapped(&raw);
7859
7860        let output: ClaudeOutput = serde_json::from_value(raw).unwrap();
7861        let ClaudeOutput::System(sys) = output else {
7862            panic!("expected System");
7863        };
7864        let init = sys.as_init().expect("parses as init");
7865        assert_eq!(
7866            init.fast_mode_disabled_reason,
7867            Some(crate::FastModeDisabledReason::NotFirstParty)
7868        );
7869        let errs = init.mcp_server_errors.unwrap();
7870        assert_eq!(errs.len(), 1);
7871        assert_eq!(errs[0].name, "broken");
7872        assert_eq!(errs[0].error_type, "invalid_config");
7873    }
7874
7875    #[test]
7876    fn test_code_change_published_fully_wrapped() {
7877        use super::{KnownSystemEvent, SystemSubtype};
7878        use serde_json::Value;
7879
7880        let raw: Value = serde_json::from_str(
7881            r#"{
7882            "type":"system","subtype":"code_change_published",
7883            "provider":"github","url":"https://github.com/owner/repo/pull/42",
7884            "repo":"owner/repo","identifier":"42",
7885            "uuid":"u1","session_id":"s1"
7886        }"#,
7887        )
7888        .unwrap();
7889        crate::io::assert_fully_wrapped(&raw);
7890
7891        let output: ClaudeOutput = serde_json::from_value(raw).unwrap();
7892        let ClaudeOutput::System(sys) = output else {
7893            panic!("expected System");
7894        };
7895        assert_eq!(sys.subtype, SystemSubtype::CodeChangePublished);
7896        let Some(KnownSystemEvent::CodeChangePublished(msg)) = sys.as_known_system_event() else {
7897            panic!("expected CodeChangePublished event");
7898        };
7899        assert_eq!(msg.provider, "github");
7900        assert_eq!(msg.repo, "owner/repo");
7901        assert_eq!(msg.identifier, "42");
7902
7903        assert!(sys.is_code_change_published());
7904        assert!(!sys.is_vcs_state_changed());
7905        let direct = sys.as_code_change_published().expect("direct accessor");
7906        assert_eq!(direct.url, "https://github.com/owner/repo/pull/42");
7907        assert!(sys.as_vcs_state_changed().is_none());
7908    }
7909
7910    #[test]
7911    fn test_feedback_draft_queued_fully_wrapped() {
7912        use super::{KnownSystemEvent, SystemSubtype};
7913        use serde_json::Value;
7914
7915        let raw: Value = serde_json::from_str(
7916            r#"{
7917            "type":"system","subtype":"feedback_draft_queued",
7918            "draft_id":"draft-1","draft_type":"bug_report",
7919            "title":"Tool output was truncated",
7920            "details_preview":"The last command omitted its final lines",
7921            "uuid":"u1","session_id":"s1","future_field":"preserved"
7922        }"#,
7923        )
7924        .unwrap();
7925        crate::io::assert_fully_wrapped(&raw);
7926
7927        let output: ClaudeOutput = serde_json::from_value(raw).unwrap();
7928        let ClaudeOutput::System(sys) = output else {
7929            panic!("expected System");
7930        };
7931        assert_eq!(sys.subtype, SystemSubtype::FeedbackDraftQueued);
7932        assert!(sys.is_feedback_draft_queued());
7933        assert!(!sys.is_vcs_state_changed());
7934
7935        let direct = sys
7936            .as_feedback_draft_queued()
7937            .expect("direct typed accessor");
7938        assert_eq!(direct.draft_id, "draft-1");
7939        assert_eq!(direct.draft_type, "bug_report");
7940        assert_eq!(direct.extra["future_field"], "preserved");
7941
7942        let Some(KnownSystemEvent::FeedbackDraftQueued(known)) = sys.as_known_system_event() else {
7943            panic!("expected FeedbackDraftQueued event");
7944        };
7945        assert_eq!(known.title, "Tool output was truncated");
7946        assert_eq!(
7947            sys.typed_value().expect("typed value")["future_field"],
7948            "preserved"
7949        );
7950    }
7951
7952    #[test]
7953    fn test_cloud_session_delta_fully_wrapped() {
7954        use super::{KnownSystemEvent, SystemSubtype};
7955        use serde_json::Value;
7956
7957        let raw: Value = serde_json::from_str(
7958            r#"{
7959            "type":"system","subtype":"cloud_session_delta",
7960            "seq":3,"changed":["serving","connection"],
7961            "cloud_session":{"id":"session_abc","view_url":"https://example.invalid/s/abc",
7962                "serving":{"state":"on"},"connection":{"state":"live"}},
7963            "uuid":"u1","session_id":"s1","future_field":"preserved"
7964        }"#,
7965        )
7966        .unwrap();
7967        crate::io::assert_fully_wrapped(&raw);
7968
7969        let output: ClaudeOutput = serde_json::from_value(raw).unwrap();
7970        let ClaudeOutput::System(sys) = output else {
7971            panic!("expected System");
7972        };
7973        assert_eq!(sys.subtype, SystemSubtype::CloudSessionDelta);
7974        assert!(sys.is_cloud_session_delta());
7975        assert!(!sys.is_feedback_draft_queued());
7976
7977        let direct = sys.as_cloud_session_delta().expect("direct typed accessor");
7978        assert_eq!(direct.seq, 3);
7979        assert_eq!(direct.changed, vec!["serving", "connection"]);
7980        assert_eq!(direct.cloud_session["id"], "session_abc");
7981        assert_eq!(direct.extra["future_field"], "preserved");
7982
7983        let Some(KnownSystemEvent::CloudSessionDelta(known)) = sys.as_known_system_event() else {
7984            panic!("expected CloudSessionDelta event");
7985        };
7986        assert_eq!(known.session_id, "s1");
7987        assert_eq!(
7988            sys.typed_value().expect("typed value")["future_field"],
7989            "preserved"
7990        );
7991    }
7992
7993    #[test]
7994    fn test_vcs_state_changed_fully_wrapped() {
7995        use super::{KnownSystemEvent, VcsMutationKind};
7996        use serde_json::Value;
7997
7998        for kind in ["commit", "push", "merge", "rebase"] {
7999            let raw: Value = serde_json::from_str(&format!(
8000                r#"{{"type":"system","subtype":"vcs_state_changed","kind":"{}","cwd":"/repo","uuid":"u1","session_id":"s1"}}"#,
8001                kind
8002            ))
8003            .unwrap();
8004            crate::io::assert_fully_wrapped(&raw);
8005
8006            let output: ClaudeOutput = serde_json::from_value(raw).unwrap();
8007            let ClaudeOutput::System(sys) = output else {
8008                panic!("expected System");
8009            };
8010            let Some(KnownSystemEvent::VcsStateChanged(msg)) = sys.as_known_system_event() else {
8011                panic!("expected VcsStateChanged event");
8012            };
8013            assert_eq!(msg.kind.as_str(), kind);
8014            assert!(!matches!(msg.kind, VcsMutationKind::Unknown(_)));
8015        }
8016
8017        // Unknown kinds are valid per the wire contract.
8018        let raw: Value = serde_json::from_str(
8019            r#"{"type":"system","subtype":"vcs_state_changed","kind":"tag","cwd":"/repo","uuid":"u2","session_id":"s2"}"#,
8020        )
8021        .unwrap();
8022        crate::io::assert_fully_wrapped(&raw);
8023        let output: ClaudeOutput = serde_json::from_value(raw).unwrap();
8024        let ClaudeOutput::System(sys) = output else {
8025            panic!("expected System");
8026        };
8027        let Some(KnownSystemEvent::VcsStateChanged(msg)) = sys.as_known_system_event() else {
8028            panic!("expected VcsStateChanged event");
8029        };
8030        assert_eq!(msg.kind, VcsMutationKind::Unknown("tag".to_string()));
8031
8032        assert!(sys.is_vcs_state_changed());
8033        let direct = sys.as_vcs_state_changed().expect("direct accessor");
8034        assert_eq!(direct.cwd, "/repo");
8035        assert!(sys.as_code_change_published().is_none());
8036    }
8037
8038    #[test]
8039    fn test_assistant_aborted_and_resume_flags_roundtrip() {
8040        let json = r#"{
8041            "type":"assistant",
8042            "message":{"id":"msg_1","role":"assistant","model":"claude-3","content":[{"type":"text","text":"partial"}]},
8043            "session_id":"s1",
8044            "aborted":true,
8045            "resumed_from_incomplete_thinking":true
8046        }"#;
8047        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
8048        let ClaudeOutput::Assistant(msg) = &output else {
8049            panic!("expected Assistant");
8050        };
8051        assert_eq!(msg.aborted, Some(true));
8052        assert_eq!(msg.resumed_from_incomplete_thinking, Some(true));
8053        let reserialized = serde_json::to_string(&output).unwrap();
8054        assert!(reserialized.contains("\"aborted\":true"));
8055        assert!(reserialized.contains("\"resumed_from_incomplete_thinking\":true"));
8056
8057        // Absent flags stay absent on the wire.
8058        let json = r#"{
8059            "type":"assistant",
8060            "message":{"id":"msg_2","role":"assistant","model":"claude-3","content":[]},
8061            "session_id":"s2"
8062        }"#;
8063        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
8064        let reserialized = serde_json::to_string(&output).unwrap();
8065        assert!(!reserialized.contains("aborted"));
8066        assert!(!reserialized.contains("resumed_from_incomplete_thinking"));
8067    }
8068
8069    #[test]
8070    fn test_user_tool_result_meta_roundtrip() {
8071        let json = r#"{
8072            "type":"user",
8073            "message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_1","content":"denied"}]},
8074            "session_id":"622ae0c3-3d50-4fa7-9ee0-69d691238c6d",
8075            "tool_result_meta":[
8076                {"id":"toolu_1","non_execution_kind":"user-rejected","user_feedback":"use the staging db"},
8077                {"id":"toolu_2","non_execution_kind":"permission-rule"}
8078            ]
8079        }"#;
8080        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
8081        let ClaudeOutput::User(user) = &output else {
8082            panic!("expected User");
8083        };
8084        let meta = user.tool_result_meta.as_ref().unwrap();
8085        assert_eq!(meta.len(), 2);
8086        assert_eq!(meta[0].non_execution_kind.as_deref(), Some("user-rejected"));
8087        assert_eq!(meta[0].user_feedback.as_deref(), Some("use the staging db"));
8088        assert_eq!(meta[1].user_feedback, None);
8089
8090        let reserialized = serde_json::to_string(&output).unwrap();
8091        assert!(reserialized.contains("\"non_execution_kind\":\"user-rejected\""));
8092        assert!(!reserialized.contains("\"user_feedback\":null"));
8093    }
8094
8095    /// CLI 2.1.222 added `scope` to `system/model_refusal_fallback`:
8096    /// "session" (main-thread swap, also the meaning when absent on older
8097    /// CLIs) vs "local" (subagent/side-question fallback only).
8098    #[test]
8099    fn model_refusal_fallback_scope_roundtrips_and_defaults() {
8100        use super::{ModelRefusalFallbackMessage, RefusalFallbackScope};
8101        let with_scope = serde_json::json!({
8102            "trigger": "refusal",
8103            "direction": "retry",
8104            "scope": "local",
8105            "original_model": "claude-fable-5",
8106            "fallback_model": "claude-opus-5",
8107            "request_id": null,
8108            "content": "Refused; retried on fallback model.",
8109            "uuid": "u1",
8110            "session_id": "s1"
8111        });
8112        let msg: ModelRefusalFallbackMessage = serde_json::from_value(with_scope.clone()).unwrap();
8113        assert_eq!(msg.scope, Some(RefusalFallbackScope::Local));
8114        assert_eq!(serde_json::to_value(&msg).unwrap(), with_scope);
8115
8116        // Older CLIs omit scope — absent, not null, and treated as session
8117        // by consumers per the wire docs.
8118        let mut without = with_scope.clone();
8119        without.as_object_mut().unwrap().remove("scope");
8120        let msg: ModelRefusalFallbackMessage = serde_json::from_value(without.clone()).unwrap();
8121        assert_eq!(msg.scope, None);
8122        assert_eq!(serde_json::to_value(&msg).unwrap(), without);
8123
8124        // Open enum: unknown scopes pass through verbatim.
8125        assert_eq!(
8126            RefusalFallbackScope::from("workspace").as_str(),
8127            "workspace"
8128        );
8129    }
8130}