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#[derive(Debug, Clone, PartialEq, Eq, Hash)]
16pub enum SystemSubtype {
17 Init,
18 Status,
19 CompactBoundary,
20 ThinkingTokens,
21 TaskStarted,
22 TaskProgress,
23 TaskUpdated,
24 TaskNotification,
25 ApiRetry,
26 ControlRequestProgress,
27 ModelRefusalFallback,
28 ModelRefusalNoFallback,
29 LocalCommandOutput,
30 HookStarted,
31 HookProgress,
32 HookResponse,
33 PluginInstall,
34 BackgroundTasksChanged,
35 SessionStateChanged,
36 WorkerShuttingDown,
37 CommandsChanged,
38 Notification,
39 FilesPersisted,
40 MemoryRecall,
41 ElicitationComplete,
42 PermissionDenied,
43 MirrorError,
44 Informational,
45 CodeChangePublished,
46 VcsStateChanged,
47 FeedbackDraftQueued,
48 CloudSessionDelta,
49 DevIntent,
50 TurnHandoffAvailable,
51 TurnPreempted,
52 PeerMessageHold,
53 PerTurnEffortChanged,
54 SessionTitleChanged,
55 SessionWritesLost,
56 InstructionSizeWarning,
57 FileAttachmentsMissing,
58 PermissionCheckStatus,
59 InheritedAsksSettled,
60 LateAllowNotRun,
61 ShellCwd,
62 UiFocus,
63 UiInvalidate,
64 UiLog,
65 UiNotify,
66 UiNotifyCancel,
67 UiPanes,
68 UiPlaced,
69 UiScroll,
70 UiStatus,
71 UiToast,
72 Unknown(String),
74}
75
76impl SystemSubtype {
77 pub fn as_str(&self) -> &str {
78 match self {
79 Self::Init => "init",
80 Self::Status => "status",
81 Self::CompactBoundary => "compact_boundary",
82 Self::ThinkingTokens => "thinking_tokens",
83 Self::TaskStarted => "task_started",
84 Self::TaskProgress => "task_progress",
85 Self::TaskUpdated => "task_updated",
86 Self::TaskNotification => "task_notification",
87 Self::ApiRetry => "api_retry",
88 Self::ControlRequestProgress => "control_request_progress",
89 Self::ModelRefusalFallback => "model_refusal_fallback",
90 Self::ModelRefusalNoFallback => "model_refusal_no_fallback",
91 Self::LocalCommandOutput => "local_command_output",
92 Self::HookStarted => "hook_started",
93 Self::HookProgress => "hook_progress",
94 Self::HookResponse => "hook_response",
95 Self::PluginInstall => "plugin_install",
96 Self::BackgroundTasksChanged => "background_tasks_changed",
97 Self::SessionStateChanged => "session_state_changed",
98 Self::WorkerShuttingDown => "worker_shutting_down",
99 Self::CommandsChanged => "commands_changed",
100 Self::Notification => "notification",
101 Self::FilesPersisted => "files_persisted",
102 Self::MemoryRecall => "memory_recall",
103 Self::ElicitationComplete => "elicitation_complete",
104 Self::PermissionDenied => "permission_denied",
105 Self::MirrorError => "mirror_error",
106 Self::Informational => "informational",
107 Self::CodeChangePublished => "code_change_published",
108 Self::VcsStateChanged => "vcs_state_changed",
109 Self::FeedbackDraftQueued => "feedback_draft_queued",
110 Self::CloudSessionDelta => "cloud_session_delta",
111 Self::DevIntent => "dev_intent",
112 Self::TurnHandoffAvailable => "turn_handoff_available",
113 Self::TurnPreempted => "turn_preempted",
114 Self::PeerMessageHold => "peer_message_hold",
115 Self::PerTurnEffortChanged => "per_turn_effort_changed",
116 Self::SessionTitleChanged => "session_title_changed",
117 Self::SessionWritesLost => "session_writes_lost",
118 Self::InstructionSizeWarning => "instruction_size_warning",
119 Self::FileAttachmentsMissing => "file_attachments_missing",
120 Self::PermissionCheckStatus => "permission_check_status",
121 Self::InheritedAsksSettled => "inherited_asks_settled",
122 Self::LateAllowNotRun => "late_allow_not_run",
123 Self::ShellCwd => "shell_cwd",
124 Self::UiFocus => "ui_focus",
125 Self::UiInvalidate => "ui_invalidate",
126 Self::UiLog => "ui_log",
127 Self::UiNotify => "ui_notify",
128 Self::UiNotifyCancel => "ui_notify_cancel",
129 Self::UiPanes => "ui_panes",
130 Self::UiPlaced => "ui_placed",
131 Self::UiScroll => "ui_scroll",
132 Self::UiStatus => "ui_status",
133 Self::UiToast => "ui_toast",
134 Self::Unknown(s) => s.as_str(),
135 }
136 }
137}
138
139impl fmt::Display for SystemSubtype {
140 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141 f.write_str(self.as_str())
142 }
143}
144
145impl From<&str> for SystemSubtype {
146 fn from(s: &str) -> Self {
147 match s {
148 "init" => Self::Init,
149 "status" => Self::Status,
150 "compact_boundary" => Self::CompactBoundary,
151 "thinking_tokens" => Self::ThinkingTokens,
152 "task_started" => Self::TaskStarted,
153 "task_progress" => Self::TaskProgress,
154 "task_updated" => Self::TaskUpdated,
155 "task_notification" => Self::TaskNotification,
156 "api_retry" => Self::ApiRetry,
157 "control_request_progress" => Self::ControlRequestProgress,
158 "model_refusal_fallback" => Self::ModelRefusalFallback,
159 "model_refusal_no_fallback" => Self::ModelRefusalNoFallback,
160 "local_command_output" => Self::LocalCommandOutput,
161 "hook_started" => Self::HookStarted,
162 "hook_progress" => Self::HookProgress,
163 "hook_response" => Self::HookResponse,
164 "plugin_install" => Self::PluginInstall,
165 "background_tasks_changed" => Self::BackgroundTasksChanged,
166 "session_state_changed" => Self::SessionStateChanged,
167 "worker_shutting_down" => Self::WorkerShuttingDown,
168 "commands_changed" => Self::CommandsChanged,
169 "notification" => Self::Notification,
170 "files_persisted" => Self::FilesPersisted,
171 "memory_recall" => Self::MemoryRecall,
172 "elicitation_complete" => Self::ElicitationComplete,
173 "permission_denied" => Self::PermissionDenied,
174 "mirror_error" => Self::MirrorError,
175 "informational" => Self::Informational,
176 "code_change_published" => Self::CodeChangePublished,
177 "vcs_state_changed" => Self::VcsStateChanged,
178 "feedback_draft_queued" => Self::FeedbackDraftQueued,
179 "cloud_session_delta" => Self::CloudSessionDelta,
180 "dev_intent" => Self::DevIntent,
181 "turn_handoff_available" => Self::TurnHandoffAvailable,
182 "turn_preempted" => Self::TurnPreempted,
183 "peer_message_hold" => Self::PeerMessageHold,
184 "per_turn_effort_changed" => Self::PerTurnEffortChanged,
185 "session_title_changed" => Self::SessionTitleChanged,
186 "session_writes_lost" => Self::SessionWritesLost,
187 "instruction_size_warning" => Self::InstructionSizeWarning,
188 "file_attachments_missing" => Self::FileAttachmentsMissing,
189 "permission_check_status" => Self::PermissionCheckStatus,
190 "inherited_asks_settled" => Self::InheritedAsksSettled,
191 "late_allow_not_run" => Self::LateAllowNotRun,
192 "shell_cwd" => Self::ShellCwd,
193 "ui_focus" => Self::UiFocus,
194 "ui_invalidate" => Self::UiInvalidate,
195 "ui_log" => Self::UiLog,
196 "ui_notify" => Self::UiNotify,
197 "ui_notify_cancel" => Self::UiNotifyCancel,
198 "ui_panes" => Self::UiPanes,
199 "ui_placed" => Self::UiPlaced,
200 "ui_scroll" => Self::UiScroll,
201 "ui_status" => Self::UiStatus,
202 "ui_toast" => Self::UiToast,
203 other => Self::Unknown(other.to_string()),
204 }
205 }
206}
207
208impl Serialize for SystemSubtype {
209 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
210 serializer.serialize_str(self.as_str())
211 }
212}
213
214impl<'de> Deserialize<'de> for SystemSubtype {
215 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
216 let s = String::deserialize(deserializer)?;
217 Ok(Self::from(s.as_str()))
218 }
219}
220
221#[derive(Debug, Clone, PartialEq, Eq, Hash)]
226pub enum MessageRole {
227 User,
228 Assistant,
229 Unknown(String),
231}
232
233impl MessageRole {
234 pub fn as_str(&self) -> &str {
235 match self {
236 Self::User => "user",
237 Self::Assistant => "assistant",
238 Self::Unknown(s) => s.as_str(),
239 }
240 }
241}
242
243impl fmt::Display for MessageRole {
244 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
245 f.write_str(self.as_str())
246 }
247}
248
249impl From<&str> for MessageRole {
250 fn from(s: &str) -> Self {
251 match s {
252 "user" => Self::User,
253 "assistant" => Self::Assistant,
254 other => Self::Unknown(other.to_string()),
255 }
256 }
257}
258
259impl Serialize for MessageRole {
260 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
261 serializer.serialize_str(self.as_str())
262 }
263}
264
265impl<'de> Deserialize<'de> for MessageRole {
266 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
267 let s = String::deserialize(deserializer)?;
268 Ok(Self::from(s.as_str()))
269 }
270}
271
272#[derive(Debug, Clone, PartialEq, Eq, Hash)]
274pub enum CompactionTrigger {
275 Auto,
277 Manual,
279 Unknown(String),
281}
282
283impl CompactionTrigger {
284 pub fn as_str(&self) -> &str {
285 match self {
286 Self::Auto => "auto",
287 Self::Manual => "manual",
288 Self::Unknown(s) => s.as_str(),
289 }
290 }
291}
292
293impl fmt::Display for CompactionTrigger {
294 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
295 f.write_str(self.as_str())
296 }
297}
298
299impl From<&str> for CompactionTrigger {
300 fn from(s: &str) -> Self {
301 match s {
302 "auto" => Self::Auto,
303 "manual" => Self::Manual,
304 other => Self::Unknown(other.to_string()),
305 }
306 }
307}
308
309impl Serialize for CompactionTrigger {
310 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
311 serializer.serialize_str(self.as_str())
312 }
313}
314
315impl<'de> Deserialize<'de> for CompactionTrigger {
316 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
317 let s = String::deserialize(deserializer)?;
318 Ok(Self::from(s.as_str()))
319 }
320}
321
322#[derive(Debug, Clone, PartialEq, Eq, Hash)]
324pub enum StopReason {
325 EndTurn,
327 MaxTokens,
329 ToolUse,
331 Unknown(String),
333}
334
335impl StopReason {
336 pub fn as_str(&self) -> &str {
337 match self {
338 Self::EndTurn => "end_turn",
339 Self::MaxTokens => "max_tokens",
340 Self::ToolUse => "tool_use",
341 Self::Unknown(s) => s.as_str(),
342 }
343 }
344}
345
346impl fmt::Display for StopReason {
347 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
348 f.write_str(self.as_str())
349 }
350}
351
352impl From<&str> for StopReason {
353 fn from(s: &str) -> Self {
354 match s {
355 "end_turn" => Self::EndTurn,
356 "max_tokens" => Self::MaxTokens,
357 "tool_use" => Self::ToolUse,
358 other => Self::Unknown(other.to_string()),
359 }
360 }
361}
362
363impl Serialize for StopReason {
364 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
365 serializer.serialize_str(self.as_str())
366 }
367}
368
369impl<'de> Deserialize<'de> for StopReason {
370 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
371 let s = String::deserialize(deserializer)?;
372 Ok(Self::from(s.as_str()))
373 }
374}
375
376#[derive(Debug, Clone, PartialEq, Eq, Hash)]
378pub enum ApiKeySource {
379 None,
381 User,
382 Project,
383 Org,
384 Temporary,
385 Oauth,
386 Unknown(String),
388}
389
390impl ApiKeySource {
391 pub fn as_str(&self) -> &str {
392 match self {
393 Self::None => "none",
394 Self::User => "user",
395 Self::Project => "project",
396 Self::Org => "org",
397 Self::Temporary => "temporary",
398 Self::Oauth => "oauth",
399 Self::Unknown(s) => s.as_str(),
400 }
401 }
402}
403
404impl fmt::Display for ApiKeySource {
405 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
406 f.write_str(self.as_str())
407 }
408}
409
410impl From<&str> for ApiKeySource {
411 fn from(s: &str) -> Self {
412 match s {
413 "none" => Self::None,
414 "user" => Self::User,
415 "project" => Self::Project,
416 "org" => Self::Org,
417 "temporary" => Self::Temporary,
418 "oauth" => Self::Oauth,
419 other => Self::Unknown(other.to_string()),
420 }
421 }
422}
423
424impl Serialize for ApiKeySource {
425 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
426 serializer.serialize_str(self.as_str())
427 }
428}
429
430impl<'de> Deserialize<'de> for ApiKeySource {
431 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
432 let s = String::deserialize(deserializer)?;
433 Ok(Self::from(s.as_str()))
434 }
435}
436
437#[derive(Debug, Clone, PartialEq, Eq, Hash)]
439pub enum OutputStyle {
440 Default,
442 Unknown(String),
444}
445
446impl OutputStyle {
447 pub fn as_str(&self) -> &str {
448 match self {
449 Self::Default => "default",
450 Self::Unknown(s) => s.as_str(),
451 }
452 }
453}
454
455impl fmt::Display for OutputStyle {
456 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
457 f.write_str(self.as_str())
458 }
459}
460
461impl From<&str> for OutputStyle {
462 fn from(s: &str) -> Self {
463 match s {
464 "default" => Self::Default,
465 other => Self::Unknown(other.to_string()),
466 }
467 }
468}
469
470impl Serialize for OutputStyle {
471 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
472 serializer.serialize_str(self.as_str())
473 }
474}
475
476impl<'de> Deserialize<'de> for OutputStyle {
477 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
478 let s = String::deserialize(deserializer)?;
479 Ok(Self::from(s.as_str()))
480 }
481}
482
483#[derive(Debug, Clone, PartialEq, Eq, Hash)]
485pub enum InitPermissionMode {
486 Default,
488 AcceptEdits,
489 BypassPermissions,
490 Plan,
491 DontAsk,
492 Auto,
493 Unknown(String),
495}
496
497impl InitPermissionMode {
498 pub fn as_str(&self) -> &str {
499 match self {
500 Self::Default => "default",
501 Self::AcceptEdits => "acceptEdits",
502 Self::BypassPermissions => "bypassPermissions",
503 Self::Plan => "plan",
504 Self::DontAsk => "dontAsk",
505 Self::Auto => "auto",
506 Self::Unknown(s) => s.as_str(),
507 }
508 }
509}
510
511impl fmt::Display for InitPermissionMode {
512 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
513 f.write_str(self.as_str())
514 }
515}
516
517impl From<&str> for InitPermissionMode {
518 fn from(s: &str) -> Self {
519 match s {
520 "default" => Self::Default,
521 "acceptEdits" => Self::AcceptEdits,
522 "bypassPermissions" => Self::BypassPermissions,
523 "plan" => Self::Plan,
524 "dontAsk" => Self::DontAsk,
525 "auto" => Self::Auto,
526 other => Self::Unknown(other.to_string()),
527 }
528 }
529}
530
531impl Serialize for InitPermissionMode {
532 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
533 serializer.serialize_str(self.as_str())
534 }
535}
536
537impl<'de> Deserialize<'de> for InitPermissionMode {
538 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
539 let s = String::deserialize(deserializer)?;
540 Ok(Self::from(s.as_str()))
541 }
542}
543
544#[derive(Debug, Clone, PartialEq, Eq, Hash)]
546pub enum StatusMessageStatus {
547 Compacting,
549 Requesting,
551 Unknown(String),
553}
554
555impl StatusMessageStatus {
556 pub fn as_str(&self) -> &str {
557 match self {
558 Self::Compacting => "compacting",
559 Self::Requesting => "requesting",
560 Self::Unknown(s) => s.as_str(),
561 }
562 }
563}
564
565impl fmt::Display for StatusMessageStatus {
566 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
567 f.write_str(self.as_str())
568 }
569}
570
571impl From<&str> for StatusMessageStatus {
572 fn from(s: &str) -> Self {
573 match s {
574 "compacting" => Self::Compacting,
575 "requesting" => Self::Requesting,
576 other => Self::Unknown(other.to_string()),
577 }
578 }
579}
580
581impl Serialize for StatusMessageStatus {
582 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
583 serializer.serialize_str(self.as_str())
584 }
585}
586
587impl<'de> Deserialize<'de> for StatusMessageStatus {
588 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
589 let s = String::deserialize(deserializer)?;
590 Ok(Self::from(s.as_str()))
591 }
592}
593
594pub(crate) fn serialize_optional_uuid<S>(
596 uuid: &Option<Uuid>,
597 serializer: S,
598) -> Result<S::Ok, S::Error>
599where
600 S: Serializer,
601{
602 match uuid {
603 Some(id) => serializer.serialize_str(&id.to_string()),
604 None => serializer.serialize_none(),
605 }
606}
607
608pub(crate) fn deserialize_optional_uuid<'de, D>(deserializer: D) -> Result<Option<Uuid>, D::Error>
610where
611 D: Deserializer<'de>,
612{
613 let opt_str: Option<String> = Option::deserialize(deserializer)?;
614 match opt_str {
615 Some(s) => Uuid::parse_str(&s)
616 .map(Some)
617 .map_err(serde::de::Error::custom),
618 None => Ok(None),
619 }
620}
621
622#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
625pub struct MessageOrigin {
626 pub kind: String,
627 #[serde(flatten)]
628 pub extra: serde_json::Map<String, Value>,
629}
630
631#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
633pub struct SummarizeMetadata {
634 pub messages_summarized: u64,
635 #[serde(default, skip_serializing_if = "Option::is_none")]
636 pub user_context: Option<String>,
637 #[serde(default, skip_serializing_if = "Option::is_none")]
638 pub direction: Option<String>,
639}
640
641#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
643pub struct McpMeta {
644 #[serde(default, skip_serializing_if = "Option::is_none", rename = "_meta")]
645 pub meta: Option<Value>,
646 #[serde(default, skip_serializing_if = "Option::is_none")]
647 pub structured_content: Option<Value>,
648 #[serde(default, skip_serializing_if = "Vec::is_empty")]
653 pub resource_links: Vec<ResourceLink>,
654}
655
656#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
660pub struct ResourceLink {
661 pub uri: String,
662 pub name: String,
663 #[serde(default, skip_serializing_if = "Option::is_none")]
664 pub title: Option<String>,
665 #[serde(default, skip_serializing_if = "Option::is_none")]
666 pub description: Option<String>,
667 #[serde(default, skip_serializing_if = "Option::is_none", rename = "mimeType")]
668 pub mime_type: Option<String>,
669 #[serde(default, skip_serializing_if = "Option::is_none")]
670 pub size: Option<u64>,
671 #[serde(default, skip_serializing_if = "Option::is_none")]
672 pub annotations: Option<Value>,
673}
674
675#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
677pub struct ToolResultMeta {
678 pub id: String,
680 #[serde(default, skip_serializing_if = "Option::is_none")]
687 pub non_execution_kind: Option<String>,
688 #[serde(default, skip_serializing_if = "Option::is_none")]
690 pub user_feedback: Option<String>,
691 #[serde(default, skip_serializing_if = "Option::is_none")]
696 pub remedy: Option<ToolResultRemedy>,
697 #[serde(default, skip_serializing_if = "Option::is_none")]
704 pub permission_decision: Option<ToolPermissionDecision>,
705 #[serde(default, skip_serializing_if = "Option::is_none")]
712 pub built_in_tool: Option<String>,
713 #[serde(default, skip_serializing_if = "Option::is_none")]
720 pub run_input: Option<String>,
721}
722
723#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
727pub struct ToolPermissionDecision {
728 pub decision: PermissionDecisionOutcome,
730 pub source: String,
738 #[serde(default, skip_serializing_if = "Option::is_none")]
744 pub reason_type: Option<PermissionDecisionReasonType>,
745 #[serde(default, skip_serializing_if = "Option::is_none")]
751 pub plugin_approval: Option<PluginApproval>,
752 #[serde(default, skip_serializing_if = "Option::is_none")]
758 pub auto_mode_rule: Option<AutoModeRule>,
759}
760
761#[derive(Debug, Clone, PartialEq, Eq, Hash)]
764pub enum PluginApproval {
765 Applied,
767 Refused,
769 Unknown(String),
771}
772
773impl PluginApproval {
774 pub fn as_str(&self) -> &str {
775 match self {
776 Self::Applied => "applied",
777 Self::Refused => "refused",
778 Self::Unknown(s) => s.as_str(),
779 }
780 }
781}
782
783impl fmt::Display for PluginApproval {
784 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
785 f.write_str(self.as_str())
786 }
787}
788
789impl From<&str> for PluginApproval {
790 fn from(s: &str) -> Self {
791 match s {
792 "applied" => Self::Applied,
793 "refused" => Self::Refused,
794 other => Self::Unknown(other.to_string()),
795 }
796 }
797}
798
799impl Serialize for PluginApproval {
800 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
801 serializer.serialize_str(self.as_str())
802 }
803}
804
805impl<'de> Deserialize<'de> for PluginApproval {
806 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
807 let s = String::deserialize(deserializer)?;
808 Ok(Self::from(s.as_str()))
809 }
810}
811
812#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
815pub struct AutoModeRule {
816 pub list: AutoModeRuleList,
818 pub name: String,
820}
821
822#[derive(Debug, Clone, PartialEq, Eq, Hash)]
824pub enum AutoModeRuleList {
825 Allow,
827 SoftDeny,
829 Unknown(String),
831}
832
833impl AutoModeRuleList {
834 pub fn as_str(&self) -> &str {
835 match self {
836 Self::Allow => "allow",
837 Self::SoftDeny => "soft_deny",
838 Self::Unknown(s) => s.as_str(),
839 }
840 }
841}
842
843impl fmt::Display for AutoModeRuleList {
844 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
845 f.write_str(self.as_str())
846 }
847}
848
849impl From<&str> for AutoModeRuleList {
850 fn from(s: &str) -> Self {
851 match s {
852 "allow" => Self::Allow,
853 "soft_deny" => Self::SoftDeny,
854 other => Self::Unknown(other.to_string()),
855 }
856 }
857}
858
859impl Serialize for AutoModeRuleList {
860 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
861 serializer.serialize_str(self.as_str())
862 }
863}
864
865impl<'de> Deserialize<'de> for AutoModeRuleList {
866 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
867 let s = String::deserialize(deserializer)?;
868 Ok(Self::from(s.as_str()))
869 }
870}
871
872#[derive(Debug, Clone, PartialEq, Eq, Hash)]
874pub enum PermissionDecisionOutcome {
875 Accept,
877 Reject,
879 Cancelled,
881 Unknown(String),
883}
884
885impl PermissionDecisionOutcome {
886 pub fn as_str(&self) -> &str {
887 match self {
888 Self::Accept => "accept",
889 Self::Reject => "reject",
890 Self::Cancelled => "cancelled",
891 Self::Unknown(s) => s.as_str(),
892 }
893 }
894}
895
896impl fmt::Display for PermissionDecisionOutcome {
897 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
898 f.write_str(self.as_str())
899 }
900}
901
902impl From<&str> for PermissionDecisionOutcome {
903 fn from(s: &str) -> Self {
904 match s {
905 "accept" => Self::Accept,
906 "reject" => Self::Reject,
907 "cancelled" => Self::Cancelled,
908 other => Self::Unknown(other.to_string()),
909 }
910 }
911}
912
913impl Serialize for PermissionDecisionOutcome {
914 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
915 serializer.serialize_str(self.as_str())
916 }
917}
918
919impl<'de> Deserialize<'de> for PermissionDecisionOutcome {
920 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
921 let s = String::deserialize(deserializer)?;
922 Ok(Self::from(s.as_str()))
923 }
924}
925
926#[derive(Debug, Clone, PartialEq, Eq, Hash)]
929pub enum PermissionDecisionReasonType {
930 Rule,
932 Mode,
934 SubcommandResults,
936 PermissionPromptTool,
938 Hook,
940 AsyncAgent,
942 SandboxOverride,
944 WorkingDir,
946 SafetyCheck,
948 Classifier,
950 Other,
952 Unknown(String),
954}
955
956impl PermissionDecisionReasonType {
957 pub fn as_str(&self) -> &str {
958 match self {
959 Self::Rule => "rule",
960 Self::Mode => "mode",
961 Self::SubcommandResults => "subcommandResults",
962 Self::PermissionPromptTool => "permissionPromptTool",
963 Self::Hook => "hook",
964 Self::AsyncAgent => "asyncAgent",
965 Self::SandboxOverride => "sandboxOverride",
966 Self::WorkingDir => "workingDir",
967 Self::SafetyCheck => "safetyCheck",
968 Self::Classifier => "classifier",
969 Self::Other => "other",
970 Self::Unknown(s) => s.as_str(),
971 }
972 }
973}
974
975impl fmt::Display for PermissionDecisionReasonType {
976 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
977 f.write_str(self.as_str())
978 }
979}
980
981impl From<&str> for PermissionDecisionReasonType {
982 fn from(s: &str) -> Self {
983 match s {
984 "rule" => Self::Rule,
985 "mode" => Self::Mode,
986 "subcommandResults" => Self::SubcommandResults,
987 "permissionPromptTool" => Self::PermissionPromptTool,
988 "hook" => Self::Hook,
989 "asyncAgent" => Self::AsyncAgent,
990 "sandboxOverride" => Self::SandboxOverride,
991 "workingDir" => Self::WorkingDir,
992 "safetyCheck" => Self::SafetyCheck,
993 "classifier" => Self::Classifier,
994 "other" => Self::Other,
995 other => Self::Unknown(other.to_string()),
996 }
997 }
998}
999
1000impl Serialize for PermissionDecisionReasonType {
1001 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1002 serializer.serialize_str(self.as_str())
1003 }
1004}
1005
1006impl<'de> Deserialize<'de> for PermissionDecisionReasonType {
1007 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1008 let s = String::deserialize(deserializer)?;
1009 Ok(Self::from(s.as_str()))
1010 }
1011}
1012
1013#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1018pub struct ToolResultRemedy {
1019 pub kind: ToolResultRemedyKind,
1022 #[serde(default, skip_serializing_if = "Option::is_none")]
1026 pub servers: Option<Vec<String>>,
1027 #[serde(default, skip_serializing_if = "Option::is_none")]
1030 pub provider: Option<RemedyLoginProvider>,
1031 #[serde(default, skip_serializing_if = "Option::is_none")]
1035 pub path: Option<String>,
1036 #[serde(default, skip_serializing_if = "Option::is_none")]
1041 pub managed: Option<bool>,
1042 #[serde(default, skip_serializing_if = "Option::is_none")]
1044 pub feature: Option<RemedyFeature>,
1045 #[serde(default, skip_serializing_if = "Option::is_none")]
1047 pub cause: Option<RemedyFeatureCause>,
1048 #[serde(default, skip_serializing_if = "Option::is_none")]
1050 pub policy_kind: Option<RemedyPolicyKind>,
1051}
1052
1053#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1055pub enum ToolResultRemedyKind {
1056 McpNeedsAuth,
1058 McpDisabled,
1060 McpRequiredMissing,
1062 AuthExpired,
1064 AuthOverridden,
1066 AuthMissingScope,
1068 DesignNeedsAuthorization,
1070 SandboxViolation,
1072 OutsideReadsBlocked,
1074 MemoryPaused,
1076 FeatureDisabled,
1078 PolicyDenied,
1081 SpawnArgLimit,
1083 StagedForReview,
1085 Unknown(String),
1087}
1088
1089impl ToolResultRemedyKind {
1090 pub fn as_str(&self) -> &str {
1091 match self {
1092 Self::McpNeedsAuth => "mcp_needs_auth",
1093 Self::McpDisabled => "mcp_disabled",
1094 Self::McpRequiredMissing => "mcp_required_missing",
1095 Self::AuthExpired => "auth_expired",
1096 Self::AuthOverridden => "auth_overridden",
1097 Self::AuthMissingScope => "auth_missing_scope",
1098 Self::DesignNeedsAuthorization => "design_needs_authorization",
1099 Self::SandboxViolation => "sandbox_violation",
1100 Self::OutsideReadsBlocked => "outside_reads_blocked",
1101 Self::MemoryPaused => "memory_paused",
1102 Self::FeatureDisabled => "feature_disabled",
1103 Self::PolicyDenied => "policy_denied",
1104 Self::SpawnArgLimit => "spawn_arg_limit",
1105 Self::StagedForReview => "staged_for_review",
1106 Self::Unknown(s) => s.as_str(),
1107 }
1108 }
1109}
1110
1111impl fmt::Display for ToolResultRemedyKind {
1112 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1113 f.write_str(self.as_str())
1114 }
1115}
1116
1117impl From<&str> for ToolResultRemedyKind {
1118 fn from(s: &str) -> Self {
1119 match s {
1120 "mcp_needs_auth" => Self::McpNeedsAuth,
1121 "mcp_disabled" => Self::McpDisabled,
1122 "mcp_required_missing" => Self::McpRequiredMissing,
1123 "auth_expired" => Self::AuthExpired,
1124 "auth_overridden" => Self::AuthOverridden,
1125 "auth_missing_scope" => Self::AuthMissingScope,
1126 "design_needs_authorization" => Self::DesignNeedsAuthorization,
1127 "sandbox_violation" => Self::SandboxViolation,
1128 "outside_reads_blocked" => Self::OutsideReadsBlocked,
1129 "memory_paused" => Self::MemoryPaused,
1130 "feature_disabled" => Self::FeatureDisabled,
1131 "policy_denied" => Self::PolicyDenied,
1132 "spawn_arg_limit" => Self::SpawnArgLimit,
1133 "staged_for_review" => Self::StagedForReview,
1134 other => Self::Unknown(other.to_string()),
1135 }
1136 }
1137}
1138
1139impl Serialize for ToolResultRemedyKind {
1140 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1141 serializer.serialize_str(self.as_str())
1142 }
1143}
1144
1145impl<'de> Deserialize<'de> for ToolResultRemedyKind {
1146 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1147 let s = String::deserialize(deserializer)?;
1148 Ok(Self::from(s.as_str()))
1149 }
1150}
1151
1152#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1154pub enum RemedyLoginProvider {
1155 ClaudeAi,
1157 ClaudeDesign,
1159 Unknown(String),
1161}
1162
1163impl RemedyLoginProvider {
1164 pub fn as_str(&self) -> &str {
1165 match self {
1166 Self::ClaudeAi => "claude_ai",
1167 Self::ClaudeDesign => "claude_design",
1168 Self::Unknown(s) => s.as_str(),
1169 }
1170 }
1171}
1172
1173impl fmt::Display for RemedyLoginProvider {
1174 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1175 f.write_str(self.as_str())
1176 }
1177}
1178
1179impl From<&str> for RemedyLoginProvider {
1180 fn from(s: &str) -> Self {
1181 match s {
1182 "claude_ai" => Self::ClaudeAi,
1183 "claude_design" => Self::ClaudeDesign,
1184 other => Self::Unknown(other.to_string()),
1185 }
1186 }
1187}
1188
1189impl Serialize for RemedyLoginProvider {
1190 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1191 serializer.serialize_str(self.as_str())
1192 }
1193}
1194
1195impl<'de> Deserialize<'de> for RemedyLoginProvider {
1196 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1197 let s = String::deserialize(deserializer)?;
1198 Ok(Self::from(s.as_str()))
1199 }
1200}
1201
1202#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1205pub enum RemedyFeature {
1206 Workflows,
1207 Artifacts,
1208 Unknown(String),
1210}
1211
1212impl RemedyFeature {
1213 pub fn as_str(&self) -> &str {
1214 match self {
1215 Self::Workflows => "workflows",
1216 Self::Artifacts => "artifacts",
1217 Self::Unknown(s) => s.as_str(),
1218 }
1219 }
1220}
1221
1222impl fmt::Display for RemedyFeature {
1223 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1224 f.write_str(self.as_str())
1225 }
1226}
1227
1228impl From<&str> for RemedyFeature {
1229 fn from(s: &str) -> Self {
1230 match s {
1231 "workflows" => Self::Workflows,
1232 "artifacts" => Self::Artifacts,
1233 other => Self::Unknown(other.to_string()),
1234 }
1235 }
1236}
1237
1238impl Serialize for RemedyFeature {
1239 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1240 serializer.serialize_str(self.as_str())
1241 }
1242}
1243
1244impl<'de> Deserialize<'de> for RemedyFeature {
1245 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1246 let s = String::deserialize(deserializer)?;
1247 Ok(Self::from(s.as_str()))
1248 }
1249}
1250
1251#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1254pub enum RemedyFeatureCause {
1255 ManagedSettings,
1258 OrgPolicy,
1260 Unavailable,
1262 UserSetting,
1265 UnsupportedRuntime,
1269 Unknown(String),
1271}
1272
1273impl RemedyFeatureCause {
1274 pub fn as_str(&self) -> &str {
1275 match self {
1276 Self::ManagedSettings => "managed_settings",
1277 Self::OrgPolicy => "org_policy",
1278 Self::Unavailable => "unavailable",
1279 Self::UserSetting => "user_setting",
1280 Self::UnsupportedRuntime => "unsupported_runtime",
1281 Self::Unknown(s) => s.as_str(),
1282 }
1283 }
1284}
1285
1286impl fmt::Display for RemedyFeatureCause {
1287 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1288 f.write_str(self.as_str())
1289 }
1290}
1291
1292impl From<&str> for RemedyFeatureCause {
1293 fn from(s: &str) -> Self {
1294 match s {
1295 "managed_settings" => Self::ManagedSettings,
1296 "org_policy" => Self::OrgPolicy,
1297 "unavailable" => Self::Unavailable,
1298 "user_setting" => Self::UserSetting,
1299 "unsupported_runtime" => Self::UnsupportedRuntime,
1300 other => Self::Unknown(other.to_string()),
1301 }
1302 }
1303}
1304
1305impl Serialize for RemedyFeatureCause {
1306 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1307 serializer.serialize_str(self.as_str())
1308 }
1309}
1310
1311impl<'de> Deserialize<'de> for RemedyFeatureCause {
1312 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1313 let s = String::deserialize(deserializer)?;
1314 Ok(Self::from(s.as_str()))
1315 }
1316}
1317
1318#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1321pub enum RemedyPolicyKind {
1322 OrgDenied,
1324 Latched,
1327 Unknown(String),
1329}
1330
1331impl RemedyPolicyKind {
1332 pub fn as_str(&self) -> &str {
1333 match self {
1334 Self::OrgDenied => "org_denied",
1335 Self::Latched => "latched",
1336 Self::Unknown(s) => s.as_str(),
1337 }
1338 }
1339}
1340
1341impl fmt::Display for RemedyPolicyKind {
1342 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1343 f.write_str(self.as_str())
1344 }
1345}
1346
1347impl From<&str> for RemedyPolicyKind {
1348 fn from(s: &str) -> Self {
1349 match s {
1350 "org_denied" => Self::OrgDenied,
1351 "latched" => Self::Latched,
1352 other => Self::Unknown(other.to_string()),
1353 }
1354 }
1355}
1356
1357impl Serialize for RemedyPolicyKind {
1358 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1359 serializer.serialize_str(self.as_str())
1360 }
1361}
1362
1363impl<'de> Deserialize<'de> for RemedyPolicyKind {
1364 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1365 let s = String::deserialize(deserializer)?;
1366 Ok(Self::from(s.as_str()))
1367 }
1368}
1369
1370#[derive(Debug, Clone, Serialize, Deserialize)]
1372pub struct UserMessage {
1373 pub message: MessageContent,
1374 #[serde(skip_serializing_if = "Option::is_none", alias = "sessionId")]
1375 #[serde(
1376 serialize_with = "serialize_optional_uuid",
1377 deserialize_with = "deserialize_optional_uuid"
1378 )]
1379 pub session_id: Option<Uuid>,
1380 #[serde(skip_serializing_if = "Option::is_none")]
1382 pub parent_tool_use_id: Option<String>,
1383 #[serde(skip_serializing_if = "Option::is_none")]
1385 pub uuid: Option<String>,
1386 #[serde(skip_serializing_if = "Option::is_none")]
1388 pub timestamp: Option<String>,
1389 #[serde(skip_serializing_if = "Option::is_none")]
1396 pub tool_use_result: Option<serde_json::Value>,
1397 #[serde(default, skip_serializing_if = "Option::is_none")]
1402 pub agent_id: Option<String>,
1403 #[serde(skip_serializing_if = "Option::is_none")]
1406 pub subagent_type: Option<String>,
1407 #[serde(skip_serializing_if = "Option::is_none")]
1409 pub task_description: Option<String>,
1410 #[serde(skip_serializing_if = "Option::is_none")]
1411 pub origin: Option<MessageOrigin>,
1412 #[serde(skip_serializing_if = "Option::is_none")]
1413 pub priority: Option<String>,
1414 #[serde(skip_serializing_if = "Option::is_none", rename = "isSynthetic")]
1415 pub is_synthetic: Option<bool>,
1416 #[serde(skip_serializing_if = "Option::is_none", rename = "shouldQuery")]
1417 pub should_query: Option<bool>,
1418 #[serde(default, skip_serializing_if = "Option::is_none")]
1419 pub is_meta: Option<bool>,
1420 #[serde(default, skip_serializing_if = "Option::is_none")]
1421 pub is_visible_in_transcript_only: Option<bool>,
1422 #[serde(default, skip_serializing_if = "Option::is_none")]
1423 pub is_virtual: Option<bool>,
1424 #[serde(default, skip_serializing_if = "Option::is_none")]
1425 pub is_compact_summary: Option<bool>,
1426 #[serde(skip_serializing_if = "Option::is_none")]
1427 pub summarize_metadata: Option<SummarizeMetadata>,
1428 #[serde(skip_serializing_if = "Option::is_none")]
1429 pub mcp_meta: Option<McpMeta>,
1430 #[serde(skip_serializing_if = "Option::is_none")]
1433 pub tool_result_meta: Option<Vec<ToolResultMeta>>,
1434 #[serde(skip_serializing_if = "Option::is_none")]
1435 pub source_tool_use_id: Option<String>,
1436 #[serde(skip_serializing_if = "Option::is_none")]
1437 pub source_tool_assistant_uuid: Option<String>,
1438 #[serde(skip_serializing_if = "Option::is_none")]
1439 pub image_paste_ids: Option<Vec<u64>>,
1440 #[serde(skip_serializing_if = "Option::is_none")]
1441 pub client_platform: Option<String>,
1442 #[serde(skip_serializing_if = "Option::is_none")]
1443 pub inbound_origin: Option<String>,
1444 #[serde(default, skip_serializing_if = "Option::is_none")]
1449 pub keeps_request_id: Option<String>,
1450 #[serde(skip_serializing_if = "Option::is_none", rename = "isReplay")]
1451 pub is_replay: Option<bool>,
1452 #[serde(skip_serializing_if = "Option::is_none")]
1453 pub file_attachments: Option<Vec<Value>>,
1454 #[serde(default, skip_serializing_if = "Option::is_none")]
1456 pub seeded_summon: Option<bool>,
1457 #[serde(default, skip_serializing_if = "Option::is_none")]
1460 pub client_composed: Option<bool>,
1461 #[serde(default, skip_serializing_if = "Option::is_none")]
1470 pub text_not_typed: Option<bool>,
1471 #[serde(default, skip_serializing_if = "Option::is_none")]
1478 pub initiator: Option<String>,
1479 #[serde(default, skip_serializing_if = "Option::is_none")]
1485 pub pasted_content: Option<Vec<Value>>,
1486 #[serde(default, skip_serializing_if = "Option::is_none")]
1490 pub historical: Option<bool>,
1491 #[serde(default, skip_serializing_if = "Option::is_none")]
1497 pub server_received_wall_ms: Option<f64>,
1498 #[serde(default, skip_serializing_if = "Option::is_none")]
1502 pub refused_message_id: Option<String>,
1503 #[serde(default, skip_serializing_if = "Option::is_none")]
1510 pub requeue_if_interrupted_within_ms: Option<u64>,
1511 #[serde(default, skip_serializing_if = "Option::is_none")]
1520 pub ultrathink_typed: Option<bool>,
1521 #[serde(default, skip_serializing_if = "Option::is_none")]
1525 pub tool_states: Option<Vec<Value>>,
1526 #[serde(default, skip_serializing_if = "Option::is_none")]
1532 pub plugin_prompt: Option<PluginPrompt>,
1533 #[serde(default, skip_serializing_if = "Option::is_none")]
1544 pub retracted_message_uuids: Option<Vec<String>>,
1545}
1546
1547#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1550pub struct PluginPrompt {
1551 pub name: String,
1554 pub text: String,
1560}
1561
1562impl UserMessage {
1563 pub fn tool_use_result_as<T: serde::de::DeserializeOwned>(
1571 &self,
1572 ) -> Option<Result<T, serde_json::Error>> {
1573 self.tool_use_result
1574 .as_ref()
1575 .map(|v| serde_json::from_value(v.clone()))
1576 }
1577
1578 pub fn subagent_result(&self) -> Option<SubagentResult> {
1589 self.tool_use_result
1590 .as_ref()
1591 .and_then(|v| serde_json::from_value(v.clone()).ok())
1592 }
1593}
1594
1595#[derive(Debug, Clone, Serialize, Deserialize)]
1606pub struct SubagentResult {
1607 #[serde(skip_serializing_if = "Option::is_none")]
1609 pub status: Option<String>,
1610 #[serde(skip_serializing_if = "Option::is_none")]
1612 pub prompt: Option<String>,
1613 #[serde(rename = "agentId", skip_serializing_if = "Option::is_none")]
1615 pub agent_id: Option<String>,
1616 #[serde(rename = "agentType", skip_serializing_if = "Option::is_none")]
1618 pub agent_type: Option<String>,
1619 #[serde(
1621 default,
1622 deserialize_with = "deserialize_content_blocks",
1623 skip_serializing_if = "Vec::is_empty"
1624 )]
1625 pub content: Vec<ContentBlock>,
1626 #[serde(rename = "resolvedModel", skip_serializing_if = "Option::is_none")]
1628 pub resolved_model: Option<String>,
1629 #[serde(rename = "totalDurationMs", skip_serializing_if = "Option::is_none")]
1631 pub total_duration_ms: Option<u64>,
1632 #[serde(rename = "totalTokens", skip_serializing_if = "Option::is_none")]
1634 pub total_tokens: Option<u64>,
1635 #[serde(rename = "totalToolUseCount", skip_serializing_if = "Option::is_none")]
1637 pub total_tool_use_count: Option<u64>,
1638 #[serde(skip_serializing_if = "Option::is_none")]
1640 pub usage: Option<super::result::UsageInfo>,
1641 #[serde(rename = "toolStats", skip_serializing_if = "Option::is_none")]
1643 pub tool_stats: Option<SubagentToolStats>,
1644}
1645
1646#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1651#[serde(rename_all = "camelCase")]
1652pub struct SubagentToolStats {
1653 #[serde(default)]
1654 pub read_count: u64,
1655 #[serde(default)]
1656 pub search_count: u64,
1657 #[serde(default)]
1658 pub bash_count: u64,
1659 #[serde(default)]
1660 pub edit_file_count: u64,
1661 #[serde(default)]
1662 pub lines_added: u64,
1663 #[serde(default)]
1664 pub lines_removed: u64,
1665 #[serde(default)]
1666 pub other_tool_count: u64,
1667 #[serde(flatten)]
1668 pub extra: serde_json::Map<String, Value>,
1669}
1670
1671#[derive(Debug, Clone, Default, PartialEq, Eq)]
1698pub struct SubagentUsageRollup {
1699 pub subagent_tokens: u64,
1702 pub agent_count: u32,
1704 pub tool_uses: u64,
1706 pub duration_ms: u64,
1708 seen_agent_ids: std::collections::BTreeSet<String>,
1709}
1710
1711impl SubagentUsageRollup {
1712 pub fn observe(&mut self, output: &ClaudeOutput) -> bool {
1718 match output {
1719 ClaudeOutput::User(user) => self.observe_user(user),
1720 _ => false,
1721 }
1722 }
1723
1724 pub fn observe_user(&mut self, user: &UserMessage) -> bool {
1731 let Some(result) = user.subagent_result() else {
1732 return false;
1733 };
1734 if result.total_tokens.is_none() && result.agent_id.is_none() {
1735 return false;
1736 }
1737 if let Some(agent_id) = &result.agent_id {
1738 if !self.seen_agent_ids.insert(agent_id.clone()) {
1739 return false;
1740 }
1741 }
1742 self.agent_count += 1;
1743 self.subagent_tokens += result.total_tokens.unwrap_or(0);
1744 self.tool_uses += result.total_tool_use_count.unwrap_or(0);
1745 self.duration_ms += result.total_duration_ms.unwrap_or(0);
1746 true
1747 }
1748}
1749
1750#[derive(Debug, Clone, Serialize, Deserialize)]
1752pub struct MessageContent {
1753 pub role: MessageRole,
1754 #[serde(deserialize_with = "deserialize_content_blocks")]
1755 pub content: Vec<ContentBlock>,
1756}
1757
1758#[derive(Debug, Clone, Serialize, Deserialize)]
1760pub struct SystemMessage {
1761 pub subtype: SystemSubtype,
1762 #[serde(flatten)]
1763 pub data: Value, }
1765
1766impl SystemMessage {
1767 pub fn is_init(&self) -> bool {
1769 self.subtype == SystemSubtype::Init
1770 }
1771
1772 pub fn is_status(&self) -> bool {
1774 self.subtype == SystemSubtype::Status
1775 }
1776
1777 pub fn is_compact_boundary(&self) -> bool {
1779 self.subtype == SystemSubtype::CompactBoundary
1780 }
1781
1782 pub fn as_init(&self) -> Option<InitMessage> {
1784 if self.subtype != SystemSubtype::Init {
1785 return None;
1786 }
1787 serde_json::from_value(self.data.clone()).ok()
1788 }
1789
1790 pub fn as_status(&self) -> Option<StatusMessage> {
1792 if self.subtype != SystemSubtype::Status {
1793 return None;
1794 }
1795 serde_json::from_value(self.data.clone()).ok()
1796 }
1797
1798 pub fn as_compact_boundary(&self) -> Option<CompactBoundaryMessage> {
1800 if self.subtype != SystemSubtype::CompactBoundary {
1801 return None;
1802 }
1803 serde_json::from_value(self.data.clone()).ok()
1804 }
1805
1806 pub fn is_task_started(&self) -> bool {
1808 self.subtype == SystemSubtype::TaskStarted
1809 }
1810
1811 pub fn is_task_progress(&self) -> bool {
1813 self.subtype == SystemSubtype::TaskProgress
1814 }
1815
1816 pub fn is_task_notification(&self) -> bool {
1818 self.subtype == SystemSubtype::TaskNotification
1819 }
1820
1821 pub fn as_task_started(&self) -> Option<TaskStartedMessage> {
1823 if self.subtype != SystemSubtype::TaskStarted {
1824 return None;
1825 }
1826 serde_json::from_value(self.data.clone()).ok()
1827 }
1828
1829 pub fn as_task_progress(&self) -> Option<TaskProgressMessage> {
1831 if self.subtype != SystemSubtype::TaskProgress {
1832 return None;
1833 }
1834 serde_json::from_value(self.data.clone()).ok()
1835 }
1836
1837 pub fn as_task_notification(&self) -> Option<TaskNotificationMessage> {
1839 if self.subtype != SystemSubtype::TaskNotification {
1840 return None;
1841 }
1842 serde_json::from_value(self.data.clone()).ok()
1843 }
1844
1845 pub fn is_task_updated(&self) -> bool {
1847 self.subtype == SystemSubtype::TaskUpdated
1848 }
1849
1850 pub fn as_task_updated(&self) -> Option<TaskUpdatedMessage> {
1852 if self.subtype != SystemSubtype::TaskUpdated {
1853 return None;
1854 }
1855 serde_json::from_value(self.data.clone()).ok()
1856 }
1857
1858 pub fn is_thinking_tokens(&self) -> bool {
1860 self.subtype == SystemSubtype::ThinkingTokens
1861 }
1862
1863 pub fn as_thinking_tokens(&self) -> Option<ThinkingTokensMessage> {
1865 if self.subtype != SystemSubtype::ThinkingTokens {
1866 return None;
1867 }
1868 serde_json::from_value(self.data.clone()).ok()
1869 }
1870
1871 pub fn is_code_change_published(&self) -> bool {
1873 self.subtype == SystemSubtype::CodeChangePublished
1874 }
1875
1876 pub fn as_code_change_published(&self) -> Option<CodeChangePublishedMessage> {
1878 if self.subtype != SystemSubtype::CodeChangePublished {
1879 return None;
1880 }
1881 serde_json::from_value(self.data.clone()).ok()
1882 }
1883
1884 pub fn is_vcs_state_changed(&self) -> bool {
1886 self.subtype == SystemSubtype::VcsStateChanged
1887 }
1888
1889 pub fn as_vcs_state_changed(&self) -> Option<VcsStateChangedMessage> {
1891 if self.subtype != SystemSubtype::VcsStateChanged {
1892 return None;
1893 }
1894 serde_json::from_value(self.data.clone()).ok()
1895 }
1896
1897 pub fn is_feedback_draft_queued(&self) -> bool {
1899 self.subtype == SystemSubtype::FeedbackDraftQueued
1900 }
1901
1902 pub fn as_feedback_draft_queued(&self) -> Option<FeedbackDraftQueuedMessage> {
1904 if self.subtype != SystemSubtype::FeedbackDraftQueued {
1905 return None;
1906 }
1907 serde_json::from_value(self.data.clone()).ok()
1908 }
1909
1910 pub fn is_cloud_session_delta(&self) -> bool {
1912 self.subtype == SystemSubtype::CloudSessionDelta
1913 }
1914
1915 pub fn as_cloud_session_delta(&self) -> Option<CloudSessionDeltaMessage> {
1917 if self.subtype != SystemSubtype::CloudSessionDelta {
1918 return None;
1919 }
1920 serde_json::from_value(self.data.clone()).ok()
1921 }
1922
1923 pub fn is_dev_intent(&self) -> bool {
1925 self.subtype == SystemSubtype::DevIntent
1926 }
1927
1928 pub fn as_dev_intent(&self) -> Option<DevIntentMessage> {
1930 if self.subtype != SystemSubtype::DevIntent {
1931 return None;
1932 }
1933 serde_json::from_value(self.data.clone()).ok()
1934 }
1935
1936 pub fn is_turn_handoff_available(&self) -> bool {
1938 self.subtype == SystemSubtype::TurnHandoffAvailable
1939 }
1940
1941 pub fn as_turn_handoff_available(&self) -> Option<TurnHandoffAvailableMessage> {
1943 if self.subtype != SystemSubtype::TurnHandoffAvailable {
1944 return None;
1945 }
1946 serde_json::from_value(self.data.clone()).ok()
1947 }
1948
1949 pub fn is_turn_preempted(&self) -> bool {
1951 self.subtype == SystemSubtype::TurnPreempted
1952 }
1953
1954 pub fn as_turn_preempted(&self) -> Option<TurnPreemptedMessage> {
1956 if self.subtype != SystemSubtype::TurnPreempted {
1957 return None;
1958 }
1959 serde_json::from_value(self.data.clone()).ok()
1960 }
1961
1962 pub fn is_peer_message_hold(&self) -> bool {
1964 self.subtype == SystemSubtype::PeerMessageHold
1965 }
1966
1967 pub fn as_peer_message_hold(&self) -> Option<PeerMessageHoldMessage> {
1969 if self.subtype != SystemSubtype::PeerMessageHold {
1970 return None;
1971 }
1972 serde_json::from_value(self.data.clone()).ok()
1973 }
1974
1975 pub fn is_per_turn_effort_changed(&self) -> bool {
1977 self.subtype == SystemSubtype::PerTurnEffortChanged
1978 }
1979
1980 pub fn as_per_turn_effort_changed(&self) -> Option<PerTurnEffortChangedMessage> {
1982 if self.subtype != SystemSubtype::PerTurnEffortChanged {
1983 return None;
1984 }
1985 serde_json::from_value(self.data.clone()).ok()
1986 }
1987
1988 pub fn is_session_title_changed(&self) -> bool {
1990 self.subtype == SystemSubtype::SessionTitleChanged
1991 }
1992
1993 pub fn as_session_title_changed(&self) -> Option<SessionTitleChangedMessage> {
1995 if self.subtype != SystemSubtype::SessionTitleChanged {
1996 return None;
1997 }
1998 serde_json::from_value(self.data.clone()).ok()
1999 }
2000
2001 pub fn is_session_writes_lost(&self) -> bool {
2003 self.subtype == SystemSubtype::SessionWritesLost
2004 }
2005
2006 pub fn as_session_writes_lost(&self) -> Option<SessionWritesLostMessage> {
2008 if self.subtype != SystemSubtype::SessionWritesLost {
2009 return None;
2010 }
2011 serde_json::from_value(self.data.clone()).ok()
2012 }
2013
2014 pub fn is_instruction_size_warning(&self) -> bool {
2016 self.subtype == SystemSubtype::InstructionSizeWarning
2017 }
2018
2019 pub fn as_instruction_size_warning(&self) -> Option<InstructionSizeWarningMessage> {
2021 if self.subtype != SystemSubtype::InstructionSizeWarning {
2022 return None;
2023 }
2024 serde_json::from_value(self.data.clone()).ok()
2025 }
2026
2027 pub fn is_permission_check_status(&self) -> bool {
2029 self.subtype == SystemSubtype::PermissionCheckStatus
2030 }
2031
2032 pub fn as_permission_check_status(&self) -> Option<PermissionCheckStatusMessage> {
2034 if self.subtype != SystemSubtype::PermissionCheckStatus {
2035 return None;
2036 }
2037 serde_json::from_value(self.data.clone()).ok()
2038 }
2039
2040 pub fn is_inherited_asks_settled(&self) -> bool {
2042 self.subtype == SystemSubtype::InheritedAsksSettled
2043 }
2044
2045 pub fn as_inherited_asks_settled(&self) -> Option<InheritedAsksSettledMessage> {
2047 if self.subtype != SystemSubtype::InheritedAsksSettled {
2048 return None;
2049 }
2050 serde_json::from_value(self.data.clone()).ok()
2051 }
2052
2053 pub fn is_late_allow_not_run(&self) -> bool {
2055 self.subtype == SystemSubtype::LateAllowNotRun
2056 }
2057
2058 pub fn as_late_allow_not_run(&self) -> Option<LateAllowNotRunMessage> {
2060 if self.subtype != SystemSubtype::LateAllowNotRun {
2061 return None;
2062 }
2063 serde_json::from_value(self.data.clone()).ok()
2064 }
2065
2066 pub fn is_shell_cwd(&self) -> bool {
2068 self.subtype == SystemSubtype::ShellCwd
2069 }
2070
2071 pub fn as_shell_cwd(&self) -> Option<ShellCwdMessage> {
2073 if self.subtype != SystemSubtype::ShellCwd {
2074 return None;
2075 }
2076 serde_json::from_value(self.data.clone()).ok()
2077 }
2078
2079 pub fn is_file_attachments_missing(&self) -> bool {
2081 self.subtype == SystemSubtype::FileAttachmentsMissing
2082 }
2083
2084 pub fn as_file_attachments_missing(&self) -> Option<FileAttachmentsMissingMessage> {
2086 if self.subtype != SystemSubtype::FileAttachmentsMissing {
2087 return None;
2088 }
2089 serde_json::from_value(self.data.clone()).ok()
2090 }
2091
2092 pub fn is_ui_focus(&self) -> bool {
2094 self.subtype == SystemSubtype::UiFocus
2095 }
2096
2097 pub fn as_ui_focus(&self) -> Option<UiFocusMessage> {
2099 if self.subtype != SystemSubtype::UiFocus {
2100 return None;
2101 }
2102 serde_json::from_value(self.data.clone()).ok()
2103 }
2104
2105 pub fn is_ui_invalidate(&self) -> bool {
2107 self.subtype == SystemSubtype::UiInvalidate
2108 }
2109
2110 pub fn as_ui_invalidate(&self) -> Option<UiInvalidateMessage> {
2112 if self.subtype != SystemSubtype::UiInvalidate {
2113 return None;
2114 }
2115 serde_json::from_value(self.data.clone()).ok()
2116 }
2117
2118 pub fn is_ui_log(&self) -> bool {
2120 self.subtype == SystemSubtype::UiLog
2121 }
2122
2123 pub fn as_ui_log(&self) -> Option<UiLogMessage> {
2125 if self.subtype != SystemSubtype::UiLog {
2126 return None;
2127 }
2128 serde_json::from_value(self.data.clone()).ok()
2129 }
2130
2131 pub fn is_ui_notify(&self) -> bool {
2133 self.subtype == SystemSubtype::UiNotify
2134 }
2135
2136 pub fn as_ui_notify(&self) -> Option<UiNotifyMessage> {
2138 if self.subtype != SystemSubtype::UiNotify {
2139 return None;
2140 }
2141 serde_json::from_value(self.data.clone()).ok()
2142 }
2143
2144 pub fn is_ui_notify_cancel(&self) -> bool {
2146 self.subtype == SystemSubtype::UiNotifyCancel
2147 }
2148
2149 pub fn as_ui_notify_cancel(&self) -> Option<UiNotifyCancelMessage> {
2151 if self.subtype != SystemSubtype::UiNotifyCancel {
2152 return None;
2153 }
2154 serde_json::from_value(self.data.clone()).ok()
2155 }
2156
2157 pub fn is_ui_panes(&self) -> bool {
2159 self.subtype == SystemSubtype::UiPanes
2160 }
2161
2162 pub fn as_ui_panes(&self) -> Option<UiPanesMessage> {
2164 if self.subtype != SystemSubtype::UiPanes {
2165 return None;
2166 }
2167 serde_json::from_value(self.data.clone()).ok()
2168 }
2169
2170 pub fn is_ui_placed(&self) -> bool {
2172 self.subtype == SystemSubtype::UiPlaced
2173 }
2174
2175 pub fn as_ui_placed(&self) -> Option<UiPlacedMessage> {
2177 if self.subtype != SystemSubtype::UiPlaced {
2178 return None;
2179 }
2180 serde_json::from_value(self.data.clone()).ok()
2181 }
2182
2183 pub fn is_ui_scroll(&self) -> bool {
2185 self.subtype == SystemSubtype::UiScroll
2186 }
2187
2188 pub fn as_ui_scroll(&self) -> Option<UiScrollMessage> {
2190 if self.subtype != SystemSubtype::UiScroll {
2191 return None;
2192 }
2193 serde_json::from_value(self.data.clone()).ok()
2194 }
2195
2196 pub fn is_ui_status(&self) -> bool {
2198 self.subtype == SystemSubtype::UiStatus
2199 }
2200
2201 pub fn as_ui_status(&self) -> Option<UiStatusMessage> {
2203 if self.subtype != SystemSubtype::UiStatus {
2204 return None;
2205 }
2206 serde_json::from_value(self.data.clone()).ok()
2207 }
2208
2209 pub fn is_ui_toast(&self) -> bool {
2211 self.subtype == SystemSubtype::UiToast
2212 }
2213
2214 pub fn as_ui_toast(&self) -> Option<UiToastMessage> {
2216 if self.subtype != SystemSubtype::UiToast {
2217 return None;
2218 }
2219 serde_json::from_value(self.data.clone()).ok()
2220 }
2221
2222 pub fn as_known_system_event(&self) -> Option<KnownSystemEvent> {
2224 macro_rules! parse {
2225 ($variant:ident, $ty:ty) => {
2226 serde_json::from_value::<$ty>(self.data.clone())
2227 .ok()
2228 .map(KnownSystemEvent::$variant)
2229 };
2230 }
2231
2232 match self.subtype {
2233 SystemSubtype::Init => parse!(Init, InitMessage),
2234 SystemSubtype::Status => parse!(Status, StatusMessage),
2235 SystemSubtype::CompactBoundary => parse!(CompactBoundary, CompactBoundaryMessage),
2236 SystemSubtype::ThinkingTokens => parse!(ThinkingTokens, ThinkingTokensMessage),
2237 SystemSubtype::TaskStarted => parse!(TaskStarted, TaskStartedMessage),
2238 SystemSubtype::TaskProgress => parse!(TaskProgress, TaskProgressMessage),
2239 SystemSubtype::TaskUpdated => parse!(TaskUpdated, TaskUpdatedMessage),
2240 SystemSubtype::TaskNotification => parse!(TaskNotification, TaskNotificationMessage),
2241 SystemSubtype::ApiRetry => parse!(ApiRetry, ApiRetryMessage),
2242 SystemSubtype::ControlRequestProgress => {
2243 parse!(ControlRequestProgress, ControlRequestProgressMessage)
2244 }
2245 SystemSubtype::ModelRefusalFallback => {
2246 parse!(ModelRefusalFallback, ModelRefusalFallbackMessage)
2247 }
2248 SystemSubtype::ModelRefusalNoFallback => {
2249 parse!(ModelRefusalNoFallback, ModelRefusalNoFallbackMessage)
2250 }
2251 SystemSubtype::LocalCommandOutput => {
2252 parse!(LocalCommandOutput, LocalCommandOutputMessage)
2253 }
2254 SystemSubtype::HookStarted => parse!(HookStarted, HookStartedMessage),
2255 SystemSubtype::HookProgress => parse!(HookProgress, HookProgressMessage),
2256 SystemSubtype::HookResponse => parse!(HookResponse, HookResponseMessage),
2257 SystemSubtype::PluginInstall => parse!(PluginInstall, PluginInstallMessage),
2258 SystemSubtype::BackgroundTasksChanged => {
2259 parse!(BackgroundTasksChanged, BackgroundTasksChangedMessage)
2260 }
2261 SystemSubtype::SessionStateChanged => {
2262 parse!(SessionStateChanged, SessionStateChangedMessage)
2263 }
2264 SystemSubtype::WorkerShuttingDown => {
2265 parse!(WorkerShuttingDown, WorkerShuttingDownMessage)
2266 }
2267 SystemSubtype::CommandsChanged => parse!(CommandsChanged, CommandsChangedMessage),
2268 SystemSubtype::Notification => parse!(Notification, NotificationMessage),
2269 SystemSubtype::FilesPersisted => parse!(FilesPersisted, FilesPersistedMessage),
2270 SystemSubtype::MemoryRecall => parse!(MemoryRecall, MemoryRecallMessage),
2271 SystemSubtype::ElicitationComplete => {
2272 parse!(ElicitationComplete, ElicitationCompleteMessage)
2273 }
2274 SystemSubtype::PermissionDenied => parse!(PermissionDenied, PermissionDeniedMessage),
2275 SystemSubtype::MirrorError => parse!(MirrorError, MirrorErrorMessage),
2276 SystemSubtype::Informational => parse!(Informational, InformationalMessage),
2277 SystemSubtype::CodeChangePublished => {
2278 parse!(CodeChangePublished, CodeChangePublishedMessage)
2279 }
2280 SystemSubtype::VcsStateChanged => parse!(VcsStateChanged, VcsStateChangedMessage),
2281 SystemSubtype::FeedbackDraftQueued => {
2282 parse!(FeedbackDraftQueued, FeedbackDraftQueuedMessage)
2283 }
2284 SystemSubtype::CloudSessionDelta => {
2285 parse!(CloudSessionDelta, CloudSessionDeltaMessage)
2286 }
2287 SystemSubtype::DevIntent => parse!(DevIntent, DevIntentMessage),
2288 SystemSubtype::TurnHandoffAvailable => {
2289 parse!(TurnHandoffAvailable, TurnHandoffAvailableMessage)
2290 }
2291 SystemSubtype::TurnPreempted => parse!(TurnPreempted, TurnPreemptedMessage),
2292 SystemSubtype::PeerMessageHold => parse!(PeerMessageHold, PeerMessageHoldMessage),
2293 SystemSubtype::PerTurnEffortChanged => {
2294 parse!(PerTurnEffortChanged, PerTurnEffortChangedMessage)
2295 }
2296 SystemSubtype::SessionTitleChanged => {
2297 parse!(SessionTitleChanged, SessionTitleChangedMessage)
2298 }
2299 SystemSubtype::SessionWritesLost => {
2300 parse!(SessionWritesLost, SessionWritesLostMessage)
2301 }
2302 SystemSubtype::InstructionSizeWarning => {
2303 parse!(InstructionSizeWarning, InstructionSizeWarningMessage)
2304 }
2305 SystemSubtype::FileAttachmentsMissing => {
2306 parse!(FileAttachmentsMissing, FileAttachmentsMissingMessage)
2307 }
2308 SystemSubtype::PermissionCheckStatus => {
2309 parse!(PermissionCheckStatus, PermissionCheckStatusMessage)
2310 }
2311 SystemSubtype::InheritedAsksSettled => {
2312 parse!(InheritedAsksSettled, InheritedAsksSettledMessage)
2313 }
2314 SystemSubtype::LateAllowNotRun => parse!(LateAllowNotRun, LateAllowNotRunMessage),
2315 SystemSubtype::ShellCwd => parse!(ShellCwd, ShellCwdMessage),
2316 SystemSubtype::UiFocus => parse!(UiFocus, UiFocusMessage),
2317 SystemSubtype::UiInvalidate => parse!(UiInvalidate, UiInvalidateMessage),
2318 SystemSubtype::UiLog => parse!(UiLog, UiLogMessage),
2319 SystemSubtype::UiNotify => parse!(UiNotify, UiNotifyMessage),
2320 SystemSubtype::UiNotifyCancel => parse!(UiNotifyCancel, UiNotifyCancelMessage),
2321 SystemSubtype::UiPanes => parse!(UiPanes, UiPanesMessage),
2322 SystemSubtype::UiPlaced => parse!(UiPlaced, UiPlacedMessage),
2323 SystemSubtype::UiScroll => parse!(UiScroll, UiScrollMessage),
2324 SystemSubtype::UiStatus => parse!(UiStatus, UiStatusMessage),
2325 SystemSubtype::UiToast => parse!(UiToast, UiToastMessage),
2326 SystemSubtype::Unknown(_) => None,
2327 }
2328 }
2329
2330 pub fn typed_value(&self) -> Option<Value> {
2339 fn reserialize<T: Serialize>(parsed: Option<T>) -> Option<Value> {
2340 parsed.and_then(|v| serde_json::to_value(v).ok())
2341 }
2342 match self.subtype {
2343 SystemSubtype::Init => reserialize(self.as_init()),
2344 SystemSubtype::Status => reserialize(self.as_status()),
2345 SystemSubtype::CompactBoundary => reserialize(self.as_compact_boundary()),
2346 SystemSubtype::ThinkingTokens => reserialize(self.as_thinking_tokens()),
2347 SystemSubtype::TaskStarted => reserialize(self.as_task_started()),
2348 SystemSubtype::TaskProgress => reserialize(self.as_task_progress()),
2349 SystemSubtype::TaskUpdated => reserialize(self.as_task_updated()),
2350 SystemSubtype::TaskNotification => reserialize(self.as_task_notification()),
2351 SystemSubtype::ApiRetry => reserialize(parse_system::<ApiRetryMessage>(self)),
2352 SystemSubtype::ControlRequestProgress => {
2353 reserialize(parse_system::<ControlRequestProgressMessage>(self))
2354 }
2355 SystemSubtype::ModelRefusalFallback => {
2356 reserialize(parse_system::<ModelRefusalFallbackMessage>(self))
2357 }
2358 SystemSubtype::ModelRefusalNoFallback => {
2359 reserialize(parse_system::<ModelRefusalNoFallbackMessage>(self))
2360 }
2361 SystemSubtype::LocalCommandOutput => {
2362 reserialize(parse_system::<LocalCommandOutputMessage>(self))
2363 }
2364 SystemSubtype::HookStarted => reserialize(parse_system::<HookStartedMessage>(self)),
2365 SystemSubtype::HookProgress => reserialize(parse_system::<HookProgressMessage>(self)),
2366 SystemSubtype::HookResponse => reserialize(parse_system::<HookResponseMessage>(self)),
2367 SystemSubtype::PluginInstall => reserialize(parse_system::<PluginInstallMessage>(self)),
2368 SystemSubtype::BackgroundTasksChanged => {
2369 reserialize(parse_system::<BackgroundTasksChangedMessage>(self))
2370 }
2371 SystemSubtype::SessionStateChanged => {
2372 reserialize(parse_system::<SessionStateChangedMessage>(self))
2373 }
2374 SystemSubtype::WorkerShuttingDown => {
2375 reserialize(parse_system::<WorkerShuttingDownMessage>(self))
2376 }
2377 SystemSubtype::CommandsChanged => {
2378 reserialize(parse_system::<CommandsChangedMessage>(self))
2379 }
2380 SystemSubtype::Notification => reserialize(parse_system::<NotificationMessage>(self)),
2381 SystemSubtype::FilesPersisted => {
2382 reserialize(parse_system::<FilesPersistedMessage>(self))
2383 }
2384 SystemSubtype::MemoryRecall => reserialize(parse_system::<MemoryRecallMessage>(self)),
2385 SystemSubtype::ElicitationComplete => {
2386 reserialize(parse_system::<ElicitationCompleteMessage>(self))
2387 }
2388 SystemSubtype::PermissionDenied => {
2389 reserialize(parse_system::<PermissionDeniedMessage>(self))
2390 }
2391 SystemSubtype::MirrorError => reserialize(parse_system::<MirrorErrorMessage>(self)),
2392 SystemSubtype::Informational => reserialize(parse_system::<InformationalMessage>(self)),
2393 SystemSubtype::CodeChangePublished => {
2394 reserialize(parse_system::<CodeChangePublishedMessage>(self))
2395 }
2396 SystemSubtype::VcsStateChanged => {
2397 reserialize(parse_system::<VcsStateChangedMessage>(self))
2398 }
2399 SystemSubtype::FeedbackDraftQueued => {
2400 reserialize(parse_system::<FeedbackDraftQueuedMessage>(self))
2401 }
2402 SystemSubtype::CloudSessionDelta => {
2403 reserialize(parse_system::<CloudSessionDeltaMessage>(self))
2404 }
2405 SystemSubtype::DevIntent => reserialize(parse_system::<DevIntentMessage>(self)),
2406 SystemSubtype::TurnHandoffAvailable => {
2407 reserialize(parse_system::<TurnHandoffAvailableMessage>(self))
2408 }
2409 SystemSubtype::TurnPreempted => reserialize(parse_system::<TurnPreemptedMessage>(self)),
2410 SystemSubtype::PeerMessageHold => {
2411 reserialize(parse_system::<PeerMessageHoldMessage>(self))
2412 }
2413 SystemSubtype::PerTurnEffortChanged => {
2414 reserialize(parse_system::<PerTurnEffortChangedMessage>(self))
2415 }
2416 SystemSubtype::SessionTitleChanged => {
2417 reserialize(parse_system::<SessionTitleChangedMessage>(self))
2418 }
2419 SystemSubtype::SessionWritesLost => {
2420 reserialize(parse_system::<SessionWritesLostMessage>(self))
2421 }
2422 SystemSubtype::InstructionSizeWarning => {
2423 reserialize(parse_system::<InstructionSizeWarningMessage>(self))
2424 }
2425 SystemSubtype::FileAttachmentsMissing => {
2426 reserialize(parse_system::<FileAttachmentsMissingMessage>(self))
2427 }
2428 SystemSubtype::PermissionCheckStatus => {
2429 reserialize(parse_system::<PermissionCheckStatusMessage>(self))
2430 }
2431 SystemSubtype::InheritedAsksSettled => {
2432 reserialize(parse_system::<InheritedAsksSettledMessage>(self))
2433 }
2434 SystemSubtype::LateAllowNotRun => {
2435 reserialize(parse_system::<LateAllowNotRunMessage>(self))
2436 }
2437 SystemSubtype::ShellCwd => reserialize(parse_system::<ShellCwdMessage>(self)),
2438 SystemSubtype::UiFocus => reserialize(parse_system::<UiFocusMessage>(self)),
2439 SystemSubtype::UiInvalidate => reserialize(parse_system::<UiInvalidateMessage>(self)),
2440 SystemSubtype::UiLog => reserialize(parse_system::<UiLogMessage>(self)),
2441 SystemSubtype::UiNotify => reserialize(parse_system::<UiNotifyMessage>(self)),
2442 SystemSubtype::UiNotifyCancel => {
2443 reserialize(parse_system::<UiNotifyCancelMessage>(self))
2444 }
2445 SystemSubtype::UiPanes => reserialize(parse_system::<UiPanesMessage>(self)),
2446 SystemSubtype::UiPlaced => reserialize(parse_system::<UiPlacedMessage>(self)),
2447 SystemSubtype::UiScroll => reserialize(parse_system::<UiScrollMessage>(self)),
2448 SystemSubtype::UiStatus => reserialize(parse_system::<UiStatusMessage>(self)),
2449 SystemSubtype::UiToast => reserialize(parse_system::<UiToastMessage>(self)),
2450 SystemSubtype::Unknown(_) => None,
2451 }
2452 }
2453}
2454
2455fn parse_system<T: serde::de::DeserializeOwned>(message: &SystemMessage) -> Option<T> {
2456 serde_json::from_value(message.data.clone()).ok()
2457}
2458
2459#[allow(clippy::large_enum_variant)]
2465#[derive(Debug, Clone, Serialize, Deserialize)]
2466pub enum KnownSystemEvent {
2467 Init(InitMessage),
2468 Status(StatusMessage),
2469 CompactBoundary(CompactBoundaryMessage),
2470 ThinkingTokens(ThinkingTokensMessage),
2471 TaskStarted(TaskStartedMessage),
2472 TaskProgress(TaskProgressMessage),
2473 TaskUpdated(TaskUpdatedMessage),
2474 TaskNotification(TaskNotificationMessage),
2475 ApiRetry(ApiRetryMessage),
2476 ControlRequestProgress(ControlRequestProgressMessage),
2477 ModelRefusalFallback(ModelRefusalFallbackMessage),
2478 ModelRefusalNoFallback(ModelRefusalNoFallbackMessage),
2479 LocalCommandOutput(LocalCommandOutputMessage),
2480 HookStarted(HookStartedMessage),
2481 HookProgress(HookProgressMessage),
2482 HookResponse(HookResponseMessage),
2483 PluginInstall(PluginInstallMessage),
2484 BackgroundTasksChanged(BackgroundTasksChangedMessage),
2485 SessionStateChanged(SessionStateChangedMessage),
2486 WorkerShuttingDown(WorkerShuttingDownMessage),
2487 CommandsChanged(CommandsChangedMessage),
2488 Notification(NotificationMessage),
2489 FilesPersisted(FilesPersistedMessage),
2490 MemoryRecall(MemoryRecallMessage),
2491 ElicitationComplete(ElicitationCompleteMessage),
2492 PermissionDenied(PermissionDeniedMessage),
2493 MirrorError(MirrorErrorMessage),
2494 Informational(InformationalMessage),
2495 CodeChangePublished(CodeChangePublishedMessage),
2496 VcsStateChanged(VcsStateChangedMessage),
2497 FeedbackDraftQueued(FeedbackDraftQueuedMessage),
2498 CloudSessionDelta(CloudSessionDeltaMessage),
2499 DevIntent(DevIntentMessage),
2500 TurnHandoffAvailable(TurnHandoffAvailableMessage),
2501 TurnPreempted(TurnPreemptedMessage),
2502 PeerMessageHold(PeerMessageHoldMessage),
2503 PerTurnEffortChanged(PerTurnEffortChangedMessage),
2504 SessionTitleChanged(SessionTitleChangedMessage),
2505 SessionWritesLost(SessionWritesLostMessage),
2506 InstructionSizeWarning(InstructionSizeWarningMessage),
2507 FileAttachmentsMissing(FileAttachmentsMissingMessage),
2508 PermissionCheckStatus(PermissionCheckStatusMessage),
2509 InheritedAsksSettled(InheritedAsksSettledMessage),
2510 LateAllowNotRun(LateAllowNotRunMessage),
2511 ShellCwd(ShellCwdMessage),
2512 UiFocus(UiFocusMessage),
2513 UiInvalidate(UiInvalidateMessage),
2514 UiLog(UiLogMessage),
2515 UiNotify(UiNotifyMessage),
2516 UiNotifyCancel(UiNotifyCancelMessage),
2517 UiPanes(UiPanesMessage),
2518 UiPlaced(UiPlacedMessage),
2519 UiScroll(UiScrollMessage),
2520 UiStatus(UiStatusMessage),
2521 UiToast(UiToastMessage),
2522}
2523
2524#[derive(Debug, Clone, Serialize, Deserialize)]
2525pub struct ApiRetryMessage {
2526 pub attempt: u64,
2527 pub max_retries: u64,
2528 pub retry_delay_ms: u64,
2529 pub error_status: Option<u16>,
2530 pub error: String,
2531 #[serde(default, skip_serializing_if = "Option::is_none")]
2536 pub no_response: Option<ApiRetryNoResponse>,
2537 #[serde(default, skip_serializing_if = "Option::is_none")]
2538 pub uuid: Option<String>,
2539 #[serde(default, skip_serializing_if = "Option::is_none")]
2540 pub session_id: Option<String>,
2541}
2542
2543#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2546pub struct ApiRetryNoResponse {
2547 pub waited_ms: u64,
2549 pub retry_wait_ms: u64,
2551}
2552
2553#[derive(Debug, Clone, Serialize, Deserialize)]
2554pub struct ControlRequestProgressMessage {
2555 pub request_id: String,
2556 pub status: String,
2557 #[serde(default, skip_serializing_if = "Option::is_none")]
2558 pub attempt: Option<u64>,
2559 #[serde(default, skip_serializing_if = "Option::is_none")]
2560 pub max_retries: Option<u64>,
2561 #[serde(default, skip_serializing_if = "Option::is_none")]
2562 pub retry_delay_ms: Option<u64>,
2563 #[serde(default, skip_serializing_if = "Option::is_none")]
2564 pub error_status: Option<u16>,
2565 #[serde(default, skip_serializing_if = "Option::is_none")]
2566 pub error: Option<String>,
2567 #[serde(default, skip_serializing_if = "Option::is_none")]
2568 pub uuid: Option<String>,
2569 #[serde(default, skip_serializing_if = "Option::is_none")]
2570 pub session_id: Option<String>,
2571}
2572
2573#[derive(Debug, Clone, Serialize, Deserialize)]
2574pub struct ModelRefusalFallbackMessage {
2575 pub trigger: String,
2576 pub direction: String,
2577 #[serde(default, skip_serializing_if = "Option::is_none")]
2583 pub scope: Option<RefusalFallbackScope>,
2584 pub original_model: String,
2585 pub fallback_model: String,
2586 pub request_id: Option<String>,
2587 #[serde(default, skip_serializing_if = "Option::is_none")]
2588 pub api_refusal_category: Option<String>,
2589 #[serde(default, skip_serializing_if = "Option::is_none")]
2594 pub saw_cyber_refusal: Option<bool>,
2595 #[serde(default, skip_serializing_if = "Option::is_none")]
2596 pub api_refusal_explanation: Option<String>,
2597 #[serde(default, skip_serializing_if = "Option::is_none")]
2605 pub api_refusal_cyber_verification: Option<CyberVerificationStatus>,
2606 #[serde(default, skip_serializing_if = "Option::is_none")]
2607 pub retracted_message_uuids: Option<Vec<String>>,
2608 #[serde(default, skip_serializing_if = "Option::is_none")]
2609 pub refused_user_message_uuid: Option<String>,
2610 pub content: Value,
2611 #[serde(default, skip_serializing_if = "Option::is_none")]
2612 pub uuid: Option<String>,
2613 #[serde(default, skip_serializing_if = "Option::is_none")]
2614 pub session_id: Option<String>,
2615}
2616
2617#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2621pub struct CyberVerificationStatus {
2622 #[serde(rename = "type")]
2623 pub verification_type: String,
2624 #[serde(default, skip_serializing_if = "Option::is_none")]
2625 pub tier: Option<String>,
2626 #[serde(default, skip_serializing_if = "Option::is_none")]
2627 pub reason: Option<String>,
2628}
2629
2630#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2634pub enum RefusalFallbackScope {
2635 Session,
2637 Local,
2640 Unknown(String),
2642}
2643
2644impl RefusalFallbackScope {
2645 pub fn as_str(&self) -> &str {
2646 match self {
2647 Self::Session => "session",
2648 Self::Local => "local",
2649 Self::Unknown(s) => s.as_str(),
2650 }
2651 }
2652}
2653
2654impl fmt::Display for RefusalFallbackScope {
2655 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2656 f.write_str(self.as_str())
2657 }
2658}
2659
2660impl From<&str> for RefusalFallbackScope {
2661 fn from(s: &str) -> Self {
2662 match s {
2663 "session" => Self::Session,
2664 "local" => Self::Local,
2665 other => Self::Unknown(other.to_string()),
2666 }
2667 }
2668}
2669
2670impl Serialize for RefusalFallbackScope {
2671 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2672 serializer.serialize_str(self.as_str())
2673 }
2674}
2675
2676impl<'de> Deserialize<'de> for RefusalFallbackScope {
2677 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
2678 let s = String::deserialize(deserializer)?;
2679 Ok(Self::from(s.as_str()))
2680 }
2681}
2682
2683#[derive(Debug, Clone, Serialize, Deserialize)]
2684pub struct ModelRefusalNoFallbackMessage {
2685 pub original_model: String,
2686 pub request_id: Option<String>,
2687 #[serde(default, skip_serializing_if = "Option::is_none")]
2688 pub api_refusal_category: Option<String>,
2689 #[serde(default, skip_serializing_if = "Option::is_none")]
2690 pub api_refusal_explanation: Option<String>,
2691 pub content: Value,
2692 #[serde(default, skip_serializing_if = "Option::is_none")]
2693 pub uuid: Option<String>,
2694 #[serde(default, skip_serializing_if = "Option::is_none")]
2695 pub session_id: Option<String>,
2696}
2697
2698#[derive(Debug, Clone, Serialize, Deserialize)]
2699pub struct LocalCommandOutputMessage {
2700 pub content: String,
2701 #[serde(default, skip_serializing_if = "Option::is_none")]
2702 pub uuid: Option<String>,
2703 #[serde(default, skip_serializing_if = "Option::is_none")]
2704 pub session_id: Option<String>,
2705}
2706
2707#[derive(Debug, Clone, Serialize, Deserialize)]
2708pub struct HookStartedMessage {
2709 pub hook_id: String,
2710 pub hook_name: String,
2711 pub hook_event: String,
2712 #[serde(default, skip_serializing_if = "Option::is_none")]
2717 pub origin: Option<String>,
2718 #[serde(default, skip_serializing_if = "Option::is_none")]
2722 pub label: Option<String>,
2723 #[serde(default, skip_serializing_if = "Option::is_none")]
2726 pub plugin_name: Option<String>,
2727 #[serde(default, skip_serializing_if = "Option::is_none")]
2728 pub uuid: Option<String>,
2729 #[serde(default, skip_serializing_if = "Option::is_none")]
2730 pub session_id: Option<String>,
2731}
2732
2733#[derive(Debug, Clone, Serialize, Deserialize)]
2734pub struct HookProgressMessage {
2735 pub hook_id: String,
2736 pub hook_name: String,
2737 pub hook_event: String,
2738 #[serde(default, skip_serializing_if = "Option::is_none")]
2739 pub stdout: Option<String>,
2740 #[serde(default, skip_serializing_if = "Option::is_none")]
2741 pub stderr: Option<String>,
2742 #[serde(default, skip_serializing_if = "Option::is_none")]
2743 pub output: Option<String>,
2744 #[serde(default, skip_serializing_if = "Option::is_none")]
2748 pub backgrounded: Option<bool>,
2749 #[serde(default, skip_serializing_if = "Option::is_none")]
2750 pub uuid: Option<String>,
2751 #[serde(default, skip_serializing_if = "Option::is_none")]
2752 pub session_id: Option<String>,
2753}
2754
2755#[derive(Debug, Clone, Serialize, Deserialize)]
2756pub struct HookResponseMessage {
2757 pub hook_id: String,
2758 pub hook_name: String,
2759 pub hook_event: String,
2760 #[serde(default, skip_serializing_if = "Option::is_none")]
2761 pub stdout: Option<String>,
2762 #[serde(default, skip_serializing_if = "Option::is_none")]
2763 pub stderr: Option<String>,
2764 #[serde(default, skip_serializing_if = "Option::is_none")]
2765 pub output: Option<String>,
2766 #[serde(default, skip_serializing_if = "Option::is_none")]
2767 pub exit_code: Option<i32>,
2768 pub outcome: String,
2769 #[serde(default, skip_serializing_if = "Option::is_none")]
2770 pub uuid: Option<String>,
2771 #[serde(default, skip_serializing_if = "Option::is_none")]
2772 pub session_id: Option<String>,
2773}
2774
2775#[derive(Debug, Clone, Serialize, Deserialize)]
2776pub struct PluginInstallMessage {
2777 pub status: String,
2778 #[serde(default, skip_serializing_if = "Option::is_none")]
2779 pub name: Option<String>,
2780 #[serde(default, skip_serializing_if = "Option::is_none")]
2781 pub error: Option<String>,
2782 #[serde(default, skip_serializing_if = "Option::is_none")]
2783 pub uuid: Option<String>,
2784 #[serde(default, skip_serializing_if = "Option::is_none")]
2785 pub session_id: Option<String>,
2786}
2787
2788#[derive(Debug, Clone, Serialize, Deserialize)]
2789pub struct BackgroundTasksChangedMessage {
2790 pub tasks: Vec<BackgroundTaskInfo>,
2791 #[serde(default, skip_serializing_if = "Option::is_none")]
2792 pub uuid: Option<String>,
2793 #[serde(default, skip_serializing_if = "Option::is_none")]
2794 pub session_id: Option<String>,
2795}
2796
2797#[derive(Debug, Clone, Serialize, Deserialize)]
2798pub struct BackgroundTaskInfo {
2799 pub task_id: String,
2800 #[serde(default, skip_serializing_if = "Option::is_none")]
2803 pub run_id: Option<String>,
2804 pub task_type: String,
2805 #[serde(default, skip_serializing_if = "Option::is_none")]
2809 pub subagent_type: Option<String>,
2810 pub description: String,
2811 #[serde(default, skip_serializing_if = "Option::is_none")]
2814 pub parent_task_id: Option<String>,
2815 #[serde(default, skip_serializing_if = "Option::is_none")]
2818 pub ambient: Option<bool>,
2819 #[serde(default, skip_serializing_if = "Option::is_none")]
2822 pub awaited: Option<bool>,
2823 #[serde(default, skip_serializing_if = "Option::is_none")]
2827 pub off_host: Option<bool>,
2828}
2829
2830#[derive(Debug, Clone, Serialize, Deserialize)]
2831pub struct SessionStateChangedMessage {
2832 pub state: String,
2833 #[serde(default, skip_serializing_if = "Option::is_none")]
2834 pub uuid: Option<String>,
2835 #[serde(default, skip_serializing_if = "Option::is_none")]
2836 pub session_id: Option<String>,
2837}
2838
2839#[derive(Debug, Clone, Serialize, Deserialize)]
2840pub struct WorkerShuttingDownMessage {
2841 pub reason: String,
2842 #[serde(default, skip_serializing_if = "Option::is_none")]
2843 pub uuid: Option<String>,
2844 #[serde(default, skip_serializing_if = "Option::is_none")]
2845 pub session_id: Option<String>,
2846}
2847
2848#[derive(Debug, Clone, Serialize, Deserialize)]
2849pub struct CommandsChangedMessage {
2850 pub commands: Vec<CommandInfo>,
2851 #[serde(default, skip_serializing_if = "Option::is_none")]
2852 pub uuid: Option<String>,
2853 #[serde(default, skip_serializing_if = "Option::is_none")]
2854 pub session_id: Option<String>,
2855}
2856
2857#[derive(Debug, Clone, Serialize, Deserialize)]
2858pub struct CommandInfo {
2859 pub name: String,
2860 pub description: String,
2861 #[serde(rename = "argumentHint")]
2862 pub argument_hint: String,
2863 #[serde(default, skip_serializing_if = "Option::is_none")]
2864 pub aliases: Option<Vec<String>>,
2865 #[serde(default, skip_serializing_if = "Option::is_none")]
2871 pub builtin: Option<bool>,
2872}
2873
2874#[derive(Debug, Clone, Serialize, Deserialize)]
2875pub struct NotificationMessage {
2876 pub key: String,
2877 pub text: String,
2878 pub priority: String,
2879 #[serde(default, skip_serializing_if = "Option::is_none")]
2880 pub color: Option<String>,
2881 #[serde(default, skip_serializing_if = "Option::is_none")]
2882 pub timeout_ms: Option<u64>,
2883 #[serde(default, skip_serializing_if = "Option::is_none")]
2884 pub uuid: Option<String>,
2885 #[serde(default, skip_serializing_if = "Option::is_none")]
2886 pub session_id: Option<String>,
2887}
2888
2889#[derive(Debug, Clone, Serialize, Deserialize)]
2890pub struct FilesPersistedMessage {
2891 pub files: Vec<PersistedFile>,
2892 pub failed: Vec<FailedPersistedFile>,
2893 pub processed_at: String,
2894 #[serde(default, skip_serializing_if = "Option::is_none")]
2895 pub uuid: Option<String>,
2896 #[serde(default, skip_serializing_if = "Option::is_none")]
2897 pub session_id: Option<String>,
2898}
2899
2900#[derive(Debug, Clone, Serialize, Deserialize)]
2901pub struct PersistedFile {
2902 pub filename: String,
2903 pub file_id: String,
2904}
2905
2906#[derive(Debug, Clone, Serialize, Deserialize)]
2907pub struct FailedPersistedFile {
2908 pub filename: String,
2909 pub error: String,
2910}
2911
2912#[derive(Debug, Clone, Serialize, Deserialize)]
2913pub struct MemoryRecallMessage {
2914 pub mode: String,
2915 pub memories: Vec<MemoryRecallItem>,
2916 #[serde(default, skip_serializing_if = "Option::is_none")]
2917 pub uuid: Option<String>,
2918 #[serde(default, skip_serializing_if = "Option::is_none")]
2919 pub session_id: Option<String>,
2920}
2921
2922#[derive(Debug, Clone, Serialize, Deserialize)]
2923pub struct MemoryRecallItem {
2924 pub path: String,
2925 pub scope: String,
2926 #[serde(default, skip_serializing_if = "Option::is_none")]
2927 pub content: Option<String>,
2928}
2929
2930#[derive(Debug, Clone, Serialize, Deserialize)]
2931pub struct ElicitationCompleteMessage {
2932 pub mcp_server_name: String,
2933 pub elicitation_id: String,
2934 #[serde(default, skip_serializing_if = "Option::is_none")]
2935 pub uuid: Option<String>,
2936 #[serde(default, skip_serializing_if = "Option::is_none")]
2937 pub session_id: Option<String>,
2938}
2939
2940#[derive(Debug, Clone, Serialize, Deserialize)]
2941pub struct PermissionDeniedMessage {
2942 pub tool_name: String,
2943 pub tool_use_id: String,
2944 #[serde(default, skip_serializing_if = "Option::is_none")]
2945 pub agent_id: Option<String>,
2946 #[serde(default, skip_serializing_if = "Option::is_none")]
2947 pub decision_reason_type: Option<String>,
2948 #[serde(default, skip_serializing_if = "Option::is_none")]
2952 pub decision_reason_code: Option<PermissionDeniedReasonCode>,
2953 #[serde(default, skip_serializing_if = "Option::is_none")]
2954 pub decision_reason: Option<String>,
2955 pub message: String,
2956 #[serde(default, skip_serializing_if = "Option::is_none")]
2957 pub uuid: Option<String>,
2958 #[serde(default, skip_serializing_if = "Option::is_none")]
2959 pub session_id: Option<String>,
2960}
2961
2962#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2965pub enum PermissionDeniedReasonCode {
2966 ClassifierTranscriptTooLong,
2968 OutsideReadsBlocked,
2970 MemoryPaused,
2972 AutoModeNoCheckInSession,
2977 AutoModeStopNoCheckInSession,
2981 AutoModeStopNoResultForCalls,
2984 AutoModeStopNoVerdict,
2988 Unknown(String),
2990}
2991
2992impl PermissionDeniedReasonCode {
2993 pub fn as_str(&self) -> &str {
2994 match self {
2995 Self::ClassifierTranscriptTooLong => "classifier_transcript_too_long",
2996 Self::OutsideReadsBlocked => "outside_reads_blocked",
2997 Self::MemoryPaused => "memory_paused",
2998 Self::AutoModeNoCheckInSession => "auto_mode_no_check_in_session",
2999 Self::AutoModeStopNoCheckInSession => "auto_mode_stop_no_check_in_session",
3000 Self::AutoModeStopNoResultForCalls => "auto_mode_stop_no_result_for_calls",
3001 Self::AutoModeStopNoVerdict => "auto_mode_stop_no_verdict",
3002 Self::Unknown(s) => s.as_str(),
3003 }
3004 }
3005}
3006
3007impl fmt::Display for PermissionDeniedReasonCode {
3008 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3009 f.write_str(self.as_str())
3010 }
3011}
3012
3013impl From<&str> for PermissionDeniedReasonCode {
3014 fn from(s: &str) -> Self {
3015 match s {
3016 "classifier_transcript_too_long" => Self::ClassifierTranscriptTooLong,
3017 "outside_reads_blocked" => Self::OutsideReadsBlocked,
3018 "memory_paused" => Self::MemoryPaused,
3019 "auto_mode_no_check_in_session" => Self::AutoModeNoCheckInSession,
3020 "auto_mode_stop_no_check_in_session" => Self::AutoModeStopNoCheckInSession,
3021 "auto_mode_stop_no_result_for_calls" => Self::AutoModeStopNoResultForCalls,
3022 "auto_mode_stop_no_verdict" => Self::AutoModeStopNoVerdict,
3023 other => Self::Unknown(other.to_string()),
3024 }
3025 }
3026}
3027
3028impl Serialize for PermissionDeniedReasonCode {
3029 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
3030 serializer.serialize_str(self.as_str())
3031 }
3032}
3033
3034impl<'de> Deserialize<'de> for PermissionDeniedReasonCode {
3035 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
3036 let s = String::deserialize(deserializer)?;
3037 Ok(Self::from(s.as_str()))
3038 }
3039}
3040
3041#[derive(Debug, Clone, Serialize, Deserialize)]
3042pub struct MirrorErrorMessage {
3043 pub error: String,
3044 pub key: MirrorErrorKey,
3045 #[serde(default, skip_serializing_if = "Option::is_none")]
3046 pub uuid: Option<String>,
3047 #[serde(default, skip_serializing_if = "Option::is_none")]
3048 pub session_id: Option<String>,
3049}
3050
3051#[derive(Debug, Clone, Serialize, Deserialize)]
3052pub struct MirrorErrorKey {
3053 #[serde(rename = "projectKey")]
3054 pub project_key: String,
3055 #[serde(rename = "sessionId")]
3056 pub session_id: String,
3057 #[serde(default, skip_serializing_if = "Option::is_none")]
3058 pub subpath: Option<String>,
3059}
3060
3061#[derive(Debug, Clone, Serialize, Deserialize)]
3062pub struct InformationalMessage {
3063 pub content: String,
3064 pub level: String,
3065 #[serde(default, skip_serializing_if = "Option::is_none")]
3066 pub tool_use_id: Option<String>,
3067 #[serde(default, skip_serializing_if = "Option::is_none")]
3068 pub prevent_continuation: Option<bool>,
3069 #[serde(default, skip_serializing_if = "Option::is_none")]
3072 pub tag: Option<String>,
3073 #[serde(default, skip_serializing_if = "Option::is_none")]
3079 pub prompt_submit_outcome: Option<PromptSubmitOutcome>,
3080 #[serde(default, skip_serializing_if = "Option::is_none")]
3084 pub model_restriction: Option<ModelRestriction>,
3085 #[serde(default, skip_serializing_if = "Option::is_none")]
3091 pub hook_no_verdict: Option<HookNoVerdict>,
3092 #[serde(default, skip_serializing_if = "Option::is_none")]
3093 pub uuid: Option<String>,
3094 #[serde(default, skip_serializing_if = "Option::is_none")]
3095 pub session_id: Option<String>,
3096}
3097
3098#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3104pub struct HookNoVerdict {
3105 pub hook_event: String,
3107 pub tool_use_id: String,
3109 pub timed_out: bool,
3111 #[serde(default, skip_serializing_if = "Option::is_none")]
3113 pub plugin_id: Option<String>,
3114 #[serde(default, skip_serializing_if = "Option::is_none")]
3116 pub plugin_root: Option<String>,
3117}
3118
3119#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3125pub struct ModelRestriction {
3126 pub requested_model: String,
3129 pub effective_model: String,
3132 #[serde(default, skip_serializing_if = "Option::is_none")]
3137 pub at: Option<String>,
3138}
3139
3140#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3143pub struct PromptSubmitOutcome {
3144 #[serde(default, skip_serializing_if = "Option::is_none")]
3148 pub kind: Option<PromptSubmitOutcomeKind>,
3149 #[serde(default, skip_serializing_if = "Option::is_none")]
3156 pub no_verdict_kind: Option<String>,
3157 pub prompt_kept: bool,
3160 #[serde(default, skip_serializing_if = "Option::is_none")]
3164 pub reason: Option<String>,
3165}
3166
3167#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3169pub enum PromptSubmitOutcomeKind {
3170 BlockedByHook,
3172 StoppedByHook,
3174 DroppedByHook,
3176 NotPassedOn,
3178 NoVerdict,
3181 Other(String),
3183}
3184
3185impl PromptSubmitOutcomeKind {
3186 pub fn as_str(&self) -> &str {
3187 match self {
3188 Self::BlockedByHook => "blocked_by_hook",
3189 Self::StoppedByHook => "stopped_by_hook",
3190 Self::DroppedByHook => "dropped_by_hook",
3191 Self::NotPassedOn => "not_passed_on",
3192 Self::NoVerdict => "no_verdict",
3193 Self::Other(s) => s.as_str(),
3194 }
3195 }
3196}
3197
3198impl fmt::Display for PromptSubmitOutcomeKind {
3199 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3200 f.write_str(self.as_str())
3201 }
3202}
3203
3204impl From<&str> for PromptSubmitOutcomeKind {
3205 fn from(s: &str) -> Self {
3206 match s {
3207 "blocked_by_hook" => Self::BlockedByHook,
3208 "stopped_by_hook" => Self::StoppedByHook,
3209 "dropped_by_hook" => Self::DroppedByHook,
3210 "not_passed_on" => Self::NotPassedOn,
3211 "no_verdict" => Self::NoVerdict,
3212 other => Self::Other(other.to_string()),
3213 }
3214 }
3215}
3216
3217impl Serialize for PromptSubmitOutcomeKind {
3218 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
3219 serializer.serialize_str(self.as_str())
3220 }
3221}
3222
3223impl<'de> Deserialize<'de> for PromptSubmitOutcomeKind {
3224 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
3225 let s = String::deserialize(deserializer)?;
3226 Ok(Self::from(s.as_str()))
3227 }
3228}
3229
3230#[derive(Debug, Clone, Serialize, Deserialize)]
3232pub struct PluginInfo {
3233 pub name: String,
3235 pub path: String,
3237 #[serde(skip_serializing_if = "Option::is_none")]
3239 pub source: Option<String>,
3240 #[serde(default, skip_serializing_if = "Option::is_none")]
3242 pub version: Option<String>,
3243}
3244
3245#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3247pub struct PluginDiagnostic {
3248 pub plugin: String,
3249 #[serde(rename = "type")]
3250 pub diagnostic_type: String,
3251 pub message: String,
3252 #[serde(default, skip_serializing_if = "Option::is_none")]
3258 pub path: Option<String>,
3259 #[serde(default, skip_serializing_if = "Option::is_none")]
3262 pub managed_lock: Option<PluginManagedLock>,
3263}
3264
3265#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3272pub struct PluginManagedLock {
3273 pub plugin_enabled: bool,
3277 pub name: String,
3280 #[serde(default, skip_serializing_if = "Option::is_none")]
3283 pub marketplace: Option<String>,
3284}
3285
3286#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3288pub struct MemoryPaths {
3289 #[serde(default, skip_serializing_if = "Option::is_none")]
3290 pub auto: Option<String>,
3291 #[serde(default, skip_serializing_if = "Option::is_none")]
3292 pub team: Option<String>,
3293 #[serde(flatten)]
3294 pub extra: serde_json::Map<String, Value>,
3295}
3296
3297#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3301pub struct McpServerError {
3302 pub name: String,
3303 #[serde(rename = "type")]
3305 pub error_type: String,
3306 pub message: String,
3307}
3308
3309#[derive(Debug, Clone, Serialize, Deserialize)]
3311pub struct InitMessage {
3312 pub session_id: String,
3314 #[serde(skip_serializing_if = "Option::is_none")]
3316 pub cwd: Option<String>,
3317 #[serde(skip_serializing_if = "Option::is_none")]
3319 pub model: Option<String>,
3320 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3322 pub tools: Vec<String>,
3323 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3325 pub mcp_servers: Vec<Value>,
3326 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3328 pub slash_commands: Vec<String>,
3329 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3332 pub terminal_slash_commands: Vec<String>,
3333 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3335 pub agents: Vec<String>,
3336 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3338 pub plugins: Vec<PluginInfo>,
3339 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3341 pub skills: Vec<Value>,
3342 #[serde(skip_serializing_if = "Option::is_none")]
3344 pub claude_code_version: Option<String>,
3345 #[serde(skip_serializing_if = "Option::is_none")]
3348 pub messaging_socket_path: Option<String>,
3349 #[serde(skip_serializing_if = "Option::is_none", rename = "apiKeySource")]
3351 pub api_key_source: Option<ApiKeySource>,
3352 #[serde(skip_serializing_if = "Option::is_none")]
3354 pub output_style: Option<OutputStyle>,
3355 #[serde(skip_serializing_if = "Option::is_none", rename = "permissionMode")]
3357 pub permission_mode: Option<InitPermissionMode>,
3358
3359 #[serde(skip_serializing_if = "Option::is_none")]
3361 pub uuid: Option<String>,
3362
3363 #[serde(skip_serializing_if = "Option::is_none")]
3365 pub memory_paths: Option<MemoryPaths>,
3366
3367 #[serde(default, skip_serializing_if = "Option::is_none")]
3372 pub scratchpad_path: Option<String>,
3373
3374 #[serde(skip_serializing_if = "Option::is_none")]
3376 pub fast_mode_state: Option<String>,
3377
3378 #[serde(default, skip_serializing_if = "Option::is_none")]
3380 pub fast_mode_disabled_reason: Option<super::result::FastModeDisabledReason>,
3381
3382 #[serde(default, skip_serializing_if = "Option::is_none")]
3385 pub mcp_server_errors: Option<Vec<McpServerError>>,
3386
3387 #[serde(default, skip_serializing_if = "Option::is_none")]
3389 pub analytics_disabled: Option<bool>,
3390
3391 #[serde(default, skip_serializing_if = "Option::is_none")]
3393 pub product_feedback_disabled: Option<bool>,
3394
3395 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3397 pub betas: Vec<String>,
3398
3399 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3401 pub capabilities: Vec<String>,
3402
3403 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3405 pub plugin_errors: Vec<PluginDiagnostic>,
3406
3407 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3409 pub plugin_warnings: Vec<PluginDiagnostic>,
3410
3411 #[serde(default, skip_serializing_if = "Option::is_none")]
3416 pub effort: Option<String>,
3417
3418 #[serde(default, skip_serializing_if = "Option::is_none")]
3423 pub cloud_session: Option<Value>,
3424
3425 #[serde(default, skip_serializing_if = "Option::is_none")]
3429 pub footer_indicator: Option<FooterIndicator>,
3430
3431 #[serde(default, skip_serializing_if = "Option::is_none")]
3435 pub worker_epoch: Option<u64>,
3436
3437 #[serde(default, skip_serializing_if = "Option::is_none")]
3441 pub powershell_path: Option<Option<String>>,
3442
3443 #[serde(default, skip_serializing_if = "Option::is_none")]
3447 pub startup_timing: Option<serde_json::Map<String, Value>>,
3448
3449 #[serde(default, skip_serializing_if = "Option::is_none")]
3459 pub per_turn_effort_active: Option<bool>,
3460
3461 #[serde(default, skip_serializing_if = "Option::is_none")]
3469 pub ultrathink_available: Option<bool>,
3470
3471 #[serde(default, skip_serializing_if = "Option::is_none")]
3481 pub ultrathink_typed_raises: Option<bool>,
3482
3483 #[serde(default, skip_serializing_if = "Option::is_none")]
3488 pub client_thinking: Option<ClientThinking>,
3489
3490 #[serde(default, skip_serializing_if = "Option::is_none")]
3495 pub flag_restate_noop: Option<bool>,
3496
3497 #[serde(default, skip_serializing_if = "Option::is_none")]
3505 pub synced_skills_path: Option<String>,
3506
3507 #[serde(default, skip_serializing_if = "Option::is_none")]
3514 pub view_mode: Option<ViewMode>,
3515
3516 #[serde(default, skip_serializing_if = "Option::is_none")]
3523 pub original_cwd: Option<String>,
3524
3525 #[serde(default, skip_serializing_if = "Option::is_none")]
3534 pub additional_directories: Option<Vec<String>>,
3535
3536 #[serde(default, skip_serializing_if = "Option::is_none")]
3543 pub host_dropped_env: Option<Vec<HostDroppedEnv>>,
3544}
3545
3546#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3548pub struct HostDroppedEnv {
3549 pub source: String,
3552 pub names: Vec<String>,
3554}
3555
3556#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3559pub struct ClientThinking {
3560 #[serde(default)]
3563 pub max_thinking_tokens: Option<u64>,
3564 #[serde(default)]
3568 pub thinking_display: Option<String>,
3569}
3570
3571#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3575pub struct FooterIndicator {
3576 pub text: String,
3579}
3580
3581#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3584pub enum ViewMode {
3585 Focus,
3588 Default,
3590 Unknown(String),
3592}
3593
3594impl ViewMode {
3595 pub fn as_str(&self) -> &str {
3596 match self {
3597 Self::Focus => "focus",
3598 Self::Default => "default",
3599 Self::Unknown(s) => s.as_str(),
3600 }
3601 }
3602}
3603
3604impl fmt::Display for ViewMode {
3605 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3606 f.write_str(self.as_str())
3607 }
3608}
3609
3610impl From<&str> for ViewMode {
3611 fn from(s: &str) -> Self {
3612 match s {
3613 "focus" => Self::Focus,
3614 "default" => Self::Default,
3615 other => Self::Unknown(other.to_string()),
3616 }
3617 }
3618}
3619
3620impl Serialize for ViewMode {
3621 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
3622 serializer.serialize_str(self.as_str())
3623 }
3624}
3625
3626impl<'de> Deserialize<'de> for ViewMode {
3627 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
3628 let s = String::deserialize(deserializer)?;
3629 Ok(Self::from(s.as_str()))
3630 }
3631}
3632
3633#[derive(Debug, Clone, Serialize, Deserialize)]
3635pub struct StatusMessage {
3636 pub session_id: String,
3638 pub status: Option<StatusMessageStatus>,
3640 #[serde(skip_serializing_if = "Option::is_none")]
3642 pub uuid: Option<String>,
3643 #[serde(skip_serializing_if = "Option::is_none", rename = "permissionMode")]
3645 pub permission_mode: Option<InitPermissionMode>,
3646 #[serde(skip_serializing_if = "Option::is_none")]
3647 pub compact_result: Option<String>,
3648 #[serde(skip_serializing_if = "Option::is_none")]
3649 pub compact_error: Option<String>,
3650 #[serde(default, skip_serializing_if = "Option::is_none")]
3657 pub compact_output_chars: Option<u64>,
3658 #[serde(default, skip_serializing_if = "Option::is_none")]
3665 pub resume_held_for_plan: Option<bool>,
3666}
3667
3668#[derive(Debug, Clone, Serialize, Deserialize)]
3670pub struct CompactBoundaryMessage {
3671 pub session_id: String,
3673 pub compact_metadata: CompactMetadata,
3675 #[serde(
3679 default,
3680 skip_serializing_if = "Option::is_none",
3681 alias = "content",
3682 alias = "text"
3683 )]
3684 pub summary: Option<String>,
3685 #[serde(
3689 default,
3690 skip_serializing_if = "Option::is_none",
3691 alias = "message_count"
3692 )]
3693 pub leaf_message_count: Option<u32>,
3694 #[serde(default, skip_serializing_if = "Option::is_none")]
3696 pub duration_ms: Option<u64>,
3697 #[serde(skip_serializing_if = "Option::is_none")]
3699 pub uuid: Option<String>,
3700 #[serde(skip_serializing_if = "Option::is_none")]
3702 pub logical_parent_uuid: Option<Option<String>>,
3703 #[serde(default, skip_serializing_if = "Option::is_none")]
3707 pub historical: Option<bool>,
3708}
3709
3710#[derive(Debug, Clone, Serialize, Deserialize)]
3712pub struct CompactMetadata {
3713 pub pre_tokens: u64,
3715 pub trigger: CompactionTrigger,
3717 #[serde(default, skip_serializing_if = "Option::is_none")]
3718 pub post_tokens: Option<u64>,
3719 #[serde(default, skip_serializing_if = "Option::is_none")]
3720 pub cumulative_dropped_tokens: Option<u64>,
3721 #[serde(default, skip_serializing_if = "Option::is_none")]
3722 pub duration_ms: Option<u64>,
3723 #[serde(default, skip_serializing_if = "Option::is_none")]
3724 pub user_context: Option<String>,
3725 #[serde(default, skip_serializing_if = "Option::is_none")]
3726 pub messages_summarized: Option<u64>,
3727 #[serde(default, skip_serializing_if = "Option::is_none")]
3728 pub precomputed: Option<bool>,
3729 #[serde(default, skip_serializing_if = "Option::is_none")]
3730 pub pre_compact_discovered_tools: Option<Vec<String>>,
3731 #[serde(default, skip_serializing_if = "Option::is_none")]
3736 pub pre_compact_artifact_read_versions: Option<Vec<ArtifactReadVersion>>,
3737 #[serde(default, skip_serializing_if = "Option::is_none")]
3738 pub preserved_segment: Option<PreservedSegment>,
3739 #[serde(default, skip_serializing_if = "Option::is_none")]
3740 pub preserved_messages: Option<PreservedMessages>,
3741}
3742
3743#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3746pub struct ArtifactReadVersion {
3747 pub slug: String,
3749 pub ver: String,
3751}
3752
3753#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3754pub struct PreservedSegment {
3755 pub head_uuid: String,
3756 pub anchor_uuid: String,
3757 pub tail_uuid: String,
3758}
3759
3760#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3761pub struct PreservedMessages {
3762 pub anchor_uuid: String,
3763 pub uuids: Vec<String>,
3764 #[serde(default, skip_serializing_if = "Option::is_none")]
3765 pub all_uuids: Option<Vec<String>>,
3766}
3767
3768#[derive(Debug, Clone, Serialize, Deserialize)]
3774pub struct TaskUsage {
3775 pub duration_ms: u64,
3777 pub tool_uses: u64,
3779 pub total_tokens: u64,
3781}
3782
3783#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3785pub enum TaskType {
3786 LocalAgent,
3788 LocalBash,
3790 LocalWorkflow,
3792 Unknown(String),
3794}
3795
3796impl TaskType {
3797 pub fn as_str(&self) -> &str {
3798 match self {
3799 Self::LocalAgent => "local_agent",
3800 Self::LocalBash => "local_bash",
3801 Self::LocalWorkflow => "local_workflow",
3802 Self::Unknown(s) => s.as_str(),
3803 }
3804 }
3805}
3806
3807impl fmt::Display for TaskType {
3808 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3809 f.write_str(self.as_str())
3810 }
3811}
3812
3813impl From<&str> for TaskType {
3814 fn from(s: &str) -> Self {
3815 match s {
3816 "local_agent" => Self::LocalAgent,
3817 "local_bash" => Self::LocalBash,
3818 "local_workflow" => Self::LocalWorkflow,
3819 other => Self::Unknown(other.to_string()),
3820 }
3821 }
3822}
3823
3824impl Serialize for TaskType {
3825 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
3826 serializer.serialize_str(self.as_str())
3827 }
3828}
3829
3830impl<'de> Deserialize<'de> for TaskType {
3831 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
3832 let s = String::deserialize(deserializer)?;
3833 Ok(Self::from(s.as_str()))
3834 }
3835}
3836
3837#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3839pub enum TaskStatus {
3840 Pending,
3841 Running,
3842 Completed,
3843 Failed,
3844 Killed,
3845 Paused,
3846 Stopped,
3847 Unknown(String),
3848}
3849
3850impl TaskStatus {
3851 pub fn as_str(&self) -> &str {
3852 match self {
3853 Self::Pending => "pending",
3854 Self::Running => "running",
3855 Self::Completed => "completed",
3856 Self::Failed => "failed",
3857 Self::Killed => "killed",
3858 Self::Paused => "paused",
3859 Self::Stopped => "stopped",
3860 Self::Unknown(s) => s.as_str(),
3861 }
3862 }
3863}
3864
3865impl fmt::Display for TaskStatus {
3866 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3867 f.write_str(self.as_str())
3868 }
3869}
3870
3871impl From<&str> for TaskStatus {
3872 fn from(s: &str) -> Self {
3873 match s {
3874 "pending" => Self::Pending,
3875 "running" => Self::Running,
3876 "completed" => Self::Completed,
3877 "failed" => Self::Failed,
3878 "killed" => Self::Killed,
3879 "paused" => Self::Paused,
3880 "stopped" => Self::Stopped,
3881 other => Self::Unknown(other.to_string()),
3882 }
3883 }
3884}
3885
3886impl Serialize for TaskStatus {
3887 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
3888 serializer.serialize_str(self.as_str())
3889 }
3890}
3891
3892impl<'de> Deserialize<'de> for TaskStatus {
3893 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
3894 let s = String::deserialize(deserializer)?;
3895 Ok(Self::from(s.as_str()))
3896 }
3897}
3898
3899#[derive(Debug, Clone, Serialize, Deserialize)]
3901pub struct TaskStartedMessage {
3902 pub session_id: String,
3903 pub task_id: String,
3904 #[serde(default, skip_serializing_if = "Option::is_none")]
3910 pub run_id: Option<String>,
3911 #[serde(default, skip_serializing_if = "Option::is_none")]
3917 pub parent_task_id: Option<String>,
3918 #[serde(default, skip_serializing_if = "Option::is_none")]
3919 pub task_type: Option<TaskType>,
3920 #[serde(default, skip_serializing_if = "Option::is_none")]
3921 pub tool_use_id: Option<String>,
3922 pub description: String,
3923 #[serde(default, skip_serializing_if = "Option::is_none")]
3926 pub subagent_type: Option<String>,
3927 #[serde(default, skip_serializing_if = "Option::is_none")]
3933 pub is_backgrounded: Option<bool>,
3934 #[serde(default, skip_serializing_if = "Option::is_none")]
3942 pub awaited: Option<bool>,
3943 #[serde(default, skip_serializing_if = "Option::is_none")]
3947 pub spawn_depth: Option<u32>,
3948 #[serde(default, skip_serializing_if = "Option::is_none")]
3954 pub prompt: Option<String>,
3955 #[serde(default, skip_serializing_if = "Option::is_none")]
3956 pub workflow_name: Option<String>,
3957 #[serde(default, skip_serializing_if = "Option::is_none")]
3958 pub skip_transcript: Option<bool>,
3959 #[serde(default, skip_serializing_if = "Option::is_none")]
3964 pub ambient: Option<bool>,
3965 pub uuid: String,
3966}
3967
3968#[derive(Debug, Clone, Serialize, Deserialize)]
3972pub struct TaskUpdatedMessage {
3973 pub session_id: String,
3974 pub task_id: String,
3975 #[serde(default, skip_serializing_if = "Option::is_none")]
3978 pub run_id: Option<String>,
3979 pub patch: TaskPatch,
3980 pub uuid: String,
3981}
3982
3983#[derive(Debug, Clone, Default, Serialize, Deserialize)]
3986pub struct TaskPatch {
3987 #[serde(default, skip_serializing_if = "Option::is_none")]
3988 pub status: Option<TaskStatus>,
3989 #[serde(default, skip_serializing_if = "Option::is_none")]
3992 pub end_time: Option<u64>,
3993 #[serde(default, skip_serializing_if = "Option::is_none")]
3994 pub description: Option<String>,
3995 #[serde(default, skip_serializing_if = "Option::is_none")]
3996 pub total_paused_ms: Option<u64>,
3997 #[serde(default, skip_serializing_if = "Option::is_none")]
3998 pub error: Option<String>,
3999 #[serde(default, skip_serializing_if = "Option::is_none")]
4000 pub is_backgrounded: Option<bool>,
4001}
4002
4003#[derive(Debug, Clone, Serialize, Deserialize)]
4006pub struct ThinkingTokensMessage {
4007 pub session_id: String,
4008 pub estimated_tokens: u64,
4010 pub estimated_tokens_delta: u64,
4012 #[serde(default, skip_serializing_if = "Option::is_none")]
4019 pub user_message_uuid: Option<String>,
4020 pub uuid: String,
4021}
4022
4023#[derive(Debug, Clone, Serialize, Deserialize)]
4026pub struct TaskProgressMessage {
4027 pub session_id: String,
4028 pub task_id: String,
4029 #[serde(default, skip_serializing_if = "Option::is_none")]
4032 pub run_id: Option<String>,
4033 #[serde(default, skip_serializing_if = "Option::is_none")]
4034 pub tool_use_id: Option<String>,
4035 pub description: String,
4036 #[serde(default, skip_serializing_if = "Option::is_none")]
4037 pub last_tool_name: Option<String>,
4038 pub usage: TaskUsage,
4039 #[serde(default, skip_serializing_if = "Option::is_none")]
4041 pub subagent_type: Option<String>,
4042 #[serde(default, skip_serializing_if = "Option::is_none")]
4043 pub summary: Option<String>,
4044 pub uuid: String,
4045}
4046
4047#[derive(Debug, Clone, Serialize, Deserialize)]
4050pub struct TaskNotificationMessage {
4051 pub session_id: String,
4052 pub task_id: String,
4053 #[serde(default, skip_serializing_if = "Option::is_none")]
4056 pub run_id: Option<String>,
4057 pub status: TaskStatus,
4058 #[serde(default, skip_serializing_if = "Option::is_none")]
4061 pub reason: Option<TaskEndReason>,
4062 pub summary: String,
4063 #[serde(default, skip_serializing_if = "Option::is_none")]
4069 pub summary_is_report: Option<bool>,
4070 pub output_file: Option<String>,
4071 #[serde(skip_serializing_if = "Option::is_none")]
4072 pub tool_use_id: Option<String>,
4073 #[serde(skip_serializing_if = "Option::is_none")]
4074 pub usage: Option<TaskUsage>,
4075 #[serde(default, skip_serializing_if = "Vec::is_empty")]
4081 pub resource_links: Vec<ResourceLink>,
4082 #[serde(default, skip_serializing_if = "Option::is_none")]
4089 pub handback: Option<TaskHandback>,
4090 #[serde(default, skip_serializing_if = "Option::is_none")]
4094 pub handback_report: Option<HandbackReport>,
4095 #[serde(default, skip_serializing_if = "Option::is_none")]
4096 pub skip_transcript: Option<bool>,
4097 #[serde(default, skip_serializing_if = "Option::is_none")]
4100 pub ambient: Option<bool>,
4101 #[serde(skip_serializing_if = "Option::is_none")]
4102 pub uuid: Option<String>,
4103}
4104
4105#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4108pub enum TaskHandback {
4109 Send,
4111 Flagged,
4113 Withheld,
4115 Unknown(String),
4117}
4118
4119impl TaskHandback {
4120 pub fn as_str(&self) -> &str {
4121 match self {
4122 Self::Send => "send",
4123 Self::Flagged => "flagged",
4124 Self::Withheld => "withheld",
4125 Self::Unknown(s) => s.as_str(),
4126 }
4127 }
4128}
4129
4130impl fmt::Display for TaskHandback {
4131 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4132 f.write_str(self.as_str())
4133 }
4134}
4135
4136impl From<&str> for TaskHandback {
4137 fn from(s: &str) -> Self {
4138 match s {
4139 "send" => Self::Send,
4140 "flagged" => Self::Flagged,
4141 "withheld" => Self::Withheld,
4142 other => Self::Unknown(other.to_string()),
4143 }
4144 }
4145}
4146
4147impl Serialize for TaskHandback {
4148 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4149 serializer.serialize_str(self.as_str())
4150 }
4151}
4152
4153impl<'de> Deserialize<'de> for TaskHandback {
4154 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4155 let s = String::deserialize(deserializer)?;
4156 Ok(Self::from(s.as_str()))
4157 }
4158}
4159
4160#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
4163pub struct HandbackReport {
4164 pub text: String,
4167 #[serde(default, skip_serializing_if = "Option::is_none")]
4170 pub warning: Option<String>,
4171 #[serde(default, rename = "toolUseId", skip_serializing_if = "Option::is_none")]
4177 pub tool_use_id: Option<String>,
4178}
4179
4180#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4182pub enum AssistantErrorKind {
4183 AuthenticationFailed,
4184 OauthOrgNotAllowed,
4185 AccountOnHold,
4186 BillingError,
4187 RateLimit,
4188 Overloaded,
4189 InvalidRequest,
4190 ModelNotFound,
4191 ServerError,
4192 UnknownError,
4193 MaxOutputTokens,
4194 Unknown(String),
4195}
4196
4197impl AssistantErrorKind {
4198 pub fn as_str(&self) -> &str {
4199 match self {
4200 Self::AuthenticationFailed => "authentication_failed",
4201 Self::OauthOrgNotAllowed => "oauth_org_not_allowed",
4202 Self::AccountOnHold => "account_on_hold",
4203 Self::BillingError => "billing_error",
4204 Self::RateLimit => "rate_limit",
4205 Self::Overloaded => "overloaded",
4206 Self::InvalidRequest => "invalid_request",
4207 Self::ModelNotFound => "model_not_found",
4208 Self::ServerError => "server_error",
4209 Self::UnknownError => "unknown",
4210 Self::MaxOutputTokens => "max_output_tokens",
4211 Self::Unknown(s) => s.as_str(),
4212 }
4213 }
4214}
4215
4216impl fmt::Display for AssistantErrorKind {
4217 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4218 f.write_str(self.as_str())
4219 }
4220}
4221
4222impl From<&str> for AssistantErrorKind {
4223 fn from(s: &str) -> Self {
4224 match s {
4225 "authentication_failed" => Self::AuthenticationFailed,
4226 "oauth_org_not_allowed" => Self::OauthOrgNotAllowed,
4227 "account_on_hold" => Self::AccountOnHold,
4228 "billing_error" => Self::BillingError,
4229 "rate_limit" => Self::RateLimit,
4230 "overloaded" => Self::Overloaded,
4231 "invalid_request" => Self::InvalidRequest,
4232 "model_not_found" => Self::ModelNotFound,
4233 "server_error" => Self::ServerError,
4234 "unknown" => Self::UnknownError,
4235 "max_output_tokens" => Self::MaxOutputTokens,
4236 other => Self::Unknown(other.to_string()),
4237 }
4238 }
4239}
4240
4241impl Serialize for AssistantErrorKind {
4242 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4243 serializer.serialize_str(self.as_str())
4244 }
4245}
4246
4247impl<'de> Deserialize<'de> for AssistantErrorKind {
4248 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4249 let s = String::deserialize(deserializer)?;
4250 Ok(Self::from(s.as_str()))
4251 }
4252}
4253
4254#[derive(Debug, Clone, Serialize, Deserialize)]
4261pub struct CodeChangePublishedMessage {
4262 pub provider: String,
4266 pub url: String,
4268 pub repo: String,
4271 pub identifier: String,
4273 #[serde(default, skip_serializing_if = "Option::is_none")]
4282 pub action: Option<String>,
4283 #[serde(default, skip_serializing_if = "Option::is_none")]
4291 pub branch: Option<String>,
4292 pub uuid: String,
4293 pub session_id: String,
4294}
4295
4296#[derive(Debug, Clone, Serialize, Deserialize)]
4301pub struct VcsStateChangedMessage {
4302 pub kind: VcsMutationKind,
4305 pub cwd: String,
4308 #[serde(default, skip_serializing_if = "Option::is_none")]
4313 pub branch: Option<String>,
4314 pub uuid: String,
4315 pub session_id: String,
4316}
4317
4318#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4320pub enum VcsMutationKind {
4321 Commit,
4322 Push,
4323 Merge,
4324 Rebase,
4325 Unknown(String),
4327}
4328
4329impl VcsMutationKind {
4330 pub fn as_str(&self) -> &str {
4331 match self {
4332 Self::Commit => "commit",
4333 Self::Push => "push",
4334 Self::Merge => "merge",
4335 Self::Rebase => "rebase",
4336 Self::Unknown(s) => s.as_str(),
4337 }
4338 }
4339}
4340
4341impl fmt::Display for VcsMutationKind {
4342 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4343 f.write_str(self.as_str())
4344 }
4345}
4346
4347impl From<&str> for VcsMutationKind {
4348 fn from(s: &str) -> Self {
4349 match s {
4350 "commit" => Self::Commit,
4351 "push" => Self::Push,
4352 "merge" => Self::Merge,
4353 "rebase" => Self::Rebase,
4354 other => Self::Unknown(other.to_string()),
4355 }
4356 }
4357}
4358
4359impl Serialize for VcsMutationKind {
4360 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4361 serializer.serialize_str(self.as_str())
4362 }
4363}
4364
4365impl<'de> Deserialize<'de> for VcsMutationKind {
4366 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4367 let s = String::deserialize(deserializer)?;
4368 Ok(Self::from(s.as_str()))
4369 }
4370}
4371
4372#[derive(Debug, Clone, Serialize, Deserialize)]
4374pub struct FeedbackDraftQueuedMessage {
4375 pub draft_id: String,
4376 pub draft_type: String,
4377 pub title: String,
4378 pub details_preview: String,
4379 #[serde(default, skip_serializing_if = "Option::is_none")]
4380 pub uuid: Option<String>,
4381 #[serde(default, skip_serializing_if = "Option::is_none")]
4382 pub session_id: Option<String>,
4383 #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
4384 pub extra: serde_json::Map<String, Value>,
4385}
4386
4387#[derive(Debug, Clone, Serialize, Deserialize)]
4395pub struct CloudSessionDeltaMessage {
4396 pub seq: u64,
4400 pub changed: Vec<String>,
4404 pub cloud_session: Value,
4408 pub uuid: String,
4409 pub session_id: String,
4410 #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
4411 pub extra: serde_json::Map<String, Value>,
4412}
4413
4414#[derive(Debug, Clone, Serialize, Deserialize)]
4430pub struct DevIntentMessage {
4431 pub kind: DevIntentKind,
4433 #[serde(default, skip_serializing_if = "Option::is_none")]
4439 pub trigger: Option<DevIntentTrigger>,
4440 pub uuid: String,
4441 pub session_id: String,
4442 #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
4443 pub extra: serde_json::Map<String, Value>,
4444}
4445
4446#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4450pub enum DevIntentKind {
4451 IosApp,
4457 AndroidApp,
4464 Unknown(String),
4466}
4467
4468impl DevIntentKind {
4469 pub fn as_str(&self) -> &str {
4470 match self {
4471 Self::IosApp => "ios_app",
4472 Self::AndroidApp => "android_app",
4473 Self::Unknown(s) => s.as_str(),
4474 }
4475 }
4476}
4477
4478impl fmt::Display for DevIntentKind {
4479 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4480 f.write_str(self.as_str())
4481 }
4482}
4483
4484impl From<&str> for DevIntentKind {
4485 fn from(s: &str) -> Self {
4486 match s {
4487 "ios_app" => Self::IosApp,
4488 "android_app" => Self::AndroidApp,
4489 other => Self::Unknown(other.to_string()),
4490 }
4491 }
4492}
4493
4494impl Serialize for DevIntentKind {
4495 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4496 serializer.serialize_str(self.as_str())
4497 }
4498}
4499
4500impl<'de> Deserialize<'de> for DevIntentKind {
4501 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4502 let s = String::deserialize(deserializer)?;
4503 Ok(Self::from(s.as_str()))
4504 }
4505}
4506
4507#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4511pub enum DevIntentTrigger {
4512 SwiftEdit,
4514 UikitImport,
4516 XcodeProject,
4519 IosCommand,
4522 KotlinEdit,
4524 JavaEdit,
4526 AndroidImport,
4528 AndroidManifest,
4530 GradlePlugin,
4532 AndroidCommand,
4535 ProjectScan,
4538 Unknown(String),
4540}
4541
4542impl DevIntentTrigger {
4543 pub fn as_str(&self) -> &str {
4544 match self {
4545 Self::SwiftEdit => "swift_edit",
4546 Self::UikitImport => "uikit_import",
4547 Self::XcodeProject => "xcode_project",
4548 Self::IosCommand => "ios_command",
4549 Self::KotlinEdit => "kotlin_edit",
4550 Self::JavaEdit => "java_edit",
4551 Self::AndroidImport => "android_import",
4552 Self::AndroidManifest => "android_manifest",
4553 Self::GradlePlugin => "gradle_plugin",
4554 Self::AndroidCommand => "android_command",
4555 Self::ProjectScan => "project_scan",
4556 Self::Unknown(s) => s.as_str(),
4557 }
4558 }
4559}
4560
4561impl fmt::Display for DevIntentTrigger {
4562 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4563 f.write_str(self.as_str())
4564 }
4565}
4566
4567impl From<&str> for DevIntentTrigger {
4568 fn from(s: &str) -> Self {
4569 match s {
4570 "swift_edit" => Self::SwiftEdit,
4571 "uikit_import" => Self::UikitImport,
4572 "xcode_project" => Self::XcodeProject,
4573 "ios_command" => Self::IosCommand,
4574 "kotlin_edit" => Self::KotlinEdit,
4575 "java_edit" => Self::JavaEdit,
4576 "android_import" => Self::AndroidImport,
4577 "android_manifest" => Self::AndroidManifest,
4578 "gradle_plugin" => Self::GradlePlugin,
4579 "android_command" => Self::AndroidCommand,
4580 "project_scan" => Self::ProjectScan,
4581 other => Self::Unknown(other.to_string()),
4582 }
4583 }
4584}
4585
4586impl Serialize for DevIntentTrigger {
4587 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4588 serializer.serialize_str(self.as_str())
4589 }
4590}
4591
4592impl<'de> Deserialize<'de> for DevIntentTrigger {
4593 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4594 let s = String::deserialize(deserializer)?;
4595 Ok(Self::from(s.as_str()))
4596 }
4597}
4598
4599#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4603pub enum TaskEndReason {
4604 WorkerRestart,
4607 Unknown(String),
4609}
4610
4611impl TaskEndReason {
4612 pub fn as_str(&self) -> &str {
4613 match self {
4614 Self::WorkerRestart => "worker_restart",
4615 Self::Unknown(s) => s.as_str(),
4616 }
4617 }
4618}
4619
4620impl fmt::Display for TaskEndReason {
4621 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4622 f.write_str(self.as_str())
4623 }
4624}
4625
4626impl From<&str> for TaskEndReason {
4627 fn from(s: &str) -> Self {
4628 match s {
4629 "worker_restart" => Self::WorkerRestart,
4630 other => Self::Unknown(other.to_string()),
4631 }
4632 }
4633}
4634
4635impl Serialize for TaskEndReason {
4636 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4637 serializer.serialize_str(self.as_str())
4638 }
4639}
4640
4641impl<'de> Deserialize<'de> for TaskEndReason {
4642 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4643 let s = String::deserialize(deserializer)?;
4644 Ok(Self::from(s.as_str()))
4645 }
4646}
4647
4648#[derive(Debug, Clone, Serialize, Deserialize)]
4657pub struct TurnHandoffAvailableMessage {
4658 pub v: u64,
4660 pub tools: Vec<String>,
4662 pub worker_epoch: u64,
4664 #[serde(default, skip_serializing_if = "Option::is_none")]
4668 pub relay_marker: Option<bool>,
4669 #[serde(default, skip_serializing_if = "Option::is_none")]
4677 pub staged_files: Option<bool>,
4678 #[serde(default, skip_serializing_if = "Option::is_none")]
4685 pub no_query_first: Option<bool>,
4686 #[serde(default, skip_serializing_if = "Option::is_none")]
4694 pub home_files: Option<bool>,
4695 #[serde(default, skip_serializing_if = "Option::is_none")]
4699 pub file_names: Option<bool>,
4700 #[serde(default, skip_serializing_if = "Option::is_none")]
4710 pub carried_writes: Option<bool>,
4711 #[serde(default, skip_serializing_if = "Option::is_none")]
4725 pub hydrates_carried_lines: Option<bool>,
4726 #[serde(default, skip_serializing_if = "Option::is_none")]
4732 pub shared_message_id: Option<bool>,
4733 #[serde(default, skip_serializing_if = "Option::is_none")]
4738 pub requires_rewind_request_id: Option<bool>,
4739 #[serde(default, skip_serializing_if = "Option::is_none")]
4743 pub comparison_fork: Option<bool>,
4744 pub uuid: String,
4745 pub session_id: String,
4746 #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
4747 pub extra: serde_json::Map<String, Value>,
4748}
4749
4750#[derive(Debug, Clone, Serialize, Deserialize)]
4762pub struct TurnPreemptedMessage {
4763 pub reason: String,
4767 pub preempted_by_uuid: String,
4771 #[serde(default)]
4774 pub preempted_message_uuids: Vec<String>,
4775 pub uuid: String,
4776 pub session_id: String,
4777 #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
4778 pub extra: serde_json::Map<String, Value>,
4779}
4780
4781#[derive(Debug, Clone, Serialize, Deserialize)]
4789pub struct PeerMessageHoldMessage {
4790 pub state: PeerMessageHoldState,
4796 #[serde(default, skip_serializing_if = "Option::is_none")]
4803 pub message_uuid: Option<String>,
4804 pub lane: PeerMessageLane,
4806 pub from: String,
4811 #[serde(default, skip_serializing_if = "Option::is_none")]
4814 pub from_name: Option<String>,
4815 #[serde(default, skip_serializing_if = "Option::is_none")]
4817 pub cause: Option<PeerMessageHoldCause>,
4818 #[serde(default, skip_serializing_if = "Option::is_none")]
4820 pub outcome: Option<PeerMessageHoldOutcome>,
4821 pub uuid: String,
4822 pub session_id: String,
4823 #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
4824 pub extra: serde_json::Map<String, Value>,
4825}
4826
4827#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4829pub enum PeerMessageHoldState {
4830 Held,
4832 Released,
4834 Dropped,
4836 Unknown(String),
4838}
4839
4840impl PeerMessageHoldState {
4841 pub fn as_str(&self) -> &str {
4842 match self {
4843 Self::Held => "held",
4844 Self::Released => "released",
4845 Self::Dropped => "dropped",
4846 Self::Unknown(s) => s.as_str(),
4847 }
4848 }
4849}
4850
4851impl fmt::Display for PeerMessageHoldState {
4852 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4853 f.write_str(self.as_str())
4854 }
4855}
4856
4857impl From<&str> for PeerMessageHoldState {
4858 fn from(s: &str) -> Self {
4859 match s {
4860 "held" => Self::Held,
4861 "released" => Self::Released,
4862 "dropped" => Self::Dropped,
4863 other => Self::Unknown(other.to_string()),
4864 }
4865 }
4866}
4867
4868impl Serialize for PeerMessageHoldState {
4869 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4870 serializer.serialize_str(self.as_str())
4871 }
4872}
4873
4874impl<'de> Deserialize<'de> for PeerMessageHoldState {
4875 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4876 let s = String::deserialize(deserializer)?;
4877 Ok(Self::from(s.as_str()))
4878 }
4879}
4880
4881#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4883pub enum PeerMessageLane {
4884 Bridge,
4886 Stdin,
4888 Socket,
4890 Unknown(String),
4892}
4893
4894impl PeerMessageLane {
4895 pub fn as_str(&self) -> &str {
4896 match self {
4897 Self::Bridge => "bridge",
4898 Self::Stdin => "stdin",
4899 Self::Socket => "socket",
4900 Self::Unknown(s) => s.as_str(),
4901 }
4902 }
4903}
4904
4905impl fmt::Display for PeerMessageLane {
4906 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4907 f.write_str(self.as_str())
4908 }
4909}
4910
4911impl From<&str> for PeerMessageLane {
4912 fn from(s: &str) -> Self {
4913 match s {
4914 "bridge" => Self::Bridge,
4915 "stdin" => Self::Stdin,
4916 "socket" => Self::Socket,
4917 other => Self::Unknown(other.to_string()),
4918 }
4919 }
4920}
4921
4922impl Serialize for PeerMessageLane {
4923 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4924 serializer.serialize_str(self.as_str())
4925 }
4926}
4927
4928impl<'de> Deserialize<'de> for PeerMessageLane {
4929 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4930 let s = String::deserialize(deserializer)?;
4931 Ok(Self::from(s.as_str()))
4932 }
4933}
4934
4935#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4942pub enum PeerMessageHoldCause {
4943 ExplicitSetting,
4944 ManagedSetting,
4945 RepoSetting,
4946 InvalidSetting,
4947 BypassDefault,
4948 ModeUnknown,
4949 ModeMismatch,
4950 NoModeAsserted,
4951 Unknown(String),
4953}
4954
4955impl PeerMessageHoldCause {
4956 pub fn as_str(&self) -> &str {
4957 match self {
4958 Self::ExplicitSetting => "explicit-setting",
4959 Self::ManagedSetting => "managed-setting",
4960 Self::RepoSetting => "repo-setting",
4961 Self::InvalidSetting => "invalid-setting",
4962 Self::BypassDefault => "bypass-default",
4963 Self::ModeUnknown => "mode-unknown",
4964 Self::ModeMismatch => "mode-mismatch",
4965 Self::NoModeAsserted => "no-mode-asserted",
4966 Self::Unknown(s) => s.as_str(),
4967 }
4968 }
4969}
4970
4971impl fmt::Display for PeerMessageHoldCause {
4972 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4973 f.write_str(self.as_str())
4974 }
4975}
4976
4977impl From<&str> for PeerMessageHoldCause {
4978 fn from(s: &str) -> Self {
4979 match s {
4980 "explicit-setting" => Self::ExplicitSetting,
4981 "managed-setting" => Self::ManagedSetting,
4982 "repo-setting" => Self::RepoSetting,
4983 "invalid-setting" => Self::InvalidSetting,
4984 "bypass-default" => Self::BypassDefault,
4985 "mode-unknown" => Self::ModeUnknown,
4986 "mode-mismatch" => Self::ModeMismatch,
4987 "no-mode-asserted" => Self::NoModeAsserted,
4988 other => Self::Unknown(other.to_string()),
4989 }
4990 }
4991}
4992
4993impl Serialize for PeerMessageHoldCause {
4994 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4995 serializer.serialize_str(self.as_str())
4996 }
4997}
4998
4999impl<'de> Deserialize<'de> for PeerMessageHoldCause {
5000 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
5001 let s = String::deserialize(deserializer)?;
5002 Ok(Self::from(s.as_str()))
5003 }
5004}
5005
5006#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5009pub enum PeerMessageHoldOutcome {
5010 Expired,
5014 Refused,
5016 Dropped,
5019 Discarded,
5021 Unknown(String),
5023}
5024
5025impl PeerMessageHoldOutcome {
5026 pub fn as_str(&self) -> &str {
5027 match self {
5028 Self::Expired => "expired",
5029 Self::Refused => "refused",
5030 Self::Dropped => "dropped",
5031 Self::Discarded => "discarded",
5032 Self::Unknown(s) => s.as_str(),
5033 }
5034 }
5035}
5036
5037impl fmt::Display for PeerMessageHoldOutcome {
5038 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5039 f.write_str(self.as_str())
5040 }
5041}
5042
5043impl From<&str> for PeerMessageHoldOutcome {
5044 fn from(s: &str) -> Self {
5045 match s {
5046 "expired" => Self::Expired,
5047 "refused" => Self::Refused,
5048 "dropped" => Self::Dropped,
5049 "discarded" => Self::Discarded,
5050 other => Self::Unknown(other.to_string()),
5051 }
5052 }
5053}
5054
5055impl Serialize for PeerMessageHoldOutcome {
5056 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
5057 serializer.serialize_str(self.as_str())
5058 }
5059}
5060
5061impl<'de> Deserialize<'de> for PeerMessageHoldOutcome {
5062 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
5063 let s = String::deserialize(deserializer)?;
5064 Ok(Self::from(s.as_str()))
5065 }
5066}
5067
5068#[derive(Debug, Clone, Serialize, Deserialize)]
5079pub struct PerTurnEffortChangedMessage {
5080 pub per_turn_effort_active: bool,
5082 pub uuid: String,
5083 pub session_id: String,
5084}
5085
5086#[derive(Debug, Clone, Serialize, Deserialize)]
5093pub struct InstructionSizeWarningMessage {
5094 pub total_chars: u64,
5097 pub total_limit_chars: u64,
5100 pub file_count: u64,
5103 #[serde(default, skip_serializing_if = "Option::is_none")]
5107 pub largest_chars: Option<u64>,
5108 pub uuid: String,
5109 pub session_id: String,
5110}
5111
5112#[derive(Debug, Clone, Serialize, Deserialize)]
5119pub struct FileAttachmentsMissingMessage {
5120 pub message_uuid: String,
5123 pub sent_count: u64,
5125 pub missing: Vec<MissingFileAttachment>,
5127 pub uuid: String,
5128 pub session_id: String,
5129}
5130
5131#[derive(Debug, Clone, Serialize, Deserialize)]
5141pub struct PermissionCheckStatusMessage {
5142 pub tool_use_id: String,
5143 #[serde(default, skip_serializing_if = "Option::is_none")]
5146 pub agent_id: Option<String>,
5147 pub status: PermissionCheckStatus,
5148 pub uuid: String,
5149 pub session_id: String,
5150}
5151
5152#[derive(Debug, Clone, Serialize, Deserialize)]
5157pub struct InheritedAsksSettledMessage {
5158 pub kept_request_ids: Vec<String>,
5161 pub uuid: String,
5162 pub session_id: String,
5163}
5164
5165#[derive(Debug, Clone, Serialize, Deserialize)]
5172pub struct LateAllowNotRunMessage {
5173 pub request_id: String,
5176 pub tool_use_id: String,
5178 pub reason: LateAllowNotRunReason,
5180 pub uuid: String,
5181 pub session_id: String,
5182}
5183
5184#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5191pub struct ShellCwdMessage {
5192 pub cwd: String,
5197 pub uuid: String,
5198 pub session_id: String,
5199}
5200
5201#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5204pub enum LateAllowNotRunReason {
5205 TurnRunning,
5206 CardOpen,
5207 CallGone,
5208 InvalidAnswer,
5209 Limited,
5210 Stopped,
5211 Declined,
5212 AskedAgain,
5213 Withdrawn,
5214 Expired,
5215 NotRun,
5216 Unknown(String),
5218}
5219
5220impl LateAllowNotRunReason {
5221 pub fn as_str(&self) -> &str {
5222 match self {
5223 Self::TurnRunning => "turn_running",
5224 Self::CardOpen => "card_open",
5225 Self::CallGone => "call_gone",
5226 Self::InvalidAnswer => "invalid_answer",
5227 Self::Limited => "limited",
5228 Self::Stopped => "stopped",
5229 Self::Declined => "declined",
5230 Self::AskedAgain => "asked_again",
5231 Self::Withdrawn => "withdrawn",
5232 Self::Expired => "expired",
5233 Self::NotRun => "not_run",
5234 Self::Unknown(s) => s.as_str(),
5235 }
5236 }
5237}
5238
5239impl fmt::Display for LateAllowNotRunReason {
5240 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5241 f.write_str(self.as_str())
5242 }
5243}
5244
5245impl From<&str> for LateAllowNotRunReason {
5246 fn from(s: &str) -> Self {
5247 match s {
5248 "turn_running" => Self::TurnRunning,
5249 "card_open" => Self::CardOpen,
5250 "call_gone" => Self::CallGone,
5251 "invalid_answer" => Self::InvalidAnswer,
5252 "limited" => Self::Limited,
5253 "stopped" => Self::Stopped,
5254 "declined" => Self::Declined,
5255 "asked_again" => Self::AskedAgain,
5256 "withdrawn" => Self::Withdrawn,
5257 "expired" => Self::Expired,
5258 "not_run" => Self::NotRun,
5259 other => Self::Unknown(other.to_string()),
5260 }
5261 }
5262}
5263
5264impl Serialize for LateAllowNotRunReason {
5265 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
5266 serializer.serialize_str(self.as_str())
5267 }
5268}
5269
5270impl<'de> Deserialize<'de> for LateAllowNotRunReason {
5271 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
5272 let s = String::deserialize(deserializer)?;
5273 Ok(Self::from(s.as_str()))
5274 }
5275}
5276
5277#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5279pub enum PermissionCheckStatus {
5280 Checking,
5283 Done,
5285 Unknown(String),
5287}
5288
5289impl PermissionCheckStatus {
5290 pub fn as_str(&self) -> &str {
5291 match self {
5292 Self::Checking => "checking",
5293 Self::Done => "done",
5294 Self::Unknown(s) => s.as_str(),
5295 }
5296 }
5297}
5298
5299impl fmt::Display for PermissionCheckStatus {
5300 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5301 f.write_str(self.as_str())
5302 }
5303}
5304
5305impl From<&str> for PermissionCheckStatus {
5306 fn from(s: &str) -> Self {
5307 match s {
5308 "checking" => Self::Checking,
5309 "done" => Self::Done,
5310 other => Self::Unknown(other.to_string()),
5311 }
5312 }
5313}
5314
5315impl Serialize for PermissionCheckStatus {
5316 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
5317 serializer.serialize_str(self.as_str())
5318 }
5319}
5320
5321impl<'de> Deserialize<'de> for PermissionCheckStatus {
5322 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
5323 let s = String::deserialize(deserializer)?;
5324 Ok(Self::from(s.as_str()))
5325 }
5326}
5327
5328#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5330pub struct MissingFileAttachment {
5331 pub file_uuid: String,
5333 pub reason: String,
5338}
5339
5340#[derive(Debug, Clone, Serialize, Deserialize)]
5350pub struct SessionTitleChangedMessage {
5351 pub title: String,
5356 pub uuid: String,
5357 pub session_id: String,
5358}
5359
5360#[derive(Debug, Clone, Serialize, Deserialize)]
5370pub struct SessionWritesLostMessage {
5371 pub error_code: SessionWriteErrorCode,
5374 pub lost: Vec<LostSessionWrite>,
5376 #[serde(default, skip_serializing_if = "Option::is_none")]
5382 pub transcript_session_ids: Option<Vec<String>>,
5383 pub uuid: String,
5384 pub session_id: String,
5388}
5389
5390#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5392pub enum SessionWriteErrorCode {
5393 Enospc,
5395 Edquot,
5397 Unknown(String),
5399}
5400
5401impl SessionWriteErrorCode {
5402 pub fn as_str(&self) -> &str {
5403 match self {
5404 Self::Enospc => "ENOSPC",
5405 Self::Edquot => "EDQUOT",
5406 Self::Unknown(s) => s.as_str(),
5407 }
5408 }
5409}
5410
5411impl fmt::Display for SessionWriteErrorCode {
5412 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5413 f.write_str(self.as_str())
5414 }
5415}
5416
5417impl From<&str> for SessionWriteErrorCode {
5418 fn from(s: &str) -> Self {
5419 match s {
5420 "ENOSPC" => Self::Enospc,
5421 "EDQUOT" => Self::Edquot,
5422 other => Self::Unknown(other.to_string()),
5423 }
5424 }
5425}
5426
5427impl Serialize for SessionWriteErrorCode {
5428 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
5429 serializer.serialize_str(self.as_str())
5430 }
5431}
5432
5433impl<'de> Deserialize<'de> for SessionWriteErrorCode {
5434 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
5435 let s = String::deserialize(deserializer)?;
5436 Ok(Self::from(s.as_str()))
5437 }
5438}
5439
5440#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5442pub enum LostSessionWrite {
5443 Transcript,
5446 GlobalConfig,
5448 Unknown(String),
5450}
5451
5452impl LostSessionWrite {
5453 pub fn as_str(&self) -> &str {
5454 match self {
5455 Self::Transcript => "transcript",
5456 Self::GlobalConfig => "global_config",
5457 Self::Unknown(s) => s.as_str(),
5458 }
5459 }
5460}
5461
5462impl fmt::Display for LostSessionWrite {
5463 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5464 f.write_str(self.as_str())
5465 }
5466}
5467
5468impl From<&str> for LostSessionWrite {
5469 fn from(s: &str) -> Self {
5470 match s {
5471 "transcript" => Self::Transcript,
5472 "global_config" => Self::GlobalConfig,
5473 other => Self::Unknown(other.to_string()),
5474 }
5475 }
5476}
5477
5478impl Serialize for LostSessionWrite {
5479 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
5480 serializer.serialize_str(self.as_str())
5481 }
5482}
5483
5484impl<'de> Deserialize<'de> for LostSessionWrite {
5485 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
5486 let s = String::deserialize(deserializer)?;
5487 Ok(Self::from(s.as_str()))
5488 }
5489}
5490
5491#[derive(Debug, Clone, Serialize, Deserialize)]
5495pub struct UiLogMessage {
5496 pub plugin: String,
5498 pub text: String,
5502 pub uuid: String,
5503 pub session_id: String,
5504}
5505
5506#[derive(Debug, Clone, Serialize, Deserialize)]
5511pub struct UiNotifyMessage {
5512 pub plugin: String,
5517 pub source: String,
5521 pub title: String,
5525 pub text: String,
5529 #[serde(default, skip_serializing_if = "Option::is_none")]
5533 pub key: Option<String>,
5534 #[serde(default, skip_serializing_if = "Option::is_none")]
5538 pub delay_ms: Option<u64>,
5539 #[serde(default, skip_serializing_if = "Option::is_none")]
5542 pub at: Option<u64>,
5543 #[serde(default, skip_serializing_if = "Option::is_none")]
5546 pub until_back: Option<bool>,
5547 #[serde(default)]
5552 pub rewritten: bool,
5553 pub uuid: String,
5554 pub session_id: String,
5555}
5556
5557#[derive(Debug, Clone, Serialize, Deserialize)]
5562pub struct UiNotifyCancelMessage {
5563 pub plugin: String,
5566 pub source: String,
5569 #[serde(default, skip_serializing_if = "Option::is_none")]
5574 pub key: Option<String>,
5575 pub uuid: String,
5576 pub session_id: String,
5577}
5578
5579#[derive(Debug, Clone, Serialize, Deserialize)]
5584pub struct UiToastMessage {
5585 pub plugin: String,
5587 pub text: String,
5591 pub timeout_ms: u64,
5594 pub uuid: String,
5595 pub session_id: String,
5596}
5597
5598#[derive(Debug, Clone, Serialize, Deserialize)]
5602pub struct UiStatusMessage {
5603 pub plugin: String,
5605 pub text: Option<String>,
5610 pub uuid: String,
5611 pub session_id: String,
5612}
5613
5614#[derive(Debug, Clone, Serialize, Deserialize)]
5621pub struct UiInvalidateMessage {
5622 pub event: String,
5625 #[serde(default, skip_serializing_if = "Option::is_none")]
5637 pub instances: Option<Vec<UiInvalidatedInstance>>,
5638 #[serde(default, skip_serializing_if = "Option::is_none")]
5646 pub prompts_screened: Option<bool>,
5647 pub uuid: String,
5648 pub session_id: String,
5649}
5650
5651#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5653pub struct UiInvalidatedInstance {
5654 pub surface: String,
5656 pub component: String,
5658 pub instance_id: String,
5661}
5662
5663#[derive(Debug, Clone, Serialize, Deserialize)]
5670pub struct UiPanesMessage {
5671 pub panes: Vec<UiPane>,
5674 pub shown_id: Option<String>,
5677 pub focused_id: Option<String>,
5680 pub focus_requested_id: Option<String>,
5684 pub uuid: String,
5685 pub session_id: String,
5686}
5687
5688#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5690pub struct UiPane {
5691 pub id: String,
5694 pub title: String,
5697 pub plugin: String,
5699 #[serde(default, skip_serializing_if = "Option::is_none")]
5702 pub close_on_escape: Option<bool>,
5703 #[serde(default, skip_serializing_if = "Option::is_none")]
5706 pub hold_toasts: Option<bool>,
5707 #[serde(default, skip_serializing_if = "Option::is_none")]
5712 pub background_color: Option<String>,
5713 #[serde(default, skip_serializing_if = "Option::is_none")]
5716 pub rows: Option<u64>,
5717 #[serde(default, skip_serializing_if = "Option::is_none")]
5720 pub columns: Option<u64>,
5721 #[serde(default, skip_serializing_if = "Option::is_none")]
5728 pub placement: Option<String>,
5729}
5730
5731#[derive(Debug, Clone, Serialize, Deserialize)]
5739pub struct UiPlacedMessage {
5740 pub rows: Vec<UiPlacedRow>,
5742 pub uuid: String,
5743 pub session_id: String,
5744}
5745
5746#[derive(Debug, Clone, Serialize, Deserialize)]
5748pub struct UiPlacedRow {
5749 pub plugin: String,
5751 pub id: String,
5753 pub request_id: String,
5756 #[serde(default, skip_serializing_if = "Option::is_none")]
5759 pub after_uuid: Option<String>,
5760}
5761
5762#[derive(Debug, Clone, Serialize, Deserialize)]
5766pub struct UiScrollMessage {
5767 pub client_id: String,
5769 pub component: UiSiteComponent,
5771 pub instance_id: String,
5773 pub offset: u64,
5776 #[serde(default, skip_serializing_if = "Option::is_none")]
5779 pub follow_end: Option<bool>,
5780 pub uuid: String,
5781 pub session_id: String,
5782}
5783
5784#[derive(Debug, Clone, Serialize, Deserialize)]
5789pub struct UiFocusMessage {
5790 pub client_id: String,
5792 pub component: UiSiteComponent,
5794 pub instance_id: String,
5796 pub plugin: String,
5798 pub key: String,
5800 pub uuid: String,
5801 pub session_id: String,
5802}
5803
5804#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5806pub enum UiSiteComponent {
5807 Pane,
5809 AbovePrompt,
5811 Unknown(String),
5813}
5814
5815impl UiSiteComponent {
5816 pub fn as_str(&self) -> &str {
5817 match self {
5818 Self::Pane => "Pane",
5819 Self::AbovePrompt => "AbovePrompt",
5820 Self::Unknown(s) => s.as_str(),
5821 }
5822 }
5823}
5824
5825impl fmt::Display for UiSiteComponent {
5826 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5827 f.write_str(self.as_str())
5828 }
5829}
5830
5831impl From<&str> for UiSiteComponent {
5832 fn from(s: &str) -> Self {
5833 match s {
5834 "Pane" => Self::Pane,
5835 "AbovePrompt" => Self::AbovePrompt,
5836 other => Self::Unknown(other.to_string()),
5837 }
5838 }
5839}
5840
5841impl Serialize for UiSiteComponent {
5842 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
5843 serializer.serialize_str(self.as_str())
5844 }
5845}
5846
5847impl<'de> Deserialize<'de> for UiSiteComponent {
5848 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
5849 let s = String::deserialize(deserializer)?;
5850 Ok(Self::from(s.as_str()))
5851 }
5852}
5853
5854#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
5857pub struct LocalCommandRun {
5858 pub command: String,
5860 pub args: String,
5863 #[serde(default, skip_serializing_if = "Option::is_none")]
5868 pub plugin: Option<String>,
5869}
5870
5871#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5875pub struct LocalCommandOutcome {
5876 pub kind: LocalCommandOutcomeKind,
5877 #[serde(default, skip_serializing_if = "Option::is_none")]
5880 pub suggestion: Option<String>,
5881}
5882
5883#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5888pub enum LocalCommandOutcomeKind {
5889 UnavailableHeadless,
5891 Unknown,
5894 Failed,
5896 RestartRequired,
5898 Other(String),
5900}
5901
5902impl LocalCommandOutcomeKind {
5903 pub fn as_str(&self) -> &str {
5904 match self {
5905 Self::UnavailableHeadless => "unavailable_headless",
5906 Self::Unknown => "unknown",
5907 Self::Failed => "failed",
5908 Self::RestartRequired => "restart_required",
5909 Self::Other(s) => s.as_str(),
5910 }
5911 }
5912}
5913
5914impl fmt::Display for LocalCommandOutcomeKind {
5915 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5916 f.write_str(self.as_str())
5917 }
5918}
5919
5920impl From<&str> for LocalCommandOutcomeKind {
5921 fn from(s: &str) -> Self {
5922 match s {
5923 "unavailable_headless" => Self::UnavailableHeadless,
5924 "unknown" => Self::Unknown,
5925 "failed" => Self::Failed,
5926 "restart_required" => Self::RestartRequired,
5927 other => Self::Other(other.to_string()),
5928 }
5929 }
5930}
5931
5932impl Serialize for LocalCommandOutcomeKind {
5933 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
5934 serializer.serialize_str(self.as_str())
5935 }
5936}
5937
5938impl<'de> Deserialize<'de> for LocalCommandOutcomeKind {
5939 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
5940 let s = String::deserialize(deserializer)?;
5941 Ok(Self::from(s.as_str()))
5942 }
5943}
5944
5945#[derive(Debug, Clone, Serialize, Deserialize)]
5951pub struct UsageReport {
5952 pub session: super::control::UsageSession,
5954 pub rate_limits: Option<UsageReportRateLimits>,
5958 #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
5959 pub extra: serde_json::Map<String, Value>,
5960}
5961
5962#[derive(Debug, Clone, Serialize, Deserialize)]
5964pub struct UsageReportRateLimits {
5965 pub limits: Option<Vec<UsageReportLimit>>,
5973 #[serde(default, skip_serializing_if = "Option::is_none")]
5976 pub extra_usage: Option<UsageReportExtraUsage>,
5977 #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
5978 pub extra: serde_json::Map<String, Value>,
5979}
5980
5981#[derive(Debug, Clone, Serialize, Deserialize)]
5983pub struct UsageReportLimit {
5984 pub kind: String,
5987 pub group: String,
5990 pub percent: f64,
5992 pub resets_at: Option<String>,
5994 #[serde(default, skip_serializing_if = "Option::is_none")]
5997 pub scope: Option<UsageReportScope>,
5998 #[serde(default, skip_serializing_if = "Option::is_none")]
6002 pub severity: Option<String>,
6003 #[serde(default, skip_serializing_if = "Option::is_none")]
6005 pub is_active: Option<bool>,
6006 #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
6007 pub extra: serde_json::Map<String, Value>,
6008}
6009
6010#[derive(Debug, Clone, Serialize, Deserialize)]
6012pub struct UsageReportScope {
6013 #[serde(default, skip_serializing_if = "Option::is_none")]
6014 pub model: Option<UsageReportScopeLabel>,
6015 #[serde(default, skip_serializing_if = "Option::is_none")]
6016 pub surface: Option<UsageReportScopeLabel>,
6017 #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
6018 pub extra: serde_json::Map<String, Value>,
6019}
6020
6021#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6023pub struct UsageReportScopeLabel {
6024 pub display_name: String,
6025}
6026
6027#[derive(Debug, Clone, Serialize, Deserialize)]
6031pub struct UsageReportExtraUsage {
6032 pub is_enabled: bool,
6034 pub monthly_limit: Option<f64>,
6035 pub used_credits: Option<f64>,
6036 pub utilization: Option<f64>,
6037 #[serde(default, skip_serializing_if = "Option::is_none")]
6038 pub currency: Option<String>,
6039 #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
6040 pub extra: serde_json::Map<String, Value>,
6041}
6042
6043#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6046pub struct BatchToolUse {
6047 pub id: String,
6048 pub name: String,
6049}
6050
6051#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6056pub struct ContextUsage {
6057 pub model: String,
6059 pub total_tokens: u64,
6062 pub raw_max_tokens: u64,
6065 pub percentage: u64,
6067 #[serde(default, skip_serializing_if = "Option::is_none")]
6069 pub over_limit: Option<ContextOverLimit>,
6070 #[serde(default)]
6072 pub categories: Vec<ContextCategory>,
6073 #[serde(default)]
6075 pub mcp_tools: Vec<ContextMcpTool>,
6076 #[serde(default)]
6078 pub memory_files: Vec<ContextMemoryFile>,
6079 #[serde(default)]
6081 pub agents: Vec<ContextAgent>,
6082 #[serde(default, skip_serializing_if = "Option::is_none")]
6084 pub skills: Option<Vec<ContextSkill>>,
6085}
6086
6087#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6089pub struct ContextOverLimit {
6090 pub tokens_over: u64,
6091 pub kind: String,
6094}
6095
6096#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6098pub struct ContextCategory {
6099 pub name: String,
6102 pub tokens: u64,
6103 pub kind: String,
6107}
6108
6109#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6111pub struct ContextMcpTool {
6112 pub name: String,
6114 pub server_name: String,
6115 pub tokens: u64,
6116}
6117
6118#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6120pub struct ContextMemoryFile {
6121 pub path: String,
6122 #[serde(rename = "type")]
6124 pub file_type: String,
6125 pub tokens: u64,
6126}
6127
6128#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6130pub struct ContextAgent {
6131 pub agent_type: String,
6132 pub source: String,
6134 pub tokens: u64,
6135}
6136
6137#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6139pub struct ContextSkill {
6140 pub name: String,
6141 pub source: String,
6143 #[serde(default, skip_serializing_if = "Option::is_none")]
6144 pub plugin_name: Option<String>,
6145 pub tokens: u64,
6146}
6147
6148#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6150pub struct ToolUseMeta {
6151 pub id: String,
6152 pub display_name: String,
6153 #[serde(default, skip_serializing_if = "Option::is_none")]
6154 pub server_display_name: Option<String>,
6155 #[serde(default, skip_serializing_if = "Option::is_none")]
6156 pub icon_url: Option<String>,
6157 #[serde(default, skip_serializing_if = "Option::is_none")]
6162 pub server_id: Option<String>,
6163 #[serde(default, skip_serializing_if = "Option::is_none")]
6171 pub server_id_stamp: Option<String>,
6172 #[serde(default, skip_serializing_if = "Option::is_none")]
6175 pub tool_name: Option<String>,
6176 #[serde(default, skip_serializing_if = "Option::is_none")]
6185 pub artifact_publish: Option<bool>,
6186}
6187
6188#[derive(Debug, Clone, Serialize, Deserialize)]
6190pub struct AssistantMessage {
6191 pub message: AssistantMessageContent,
6192 #[serde(alias = "sessionId")]
6193 pub session_id: String,
6194 #[serde(skip_serializing_if = "Option::is_none")]
6195 pub uuid: Option<String>,
6196 #[serde(skip_serializing_if = "Option::is_none")]
6197 pub parent_tool_use_id: Option<String>,
6198 #[serde(skip_serializing_if = "Option::is_none")]
6200 pub request_id: Option<String>,
6201 #[serde(default, skip_serializing_if = "Option::is_none")]
6206 pub refused_message_id: Option<String>,
6207 #[serde(default, skip_serializing_if = "Option::is_none")]
6216 pub user_message_uuid: Option<String>,
6217 #[serde(default, skip_serializing_if = "Vec::is_empty")]
6223 pub user_message_uuids: Vec<String>,
6224 #[serde(default, skip_serializing_if = "Option::is_none")]
6228 pub agent_id: Option<String>,
6229 #[serde(skip_serializing_if = "Option::is_none")]
6232 pub subagent_type: Option<String>,
6233 #[serde(skip_serializing_if = "Option::is_none")]
6235 pub task_description: Option<String>,
6236 #[serde(skip_serializing_if = "Option::is_none")]
6237 pub error: Option<AssistantErrorKind>,
6238 #[serde(default, skip_serializing_if = "Option::is_none")]
6242 pub aborted: Option<bool>,
6243 #[serde(default, skip_serializing_if = "Option::is_none")]
6248 pub resumed_from_incomplete_thinking: Option<bool>,
6249 #[serde(default, skip_serializing_if = "Vec::is_empty")]
6256 pub supersedes: Vec<String>,
6257 #[serde(skip_serializing_if = "Option::is_none")]
6258 pub timestamp: Option<String>,
6259 #[serde(default, skip_serializing_if = "Vec::is_empty")]
6260 pub tool_use_meta: Vec<ToolUseMeta>,
6261 #[serde(default, skip_serializing_if = "Vec::is_empty")]
6266 pub batch_tool_uses: Vec<BatchToolUse>,
6267 #[serde(default, skip_serializing_if = "Option::is_none")]
6273 pub wire_tool_inputs: Option<serde_json::Map<String, Value>>,
6274 #[serde(default, skip_serializing_if = "Option::is_none")]
6280 pub wire_ingest_context: Option<serde_json::Map<String, Value>>,
6281 #[serde(default, skip_serializing_if = "Option::is_none")]
6285 pub historical: Option<bool>,
6286 #[serde(default, skip_serializing_if = "Option::is_none")]
6294 pub resume_reason: Option<String>,
6295 #[serde(default, skip_serializing_if = "Option::is_none")]
6301 pub local_command_source: Option<String>,
6302 #[serde(default, skip_serializing_if = "Vec::is_empty")]
6311 pub narration_block_indexes: Vec<usize>,
6312 #[serde(default, skip_serializing_if = "Option::is_none")]
6316 pub narration_hint: Option<String>,
6317 #[serde(default, skip_serializing_if = "Option::is_none")]
6326 pub thinking_duration_ms: Option<u64>,
6327 #[serde(default, skip_serializing_if = "Option::is_none")]
6338 pub thinking_display: Option<String>,
6339 #[serde(default, skip_serializing_if = "Option::is_none")]
6343 pub context_usage: Option<ContextUsage>,
6344 #[serde(default, skip_serializing_if = "Option::is_none")]
6352 pub usage_report: Option<Box<UsageReport>>,
6353 #[serde(default, skip_serializing_if = "Option::is_none")]
6360 pub local_command_run: Option<LocalCommandRun>,
6361 #[serde(default, skip_serializing_if = "Option::is_none")]
6367 pub local_command_outcome: Option<LocalCommandOutcome>,
6368 #[serde(default, skip_serializing_if = "Option::is_none")]
6369 pub is_meta: Option<bool>,
6370 #[serde(default, skip_serializing_if = "Option::is_none")]
6371 pub is_virtual: Option<bool>,
6372 #[serde(default, skip_serializing_if = "Option::is_none")]
6373 pub is_api_error_message: Option<bool>,
6374 #[serde(skip_serializing_if = "Option::is_none")]
6375 pub api_error_status: Option<u16>,
6376 #[serde(skip_serializing_if = "Option::is_none")]
6431 pub api_error: Option<String>,
6432 #[serde(default, skip_serializing_if = "Option::is_none")]
6439 pub api_error_code: Option<String>,
6440 #[serde(default, skip_serializing_if = "Option::is_none")]
6452 pub api_error_type: Option<String>,
6453 #[serde(default, skip_serializing_if = "Option::is_none")]
6464 pub api_error_origin: Option<String>,
6465 #[serde(default, skip_serializing_if = "Option::is_none")]
6468 pub api_error_params: Option<ApiErrorParams>,
6469 #[serde(skip_serializing_if = "Option::is_none")]
6470 pub error_details: Option<String>,
6471 #[serde(skip_serializing_if = "Option::is_none")]
6472 pub advisor_model: Option<String>,
6473 #[serde(skip_serializing_if = "Option::is_none")]
6474 pub attribution_agent: Option<String>,
6475 #[serde(skip_serializing_if = "Option::is_none")]
6476 pub attribution_skill: Option<String>,
6477 #[serde(skip_serializing_if = "Option::is_none")]
6478 pub attribution_plugin: Option<String>,
6479 #[serde(skip_serializing_if = "Option::is_none")]
6480 pub attribution_mcp_server: Option<String>,
6481 #[serde(skip_serializing_if = "Option::is_none")]
6482 pub attribution_mcp_tool: Option<String>,
6483}
6484
6485#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
6489pub struct ApiErrorParams {
6490 #[serde(default, skip_serializing_if = "Option::is_none")]
6492 pub effort: Option<String>,
6493 #[serde(default, skip_serializing_if = "Option::is_none")]
6496 pub provider: Option<ApiErrorProvider>,
6497 #[serde(default, skip_serializing_if = "Option::is_none")]
6500 pub remedy: Option<ApiErrorRemedy>,
6501 #[serde(default, skip_serializing_if = "Option::is_none")]
6504 pub media: Option<ApiErrorMedia>,
6505 #[serde(default, skip_serializing_if = "Option::is_none")]
6507 pub media_reason: Option<ApiErrorMediaReason>,
6508 #[serde(default, skip_serializing_if = "Option::is_none")]
6530 pub rate_limit_info: Option<RateLimitInfo>,
6531 #[serde(default, skip_serializing_if = "Option::is_none")]
6536 pub cut: Option<ApiErrorCut>,
6537}
6538
6539#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6541pub enum ApiErrorCut {
6542 OutputLimit,
6544 ContextWindow,
6546 Unknown(String),
6548}
6549
6550impl ApiErrorCut {
6551 pub fn as_str(&self) -> &str {
6552 match self {
6553 Self::OutputLimit => "output_limit",
6554 Self::ContextWindow => "context_window",
6555 Self::Unknown(s) => s.as_str(),
6556 }
6557 }
6558}
6559
6560impl fmt::Display for ApiErrorCut {
6561 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6562 f.write_str(self.as_str())
6563 }
6564}
6565
6566impl From<&str> for ApiErrorCut {
6567 fn from(s: &str) -> Self {
6568 match s {
6569 "output_limit" => Self::OutputLimit,
6570 "context_window" => Self::ContextWindow,
6571 other => Self::Unknown(other.to_string()),
6572 }
6573 }
6574}
6575
6576impl Serialize for ApiErrorCut {
6577 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
6578 serializer.serialize_str(self.as_str())
6579 }
6580}
6581
6582impl<'de> Deserialize<'de> for ApiErrorCut {
6583 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
6584 let s = String::deserialize(deserializer)?;
6585 Ok(Self::from(s.as_str()))
6586 }
6587}
6588
6589#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6591pub enum ApiErrorMedia {
6592 Image,
6593 Document,
6594 Unknown(String),
6596}
6597
6598impl ApiErrorMedia {
6599 pub fn as_str(&self) -> &str {
6600 match self {
6601 Self::Image => "image",
6602 Self::Document => "document",
6603 Self::Unknown(s) => s.as_str(),
6604 }
6605 }
6606}
6607
6608impl fmt::Display for ApiErrorMedia {
6609 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6610 f.write_str(self.as_str())
6611 }
6612}
6613
6614impl From<&str> for ApiErrorMedia {
6615 fn from(s: &str) -> Self {
6616 match s {
6617 "image" => Self::Image,
6618 "document" => Self::Document,
6619 other => Self::Unknown(other.to_string()),
6620 }
6621 }
6622}
6623
6624impl Serialize for ApiErrorMedia {
6625 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
6626 serializer.serialize_str(self.as_str())
6627 }
6628}
6629
6630impl<'de> Deserialize<'de> for ApiErrorMedia {
6631 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
6632 let s = String::deserialize(deserializer)?;
6633 Ok(Self::from(s.as_str()))
6634 }
6635}
6636
6637#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6640pub enum ApiErrorMediaReason {
6641 Unprocessable,
6644 UnsupportedByModel,
6646 MediaBudget,
6649 Unknown(String),
6651}
6652
6653impl ApiErrorMediaReason {
6654 pub fn as_str(&self) -> &str {
6655 match self {
6656 Self::Unprocessable => "unprocessable",
6657 Self::UnsupportedByModel => "unsupported_by_model",
6658 Self::MediaBudget => "media_budget",
6659 Self::Unknown(s) => s.as_str(),
6660 }
6661 }
6662}
6663
6664impl fmt::Display for ApiErrorMediaReason {
6665 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6666 f.write_str(self.as_str())
6667 }
6668}
6669
6670impl From<&str> for ApiErrorMediaReason {
6671 fn from(s: &str) -> Self {
6672 match s {
6673 "unprocessable" => Self::Unprocessable,
6674 "unsupported_by_model" => Self::UnsupportedByModel,
6675 "media_budget" => Self::MediaBudget,
6676 other => Self::Unknown(other.to_string()),
6677 }
6678 }
6679}
6680
6681impl Serialize for ApiErrorMediaReason {
6682 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
6683 serializer.serialize_str(self.as_str())
6684 }
6685}
6686
6687impl<'de> Deserialize<'de> for ApiErrorMediaReason {
6688 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
6689 let s = String::deserialize(deserializer)?;
6690 Ok(Self::from(s.as_str()))
6691 }
6692}
6693
6694#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6696pub enum ApiErrorProvider {
6697 Bedrock,
6698 AnthropicAws,
6699 Mantle,
6700 AnthropicGoogleCloud,
6701 Vertex,
6702 Foundry,
6703 Gateway,
6704 Unknown(String),
6706}
6707
6708impl ApiErrorProvider {
6709 pub fn as_str(&self) -> &str {
6710 match self {
6711 Self::Bedrock => "bedrock",
6712 Self::AnthropicAws => "anthropicAws",
6713 Self::Mantle => "mantle",
6714 Self::AnthropicGoogleCloud => "anthropicGoogleCloud",
6715 Self::Vertex => "vertex",
6716 Self::Foundry => "foundry",
6717 Self::Gateway => "gateway",
6718 Self::Unknown(s) => s.as_str(),
6719 }
6720 }
6721}
6722
6723impl fmt::Display for ApiErrorProvider {
6724 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6725 f.write_str(self.as_str())
6726 }
6727}
6728
6729impl From<&str> for ApiErrorProvider {
6730 fn from(s: &str) -> Self {
6731 match s {
6732 "bedrock" => Self::Bedrock,
6733 "anthropicAws" => Self::AnthropicAws,
6734 "mantle" => Self::Mantle,
6735 "anthropicGoogleCloud" => Self::AnthropicGoogleCloud,
6736 "vertex" => Self::Vertex,
6737 "foundry" => Self::Foundry,
6738 "gateway" => Self::Gateway,
6739 other => Self::Unknown(other.to_string()),
6740 }
6741 }
6742}
6743
6744impl Serialize for ApiErrorProvider {
6745 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
6746 serializer.serialize_str(self.as_str())
6747 }
6748}
6749
6750impl<'de> Deserialize<'de> for ApiErrorProvider {
6751 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
6752 let s = String::deserialize(deserializer)?;
6753 Ok(Self::from(s.as_str()))
6754 }
6755}
6756
6757#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6759pub enum ApiErrorRemedy {
6760 RefreshCommand,
6763 RefreshCredentials,
6765 Adc,
6768 GatewayToken,
6771 HostManaged,
6773 ModelAccess,
6776 Unknown(String),
6778}
6779
6780impl ApiErrorRemedy {
6781 pub fn as_str(&self) -> &str {
6782 match self {
6783 Self::RefreshCommand => "refresh_command",
6784 Self::RefreshCredentials => "refresh_credentials",
6785 Self::Adc => "adc",
6786 Self::GatewayToken => "gateway_token",
6787 Self::HostManaged => "host_managed",
6788 Self::ModelAccess => "model_access",
6789 Self::Unknown(s) => s.as_str(),
6790 }
6791 }
6792}
6793
6794impl fmt::Display for ApiErrorRemedy {
6795 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6796 f.write_str(self.as_str())
6797 }
6798}
6799
6800impl From<&str> for ApiErrorRemedy {
6801 fn from(s: &str) -> Self {
6802 match s {
6803 "refresh_command" => Self::RefreshCommand,
6804 "refresh_credentials" => Self::RefreshCredentials,
6805 "adc" => Self::Adc,
6806 "gateway_token" => Self::GatewayToken,
6807 "host_managed" => Self::HostManaged,
6808 "model_access" => Self::ModelAccess,
6809 other => Self::Unknown(other.to_string()),
6810 }
6811 }
6812}
6813
6814impl Serialize for ApiErrorRemedy {
6815 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
6816 serializer.serialize_str(self.as_str())
6817 }
6818}
6819
6820impl<'de> Deserialize<'de> for ApiErrorRemedy {
6821 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
6822 let s = String::deserialize(deserializer)?;
6823 Ok(Self::from(s.as_str()))
6824 }
6825}
6826
6827#[derive(Debug, Clone, Serialize, Deserialize)]
6829pub struct AssistantMessageContent {
6830 pub id: String,
6831 #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
6833 pub message_type: Option<String>,
6834 pub role: MessageRole,
6835 pub model: String,
6836 pub content: Vec<ContentBlock>,
6837 #[serde(skip_serializing_if = "Option::is_none")]
6838 pub stop_reason: Option<StopReason>,
6839 #[serde(skip_serializing_if = "Option::is_none")]
6840 pub stop_sequence: Option<String>,
6841 #[serde(skip_serializing_if = "Option::is_none")]
6842 pub usage: Option<AssistantUsage>,
6843 #[serde(skip_serializing_if = "Option::is_none")]
6845 pub stop_details: Option<Value>,
6846 #[serde(skip_serializing_if = "Option::is_none")]
6848 pub context_management: Option<Value>,
6849}
6850
6851#[derive(Debug, Clone, Serialize, Deserialize)]
6853pub struct AssistantUsage {
6854 #[serde(default)]
6856 pub input_tokens: u32,
6857
6858 #[serde(default)]
6860 pub output_tokens: u32,
6861
6862 #[serde(default)]
6864 pub cache_creation_input_tokens: u32,
6865
6866 #[serde(default)]
6868 pub cache_read_input_tokens: u32,
6869
6870 #[serde(skip_serializing_if = "Option::is_none")]
6872 pub service_tier: Option<String>,
6873
6874 #[serde(skip_serializing_if = "Option::is_none")]
6876 pub cache_creation: Option<CacheCreationDetails>,
6877
6878 #[serde(skip_serializing_if = "Option::is_none")]
6880 pub inference_geo: Option<String>,
6881
6882 #[serde(default, skip_serializing_if = "Option::is_none")]
6885 pub speed: Option<String>,
6886
6887 #[serde(default, skip_serializing_if = "Option::is_none")]
6890 pub fallback_credit: Option<Value>,
6891}
6892
6893#[derive(Debug, Clone, Serialize, Deserialize)]
6895pub struct CacheCreationDetails {
6896 #[serde(default)]
6898 pub ephemeral_1h_input_tokens: u32,
6899
6900 #[serde(default)]
6902 pub ephemeral_5m_input_tokens: u32,
6903}
6904
6905#[cfg(test)]
6906mod tests {
6907 use crate::io::ClaudeOutput;
6908
6909 #[test]
6910 fn test_subagent_usage_rollup_accumulates_task_results() {
6911 use super::SubagentUsageRollup;
6912
6913 let mut rollup = SubagentUsageRollup::default();
6914
6915 let task_result = r#"{"type":"user","message":{"role":"user","content":[]},"session_id":"7fbc568e-2bd6-45aa-b217-a1cf80004ba1","tool_use_result":{"status":"completed","prompt":"Compute 6 times 7.","agentId":"ab52f22445470d454","agentType":"general-purpose","resolvedModel":"claude-sonnet-4-6","totalDurationMs":1853,"totalTokens":10201,"totalToolUseCount":3}}"#;
6916 let output: ClaudeOutput = serde_json::from_str(task_result).unwrap();
6917 assert!(rollup.observe(&output));
6918 assert_eq!(rollup.subagent_tokens, 10201);
6919 assert_eq!(rollup.agent_count, 1);
6920 assert_eq!(rollup.tool_uses, 3);
6921 assert_eq!(rollup.duration_ms, 1853);
6922
6923 assert!(!rollup.observe(&output));
6925 assert_eq!(rollup.agent_count, 1);
6926 assert_eq!(rollup.subagent_tokens, 10201);
6927
6928 let second = r#"{"type":"user","message":{"role":"user","content":[]},"session_id":"7fbc568e-2bd6-45aa-b217-a1cf80004ba1","tool_use_result":{"status":"completed","agentId":"ffff00001111","totalDurationMs":100,"totalTokens":500,"totalToolUseCount":1}}"#;
6930 let output: ClaudeOutput = serde_json::from_str(second).unwrap();
6931 assert!(rollup.observe(&output));
6932 assert_eq!(rollup.agent_count, 2);
6933 assert_eq!(rollup.subagent_tokens, 10701);
6934 }
6935
6936 #[test]
6937 fn test_subagent_usage_rollup_ignores_non_task_results() {
6938 use super::SubagentUsageRollup;
6939
6940 let mut rollup = SubagentUsageRollup::default();
6941
6942 let tool_search = r#"{"type":"user","message":{"role":"user","content":[]},"session_id":"7fbc568e-2bd6-45aa-b217-a1cf80004ba1","tool_use_result":{"matches":["TaskCreate"],"query":"select:TaskCreate","total_deferred_tools":27}}"#;
6945 let output: ClaudeOutput = serde_json::from_str(tool_search).unwrap();
6946 assert!(!rollup.observe(&output));
6947
6948 let plain = r#"{"type":"user","message":{"role":"user","content":[]},"session_id":"7fbc568e-2bd6-45aa-b217-a1cf80004ba1"}"#;
6950 let output: ClaudeOutput = serde_json::from_str(plain).unwrap();
6951 assert!(!rollup.observe(&output));
6952
6953 let system = r#"{"type":"system","subtype":"status","status":null,"session_id":"7fbc568e-2bd6-45aa-b217-a1cf80004ba1"}"#;
6955 let output: ClaudeOutput = serde_json::from_str(system).unwrap();
6956 assert!(!rollup.observe(&output));
6957
6958 assert_eq!(rollup, SubagentUsageRollup::default());
6959 }
6960
6961 #[test]
6962 fn test_subagent_usage_rollup_over_captured_session() {
6963 use super::SubagentUsageRollup;
6964
6965 let mut rollup = SubagentUsageRollup::default();
6966 let fixture =
6967 include_str!("../../test_cases/subagent_sessions/general_purpose_compute.jsonl");
6968 for line in fixture.lines().filter(|l| !l.trim().is_empty()) {
6969 if let Ok(output) = serde_json::from_str::<ClaudeOutput>(line) {
6970 rollup.observe(&output);
6971 }
6972 }
6973 assert_eq!(rollup.agent_count, 1);
6974 assert_eq!(rollup.subagent_tokens, 10201);
6975 }
6976
6977 #[test]
6978 fn test_system_message_init() {
6979 let json = r#"{
6980 "type": "system",
6981 "subtype": "init",
6982 "session_id": "test-session-123",
6983 "cwd": "/home/user/project",
6984 "model": "claude-sonnet-4",
6985 "tools": ["Bash", "Read", "Write"],
6986 "mcp_servers": [],
6987 "slash_commands": ["compact", "cost", "review"],
6988 "agents": ["Bash", "Explore", "Plan"],
6989 "plugins": [{"name": "rust-analyzer-lsp", "path": "/home/user/.claude/plugins/rust-analyzer-lsp/1.0.0"}],
6990 "skills": [],
6991 "claude_code_version": "2.1.15",
6992 "apiKeySource": "none",
6993 "output_style": "default",
6994 "permissionMode": "default"
6995 }"#;
6996
6997 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
6998 if let ClaudeOutput::System(sys) = output {
6999 assert!(sys.is_init());
7000 assert!(!sys.is_status());
7001 assert!(!sys.is_compact_boundary());
7002
7003 let init = sys.as_init().expect("Should parse as init");
7004 assert_eq!(init.session_id, "test-session-123");
7005 assert_eq!(init.cwd, Some("/home/user/project".to_string()));
7006 assert_eq!(init.model, Some("claude-sonnet-4".to_string()));
7007 assert_eq!(init.tools, vec!["Bash", "Read", "Write"]);
7008 assert_eq!(init.slash_commands, vec!["compact", "cost", "review"]);
7009 assert_eq!(init.agents, vec!["Bash", "Explore", "Plan"]);
7010 assert_eq!(init.plugins.len(), 1);
7011 assert_eq!(init.plugins[0].name, "rust-analyzer-lsp");
7012 assert_eq!(init.claude_code_version, Some("2.1.15".to_string()));
7013 assert_eq!(init.api_key_source, Some(super::ApiKeySource::None));
7014 assert_eq!(init.output_style, Some(super::OutputStyle::Default));
7015 assert_eq!(
7016 init.permission_mode,
7017 Some(super::InitPermissionMode::Default)
7018 );
7019 } else {
7020 panic!("Expected System message");
7021 }
7022 }
7023
7024 #[test]
7025 fn test_system_message_init_from_real_capture() {
7026 let json = include_str!("../../test_cases/tool_use_captures/tool_msg_0.json");
7027 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7028 if let ClaudeOutput::System(sys) = output {
7029 let init = sys.as_init().expect("Should parse real init capture");
7030 assert_eq!(init.slash_commands.len(), 8);
7031 assert!(init.slash_commands.contains(&"compact".to_string()));
7032 assert!(init.slash_commands.contains(&"review".to_string()));
7033 assert_eq!(init.agents.len(), 5);
7034 assert!(init.agents.contains(&"Bash".to_string()));
7035 assert!(init.agents.contains(&"Explore".to_string()));
7036 assert_eq!(init.plugins.len(), 1);
7037 assert_eq!(init.plugins[0].name, "rust-analyzer-lsp");
7038 assert_eq!(init.claude_code_version, Some("2.1.15".to_string()));
7039 } else {
7040 panic!("Expected System message");
7041 }
7042 }
7043
7044 #[test]
7045 fn test_system_message_status() {
7046 let json = r#"{
7047 "type": "system",
7048 "subtype": "status",
7049 "session_id": "879c1a88-3756-4092-aa95-0020c4ed9692",
7050 "status": "compacting",
7051 "uuid": "32eb9f9d-5ef7-47ff-8fce-bbe22fe7ed93"
7052 }"#;
7053
7054 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7055 if let ClaudeOutput::System(sys) = output {
7056 assert!(sys.is_status());
7057 assert!(!sys.is_init());
7058
7059 let status = sys.as_status().expect("Should parse as status");
7060 assert_eq!(status.session_id, "879c1a88-3756-4092-aa95-0020c4ed9692");
7061 assert_eq!(status.status, Some(super::StatusMessageStatus::Compacting));
7062 assert_eq!(
7063 status.uuid,
7064 Some("32eb9f9d-5ef7-47ff-8fce-bbe22fe7ed93".to_string())
7065 );
7066 } else {
7067 panic!("Expected System message");
7068 }
7069 }
7070
7071 #[test]
7072 fn test_system_message_status_null() {
7073 let json = r#"{
7074 "type": "system",
7075 "subtype": "status",
7076 "session_id": "879c1a88-3756-4092-aa95-0020c4ed9692",
7077 "status": null,
7078 "uuid": "92d9637e-d00e-418e-acd2-a504e3861c6a"
7079 }"#;
7080
7081 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7082 if let ClaudeOutput::System(sys) = output {
7083 let status = sys.as_status().expect("Should parse as status");
7084 assert_eq!(status.status, None);
7085 } else {
7086 panic!("Expected System message");
7087 }
7088 }
7089
7090 #[test]
7091 fn test_system_message_task_started() {
7092 let json = r#"{
7093 "type": "system",
7094 "subtype": "task_started",
7095 "session_id": "9abbc466-dad0-4b8e-b6b0-cad5eb7a16b9",
7096 "task_id": "b6daf3f",
7097 "task_type": "local_bash",
7098 "tool_use_id": "toolu_011rfSTFumpJZdCCfzeD7jaS",
7099 "description": "Wait for CI on PR #12",
7100 "uuid": "c4243261-c128-4747-b8c3-5e1c7c10eeb8"
7101 }"#;
7102
7103 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7104 if let ClaudeOutput::System(sys) = output {
7105 assert!(sys.is_task_started());
7106 assert!(!sys.is_task_progress());
7107 assert!(!sys.is_task_notification());
7108
7109 let task = sys.as_task_started().expect("Should parse as task_started");
7110 assert_eq!(task.session_id, "9abbc466-dad0-4b8e-b6b0-cad5eb7a16b9");
7111 assert_eq!(task.task_id, "b6daf3f");
7112 assert_eq!(task.task_type, Some(super::TaskType::LocalBash));
7113 assert_eq!(
7114 task.tool_use_id.as_deref(),
7115 Some("toolu_011rfSTFumpJZdCCfzeD7jaS")
7116 );
7117 assert_eq!(task.description, "Wait for CI on PR #12");
7118 } else {
7119 panic!("Expected System message");
7120 }
7121 }
7122
7123 #[test]
7124 fn test_system_message_task_started_agent() {
7125 let json = r#"{
7126 "type": "system",
7127 "subtype": "task_started",
7128 "session_id": "bff4f716-17c1-4255-ab7b-eea9d33824e3",
7129 "task_id": "a4a7e0906e5fc64cc",
7130 "task_type": "local_agent",
7131 "tool_use_id": "toolu_01SFz9FwZ1cYgCSy8vRM7wep",
7132 "description": "Explore Scene/ArrayScene duplication",
7133 "uuid": "85a39f5a-e4d4-47f7-9a6d-1125f1a8035f"
7134 }"#;
7135
7136 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7137 if let ClaudeOutput::System(sys) = output {
7138 let task = sys.as_task_started().expect("Should parse as task_started");
7139 assert_eq!(task.task_type, Some(super::TaskType::LocalAgent));
7140 assert_eq!(task.task_id, "a4a7e0906e5fc64cc");
7141 } else {
7142 panic!("Expected System message");
7143 }
7144 }
7145
7146 #[test]
7147 fn test_system_message_task_progress() {
7148 let json = r#"{
7149 "type": "system",
7150 "subtype": "task_progress",
7151 "session_id": "bff4f716-17c1-4255-ab7b-eea9d33824e3",
7152 "task_id": "a4a7e0906e5fc64cc",
7153 "tool_use_id": "toolu_01SFz9FwZ1cYgCSy8vRM7wep",
7154 "description": "Reading src/jplephem/chebyshev.rs",
7155 "last_tool_name": "Read",
7156 "usage": {
7157 "duration_ms": 13996,
7158 "tool_uses": 9,
7159 "total_tokens": 38779
7160 },
7161 "uuid": "85a39f5a-e4d4-47f7-9a6d-1125f1a8035f"
7162 }"#;
7163
7164 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7165 if let ClaudeOutput::System(sys) = output {
7166 assert!(sys.is_task_progress());
7167 assert!(!sys.is_task_started());
7168
7169 let progress = sys
7170 .as_task_progress()
7171 .expect("Should parse as task_progress");
7172 assert_eq!(progress.task_id, "a4a7e0906e5fc64cc");
7173 assert_eq!(progress.description, "Reading src/jplephem/chebyshev.rs");
7174 assert_eq!(progress.last_tool_name.as_deref(), Some("Read"));
7175 assert_eq!(progress.usage.duration_ms, 13996);
7176 assert_eq!(progress.usage.tool_uses, 9);
7177 assert_eq!(progress.usage.total_tokens, 38779);
7178 } else {
7179 panic!("Expected System message");
7180 }
7181 }
7182
7183 #[test]
7184 fn test_system_message_task_notification_completed() {
7185 let json = r#"{
7186 "type": "system",
7187 "subtype": "task_notification",
7188 "session_id": "bff4f716-17c1-4255-ab7b-eea9d33824e3",
7189 "task_id": "a0ba761e9dc9c316f",
7190 "tool_use_id": "toolu_01Ho6XVXFLVNjTQ9YqowdBXW",
7191 "status": "completed",
7192 "summary": "Agent \"Write Hipparcos data source doc\" completed",
7193 "output_file": "",
7194 "usage": {
7195 "duration_ms": 172300,
7196 "tool_uses": 11,
7197 "total_tokens": 42005
7198 },
7199 "uuid": "269f49b9-218d-4c8d-9f7e-3a5383a0c5b2"
7200 }"#;
7201
7202 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7203 if let ClaudeOutput::System(sys) = output {
7204 assert!(sys.is_task_notification());
7205
7206 let notif = sys
7207 .as_task_notification()
7208 .expect("Should parse as task_notification");
7209 assert_eq!(notif.status, super::TaskStatus::Completed);
7210 assert_eq!(
7211 notif.summary,
7212 "Agent \"Write Hipparcos data source doc\" completed"
7213 );
7214 assert_eq!(notif.output_file, Some("".to_string()));
7215 assert_eq!(
7216 notif.tool_use_id,
7217 Some("toolu_01Ho6XVXFLVNjTQ9YqowdBXW".to_string())
7218 );
7219 let usage = notif.usage.expect("Should have usage");
7220 assert_eq!(usage.duration_ms, 172300);
7221 assert_eq!(usage.tool_uses, 11);
7222 assert_eq!(usage.total_tokens, 42005);
7223 } else {
7224 panic!("Expected System message");
7225 }
7226 }
7227
7228 #[test]
7229 fn test_system_message_task_notification_failed_no_usage() {
7230 let json = r#"{
7231 "type": "system",
7232 "subtype": "task_notification",
7233 "session_id": "ea629737-3c36-48a8-a1c4-ad761ad35784",
7234 "task_id": "b98f6a3",
7235 "status": "failed",
7236 "summary": "Background command \"Run FSM calibration\" failed with exit code 1",
7237 "output_file": "/tmp/claude-1000/tasks/b98f6a3.output"
7238 }"#;
7239
7240 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7241 if let ClaudeOutput::System(sys) = output {
7242 let notif = sys
7243 .as_task_notification()
7244 .expect("Should parse as task_notification");
7245 assert_eq!(notif.status, super::TaskStatus::Failed);
7246 assert!(notif.tool_use_id.is_none());
7247 assert!(notif.usage.is_none());
7248 assert_eq!(
7249 notif.output_file,
7250 Some("/tmp/claude-1000/tasks/b98f6a3.output".to_string())
7251 );
7252 } else {
7253 panic!("Expected System message");
7254 }
7255 }
7256
7257 #[test]
7263 fn test_task_messages_roundtrip_through_value() {
7264 let cases = [
7265 r#"{"type":"system","subtype":"task_started","session_id":"s1",
7266 "task_id":"t1","task_type":"local_bash","tool_use_id":"tu1",
7267 "description":"Sleep 3s","uuid":"u1"}"#,
7268 r#"{"type":"system","subtype":"task_progress","session_id":"s1",
7269 "task_id":"t1","tool_use_id":"tu1","description":"Running ls",
7270 "last_tool_name":"Bash",
7271 "usage":{"duration_ms":100,"tool_uses":1,"total_tokens":500},
7272 "uuid":"u2"}"#,
7273 r#"{"type":"system","subtype":"task_notification","session_id":"s1",
7274 "task_id":"t1","tool_use_id":"tu1","status":"completed",
7275 "summary":"done","output_file":"",
7276 "usage":{"duration_ms":100,"tool_uses":1,"total_tokens":500},
7277 "uuid":"u3"}"#,
7278 ];
7279
7280 for json in cases {
7281 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7282 let value = serde_json::to_value(&output).unwrap();
7283 let reparsed: ClaudeOutput = serde_json::from_value(value).unwrap();
7284
7285 let ClaudeOutput::System(sys) = reparsed else {
7286 panic!("Expected System variant after round-trip");
7287 };
7288
7289 match sys.subtype {
7290 super::SystemSubtype::TaskStarted => {
7291 assert!(
7292 sys.as_task_started().is_some(),
7293 "as_task_started failed after round-trip"
7294 );
7295 }
7296 super::SystemSubtype::TaskProgress => {
7297 assert!(
7298 sys.as_task_progress().is_some(),
7299 "as_task_progress failed after round-trip"
7300 );
7301 }
7302 super::SystemSubtype::TaskNotification => {
7303 assert!(
7304 sys.as_task_notification().is_some(),
7305 "as_task_notification failed after round-trip"
7306 );
7307 }
7308 other => panic!("unexpected subtype after round-trip: {other:?}"),
7309 }
7310 }
7311 }
7312
7313 #[test]
7314 fn test_system_message_compact_boundary() {
7315 let json = r#"{
7316 "type": "system",
7317 "subtype": "compact_boundary",
7318 "session_id": "879c1a88-3756-4092-aa95-0020c4ed9692",
7319 "compact_metadata": {
7320 "pre_tokens": 155285,
7321 "trigger": "auto"
7322 },
7323 "uuid": "a67780d5-74cb-48b1-9137-7a6e7cee45d7"
7324 }"#;
7325
7326 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7327 if let ClaudeOutput::System(sys) = output {
7328 assert!(sys.is_compact_boundary());
7329 assert!(!sys.is_init());
7330 assert!(!sys.is_status());
7331
7332 let compact = sys
7333 .as_compact_boundary()
7334 .expect("Should parse as compact_boundary");
7335 assert_eq!(compact.session_id, "879c1a88-3756-4092-aa95-0020c4ed9692");
7336 assert_eq!(compact.compact_metadata.pre_tokens, 155285);
7337 assert_eq!(
7338 compact.compact_metadata.trigger,
7339 super::CompactionTrigger::Auto
7340 );
7341 assert!(compact.summary.is_none());
7343 assert!(compact.leaf_message_count.is_none());
7344 assert!(compact.duration_ms.is_none());
7345 } else {
7346 panic!("Expected System message");
7347 }
7348 }
7349
7350 #[test]
7351 fn test_compact_boundary_with_summary_stats() {
7352 let json = r#"{
7354 "type": "system",
7355 "subtype": "compact_boundary",
7356 "session_id": "s1",
7357 "compact_metadata": { "pre_tokens": 1000, "trigger": "manual" },
7358 "summary": "Summarized the earlier exploration.",
7359 "leaf_message_count": 42,
7360 "duration_ms": 1234,
7361 "uuid": "u1"
7362 }"#;
7363 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7364 let ClaudeOutput::System(sys) = output else {
7365 panic!("Expected System message");
7366 };
7367 let compact = sys.as_compact_boundary().expect("compact_boundary");
7368 assert_eq!(
7369 compact.summary.as_deref(),
7370 Some("Summarized the earlier exploration.")
7371 );
7372 assert_eq!(compact.leaf_message_count, Some(42));
7373 assert_eq!(compact.duration_ms, Some(1234));
7374
7375 let json_alt = r#"{
7378 "type": "system",
7379 "subtype": "compact_boundary",
7380 "session_id": "s2",
7381 "compact_metadata": { "pre_tokens": 2000, "trigger": "auto" },
7382 "content": "alt-key summary",
7383 "message_count": 7
7384 }"#;
7385 let output: ClaudeOutput = serde_json::from_str(json_alt).unwrap();
7386 let ClaudeOutput::System(sys) = output else {
7387 panic!("Expected System message");
7388 };
7389 let compact = sys.as_compact_boundary().expect("compact_boundary");
7390 assert_eq!(compact.summary.as_deref(), Some("alt-key summary"));
7391 assert_eq!(compact.leaf_message_count, Some(7));
7392 }
7393
7394 #[test]
7395 fn test_init_message_with_new_fields() {
7396 let json = r#"{
7397 "type": "system",
7398 "subtype": "init",
7399 "session_id": "test-session",
7400 "cwd": "/home/user",
7401 "model": "claude-opus-4-7",
7402 "tools": ["Bash"],
7403 "mcp_servers": [],
7404 "permissionMode": "default",
7405 "apiKeySource": "none",
7406 "uuid": "44841a0d-182d-493a-86b5-79800d3d9665",
7407 "memory_paths": {"auto": "/home/user/.claude/projects/memory/"},
7408 "fast_mode_state": "off",
7409 "plugins": [{"name": "lsp", "path": "/plugins/lsp", "source": "lsp@official"}],
7410 "claude_code_version": "2.1.117"
7411 }"#;
7412
7413 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7414 if let ClaudeOutput::System(sys) = output {
7415 let init = sys.as_init().expect("Should parse as init");
7416 assert_eq!(
7417 init.uuid.as_deref(),
7418 Some("44841a0d-182d-493a-86b5-79800d3d9665")
7419 );
7420 assert!(init.memory_paths.is_some());
7421 assert_eq!(init.fast_mode_state.as_deref(), Some("off"));
7422 assert_eq!(init.plugins[0].source.as_deref(), Some("lsp@official"));
7423 assert_eq!(init.claude_code_version.as_deref(), Some("2.1.117"));
7424 } else {
7425 panic!("Expected System message");
7426 }
7427 }
7428
7429 #[test]
7430 fn test_assistant_message_with_new_fields() {
7431 let json = r#"{
7432 "type": "assistant",
7433 "message": {
7434 "id": "msg_1",
7435 "type": "message",
7436 "role": "assistant",
7437 "model": "claude-opus-4-7",
7438 "content": [{"type": "text", "text": "Hello"}],
7439 "stop_reason": "end_turn",
7440 "stop_details": null,
7441 "context_management": null,
7442 "usage": {
7443 "input_tokens": 100,
7444 "output_tokens": 10,
7445 "cache_creation_input_tokens": 50,
7446 "cache_read_input_tokens": 0,
7447 "service_tier": "standard",
7448 "inference_geo": "not_available"
7449 }
7450 },
7451 "session_id": "abc",
7452 "uuid": "msg-uuid-123"
7453 }"#;
7454
7455 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7456 if let ClaudeOutput::Assistant(asst) = output {
7457 assert_eq!(asst.message.stop_details, None);
7458 assert_eq!(asst.message.context_management, None);
7459 let usage = asst.message.usage.unwrap();
7460 assert_eq!(usage.inference_geo.as_deref(), Some("not_available"));
7461 } else {
7462 panic!("Expected Assistant message");
7463 }
7464 }
7465
7466 #[test]
7467 fn test_user_message_with_new_fields() {
7468 let json = r#"{
7469 "type": "user",
7470 "message": {
7471 "role": "user",
7472 "content": [{"type": "text", "text": "Hello"}]
7473 },
7474 "session_id": "9abbc466-dad0-4b8e-b6b0-cad5eb7a16b9",
7475 "parent_tool_use_id": "toolu_123",
7476 "uuid": "user-msg-456"
7477 }"#;
7478
7479 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7480 if let ClaudeOutput::User(user) = output {
7481 assert_eq!(user.parent_tool_use_id.as_deref(), Some("toolu_123"));
7482 assert_eq!(user.uuid.as_deref(), Some("user-msg-456"));
7483 } else {
7484 panic!("Expected User message");
7485 }
7486 }
7487
7488 #[test]
7494 fn test_user_message_preserves_tool_use_result_and_timestamp() {
7495 let json = r#"{
7496 "type":"user",
7497 "message":{"role":"user","content":[{"type":"tool_result","content":"User has answered your questions: . You can now continue with the user's answers in mind.","tool_use_id":"toolu_01331duMqP2PrRaqR2yWa8e4"}]},
7498 "parent_tool_use_id":null,
7499 "session_id":"622ae0c3-3d50-4fa7-9ee0-69d691238c6d",
7500 "uuid":"8ef6e997-a849-4d15-bed3-2837c3d3f4cd",
7501 "timestamp":"2026-05-12T23:12:04.121Z",
7502 "tool_use_result":{"questions":[{"question":"Which color do you prefer?","header":"Color","options":[{"label":"Red","description":"A warm color"},{"label":"Blue","description":"A cool color"}],"multiSelect":false}],"answers":{"Color":"Blue"}}
7503 }"#;
7504
7505 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7506 let user = match output {
7507 ClaudeOutput::User(u) => u,
7508 other => panic!("Expected User message, got {:?}", other.message_type()),
7509 };
7510
7511 assert_eq!(user.timestamp.as_deref(), Some("2026-05-12T23:12:04.121Z"));
7512 let raw = user
7513 .tool_use_result
7514 .as_ref()
7515 .expect("tool_use_result must be captured");
7516 assert_eq!(raw["answers"]["Color"], "Blue");
7517 assert_eq!(raw["questions"][0]["header"], "Color");
7518
7519 let reser: serde_json::Value = serde_json::to_value(&user).unwrap();
7523 assert_eq!(reser["timestamp"], "2026-05-12T23:12:04.121Z");
7524 assert_eq!(reser["tool_use_result"]["answers"]["Color"], "Blue");
7525 assert_eq!(
7526 reser["tool_use_result"]["questions"][0]["question"],
7527 "Which color do you prefer?"
7528 );
7529
7530 let typed: crate::AskUserQuestionInput = user
7533 .tool_use_result_as::<crate::AskUserQuestionInput>()
7534 .expect("tool_use_result present")
7535 .expect("AskUserQuestionInput parses");
7536 assert_eq!(typed.questions.len(), 1);
7537 assert_eq!(typed.questions[0].header, "Color");
7538 let answers = typed.answers.expect("answers populated");
7539 assert_eq!(answers.get("Color").map(String::as_str), Some("Blue"));
7540 }
7541
7542 #[test]
7545 fn test_user_message_without_tool_use_result_omits_field() {
7546 let json = r#"{
7547 "type":"user",
7548 "message":{"role":"user","content":[{"type":"text","text":"hello"}]},
7549 "session_id":"622ae0c3-3d50-4fa7-9ee0-69d691238c6d"
7550 }"#;
7551
7552 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7553 let user = match output {
7554 ClaudeOutput::User(u) => u,
7555 _ => panic!("Expected User message"),
7556 };
7557 assert!(user.tool_use_result.is_none());
7558 assert!(user.timestamp.is_none());
7559
7560 let reser = serde_json::to_value(&user).unwrap();
7561 assert!(reser.get("tool_use_result").is_none());
7562 assert!(reser.get("timestamp").is_none());
7563 }
7564
7565 #[test]
7569 fn test_subagent_result_exposes_token_accounting() {
7570 let json = r#"{
7571 "type":"user",
7572 "message":{"role":"user","content":[{"tool_use_id":"toolu_01","type":"tool_result","content":[{"type":"text","text":"21"}]}]},
7573 "session_id":"d3fc5942-75e5-4aa1-a87d-b9484a176541",
7574 "tool_use_result":{
7575 "status":"completed",
7576 "prompt":"Count the .rs files.",
7577 "agentId":"ac4f0276e9d4b6232",
7578 "agentType":"Explore",
7579 "content":[{"type":"text","text":"21"}],
7580 "resolvedModel":"claude-haiku-4-5-20251001",
7581 "totalDurationMs":6869,
7582 "totalTokens":7834,
7583 "totalToolUseCount":1,
7584 "usage":{"input_tokens":6,"cache_creation_input_tokens":125,"cache_read_input_tokens":7699,"output_tokens":4,"service_tier":"standard"},
7585 "toolStats":{"readCount":0,"searchCount":0,"bashCount":1,"editFileCount":0,"linesAdded":0,"linesRemoved":0,"otherToolCount":0}
7586 }
7587 }"#;
7588
7589 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7590 let user = match output {
7591 ClaudeOutput::User(u) => u,
7592 _ => panic!("Expected User message"),
7593 };
7594
7595 let result = user.subagent_result().expect("subagent result parses");
7596 assert_eq!(result.agent_type.as_deref(), Some("Explore"));
7597 assert_eq!(
7598 result.resolved_model.as_deref(),
7599 Some("claude-haiku-4-5-20251001")
7600 );
7601 assert_eq!(result.total_tokens, Some(7834));
7602 assert_eq!(result.total_duration_ms, Some(6869));
7603 assert_eq!(result.total_tool_use_count, Some(1));
7604
7605 let usage = result.usage.expect("nested usage present");
7606 assert_eq!(usage.input_tokens, 6);
7607 assert_eq!(usage.cache_read_input_tokens, 7699);
7608
7609 let stats = result.tool_stats.expect("toolStats present");
7610 assert_eq!(stats.bash_count, 1);
7611 }
7612
7613 #[test]
7617 fn test_subagent_result_absent_for_non_task_result() {
7618 let json = r#"{
7619 "type":"user",
7620 "message":{"role":"user","content":[{"type":"text","text":"hi"}]},
7621 "session_id":"622ae0c3-3d50-4fa7-9ee0-69d691238c6d",
7622 "tool_use_result":{"questions":[],"answers":{"Color":"Blue"}}
7623 }"#;
7624
7625 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7626 let user = match output {
7627 ClaudeOutput::User(u) => u,
7628 _ => panic!("Expected User message"),
7629 };
7630
7631 let result = user.subagent_result().expect("lenient parse");
7632 assert_eq!(result.total_tokens, None);
7633 assert_eq!(result.agent_type, None);
7634 }
7635
7636 #[test]
7637 fn test_init_fast_mode_reason_and_mcp_server_errors_fully_wrapped() {
7638 use serde_json::Value;
7639
7640 let raw: Value = serde_json::from_str(
7641 r#"{
7642 "type":"system","subtype":"init","session_id":"s1","uuid":"u1",
7643 "fast_mode_state":"off",
7644 "fast_mode_disabled_reason":"not_first_party",
7645 "mcp_server_errors":[{"name":"broken","type":"invalid_config","message":"url entry with no type"}]
7646 }"#,
7647 )
7648 .unwrap();
7649 crate::io::assert_fully_wrapped(&raw);
7650
7651 let output: ClaudeOutput = serde_json::from_value(raw).unwrap();
7652 let ClaudeOutput::System(sys) = output else {
7653 panic!("expected System");
7654 };
7655 let init = sys.as_init().expect("parses as init");
7656 assert_eq!(
7657 init.fast_mode_disabled_reason,
7658 Some(crate::FastModeDisabledReason::NotFirstParty)
7659 );
7660 let errs = init.mcp_server_errors.unwrap();
7661 assert_eq!(errs.len(), 1);
7662 assert_eq!(errs[0].name, "broken");
7663 assert_eq!(errs[0].error_type, "invalid_config");
7664 }
7665
7666 #[test]
7667 fn test_code_change_published_fully_wrapped() {
7668 use super::{KnownSystemEvent, SystemSubtype};
7669 use serde_json::Value;
7670
7671 let raw: Value = serde_json::from_str(
7672 r#"{
7673 "type":"system","subtype":"code_change_published",
7674 "provider":"github","url":"https://github.com/owner/repo/pull/42",
7675 "repo":"owner/repo","identifier":"42",
7676 "uuid":"u1","session_id":"s1"
7677 }"#,
7678 )
7679 .unwrap();
7680 crate::io::assert_fully_wrapped(&raw);
7681
7682 let output: ClaudeOutput = serde_json::from_value(raw).unwrap();
7683 let ClaudeOutput::System(sys) = output else {
7684 panic!("expected System");
7685 };
7686 assert_eq!(sys.subtype, SystemSubtype::CodeChangePublished);
7687 let Some(KnownSystemEvent::CodeChangePublished(msg)) = sys.as_known_system_event() else {
7688 panic!("expected CodeChangePublished event");
7689 };
7690 assert_eq!(msg.provider, "github");
7691 assert_eq!(msg.repo, "owner/repo");
7692 assert_eq!(msg.identifier, "42");
7693
7694 assert!(sys.is_code_change_published());
7695 assert!(!sys.is_vcs_state_changed());
7696 let direct = sys.as_code_change_published().expect("direct accessor");
7697 assert_eq!(direct.url, "https://github.com/owner/repo/pull/42");
7698 assert!(sys.as_vcs_state_changed().is_none());
7699 }
7700
7701 #[test]
7702 fn test_feedback_draft_queued_fully_wrapped() {
7703 use super::{KnownSystemEvent, SystemSubtype};
7704 use serde_json::Value;
7705
7706 let raw: Value = serde_json::from_str(
7707 r#"{
7708 "type":"system","subtype":"feedback_draft_queued",
7709 "draft_id":"draft-1","draft_type":"bug_report",
7710 "title":"Tool output was truncated",
7711 "details_preview":"The last command omitted its final lines",
7712 "uuid":"u1","session_id":"s1","future_field":"preserved"
7713 }"#,
7714 )
7715 .unwrap();
7716 crate::io::assert_fully_wrapped(&raw);
7717
7718 let output: ClaudeOutput = serde_json::from_value(raw).unwrap();
7719 let ClaudeOutput::System(sys) = output else {
7720 panic!("expected System");
7721 };
7722 assert_eq!(sys.subtype, SystemSubtype::FeedbackDraftQueued);
7723 assert!(sys.is_feedback_draft_queued());
7724 assert!(!sys.is_vcs_state_changed());
7725
7726 let direct = sys
7727 .as_feedback_draft_queued()
7728 .expect("direct typed accessor");
7729 assert_eq!(direct.draft_id, "draft-1");
7730 assert_eq!(direct.draft_type, "bug_report");
7731 assert_eq!(direct.extra["future_field"], "preserved");
7732
7733 let Some(KnownSystemEvent::FeedbackDraftQueued(known)) = sys.as_known_system_event() else {
7734 panic!("expected FeedbackDraftQueued event");
7735 };
7736 assert_eq!(known.title, "Tool output was truncated");
7737 assert_eq!(
7738 sys.typed_value().expect("typed value")["future_field"],
7739 "preserved"
7740 );
7741 }
7742
7743 #[test]
7744 fn test_cloud_session_delta_fully_wrapped() {
7745 use super::{KnownSystemEvent, SystemSubtype};
7746 use serde_json::Value;
7747
7748 let raw: Value = serde_json::from_str(
7749 r#"{
7750 "type":"system","subtype":"cloud_session_delta",
7751 "seq":3,"changed":["serving","connection"],
7752 "cloud_session":{"id":"session_abc","view_url":"https://example.invalid/s/abc",
7753 "serving":{"state":"on"},"connection":{"state":"live"}},
7754 "uuid":"u1","session_id":"s1","future_field":"preserved"
7755 }"#,
7756 )
7757 .unwrap();
7758 crate::io::assert_fully_wrapped(&raw);
7759
7760 let output: ClaudeOutput = serde_json::from_value(raw).unwrap();
7761 let ClaudeOutput::System(sys) = output else {
7762 panic!("expected System");
7763 };
7764 assert_eq!(sys.subtype, SystemSubtype::CloudSessionDelta);
7765 assert!(sys.is_cloud_session_delta());
7766 assert!(!sys.is_feedback_draft_queued());
7767
7768 let direct = sys.as_cloud_session_delta().expect("direct typed accessor");
7769 assert_eq!(direct.seq, 3);
7770 assert_eq!(direct.changed, vec!["serving", "connection"]);
7771 assert_eq!(direct.cloud_session["id"], "session_abc");
7772 assert_eq!(direct.extra["future_field"], "preserved");
7773
7774 let Some(KnownSystemEvent::CloudSessionDelta(known)) = sys.as_known_system_event() else {
7775 panic!("expected CloudSessionDelta event");
7776 };
7777 assert_eq!(known.session_id, "s1");
7778 assert_eq!(
7779 sys.typed_value().expect("typed value")["future_field"],
7780 "preserved"
7781 );
7782 }
7783
7784 #[test]
7785 fn test_vcs_state_changed_fully_wrapped() {
7786 use super::{KnownSystemEvent, VcsMutationKind};
7787 use serde_json::Value;
7788
7789 for kind in ["commit", "push", "merge", "rebase"] {
7790 let raw: Value = serde_json::from_str(&format!(
7791 r#"{{"type":"system","subtype":"vcs_state_changed","kind":"{}","cwd":"/repo","uuid":"u1","session_id":"s1"}}"#,
7792 kind
7793 ))
7794 .unwrap();
7795 crate::io::assert_fully_wrapped(&raw);
7796
7797 let output: ClaudeOutput = serde_json::from_value(raw).unwrap();
7798 let ClaudeOutput::System(sys) = output else {
7799 panic!("expected System");
7800 };
7801 let Some(KnownSystemEvent::VcsStateChanged(msg)) = sys.as_known_system_event() else {
7802 panic!("expected VcsStateChanged event");
7803 };
7804 assert_eq!(msg.kind.as_str(), kind);
7805 assert!(!matches!(msg.kind, VcsMutationKind::Unknown(_)));
7806 }
7807
7808 let raw: Value = serde_json::from_str(
7810 r#"{"type":"system","subtype":"vcs_state_changed","kind":"tag","cwd":"/repo","uuid":"u2","session_id":"s2"}"#,
7811 )
7812 .unwrap();
7813 crate::io::assert_fully_wrapped(&raw);
7814 let output: ClaudeOutput = serde_json::from_value(raw).unwrap();
7815 let ClaudeOutput::System(sys) = output else {
7816 panic!("expected System");
7817 };
7818 let Some(KnownSystemEvent::VcsStateChanged(msg)) = sys.as_known_system_event() else {
7819 panic!("expected VcsStateChanged event");
7820 };
7821 assert_eq!(msg.kind, VcsMutationKind::Unknown("tag".to_string()));
7822
7823 assert!(sys.is_vcs_state_changed());
7824 let direct = sys.as_vcs_state_changed().expect("direct accessor");
7825 assert_eq!(direct.cwd, "/repo");
7826 assert!(sys.as_code_change_published().is_none());
7827 }
7828
7829 #[test]
7830 fn test_assistant_aborted_and_resume_flags_roundtrip() {
7831 let json = r#"{
7832 "type":"assistant",
7833 "message":{"id":"msg_1","role":"assistant","model":"claude-3","content":[{"type":"text","text":"partial"}]},
7834 "session_id":"s1",
7835 "aborted":true,
7836 "resumed_from_incomplete_thinking":true
7837 }"#;
7838 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7839 let ClaudeOutput::Assistant(msg) = &output else {
7840 panic!("expected Assistant");
7841 };
7842 assert_eq!(msg.aborted, Some(true));
7843 assert_eq!(msg.resumed_from_incomplete_thinking, Some(true));
7844 let reserialized = serde_json::to_string(&output).unwrap();
7845 assert!(reserialized.contains("\"aborted\":true"));
7846 assert!(reserialized.contains("\"resumed_from_incomplete_thinking\":true"));
7847
7848 let json = r#"{
7850 "type":"assistant",
7851 "message":{"id":"msg_2","role":"assistant","model":"claude-3","content":[]},
7852 "session_id":"s2"
7853 }"#;
7854 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7855 let reserialized = serde_json::to_string(&output).unwrap();
7856 assert!(!reserialized.contains("aborted"));
7857 assert!(!reserialized.contains("resumed_from_incomplete_thinking"));
7858 }
7859
7860 #[test]
7861 fn test_user_tool_result_meta_roundtrip() {
7862 let json = r#"{
7863 "type":"user",
7864 "message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_1","content":"denied"}]},
7865 "session_id":"622ae0c3-3d50-4fa7-9ee0-69d691238c6d",
7866 "tool_result_meta":[
7867 {"id":"toolu_1","non_execution_kind":"user-rejected","user_feedback":"use the staging db"},
7868 {"id":"toolu_2","non_execution_kind":"permission-rule"}
7869 ]
7870 }"#;
7871 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7872 let ClaudeOutput::User(user) = &output else {
7873 panic!("expected User");
7874 };
7875 let meta = user.tool_result_meta.as_ref().unwrap();
7876 assert_eq!(meta.len(), 2);
7877 assert_eq!(meta[0].non_execution_kind.as_deref(), Some("user-rejected"));
7878 assert_eq!(meta[0].user_feedback.as_deref(), Some("use the staging db"));
7879 assert_eq!(meta[1].user_feedback, None);
7880
7881 let reserialized = serde_json::to_string(&output).unwrap();
7882 assert!(reserialized.contains("\"non_execution_kind\":\"user-rejected\""));
7883 assert!(!reserialized.contains("\"user_feedback\":null"));
7884 }
7885
7886 #[test]
7890 fn model_refusal_fallback_scope_roundtrips_and_defaults() {
7891 use super::{ModelRefusalFallbackMessage, RefusalFallbackScope};
7892 let with_scope = serde_json::json!({
7893 "trigger": "refusal",
7894 "direction": "retry",
7895 "scope": "local",
7896 "original_model": "claude-fable-5",
7897 "fallback_model": "claude-opus-5",
7898 "request_id": null,
7899 "content": "Refused; retried on fallback model.",
7900 "uuid": "u1",
7901 "session_id": "s1"
7902 });
7903 let msg: ModelRefusalFallbackMessage = serde_json::from_value(with_scope.clone()).unwrap();
7904 assert_eq!(msg.scope, Some(RefusalFallbackScope::Local));
7905 assert_eq!(serde_json::to_value(&msg).unwrap(), with_scope);
7906
7907 let mut without = with_scope.clone();
7910 without.as_object_mut().unwrap().remove("scope");
7911 let msg: ModelRefusalFallbackMessage = serde_json::from_value(without.clone()).unwrap();
7912 assert_eq!(msg.scope, None);
7913 assert_eq!(serde_json::to_value(&msg).unwrap(), without);
7914
7915 assert_eq!(
7917 RefusalFallbackScope::from("workspace").as_str(),
7918 "workspace"
7919 );
7920 }
7921}