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