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