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